{"repo_name": "Winhance", "file_name": "/Winhance/src/Winhance.WPF/Features/Common/Views/MainWindow.xaml.cs", "inference_info": {"prefix_code": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Interop;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.Common.Utilities;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n public partial class MainWindow : Window\n {\n private readonly Winhance.Core.Features.Common.Interfaces.INavigationService _navigationService =\n null!;\n private WindowSizeManager _windowSizeManager;\n private readonly UserPreferencesService _userPreferencesService;\n private readonly IApplicationCloseService _applicationCloseService;\n\n private void LogDebug(string message, Exception? ex = null)\n {\n string fullMessage = message + (ex != null ? $\" - Exception: {ex.Message}\" : \"\");\n\n // Use proper logging service for application logging\n _messengerService?.Send(\n new LogMessage\n {\n Message = fullMessage,\n Level = ex != null ? LogLevel.Error : LogLevel.Debug,\n Exception = ex,\n }\n );\n\n // Also log to diagnostic file for troubleshooting\n FileLogger.Log(\"MainWindow\", fullMessage);\n\n // If there's an exception, log the stack trace as well\n if (ex != null)\n {\n FileLogger.Log(\"MainWindow\", $\"Stack trace: {ex.StackTrace}\");\n }\n\n // Also log to WinhanceStartupLog.txt for debugging the white screen issue\n LogToStartupLog(fullMessage);\n if (ex != null)\n {\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n }\n }\n\n /// \n /// Logs a message directly to the WinhanceStartupLog.txt file\n /// \n private void LogToStartupLog(string message)\n {\n#if DEBUG\n try\n {\n string logsDir = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\"\n );\n string logFile = Path.Combine(logsDir, \"WinhanceStartupLog.txt\");\n\n // Ensure the logs directory exists\n if (!Directory.Exists(logsDir))\n {\n Directory.CreateDirectory(logsDir);\n }\n\n // Format the log message with timestamp\n string formattedMessage =\n $\"[{DateTime.Now:yyyy/MM/dd HH:mm:ss}] [MainWindow] {message}\";\n\n // Append to the log file\n using (StreamWriter writer = File.AppendText(logFile))\n {\n writer.WriteLine(formattedMessage);\n }\n }\n catch\n {\n // Ignore errors in logging to avoid cascading issues\n }\n#endif\n }\n\n public MainWindow()\n {\n LogDebug(\"Default constructor called - THIS SHOULD NOT HAPPEN\");\n try\n {\n // Don't worry about this error, it is initialized at runtime.\n InitializeComponent();\n LogDebug(\"Default constructor completed initialization\");\n\n // Direct event handlers for window control buttons\n this.MinimizeButton.Click += (s, e) => this.WindowState = WindowState.Minimized;\n this.MaximizeRestoreButton.Click += (s, e) =>\n {\n this.WindowState =\n (this.WindowState == WindowState.Maximized)\n ? WindowState.Normal\n : WindowState.Maximized;\n };\n this.CloseButton.Click += CloseButton_Click;\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in default constructor\", ex);\n throw;\n }\n }\n\n // No need to define InitializeComponent here, it's generated by the WPF build system\n\n public MainWindow(\n IThemeManager themeManager,\n IServiceProvider serviceProvider,\n IMessengerService messengerService,\n Winhance.Core.Features.Common.Interfaces.INavigationService navigationService,\n IVersionService versionService,\n UserPreferencesService userPreferencesService,\n IApplicationCloseService applicationCloseService\n )\n {\n try\n {\n // Use FileLogger directly to ensure we capture everything\n FileLogger.Log(\"MainWindow\", \"MainWindow constructor starting\");\n FileLogger.Log(\n \"MainWindow\",\n $\"Parameters: themeManager={themeManager != null}, serviceProvider={serviceProvider != null}, messengerService={messengerService != null}, navigationService={navigationService != null}, versionService={versionService != null}, userPreferencesService={userPreferencesService != null}\"\n );\n\n // Verify dependencies\n if (themeManager == null)\n throw new ArgumentNullException(nameof(themeManager));\n if (serviceProvider == null)\n throw new ArgumentNullException(nameof(serviceProvider));\n if (messengerService == null)\n throw new ArgumentNullException(nameof(messengerService));\n if (navigationService == null)\n throw new ArgumentNullException(nameof(navigationService));\n if (versionService == null)\n throw new ArgumentNullException(nameof(versionService));\n if (userPreferencesService == null)\n throw new ArgumentNullException(nameof(userPreferencesService));\n FileLogger.Log(\"MainWindow\", \"Dependencies verified\");\n\n // Let the build system initialize the component\n try\n {\n LogToStartupLog(\"Starting InitializeComponent\");\n\n // We'll use a try-catch block around each part of the InitializeComponent process\n try\n {\n LogToStartupLog(\"Calling InitializeComponent()\");\n InitializeComponent();\n LogToStartupLog(\"InitializeComponent() completed successfully\");\n }\n catch (Exception initEx)\n {\n LogToStartupLog($\"ERROR in InitializeComponent(): {initEx.Message}\");\n LogToStartupLog($\"Stack trace: {initEx.StackTrace}\");\n throw; // Re-throw to be caught by the outer try-catch\n }\n\n LogToStartupLog(\"InitializeComponent completed\");\n\n // Direct event handlers for window control buttons\n try\n {\n LogToStartupLog(\"Setting up window control button event handlers\");\n\n LogToStartupLog($\"MinimizeButton exists: {this.MinimizeButton != null}\");\n this.MinimizeButton.Click += (s, e) =>\n this.WindowState = WindowState.Minimized;\n\n LogToStartupLog(\n $\"MaximizeRestoreButton exists: {this.MaximizeRestoreButton != null}\"\n );\n this.MaximizeRestoreButton.Click += (s, e) =>\n {\n this.WindowState =\n (this.WindowState == WindowState.Maximized)\n ? WindowState.Normal\n : WindowState.Maximized;\n\n // Update button content when window state changes\n if (DataContext is MainViewModel viewModel)\n {\n viewModel.MaximizeButtonContent =\n (this.WindowState == WindowState.Maximized)\n ? \"WindowRestore\"\n : \"WindowMaximize\";\n }\n };\n\n LogToStartupLog($\"CloseButton exists: {this.CloseButton != null}\");\n this.CloseButton.Click += CloseButton_Click;\n\n LogToStartupLog($\"MoreButton exists: {this.MoreButton != null}\");\n LogToStartupLog($\"MoreMenuControl exists: {this.MoreMenuControl != null}\");\n this.MoreButton.Click += MoreButton_Click;\n\n LogToStartupLog(\n \"Successfully set up all window control button event handlers\"\n );\n }\n catch (Exception buttonEx)\n {\n LogToStartupLog(\n $\"ERROR setting up button event handlers: {buttonEx.Message}\"\n );\n LogToStartupLog($\"Stack trace: {buttonEx.StackTrace}\");\n }\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in InitializeComponent\", ex);\n // This is not ideal, but we'll continue since the constructor errors will be handled\n }\n\n LogDebug(\"Setting fields\");\n _themeManager = themeManager;\n _serviceProvider = serviceProvider;\n _messengerService = messengerService;\n _navigationService = navigationService;\n _versionService =\n versionService ?? throw new ArgumentNullException(nameof(versionService));\n\n // Create the window size manager\n try\n {\n var logService =\n _serviceProvider.GetService(typeof(ILogService)) as ILogService;\n\n if (userPreferencesService != null && logService != null)\n {\n _windowSizeManager = new WindowSizeManager(\n this,\n userPreferencesService,\n logService\n );\n LogDebug(\"WindowSizeManager created successfully\");\n }\n else\n {\n LogDebug(\"Could not create WindowSizeManager: services not available\");\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error creating WindowSizeManager: {ex.Message}\", ex);\n }\n _userPreferencesService =\n userPreferencesService\n ?? throw new ArgumentNullException(nameof(userPreferencesService));\n _applicationCloseService =\n applicationCloseService\n ?? throw new ArgumentNullException(nameof(applicationCloseService));\n LogDebug(\"Fields set\");\n\n // Hook up events for ContentPresenter-based navigation\n if (\n _navigationService\n is Winhance.Core.Features.Common.Interfaces.INavigationService navService\n )\n {\n LogDebug(\"Setting up navigation service for ContentPresenter-based navigation\");\n\n // Add PreviewMouseWheel event handler for better scrolling\n this.PreviewMouseWheel += MainWindow_PreviewMouseWheel;\n\n // We'll navigate once the window is fully loaded\n this.Loaded += (sender, e) =>\n {\n LogDebug(\"Window loaded, navigating to default view\");\n\n // Apply the theme to ensure all toggle switches are properly initialized\n try\n {\n LogDebug(\"Applying theme to initialize toggle switches\");\n if (_themeManager != null)\n {\n // Apply the theme which will update all toggle switches\n _themeManager.ApplyTheme();\n LogDebug(\"Successfully initialized toggle switches\");\n\n // Update the app icon based on the theme\n UpdateThemeIcon();\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error initializing toggle switches: {ex.Message}\", ex);\n }\n\n if (DataContext is MainViewModel mainViewModel)\n {\n try\n {\n // Navigate to SoftwareApps view by default\n LogDebug(\"Navigating to SoftwareApps view\");\n _navigationService.NavigateTo(\"SoftwareApps\");\n\n // Verify that navigation succeeded\n if (mainViewModel.CurrentViewModel == null)\n {\n LogDebug(\n \"WARNING: Navigation succeeded but CurrentViewModel is null\"\n );\n }\n else\n {\n LogDebug(\n $\"Navigation succeeded, CurrentViewModel is {mainViewModel.CurrentViewModel.GetType().Name}\"\n );\n }\n }\n catch (Exception ex)\n {\n LogDebug(\n $\"Error navigating to SoftwareApps view: {ex.Message}\",\n ex\n );\n\n // Try to recover by navigating to another view\n try\n {\n LogDebug(\"Attempting to navigate to About view as fallback\");\n _navigationService.NavigateTo(\"About\");\n }\n catch (Exception fallbackEx)\n {\n LogDebug(\n $\"Error navigating to fallback view: {fallbackEx.Message}\",\n fallbackEx\n );\n }\n }\n }\n else\n {\n LogDebug(\n $\"DataContext is not MainViewModel, it is {DataContext?.GetType().Name ?? \"null\"}\"\n );\n }\n };\n\n // Add StateChanged event to update Maximize/Restore button content only\n this.StateChanged += (sender, e) =>\n {\n if (DataContext is MainViewModel viewModel)\n {\n viewModel.MaximizeButtonContent =\n (this.WindowState == WindowState.Maximized)\n ? \"WindowRestore\"\n : \"WindowMaximize\";\n }\n };\n\n // We no longer save window position/size to preferences\n }\n else\n {\n LogDebug(\n $\"_navigationService is not INavigationService, it is {_navigationService?.GetType().Name ?? \"null\"}\"\n );\n }\n\n // Register for window state messages\n LogDebug(\"Registering for window state messages\");\n _messengerService.Register(this, HandleWindowStateMessage);\n LogDebug(\"Registered for window state messages\");\n\n // Add Closing event handler to log the closing process\n this.Closing += MainWindow_Closing;\n\n // Clean up when window is closed\n this.Closed += (sender, e) =>\n {\n LogDebug(\"Window closed, unregistering from messenger service\");\n _messengerService.Unregister(this);\n };\n\n LogDebug($\"DataContext is {(DataContext == null ? \"null\" : \"not null\")}\");\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in parameterized constructor\", ex);\n throw;\n }\n }\n\n private async void CloseButton_Click(object sender, RoutedEventArgs e)\n {\n try\n {\n LogDebug(\"CloseButton_Click called, delegating to ApplicationCloseService\");\n await _applicationCloseService.CloseApplicationWithSupportDialogAsync();\n }\n catch (Exception ex)\n {\n LogDebug($\"Error in CloseButton_Click: {ex.Message}\", ex);\n\n // Fallback to direct close if there's an error\n try\n {\n this.Close();\n }\n catch\n {\n // Last resort\n Application.Current.Shutdown();\n }\n }\n }\n\n private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)\n {\n try\n {\n // Check if the DataContext is MainViewModel\n if (DataContext is MainViewModel viewModel)\n {\n LogDebug(\"DataContext is MainViewModel\");\n\n // Log any relevant properties or state from the ViewModel\n LogDebug($\"CurrentViewName: {viewModel.CurrentViewName}\");\n LogDebug(\n $\"CurrentViewModel type: {viewModel.CurrentViewModel?.GetType().FullName ?? \"null\"}\"\n );\n }\n else\n {\n LogDebug(\n $\"DataContext is not MainViewModel, it is {DataContext?.GetType().Name ?? \"null\"}\"\n );\n }\n\n // Log active windows\n LogDebug(\"Active windows:\");\n foreach (Window window in Application.Current.Windows)\n {\n LogDebug(\n $\"Window: {window.GetType().FullName}, IsVisible: {window.IsVisible}, WindowState: {window.WindowState}\"\n );\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error in MainWindow_Closing: {ex.Message}\", ex);\n }\n }\n\n private readonly IMessengerService _messengerService = null!;\n private readonly IVersionService _versionService = null!;\n\n #region More Button Event Handlers\n\n /// \n /// Event handler for the More button click\n /// Shows the context menu when the More button is clicked\n /// \n private void MoreButton_Click(object sender, RoutedEventArgs e)\n {\n // Log to the startup log file\n LogToStartupLog(\"More button clicked\");\n\n try\n {\n // Show the context menu using the MoreMenu control\n LogToStartupLog($\"MoreMenuControl exists: {MoreMenuControl != null}\");\n LogToStartupLog($\"MoreButton exists: {MoreButton != null}\");\n\n if (MoreMenuControl != null)\n {\n LogToStartupLog(\"About to call MoreMenuControl.ShowMenu()\");\n\n try\n {\n // Show the menu with the More button as the placement target\n MoreMenuControl.ShowMenu(MoreButton);\n LogToStartupLog(\"MoreMenuControl.ShowMenu() called successfully\");\n }\n catch (Exception menuEx)\n {\n LogToStartupLog($\"ERROR in MoreMenuControl.ShowMenu(): {menuEx.Message}\");\n LogToStartupLog($\"Stack trace: {menuEx.StackTrace}\");\n }\n }\n else\n {\n LogToStartupLog(\"MoreMenuControl is null, cannot show menu\");\n }\n }\n catch (Exception ex)\n {\n LogToStartupLog($\"Error in MoreButton_Click: {ex.Message}\");\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n }\n }\n\n // Context menu event handlers have been moved to MoreMenuViewModel\n\n #endregion\n\n private void HandleWindowStateMessage(WindowStateMessage message)\n {\n LogDebug($\"Received window state message: {message.Action}\");\n\n try\n {\n switch (message.Action)\n {\n case WindowStateMessage.WindowStateAction.Minimize:\n LogDebug(\"Processing minimize action\");\n WindowState = WindowState.Minimized;\n break;\n\n case WindowStateMessage.WindowStateAction.Maximize:\n LogDebug(\"Processing maximize action\");\n WindowState = WindowState.Maximized;\n break;\n\n case WindowStateMessage.WindowStateAction.Restore:\n LogDebug(\"Processing restore action\");\n WindowState = WindowState.Normal;\n break;\n\n case WindowStateMessage.WindowStateAction.Close:\n LogDebug(\"Processing close action\");\n Close();\n break;\n\n default:\n LogDebug($\"Unknown window state action: {message.Action}\");\n break;\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error handling window state message: {ex.Message}\", ex);\n }\n }\n\n private readonly IServiceProvider _serviceProvider = null!;\n private readonly IThemeManager _themeManager = null!;\n\n protected override void OnSourceInitialized(EventArgs e)\n {\n LogDebug(\"OnSourceInitialized starting\");\n try\n {\n base.OnSourceInitialized(e);\n LogDebug(\"Base OnSourceInitialized called\");\n\n var helper = new WindowInteropHelper(this);\n if (helper.Handle == IntPtr.Zero)\n {\n throw new InvalidOperationException(\"Window handle not available\");\n }\n LogDebug(\"Window handle verified\");\n\n // Initialize the window size manager to set size and center the window\n if (_windowSizeManager != null)\n {\n _windowSizeManager.Initialize();\n LogDebug(\"WindowSizeManager initialized\");\n }\n else\n {\n // Fallback if window size manager is not available\n SetDynamicWindowSize();\n LogDebug(\"Used fallback dynamic window sizing\");\n }\n\n EnableBlur();\n LogDebug(\"Blur enabled successfully\");\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in OnSourceInitialized\", ex);\n // Don't throw - blur is not critical\n }\n }\n\n /// \n /// Sets the window size dynamically based on the screen resolution\n /// \n private void SetDynamicWindowSize()\n {\n try\n {\n LogDebug(\"Setting dynamic window size\");\n\n // Get the current screen's working area (excludes taskbar)\n var workArea = GetCurrentScreenWorkArea();\n\n // Get DPI scaling factor for the current screen\n double dpiScaleX = 1.0;\n double dpiScaleY = 1.0;\n\n try\n {\n var presentationSource = PresentationSource.FromVisual(this);\n if (presentationSource?.CompositionTarget != null)\n {\n dpiScaleX = presentationSource.CompositionTarget.TransformToDevice.M11;\n dpiScaleY = presentationSource.CompositionTarget.TransformToDevice.M22;\n LogDebug($\"DPI scale factors: X={dpiScaleX}, Y={dpiScaleY}\");\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting DPI scale: {ex.Message}\", ex);\n }\n\n // Calculate available screen space\n double screenWidth = workArea.Width / dpiScaleX;\n double screenHeight = workArea.Height / dpiScaleY;\n double screenLeft = workArea.X / dpiScaleX;\n double screenTop = workArea.Y / dpiScaleY;\n\n // Calculate window size (75% of screen size with minimum/maximum constraints)\n double windowWidth = Math.Min(1600, screenWidth * 0.75);\n double windowHeight = Math.Min(900, screenHeight * 0.75);\n\n // Ensure minimum size for usability\n windowWidth = Math.Max(windowWidth, 1024);\n windowHeight = Math.Max(windowHeight, 700);\n\n // Set the window size\n this.Width = windowWidth;\n this.Height = windowHeight;\n\n // Center the window on screen\n this.Left = screenLeft + (screenWidth - windowWidth) / 2;\n this.Top = screenTop + (screenHeight - windowHeight) / 2;\n\n LogDebug(\n $\"Screen resolution: {screenWidth}x{screenHeight}, Window size set to: {windowWidth}x{windowHeight}\"\n );\n LogDebug($\"Window centered at: Left={this.Left}, Top={this.Top}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error setting dynamic window size: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Gets the working area of the screen that contains the window\n /// \n private Rect GetCurrentScreenWorkArea()\n {\n try\n {\n // Get the window handle\n var windowHandle = new WindowInteropHelper(this).Handle;\n if (windowHandle != IntPtr.Zero)\n {\n // Get the monitor info for the monitor containing the window\n var monitorInfo = new MONITORINFO();\n monitorInfo.cbSize = Marshal.SizeOf(typeof(MONITORINFO));\n\n if (\n GetMonitorInfo(\n MonitorFromWindow(windowHandle, MONITOR_DEFAULTTONEAREST),\n ref monitorInfo\n )\n )\n {\n // Convert the working area to a WPF Rect\n return new Rect(\n monitorInfo.rcWork.left,\n monitorInfo.rcWork.top,\n monitorInfo.rcWork.right - monitorInfo.rcWork.left,\n monitorInfo.rcWork.bottom - monitorInfo.rcWork.top\n );\n }\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting current screen: {ex.Message}\", ex);\n }\n\n // Fallback to primary screen working area\n return SystemParameters.WorkArea;\n }\n\n [DllImport(\"user32.dll\")]\n private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);\n\n [DllImport(\"user32.dll\")]\n private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);\n\n private const uint MONITOR_DEFAULTTONEAREST = 2;\n\n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int left;\n public int top;\n public int right;\n public int bottom;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct MONITORINFO\n {\n public int cbSize;\n public RECT rcMonitor;\n public RECT rcWork;\n public uint dwFlags;\n }\n\n private void EnableBlur()\n {\n LogDebug(\"EnableBlur starting\");\n var windowHelper = new WindowInteropHelper(this);\n var accent = new AccentPolicy { AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND };\n var accentStructSize = Marshal.SizeOf(accent);\n\n var accentPtr = IntPtr.Zero;\n try\n {\n accentPtr = Marshal.AllocHGlobal(accentStructSize);\n Marshal.StructureToPtr(accent, accentPtr, false);\n\n var data = new WindowCompositionAttributeData\n {\n Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY,\n SizeOfData = accentStructSize,\n Data = accentPtr,\n };\n\n int result = SetWindowCompositionAttribute(windowHelper.Handle, ref data);\n if (result == 0)\n {\n throw new InvalidOperationException(\"SetWindowCompositionAttribute failed\");\n }\n LogDebug(\"Blur effect applied successfully\");\n }\n catch (Exception ex)\n {\n LogDebug(\"Error enabling blur\", ex);\n throw;\n }\n finally\n {\n if (accentPtr != IntPtr.Zero)\n {\n Marshal.FreeHGlobal(accentPtr);\n }\n }\n }\n\n [DllImport(\"user32.dll\")]\n internal static extern int SetWindowCompositionAttribute(\n IntPtr hwnd,\n ref WindowCompositionAttributeData data\n );\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct AccentPolicy\n {\n public AccentState AccentState;\n public int AccentFlags;\n public int GradientColor;\n public int AnimationId;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct WindowCompositionAttributeData\n {\n public WindowCompositionAttribute Attribute;\n public IntPtr Data;\n public int SizeOfData;\n }\n\n internal enum AccentState\n {\n ACCENT_DISABLED = 0,\n ACCENT_ENABLE_GRADIENT = 1,\n ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,\n ACCENT_ENABLE_BLURBEHIND = 3,\n ACCENT_ENABLE_ACRYLICBLURBEHIND = 4,\n ACCENT_INVALID_STATE = 5,\n }\n\n internal enum WindowCompositionAttribute\n {\n WCA_ACCENT_POLICY = 19,\n }\n\n // Window control is now handled through ViewModel commands and messaging\n\n /// \n /// Updates the window and image icons based on the current theme\n /// \n private void UpdateThemeIcon()\n {\n if (_themeManager == null)\n {\n LogDebug(\"Cannot update theme icon: ThemeManager is null\");\n return;\n }\n\n try\n {\n LogDebug(\n $\"Updating theme icon. Current theme: {(_themeManager.IsDarkTheme ? \"Dark\" : \"Light\")}\"\n );\n\n // Get the appropriate icon based on the theme\n string iconPath = _themeManager.IsDarkTheme\n ? \"pack://application:,,,/Resources/AppIcons/winhance-rocket-white-transparent-bg.ico\"\n : \"pack://application:,,,/Resources/AppIcons/winhance-rocket-black-transparent-bg.ico\";\n\n LogDebug($\"Selected icon path: {iconPath}\");\n\n // Create a BitmapImage from the icon path\n var iconImage = new BitmapImage(new Uri(iconPath, UriKind.Absolute));\n iconImage.Freeze(); // Freeze for better performance and thread safety\n\n // Set the window icon\n this.Icon = iconImage;\n LogDebug(\"Window icon updated\");\n\n // Set the image control source\n if (AppIconImage != null)\n {\n AppIconImage.Source = iconImage;\n LogDebug(\"AppIconImage source updated\");\n }\n else\n {\n LogDebug(\"AppIconImage is null, cannot update source\");\n }\n }\n catch (Exception ex)\n {\n LogDebug(\"Error updating theme icon\", ex);\n\n // If there's an error, fall back to the default icon\n try\n {\n var defaultIcon = new BitmapImage(\n new Uri(\n \"pack://application:,,,/Resources/AppIcons/winhance-rocket.ico\",\n UriKind.Absolute\n )\n );\n this.Icon = defaultIcon;\n if (AppIconImage != null)\n {\n AppIconImage.Source = defaultIcon;\n }\n }\n catch (Exception fallbackEx)\n {\n LogDebug(\"Error setting fallback icon\", fallbackEx);\n }\n }\n }\n\n /// \n /// Handles mouse wheel events at the window level and redirects them to the ScrollViewer\n /// \n ", "suffix_code": "\n\n /// \n /// Finds a visual child of the specified type in the visual tree\n /// \n private static T FindVisualChild(DependencyObject obj)\n where T : DependencyObject\n {\n for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)\n {\n DependencyObject child = VisualTreeHelper.GetChild(obj, i);\n\n if (child != null && child is T)\n {\n return (T)child;\n }\n\n T childOfChild = FindVisualChild(child);\n if (childOfChild != null)\n {\n return childOfChild;\n }\n }\n\n return null;\n }\n }\n}\n", "middle_code": "private void MainWindow_PreviewMouseWheel(object sender, MouseWheelEventArgs e)\n {\n var scrollViewer = FindVisualChild(this);\n if (scrollViewer != null)\n {\n if (e.Delta < 0)\n {\n scrollViewer.LineDown();\n }\n else\n {\n scrollViewer.LineUp();\n }\n e.Handled = true;\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/Winhance/src/Winhance.WPF/Features/Common/Utilities/WindowSizeManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Interop;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.Common.Utilities;\n\nnamespace Winhance.WPF.Features.Common.Utilities\n{\n /// \n /// Manages window size and position, including dynamic sizing based on screen resolution\n /// and handling multiple monitors and DPI scaling.\n /// \n public class WindowSizeManager\n {\n private readonly Window _window;\n private readonly ILogService _logService;\n\n // Default window dimensions\n private const double DEFAULT_WIDTH = 1600;\n private const double DEFAULT_HEIGHT = 900;\n private const double MIN_WIDTH = 1024;\n private const double MIN_HEIGHT = 700; // Reduced minimum height to fit better on smaller screens\n private const double SCREEN_PERCENTAGE = 0.9; // Use 90% of screen size for better fit\n\n public WindowSizeManager(Window window, UserPreferencesService userPreferencesService, ILogService logService)\n {\n _window = window ?? throw new ArgumentNullException(nameof(window));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n \n // No events registered - we don't save window position anymore\n }\n\n /// \n /// Initializes the window size and position\n /// \n public void Initialize()\n {\n try\n {\n // Set dynamic window size based on screen resolution (75% of screen)\n SetDynamicWindowSize();\n \n // Always center the window on screen\n // This ensures consistent behavior regardless of WindowStartupLocation\n CenterWindowOnScreen();\n \n LogDebug($\"Window initialized with size: {_window.Width}x{_window.Height}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error initializing window size manager: {ex.Message}\", ex);\n }\n }\n \n /// \n /// Centers the window on the current screen\n /// \n private void CenterWindowOnScreen()\n {\n try\n {\n // Get the current screen's working area\n var workArea = GetCurrentScreenWorkArea();\n \n // Get DPI scaling factor\n double dpiScaleX = 1.0;\n double dpiScaleY = 1.0;\n \n try\n {\n var presentationSource = PresentationSource.FromVisual(_window);\n if (presentationSource?.CompositionTarget != null)\n {\n dpiScaleX = presentationSource.CompositionTarget.TransformToDevice.M11;\n dpiScaleY = presentationSource.CompositionTarget.TransformToDevice.M22;\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting DPI scale: {ex.Message}\", ex);\n }\n \n // Convert screen coordinates to account for DPI\n double screenWidth = workArea.Width / dpiScaleX;\n double screenHeight = workArea.Height / dpiScaleY;\n double screenLeft = workArea.X / dpiScaleX;\n double screenTop = workArea.Y / dpiScaleY;\n \n // Calculate center position\n double left = screenLeft + (screenWidth - _window.Width) / 2;\n double top = screenTop + (screenHeight - _window.Height) / 2;\n \n // Set window position\n _window.Left = left;\n _window.Top = top;\n \n LogDebug($\"Window explicitly centered at: Left={left}, Top={top}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error centering window: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Sets the window size dynamically based on the screen resolution\n /// \n private void SetDynamicWindowSize()\n {\n try\n {\n LogDebug(\"Setting dynamic window size\");\n \n // Get the current screen's working area (excludes taskbar)\n var workArea = GetCurrentScreenWorkArea();\n \n // Get DPI scaling factor for the current screen\n double dpiScaleX = 1.0;\n double dpiScaleY = 1.0;\n \n try\n {\n var presentationSource = PresentationSource.FromVisual(_window);\n if (presentationSource?.CompositionTarget != null)\n {\n dpiScaleX = presentationSource.CompositionTarget.TransformToDevice.M11;\n dpiScaleY = presentationSource.CompositionTarget.TransformToDevice.M22;\n LogDebug($\"DPI scale factors: X={dpiScaleX}, Y={dpiScaleY}\");\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting DPI scale: {ex.Message}\", ex);\n }\n \n // Calculate available screen space\n double screenWidth = workArea.Width / dpiScaleX;\n double screenHeight = workArea.Height / dpiScaleY;\n \n // Calculate window size (75% of screen size with minimum/maximum constraints)\n double windowWidth = Math.Min(DEFAULT_WIDTH, screenWidth * SCREEN_PERCENTAGE);\n double windowHeight = Math.Min(DEFAULT_HEIGHT, screenHeight * SCREEN_PERCENTAGE);\n \n // Ensure minimum size for usability\n windowWidth = Math.Max(windowWidth, MIN_WIDTH);\n windowHeight = Math.Max(windowHeight, MIN_HEIGHT);\n \n // Only set the window size, let WPF handle the centering via WindowStartupLocation=\"CenterScreen\"\n _window.Width = windowWidth;\n _window.Height = windowHeight;\n \n LogDebug($\"Dynamic window size set to: Width={windowWidth}, Height={windowHeight}\");\n LogDebug($\"Screen dimensions: Width={screenWidth}, Height={screenHeight}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error setting dynamic window size: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Gets the working area of the screen that contains the window\n /// \n private Rect GetCurrentScreenWorkArea()\n {\n try\n {\n // Get the window handle\n var windowHandle = new WindowInteropHelper(_window).Handle;\n if (windowHandle != IntPtr.Zero)\n {\n // Get the monitor info for the monitor containing the window\n var monitorInfo = new MONITORINFO();\n monitorInfo.cbSize = Marshal.SizeOf(typeof(MONITORINFO));\n \n if (GetMonitorInfo(MonitorFromWindow(windowHandle, MONITOR_DEFAULTTONEAREST), ref monitorInfo))\n {\n // Convert the working area to a WPF Rect\n return new Rect(\n monitorInfo.rcWork.left,\n monitorInfo.rcWork.top,\n monitorInfo.rcWork.right - monitorInfo.rcWork.left,\n monitorInfo.rcWork.bottom - monitorInfo.rcWork.top);\n }\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting current screen: {ex.Message}\", ex);\n }\n \n // Fallback to primary screen working area\n return SystemParameters.WorkArea;\n }\n\n // Event handlers for window state, location, and size changes have been removed\n // as we no longer save window position/size to preferences\n\n /// \n /// Logs a debug message\n /// \n private void LogDebug(string message, Exception ex = null)\n {\n try\n {\n _logService?.Log(LogLevel.Debug, message, ex);\n \n // Also log to file logger for troubleshooting\n FileLogger.Log(\"WindowSizeManager\", message + (ex != null ? $\" - Exception: {ex.Message}\" : \"\"));\n }\n catch\n {\n // Ignore logging errors\n }\n }\n\n #region Win32 API\n\n [DllImport(\"user32.dll\")]\n private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);\n \n [DllImport(\"user32.dll\")]\n private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);\n \n private const uint MONITOR_DEFAULTTONEAREST = 2;\n \n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int left;\n public int top;\n public int right;\n public int bottom;\n }\n \n [StructLayout(LayoutKind.Sequential)]\n private struct MONITORINFO\n {\n public int cbSize;\n public RECT rcMonitor;\n public RECT rcWork;\n public uint dwFlags;\n }\n\n #endregion\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/MainViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Input;\nusing System.Windows.Interop;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.Utilities;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n public partial class MainViewModel : BaseViewModel\n {\n // Window control is now handled through messaging\n\n private readonly IThemeManager _themeManager;\n private readonly INavigationService _navigationService;\n private readonly IMessengerService _messengerService;\n private readonly IUnifiedConfigurationService _unifiedConfigService;\n private readonly IDialogService _dialogService;\n private readonly Features.Common.Services.UserPreferencesService _userPreferencesService;\n\n public INavigationService NavigationService => _navigationService;\n\n [ObservableProperty]\n private object _currentViewModel;\n\n // Helper method to log window actions for debugging\n private void LogWindowAction(string message)\n {\n string formattedMessage = $\"Window Action: {message}\";\n\n // Send to application logging system\n _messengerService.Send(\n new LogMessage { Message = formattedMessage, Level = LogLevel.Debug }\n );\n\n // Also log to diagnostic file for troubleshooting\n FileLogger.Log(\"MainViewModel\", formattedMessage);\n }\n\n private string _currentViewName = string.Empty;\n public string CurrentViewName\n {\n get => _currentViewName;\n set => SetProperty(ref _currentViewName, value);\n }\n\n [ObservableProperty]\n private string _maximizeButtonContent = \"\\uE739\";\n\n /// \n /// Gets the ViewModel for the More menu functionality\n /// \n public MoreMenuViewModel MoreMenuViewModel { get; }\n\n /// \n /// Gets the command to save a unified configuration.\n /// \n public ICommand SaveUnifiedConfigCommand { get; }\n\n /// \n /// Gets the command to import a unified configuration.\n /// \n public ICommand ImportUnifiedConfigCommand { get; }\n\n /// \n /// Gets the command to open the donation page in a browser.\n /// \n public ICommand OpenDonateCommand { get; }\n\n public MainViewModel(\n IThemeManager themeManager,\n INavigationService navigationService,\n ITaskProgressService progressService,\n IMessengerService messengerService,\n IDialogService dialogService,\n IUnifiedConfigurationService unifiedConfigService,\n Features.Common.Services.UserPreferencesService userPreferencesService,\n ILogService logService,\n IVersionService versionService,\n IApplicationCloseService applicationCloseService\n )\n : base(progressService, messengerService)\n {\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n _navigationService =\n navigationService ?? throw new ArgumentNullException(nameof(navigationService));\n _messengerService =\n messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n _dialogService =\n dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _unifiedConfigService =\n unifiedConfigService\n ?? throw new ArgumentNullException(nameof(unifiedConfigService));\n _userPreferencesService =\n userPreferencesService\n ?? throw new ArgumentNullException(nameof(userPreferencesService));\n\n // Initialize the MoreMenuViewModel\n MoreMenuViewModel = new MoreMenuViewModel(logService, versionService, _messengerService, applicationCloseService, _dialogService);\n\n // Initialize command properties\n _minimizeWindowCommand = new RelayCommand(MinimizeWindow);\n _maximizeRestoreWindowCommand = new RelayCommand(MaximizeRestoreWindow);\n // Use AsyncRelayCommand instead of RelayCommand for async methods\n _closeWindowCommand = new AsyncRelayCommand(CloseWindowAsync);\n SaveUnifiedConfigCommand = new RelayCommand(SaveUnifiedConfig);\n ImportUnifiedConfigCommand = new RelayCommand(ImportUnifiedConfig);\n OpenDonateCommand = new RelayCommand(OpenDonate);\n\n // Note: View mappings are now registered in App.xaml.cs when configuring the FrameNavigationService\n\n // Subscribe to navigation events\n _navigationService.Navigated += NavigationService_Navigated;\n\n // We'll initialize with the default view later, after the window is loaded\n // This will be called from MainWindow.xaml.cs after the window is loaded\n // This will be called from MainWindow.xaml.cs after the window is loaded\n }\n\n private void NavigationService_Navigated(object sender, NavigationEventArgs e)\n {\n CurrentViewName = e.Route;\n\n // The NavigationService sets e.Parameter to the ViewModel instance\n // This ensures the CurrentViewModel is properly set\n if (e.Parameter != null && e.Parameter is IViewModel)\n {\n CurrentViewModel = e.Parameter;\n }\n else if (e.ViewModelType != null)\n {\n // If for some reason the parameter is not set, try to get the ViewModel from the service provider\n try\n {\n // Get the view model from the navigation event parameter\n if (e.Parameter != null)\n {\n CurrentViewModel = e.Parameter;\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error getting current view model: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n }\n\n [RelayCommand]\n private void Navigate(string viewName)\n {\n try\n {\n _navigationService.NavigateTo(viewName);\n }\n catch (Exception ex)\n {\n // Log the error using the messaging system\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Navigation error to {viewName}: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n\n MessageBox.Show(\n $\"Navigation error while attempting to navigate to {viewName}.\\nError: {ex.Message}\",\n \"Navigation Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error\n );\n }\n }\n\n [RelayCommand]\n private void ToggleTheme()\n {\n _themeManager.ToggleTheme();\n }\n\n // Explicit command property for MinimizeWindow\n private ICommand _minimizeWindowCommand;\n public ICommand MinimizeWindowCommand\n {\n get\n {\n if (_minimizeWindowCommand == null)\n {\n _minimizeWindowCommand = new RelayCommand(MinimizeWindow);\n }\n return _minimizeWindowCommand;\n }\n }\n\n private void MinimizeWindow()\n {\n LogWindowAction(\"MinimizeWindow command called\");\n\n var mainWindow = Application.Current.MainWindow;\n if (mainWindow == null)\n {\n LogWindowAction(\"MainWindow is null\");\n return;\n }\n\n // Try to minimize the window directly\n try\n {\n mainWindow.WindowState = WindowState.Minimized;\n LogWindowAction(\"Directly set WindowState to Minimized\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"Error setting WindowState directly: {ex.Message}\");\n\n // Fall back to messaging\n _messengerService.Send(\n new WindowStateMessage\n {\n Action = WindowStateMessage.WindowStateAction.Minimize,\n }\n );\n }\n }\n\n // Explicit command property for MaximizeRestoreWindow\n private ICommand _maximizeRestoreWindowCommand;\n public ICommand MaximizeRestoreWindowCommand\n {\n get\n {\n if (_maximizeRestoreWindowCommand == null)\n {\n _maximizeRestoreWindowCommand = new RelayCommand(MaximizeRestoreWindow);\n }\n return _maximizeRestoreWindowCommand;\n }\n }\n\n private void MaximizeRestoreWindow()\n {\n LogWindowAction(\"MaximizeRestoreWindow command called\");\n\n var mainWindow = Application.Current.MainWindow;\n if (mainWindow == null)\n {\n LogWindowAction(\"MainWindow is null\");\n return;\n }\n\n if (mainWindow.WindowState == WindowState.Maximized)\n {\n // Try to restore the window directly\n try\n {\n mainWindow.WindowState = WindowState.Normal;\n LogWindowAction(\"Directly set WindowState to Normal\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"Error setting WindowState directly: {ex.Message}\");\n\n // Fall back to messaging\n _messengerService.Send(\n new WindowStateMessage\n {\n Action = WindowStateMessage.WindowStateAction.Restore,\n }\n );\n }\n\n // Update the button icon\n MaximizeButtonContent = \"\\uE739\";\n LogWindowAction(\"Updated MaximizeButtonContent to Maximize icon\");\n }\n else\n {\n // Try to maximize the window directly\n try\n {\n mainWindow.WindowState = WindowState.Maximized;\n LogWindowAction(\"Directly set WindowState to Maximized\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"Error setting WindowState directly: {ex.Message}\");\n\n // Fall back to messaging\n _messengerService.Send(\n new WindowStateMessage\n {\n Action = WindowStateMessage.WindowStateAction.Maximize,\n }\n );\n }\n\n // Update the button icon\n MaximizeButtonContent = \"\\uE923\";\n LogWindowAction(\"Updated MaximizeButtonContent to Restore icon\");\n }\n }\n\n // Explicit command property for CloseWindow\n private ICommand _closeWindowCommand;\n public ICommand CloseWindowCommand\n {\n get\n {\n if (_closeWindowCommand == null)\n {\n // Use AsyncRelayCommand instead of RelayCommand for async methods\n _closeWindowCommand = new AsyncRelayCommand(CloseWindowAsync);\n }\n return _closeWindowCommand;\n }\n }\n\n // Make sure this method is public so it can be called directly for testing\n public async Task CloseWindowAsync()\n {\n LogWindowAction(\"CloseWindowAsync method called\");\n\n // Log basic information\n _messengerService.Send(\n new LogMessage\n {\n Message = \"CloseWindow method executing in MainViewModel\",\n Level = LogLevel.Debug,\n }\n );\n\n var mainWindow = Application.Current.MainWindow;\n if (mainWindow == null)\n {\n LogWindowAction(\"ERROR: MainWindow is null\");\n return;\n }\n\n // The donation dialog is now handled in MainWindow.CloseButton_Click\n // so we can simply close the window here\n\n try\n {\n LogWindowAction(\"About to call mainWindow.Close()\");\n mainWindow.Close();\n LogWindowAction(\"mainWindow.Close() called successfully\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"ERROR closing window directly: {ex.Message}\");\n\n // Fall back to messaging\n LogWindowAction(\"Falling back to WindowStateMessage.Close\");\n _messengerService.Send(\n new WindowStateMessage { Action = WindowStateMessage.WindowStateAction.Close }\n );\n }\n\n LogWindowAction(\"CloseWindowAsync method completed\");\n }\n\n /// \n /// Saves a unified configuration by delegating to the current view model.\n /// \n private async void SaveUnifiedConfig()\n {\n try\n {\n // Use the injected unified configuration service\n var unifiedConfigService = _unifiedConfigService;\n\n if (unifiedConfigService == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"UnifiedConfigurationService not available\",\n Level = LogLevel.Error,\n }\n );\n return;\n }\n\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Using UnifiedConfigurationService to save unified configuration\",\n Level = LogLevel.Info,\n }\n );\n\n // Create a unified configuration with settings from all view models\n var unifiedConfig = await unifiedConfigService.CreateUnifiedConfigurationAsync();\n\n // Get the configuration service from the application\n IConfigurationService configService = null;\n\n // Try to get the service from the application\n if (Application.Current is App appInstance3)\n {\n try\n {\n // Use reflection to access the _host.Services property\n var hostField = appInstance3\n .GetType()\n .GetField(\"_host\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (hostField != null)\n {\n var host = hostField.GetValue(appInstance3);\n var servicesProperty = host.GetType().GetProperty(\"Services\");\n if (servicesProperty != null)\n {\n var services = servicesProperty.GetValue(host);\n var getServiceMethod = services\n .GetType()\n .GetMethod(\"GetService\", new[] { typeof(Type) });\n if (getServiceMethod != null)\n {\n configService =\n getServiceMethod.Invoke(\n services,\n new object[] { typeof(IConfigurationService) }\n ) as IConfigurationService;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error accessing ConfigurationService: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n\n if (configService == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"ConfigurationService not available\",\n Level = LogLevel.Error,\n }\n );\n return;\n }\n\n // Save the unified configuration\n bool saveResult = await unifiedConfigService.SaveUnifiedConfigurationAsync(\n unifiedConfig\n );\n\n if (saveResult)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Unified configuration saved successfully\",\n Level = LogLevel.Info,\n }\n );\n\n // Show a single success dialog using CustomDialog to match the application style\n var sections = new List();\n if (unifiedConfig.WindowsApps.Items.Any())\n sections.Add(\"Windows Apps\");\n if (unifiedConfig.ExternalApps.Items.Any())\n sections.Add(\"External Apps\");\n if (unifiedConfig.Customize.Items.Any())\n sections.Add(\"Customizations\");\n if (unifiedConfig.Optimize.Items.Any())\n sections.Add(\"Optimizations\");\n\n Winhance.WPF.Features.Common.Views.CustomDialog.ShowInformation(\n \"Configuration Saved\",\n \"Configuration saved successfully.\",\n sections,\n \"You can now import this configuration on another system.\"\n );\n }\n else\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Save unified configuration canceled by user\",\n Level = LogLevel.Info,\n }\n );\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error saving unified configuration: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n\n // FallbackToViewModelImplementation method removed as part of unified configuration cleanup\n\n /// \n /// Imports a unified configuration by delegating to the current view model.\n /// \n private async void ImportUnifiedConfig()\n {\n try\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Starting unified configuration import process\",\n Level = LogLevel.Info,\n }\n );\n\n // Use the injected unified configuration service\n var unifiedConfigService = _unifiedConfigService;\n\n _messengerService.Send(\n new LogMessage\n {\n Message =\n \"Using UnifiedConfigurationService to import unified configuration\",\n Level = LogLevel.Info,\n }\n );\n\n // Get the configuration service from the application\n IConfigurationService configService = null;\n\n // Try to get the service from the application\n if (Application.Current is App appInstance2)\n {\n try\n {\n // Use reflection to access the _host.Services property\n var hostField = appInstance2\n .GetType()\n .GetField(\"_host\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (hostField != null)\n {\n var host = hostField.GetValue(appInstance2);\n var servicesProperty = host.GetType().GetProperty(\"Services\");\n if (servicesProperty != null)\n {\n var services = servicesProperty.GetValue(host);\n var getServiceMethod = services\n .GetType()\n .GetMethod(\"GetService\", new[] { typeof(Type) });\n if (getServiceMethod != null)\n {\n configService =\n getServiceMethod.Invoke(\n services,\n new object[] { typeof(IConfigurationService) }\n ) as IConfigurationService;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error accessing ConfigurationService: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n\n if (configService == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"ConfigurationService not available\",\n Level = LogLevel.Error,\n }\n );\n return;\n }\n\n // Load the unified configuration\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Showing file dialog to select configuration file\",\n Level = LogLevel.Info,\n }\n );\n\n var unifiedConfig = await unifiedConfigService.LoadUnifiedConfigurationAsync();\n\n if (unifiedConfig == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Import unified configuration canceled by user\",\n Level = LogLevel.Info,\n }\n );\n return;\n }\n\n _messengerService.Send(\n new LogMessage\n {\n Message =\n $\"Configuration loaded with sections: WindowsApps ({unifiedConfig.WindowsApps.Items.Count} items), \"\n + $\"ExternalApps ({unifiedConfig.ExternalApps.Items.Count} items), \"\n + $\"Customize ({unifiedConfig.Customize.Items.Count} items), \"\n + $\"Optimize ({unifiedConfig.Optimize.Items.Count} items)\",\n Level = LogLevel.Info,\n }\n );\n\n // Show the unified configuration dialog to let the user select which sections to import\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Showing unified configuration dialog for section selection\",\n Level = LogLevel.Info,\n }\n );\n\n // Show the unified configuration dialog to let the user select which sections to import\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Showing unified configuration dialog for section selection\",\n Level = LogLevel.Info,\n }\n );\n\n // Create a dictionary of sections with their availability and item counts\n var sectionInfo = new Dictionary<\n string,\n (bool IsSelected, bool IsAvailable, int ItemCount)\n >\n {\n {\n \"WindowsApps\",\n (\n true,\n unifiedConfig.WindowsApps.Items.Count > 0,\n unifiedConfig.WindowsApps.Items.Count\n )\n },\n {\n \"ExternalApps\",\n (\n true,\n unifiedConfig.ExternalApps.Items.Count > 0,\n unifiedConfig.ExternalApps.Items.Count\n )\n },\n {\n \"Customize\",\n (\n true,\n unifiedConfig.Customize.Items.Count > 0,\n unifiedConfig.Customize.Items.Count\n )\n },\n {\n \"Optimize\",\n (\n true,\n unifiedConfig.Optimize.Items.Count > 0,\n unifiedConfig.Optimize.Items.Count\n )\n },\n };\n\n // Create and show the dialog\n var dialog = new Views.UnifiedConfigurationDialog(\n \"Select Configuration Sections\",\n \"Select which sections you want to import from the unified configuration.\",\n sectionInfo,\n false\n );\n\n // Only set the Owner if the dialog is not the main window itself\n if (dialog != Application.Current.MainWindow)\n {\n try\n {\n dialog.Owner = Application.Current.MainWindow;\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error setting dialog owner: {ex.Message}\",\n Level = LogLevel.Warning,\n }\n );\n // Continue without setting the owner\n }\n }\n bool? dialogResult = dialog.ShowDialog();\n\n if (dialogResult != true)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"User canceled unified configuration import\",\n Level = LogLevel.Info,\n }\n );\n return;\n }\n\n // Get the selected sections from the dialog\n var result = dialog.GetResult();\n var selectedSections = result\n .Where(kvp => kvp.Value)\n .Select(kvp => kvp.Key)\n .ToList();\n\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Selected sections: {string.Join(\", \", selectedSections)}\",\n Level = LogLevel.Info,\n }\n );\n\n if (!selectedSections.Any())\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"No sections selected for import\",\n Level = LogLevel.Info,\n }\n );\n _dialogService.ShowMessage(\n \"Please select at least one section to import from the unified configuration.\",\n \"No sections selected\"\n );\n return;\n }\n\n // Apply the configuration to the selected sections\n _messengerService.Send(\n new LogMessage\n {\n Message =\n $\"Applying configuration to selected sections: {string.Join(\", \", selectedSections)}\",\n Level = LogLevel.Info,\n }\n );\n\n // Apply the configuration to the selected sections\n await unifiedConfigService.ApplyUnifiedConfigurationAsync(\n unifiedConfig,\n selectedSections\n );\n\n // Always show a success message since the settings are being applied correctly\n // even if the updatedCount is 0\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Unified configuration imported successfully\",\n Level = LogLevel.Info,\n }\n );\n\n // Show a success message using CustomDialog to match the application style\n var importedSections = new List();\n foreach (var section in selectedSections)\n {\n switch (section)\n {\n case \"WindowsApps\":\n importedSections.Add(\"Windows Apps\");\n break;\n case \"ExternalApps\":\n importedSections.Add(\"External Apps\");\n break;\n case \"Customize\":\n importedSections.Add(\"Customizations\");\n break;\n case \"Optimize\":\n importedSections.Add(\"Optimizations\");\n break;\n }\n }\n\n Winhance.WPF.Features.Common.Views.CustomDialog.ShowInformation(\n \"Configuration Imported\",\n \"The unified configuration has been imported successfully.\",\n importedSections,\n \"The selected settings have been applied to your system.\"\n );\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error importing unified configuration: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n\n // Show an error message to the user\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"An error occurred while importing the configuration: {ex.Message}\",\n \"Import Error\"\n );\n }\n }\n }\n\n // FallbackToViewModelImportImplementation method removed as part of unified configuration cleanup\n\n /// \n /// Opens the donation page in the default browser.\n /// \n private void OpenDonate()\n {\n try\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Opening donation page in browser\",\n Level = LogLevel.Info,\n }\n );\n\n // Use ProcessStartInfo to open the URL in the default browser\n var psi = new ProcessStartInfo\n {\n FileName = \"https://ko-fi.com/memstechtips\",\n UseShellExecute = true,\n };\n Process.Start(psi);\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error opening donation page: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n\n // Show an error message to the user\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"An error occurred while opening the donation page: {ex.Message}\",\n \"Error\"\n );\n }\n }\n }\n\n\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/LoadingWindow.xaml.cs", "using System;\nusing System.Diagnostics;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Media.Imaging;\nusing System.Runtime.InteropServices;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Interaction logic for LoadingWindow.xaml\n /// \n public partial class LoadingWindow : Window\n {\n private readonly IThemeManager? _themeManager;\n private LoadingWindowViewModel? _viewModel;\n\n /// \n /// Default constructor for design-time\n /// \n public LoadingWindow()\n {\n // Ignore this error, it works fine in the designer\n InitializeComponent();\n }\n\n /// \n /// Constructor with dependency injection\n /// \n /// The theme manager\n public LoadingWindow(IThemeManager themeManager)\n {\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n // Ignore this error, it works fine in the designer\n InitializeComponent();\n }\n\n /// \n /// Constructor with dependency injection and progress service\n /// \n /// The theme manager\n /// The progress service\n public LoadingWindow(IThemeManager themeManager, ITaskProgressService progressService)\n {\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n // Ignore this error, it works fine in the designer\n InitializeComponent();\n\n // Create and set the view model\n _viewModel = new LoadingWindowViewModel(progressService);\n DataContext = _viewModel;\n\n // Set the appropriate icon based on the theme\n UpdateThemeIcon();\n }\n\n /// \n /// Called when the window source is initialized\n /// \n /// Event arguments\n protected override void OnSourceInitialized(EventArgs e)\n {\n base.OnSourceInitialized(e);\n\n try\n {\n var helper = new WindowInteropHelper(this);\n if (helper.Handle != IntPtr.Zero)\n {\n EnableBlur();\n }\n }\n catch (Exception)\n {\n // Ignore blur errors - not critical for loading window\n }\n }\n\n /// \n /// Enables the blur effect on the window\n /// \n private void EnableBlur()\n {\n var windowHelper = new WindowInteropHelper(this);\n var accent = new AccentPolicy { AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND };\n var accentStructSize = Marshal.SizeOf(accent);\n\n var accentPtr = IntPtr.Zero;\n try\n {\n accentPtr = Marshal.AllocHGlobal(accentStructSize);\n Marshal.StructureToPtr(accent, accentPtr, false);\n\n var data = new WindowCompositionAttributeData\n {\n Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY,\n SizeOfData = accentStructSize,\n Data = accentPtr\n };\n\n SetWindowCompositionAttribute(windowHelper.Handle, ref data);\n }\n finally\n {\n if (accentPtr != IntPtr.Zero)\n {\n Marshal.FreeHGlobal(accentPtr);\n }\n }\n }\n\n /// \n /// P/Invoke for SetWindowCompositionAttribute\n /// \n [DllImport(\"user32.dll\")]\n internal static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data);\n\n /// \n /// Accent policy structure\n /// \n [StructLayout(LayoutKind.Sequential)]\n internal struct AccentPolicy\n {\n public AccentState AccentState;\n public int AccentFlags;\n public int GradientColor;\n public int AnimationId;\n }\n\n /// \n /// Window composition attribute data structure\n /// \n [StructLayout(LayoutKind.Sequential)]\n internal struct WindowCompositionAttributeData\n {\n public WindowCompositionAttribute Attribute;\n public IntPtr Data;\n public int SizeOfData;\n }\n\n /// \n /// Accent state enum\n /// \n internal enum AccentState\n {\n ACCENT_DISABLED = 0,\n ACCENT_ENABLE_GRADIENT = 1,\n ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,\n ACCENT_ENABLE_BLURBEHIND = 3,\n ACCENT_ENABLE_ACRYLICBLURBEHIND = 4,\n ACCENT_INVALID_STATE = 5\n }\n\n /// \n /// Window composition attribute enum\n /// \n internal enum WindowCompositionAttribute\n {\n WCA_ACCENT_POLICY = 19\n }\n\n /// \n /// Updates the window and image icons based on the current theme\n /// \n private void UpdateThemeIcon()\n {\n if (_themeManager == null)\n {\n Debug.WriteLine(\"Cannot update theme icon: ThemeManager is null\");\n return;\n }\n\n try\n {\n Debug.WriteLine($\"Updating theme icon. Current theme: {(_themeManager.IsDarkTheme ? \"Dark\" : \"Light\")}\");\n\n // Get the appropriate icon based on the theme\n string iconPath = _themeManager.IsDarkTheme\n ? \"pack://application:,,,/Resources/AppIcons/winhance-rocket-white-transparent-bg.ico\"\n : \"pack://application:,,,/Resources/AppIcons/winhance-rocket-black-transparent-bg.ico\";\n\n Debug.WriteLine($\"Selected icon path: {iconPath}\");\n\n // Create a BitmapImage from the icon path\n var iconImage = new BitmapImage(new Uri(iconPath, UriKind.Absolute));\n iconImage.Freeze(); // Freeze for better performance and thread safety\n\n // Set the window icon\n this.Icon = iconImage;\n Debug.WriteLine(\"Window icon updated\");\n\n // Set the image control source\n if (AppIconImage != null)\n {\n AppIconImage.Source = iconImage;\n Debug.WriteLine(\"AppIconImage source updated\");\n }\n else\n {\n Debug.WriteLine(\"AppIconImage is null, cannot update source\");\n }\n }\n catch (Exception ex)\n {\n // If there's an error, fall back to the default icon\n try\n {\n var defaultIcon = new BitmapImage(new Uri(\"pack://application:,,,/Resources/AppIcons/winhance-rocket.ico\", UriKind.Absolute));\n this.Icon = defaultIcon;\n if (AppIconImage != null)\n {\n AppIconImage.Source = defaultIcon;\n }\n }\n catch\n {\n // Ignore any errors with the fallback icon\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/MoreMenu.xaml.cs", "using System;\nusing System.IO;\nusing System.Windows;\nusing System.Windows.Controls;\nusing Winhance.WPF.Features.Common.Utilities;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// Interaction logic for MoreMenu.xaml\n /// \n public partial class MoreMenu : UserControl\n {\n public MoreMenu()\n {\n try\n {\n LogToStartupLog(\"MoreMenu constructor starting\");\n InitializeComponent();\n LogToStartupLog(\"MoreMenu constructor completed successfully\");\n }\n catch (Exception ex)\n {\n LogToStartupLog($\"ERROR in MoreMenu constructor: {ex.Message}\");\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n throw; // Re-throw to ensure the error is properly handled\n }\n }\n\n /// \n /// Logs a message directly to the WinhanceStartupLog.txt file\n /// \n private void LogToStartupLog(string message)\n {\n#if DEBUG\n try\n {\n string logsDir = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\"\n );\n string logFile = Path.Combine(logsDir, \"WinhanceStartupLog.txt\");\n\n // Ensure the logs directory exists\n if (!Directory.Exists(logsDir))\n {\n Directory.CreateDirectory(logsDir);\n }\n\n // Format the log message with timestamp\n string formattedMessage =\n $\"[{DateTime.Now:yyyy/MM/dd HH:mm:ss}] [MoreMenu] {message}\";\n\n // Append to the log file\n using (StreamWriter writer = File.AppendText(logFile))\n {\n writer.WriteLine(formattedMessage);\n }\n }\n catch\n {\n // Ignore errors in logging to avoid cascading issues\n }\n#endif\n }\n\n /// \n /// Shows the context menu at the specified placement target\n /// \n /// The UI element that the context menu should be positioned relative to\n public void ShowMenu(UIElement placementTarget)\n {\n try\n {\n LogToStartupLog(\"ShowMenu method called\");\n LogToStartupLog($\"placementTarget exists: {placementTarget != null}\");\n LogToStartupLog($\"DataContext exists: {DataContext != null}\");\n LogToStartupLog(\n $\"DataContext type: {(DataContext != null ? DataContext.GetType().FullName : \"null\")}\"\n );\n\n // Get the context menu from resources\n var contextMenu = Resources[\"MoreButtonContextMenu\"] as ContextMenu;\n LogToStartupLog($\"ContextMenu from resources exists: {contextMenu != null}\");\n\n if (contextMenu != null)\n {\n try\n {\n // Ensure the context menu has the same DataContext as the control\n LogToStartupLog(\"Setting context menu DataContext\");\n contextMenu.DataContext = this.DataContext;\n LogToStartupLog(\n $\"Context menu DataContext set: {contextMenu.DataContext != null}\"\n );\n\n // Add a handler to log when menu items are clicked\n foreach (var item in contextMenu.Items)\n {\n if (item is MenuItem menuItem)\n {\n LogToStartupLog(\n $\"Menu item: {menuItem.Header}, Command bound: {menuItem.Command != null}\"\n );\n\n // Add a Click handler to log when the item is clicked\n menuItem.Click += (s, e) =>\n {\n LogToStartupLog($\"Menu item clicked: {menuItem.Header}\");\n if (menuItem.Command != null)\n {\n LogToStartupLog(\n $\"Command can execute: {menuItem.Command.CanExecute(null)}\"\n );\n }\n };\n }\n }\n\n // Set the placement target\n LogToStartupLog(\"Setting placement target\");\n contextMenu.PlacementTarget = placementTarget;\n LogToStartupLog(\"Placement target set successfully\");\n\n // Set placement mode to Right to show menu to the right of the button\n LogToStartupLog(\"Setting placement mode\");\n contextMenu.Placement = System\n .Windows\n .Controls\n .Primitives\n .PlacementMode\n .Right;\n LogToStartupLog(\"Placement mode set successfully\");\n\n // No horizontal or vertical offset\n LogToStartupLog(\"Setting offset values\");\n contextMenu.HorizontalOffset = 0;\n contextMenu.VerticalOffset = 0;\n LogToStartupLog(\"Offset values set successfully\");\n\n // Open the context menu\n LogToStartupLog(\"About to open context menu\");\n contextMenu.IsOpen = true;\n LogToStartupLog(\"Context menu opened successfully\");\n }\n catch (Exception menuEx)\n {\n LogToStartupLog($\"ERROR configuring context menu: {menuEx.Message}\");\n LogToStartupLog($\"Stack trace: {menuEx.StackTrace}\");\n }\n }\n else\n {\n LogToStartupLog(\"ERROR: ContextMenu from resources is null, cannot show menu\");\n }\n }\n catch (Exception ex)\n {\n LogToStartupLog($\"ERROR in ShowMenu method: {ex.Message}\");\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/App.xaml.cs", "using System;\nusing System.IO;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Services;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\nusing Winhance.Infrastructure.Features.Common.Services;\nusing Winhance.Infrastructure.Features.Customize.Services;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Implementations;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.Common.Services.Configuration;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.Customize.ViewModels;\nusing Winhance.WPF.Features.Customize.Views;\nusing Winhance.WPF.Features.Optimize.ViewModels;\nusing Winhance.WPF.Features.Optimize.Views;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\nusing Winhance.WPF.Features.SoftwareApps.Views;\n\nnamespace Winhance.WPF\n{\n public partial class App : Application\n {\n private readonly IHost _host;\n\n public App()\n {\n // Add global unhandled exception handlers\n AppDomain.CurrentDomain.UnhandledException += (sender, args) =>\n {\n var ex = args.ExceptionObject as Exception;\n LogStartupError($\"Unhandled AppDomain exception: {ex?.Message}\", ex);\n };\n\n Current.DispatcherUnhandledException += (sender, args) =>\n {\n LogStartupError(\n $\"Unhandled Dispatcher exception: {args.Exception.Message}\",\n args.Exception\n );\n args.Handled = true; // Prevent the application from crashing\n };\n\n TaskScheduler.UnobservedTaskException += (sender, args) =>\n {\n LogStartupError(\n $\"Unobserved Task exception: {args.Exception.Message}\",\n args.Exception\n );\n args.SetObserved(); // Prevent the application from crashing\n };\n\n _host = Host.CreateDefaultBuilder()\n .ConfigureServices(\n (context, services) =>\n {\n ConfigureServices(services);\n }\n )\n .Build();\n\n LogStartupError(\"Application constructor completed\");\n }\n\n protected override async void OnStartup(StartupEventArgs e)\n {\n LogStartupError(\"OnStartup method beginning\");\n LoadingWindow? loadingWindow = null;\n\n // Ensure the application has administrator privileges\n try\n {\n LogStartupError(\"Checking for administrator privileges\");\n var systemServices = _host.Services.GetService();\n if (systemServices != null)\n {\n bool isAdmin = systemServices.RequireAdministrator();\n LogStartupError($\"Administrator privileges check result: {isAdmin}\");\n }\n else\n {\n LogStartupError(\"ISystemServices not available for admin check\");\n }\n }\n catch (Exception adminEx)\n {\n LogStartupError(\n \"Error checking administrator privileges: \" + adminEx.Message,\n adminEx\n );\n }\n\n // Set the application icon for all windows\n try\n {\n // We'll continue to use the original icon for the application icon (taskbar, shortcuts, etc.)\n var iconUri = new Uri(\"/Resources/AppIcons/winhance-rocket.ico\", UriKind.Relative);\n Current.Resources[\"ApplicationIcon\"] = new System.Windows.Media.Imaging.BitmapImage(\n iconUri\n );\n LogStartupError(\"Application icon set successfully\");\n }\n catch (Exception iconEx)\n {\n LogStartupError(\"Failed to set application icon: \" + iconEx.Message, iconEx);\n }\n\n try\n {\n // Create and show loading window first\n LogStartupError(\"Attempting to get theme manager\");\n var themeManager = _host.Services.GetRequiredService();\n LogStartupError(\"Got theme manager\");\n\n // Ensure the IsDarkTheme resource is set in the application resources\n Application.Current.Resources[\"IsDarkTheme\"] = themeManager.IsDarkTheme;\n LogStartupError($\"Set IsDarkTheme resource to {themeManager.IsDarkTheme}\");\n\n LogStartupError(\"Attempting to get task progress service\");\n var initialProgressService =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got task progress service\");\n\n LogStartupError(\"Creating loading window\");\n loadingWindow = new LoadingWindow(themeManager, initialProgressService);\n LogStartupError(\"Loading window created\");\n\n LogStartupError(\"Showing loading window\");\n loadingWindow.Show();\n LogStartupError(\"Loading window shown\");\n\n // Start the host and initialize services\n LogStartupError(\"Starting host\");\n await _host.StartAsync();\n LogStartupError(\"Host started\");\n\n // Get required services\n LogStartupError(\"Getting main window\");\n var mainWindow = _host.Services.GetRequiredService();\n LogStartupError(\"Got main window\");\n\n LogStartupError(\"Getting main view model\");\n var mainViewModel = _host.Services.GetRequiredService();\n LogStartupError(\"Got main view model\");\n\n LogStartupError(\"Getting software apps view model\");\n var windowsAppsViewModel =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got Windows apps view model\");\n\n // Set the DataContext\n LogStartupError(\"Setting main window DataContext\");\n mainWindow.DataContext = mainViewModel;\n LogStartupError(\"Main window DataContext set\");\n\n // Preload the SoftwareAppsViewModel data\n LogStartupError(\"Loading apps and checking installation status...\");\n\n // Create a progress handler to update the loading window\n var progressHandler = new EventHandler(\n (sender, args) =>\n {\n if (\n loadingWindow != null\n && loadingWindow.DataContext is LoadingWindowViewModel vm\n )\n {\n vm.Progress = args.Progress * 100;\n vm.StatusMessage = args.StatusText;\n vm.IsIndeterminate = args.IsIndeterminate;\n vm.ShowProgressText = !args.IsIndeterminate && args.IsTaskRunning;\n\n // Update detail message based on the current operation\n if (args.StatusText.Contains(\"Loading installable apps\"))\n {\n vm.DetailMessage = \"Discovering available applications...\";\n }\n else if (args.StatusText.Contains(\"Loading removable apps\"))\n {\n vm.DetailMessage = \"Identifying Windows applications...\";\n }\n else if (args.StatusText.Contains(\"Checking installation status\"))\n {\n vm.DetailMessage = \"Verifying which applications are installed...\";\n }\n else if (args.StatusText.Contains(\"Organizing apps\"))\n {\n vm.DetailMessage = \"Sorting applications for display...\";\n }\n }\n }\n );\n\n // Subscribe to progress events\n LogStartupError(\"Getting task progress service\");\n var taskProgressService = _host.Services.GetRequiredService();\n LogStartupError(\"Got task progress service\");\n\n LogStartupError(\"Subscribing to progress events\");\n taskProgressService.ProgressChanged += progressHandler;\n LogStartupError(\"Subscribed to progress events\");\n\n try\n {\n // Load apps and check installation status while showing the loading screen\n LogStartupError(\n \"Starting LoadAppsAndCheckInstallationStatusAsync for WindowsAppsViewModel\"\n );\n await windowsAppsViewModel.LoadAppsAndCheckInstallationStatusAsync();\n LogStartupError(\"WindowsApps loaded and installation status checked\");\n\n // Also preload the SoftwareAppsViewModel data\n LogStartupError(\"Getting SoftwareAppsViewModel\");\n var softwareAppsViewModel =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got SoftwareAppsViewModel\");\n\n LogStartupError(\"Starting Initialize for SoftwareAppsViewModel\");\n await softwareAppsViewModel.InitializeCommand.ExecuteAsync(null);\n LogStartupError(\"SoftwareAppsViewModel initialized\");\n\n // Preload the OptimizeViewModel to ensure all registry settings are loaded\n LogStartupError(\"Getting OptimizeViewModel\");\n var optimizeViewModel = _host.Services.GetRequiredService();\n LogStartupError(\"Got OptimizeViewModel\");\n\n // Initialize the OptimizeViewModel and wait for it to complete\n LogStartupError(\"Starting Initialize for OptimizeViewModel\");\n if (loadingWindow?.DataContext is LoadingWindowViewModel loadingVM)\n {\n loadingVM.StatusMessage = \"Loading system settings...\";\n loadingVM.DetailMessage = \"Checking registry settings...\";\n }\n await optimizeViewModel.InitializeCommand.ExecuteAsync(null);\n LogStartupError(\"OptimizeViewModel initialized\");\n\n // Preload the CustomizeViewModel to ensure all customization settings are loaded\n LogStartupError(\"Getting CustomizeViewModel\");\n var customizeViewModel =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got CustomizeViewModel\");\n\n // Initialize the CustomizeViewModel and wait for it to complete\n LogStartupError(\"Starting Initialize for CustomizeViewModel\");\n if (loadingWindow?.DataContext is LoadingWindowViewModel loadingVMCustomize)\n {\n loadingVMCustomize.StatusMessage = \"Loading customization settings...\";\n loadingVMCustomize.DetailMessage = \"Checking customization options...\";\n }\n await customizeViewModel.InitializeCommand.ExecuteAsync(null);\n LogStartupError(\"CustomizeViewModel initialized\");\n }\n finally\n {\n // Unsubscribe from progress events\n LogStartupError(\"Unsubscribing from progress events\");\n taskProgressService.ProgressChanged -= progressHandler;\n LogStartupError(\"Unsubscribed from progress events\");\n }\n\n // Show the main window\n LogStartupError(\"Showing main window\");\n mainWindow.Show();\n LogStartupError(\"Main window shown\");\n\n // Close the loading window\n LogStartupError(\"Closing loading window\");\n loadingWindow.Close();\n loadingWindow = null;\n LogStartupError(\"Loading window closed\");\n\n // Check for updates\n await CheckForUpdatesAsync(mainWindow);\n\n LogStartupError(\"Calling base.OnStartup\");\n base.OnStartup(e);\n LogStartupError(\"OnStartup method completed successfully\");\n }\n catch (Exception ex)\n {\n LogStartupError(\"Error during startup\", ex);\n MessageBox.Show(\n $\"Error during startup: {ex.Message}\\n\\nStack Trace:\\n{ex.StackTrace}\",\n \"Startup Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error\n );\n\n // Ensure loading window is closed if there was an error\n if (loadingWindow != null)\n {\n loadingWindow.Close();\n }\n\n Current.Shutdown();\n }\n }\n\n private async Task CheckForUpdatesAsync(Window ownerWindow)\n {\n try\n {\n LogStartupError(\"Checking for updates...\");\n var versionService = _host.Services.GetRequiredService();\n var latestVersion = await versionService.CheckForUpdateAsync();\n\n if (latestVersion.IsUpdateAvailable)\n {\n LogStartupError($\"Update available: {latestVersion.Version}\");\n\n // Get current version\n var currentVersion = versionService.GetCurrentVersion();\n\n // Show the styled update dialog\n string message = \"Good News! A New Version of Winhance is available.\";\n\n // Create a download and install action\n Func downloadAndInstallAction = async () =>\n {\n await versionService.DownloadAndInstallUpdateAsync();\n\n // Close the application without showing a message\n System.Windows.Application.Current.Shutdown();\n };\n\n // Show the update dialog\n bool installNow = await UpdateDialog.ShowAsync(\n \"Update Available\",\n message,\n currentVersion,\n latestVersion,\n downloadAndInstallAction\n );\n\n if (installNow)\n {\n LogStartupError(\"User chose to download and install the update\");\n }\n else\n {\n LogStartupError(\"User chose to be reminded later\");\n }\n }\n else\n {\n LogStartupError(\"No updates available\");\n }\n }\n catch (Exception ex)\n {\n LogStartupError($\"Error checking for updates: {ex.Message}\", ex);\n // Don't show error to user, just log it\n }\n }\n\n protected override async void OnExit(ExitEventArgs e)\n {\n try\n {\n // Material Design resources are automatically unloaded\n\n // Dispose of the ThemeManager to clean up event subscriptions\n try\n {\n var themeManager = _host.Services.GetService();\n themeManager?.Dispose();\n }\n catch (Exception disposeEx)\n {\n LogStartupError(\"Error disposing ThemeManager\", disposeEx);\n }\n\n using (_host)\n {\n await _host.StopAsync();\n }\n }\n catch (Exception ex)\n {\n LogStartupError(\"Error during shutdown\", ex);\n }\n finally\n {\n base.OnExit(e);\n }\n }\n\n private void LogStartupError(string message, Exception? ex = null)\n {\n string fullMessage = $\"[{DateTime.Now}] {message}\";\n if (ex != null)\n {\n fullMessage += $\"\\nException: {ex.Message}\\nStack Trace: {ex.StackTrace}\";\n if (ex.InnerException != null)\n {\n fullMessage += $\"\\nInner Exception: {ex.InnerException.Message}\";\n }\n }\n\n try\n {\n string logPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\",\n \"WinhanceStartupLog.txt\"\n );\n\n // Ensure directory exists\n Directory.CreateDirectory(Path.GetDirectoryName(logPath));\n File.AppendAllText(logPath, $\"{fullMessage}\\n\");\n }\n catch\n {\n MessageBox.Show(\n fullMessage,\n \"Startup Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error\n );\n }\n }\n\n private void ConfigureServices(IServiceCollection services)\n {\n try\n {\n LogStartupError(\"Beginning service configuration...\");\n\n // Core Services\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton<\n Winhance.Core.Interfaces.Services.IFileSystemService,\n Winhance.Infrastructure.FileSystem.FileSystemService\n >();\n\n // Register the base services\n services.AddSingleton();\n services.AddSingleton(provider =>\n provider.GetRequiredService()\n );\n services.AddSingleton();\n services.AddSingleton(\n provider => new SpecialAppHandlerService(\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton<\n ISearchService,\n Winhance.Infrastructure.Features.Common.Services.SearchService\n >();\n services.AddSingleton<\n IConfigurationService,\n Winhance.Infrastructure.Features.Common.Services.ConfigurationService\n >();\n // Register UserPreferencesService as a singleton to ensure the same instance is used throughout the app\n services.AddSingleton(provider =>\n {\n var logService = provider.GetRequiredService();\n var userPreferencesService =\n new Features.Common.Services.UserPreferencesService(logService);\n\n // Log that the UserPreferencesService has been registered\n logService.Log(LogLevel.Info, \"UserPreferencesService registered as singleton\");\n\n return userPreferencesService;\n });\n services.AddSingleton(\n provider => new Winhance.WPF.Features.Common.Services.UnifiedConfigurationService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // Register configuration services\n services.AddConfigurationServices();\n\n // Keep the old service for backward compatibility during transition\n services.AddSingleton(\n provider => new Winhance.WPF.Features.Common.Services.ConfigurationCoordinatorService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton();\n\n // Register script generation services\n services.AddScriptGenerationServices();\n\n services.AddSingleton(\n provider => new PowerShellExecutionService(\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // Register power plan service\n services.AddSingleton<\n Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService,\n Winhance.Infrastructure.Features.Optimize.Services.PowerPlanService\n >();\n\n // Register the installation and removal services\n // Register WinGet verification methods\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n\n // Register the composite verifier\n services.AddSingleton();\n\n // Register the WinGet installer\n services.AddSingleton();\n\n // Register the adapter for backward compatibility\n services.AddSingleton<\n IWinGetInstallationService,\n WinGetInstallationServiceAdapter\n >();\n\n // Register the main installation service\n services.AddSingleton(\n provider => new AppInstallationService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton(provider => new AppRemovalService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n services.AddSingleton<\n ICapabilityInstallationService,\n CapabilityInstallationService\n >();\n services.AddSingleton(\n provider => new CapabilityRemovalService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton();\n services.AddSingleton(provider => new FeatureRemovalService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n // Register the orchestrator\n services.AddSingleton();\n\n // Register the PackageManager with its dependencies\n services.AddSingleton(provider => new PackageManager(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetService()\n ));\n\n // Register the InternetConnectivityService\n services.AddSingleton(\n provider => new Winhance.Infrastructure.Features.Common.Services.InternetConnectivityService(\n provider.GetRequiredService()\n )\n );\n\n // Register the AppInstallationCoordinatorService\n services.AddSingleton(\n provider => new Winhance.Infrastructure.Features.SoftwareApps.Services.AppInstallationCoordinatorService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetService(),\n provider.GetService()\n )\n );\n\n // Use fully qualified type name to resolve ambiguity between Winhance.Core.Models.WindowsService\n // and Winhance.Infrastructure.Features.Common.Services.WindowsSystemService\n services.AddSingleton(\n provider => new Winhance.Infrastructure.Features.Common.Services.WindowsSystemService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n null, // Intentionally not passing IThemeService to break circular dependency\n provider.GetRequiredService()\n )\n );\n\n // Register theme and wallpaper services\n services.AddSingleton();\n services.AddSingleton(provider => new ThemeService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton<\n Core.Features.Common.Interfaces.IDialogService,\n Features.Common.Services.DialogService\n >();\n services.AddSingleton();\n services.AddSingleton();\n\n // Register the notification service\n services.AddSingleton<\n Core.Features.UI.Interfaces.INotificationService,\n Winhance.Infrastructure.Features.UI.Services.NotificationService\n >();\n\n // Register the messenger service\n services.AddSingleton<\n Core.Features.Common.Interfaces.IMessengerService,\n Features.Common.Services.MessengerService\n >();\n\n // Register navigation service\n services.AddSingleton(\n provider =>\n {\n var navigationService = new FrameNavigationService(\n provider,\n provider.GetRequiredService()\n );\n\n // Register view mappings\n navigationService.RegisterViewMapping(\n \"SoftwareApps\",\n typeof(Features.SoftwareApps.Views.SoftwareAppsView),\n typeof(Features.SoftwareApps.ViewModels.SoftwareAppsViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"WindowsApps\",\n typeof(Features.SoftwareApps.Views.WindowsAppsView),\n typeof(Features.SoftwareApps.ViewModels.WindowsAppsViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"ExternalApps\",\n typeof(Features.SoftwareApps.Views.ExternalAppsView),\n typeof(Features.SoftwareApps.ViewModels.ExternalAppsViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"Optimize\",\n typeof(Features.Optimize.Views.OptimizeView),\n typeof(Features.Optimize.ViewModels.OptimizeViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"Customize\",\n typeof(Features.Customize.Views.CustomizeView),\n typeof(Features.Customize.ViewModels.CustomizeViewModel)\n );\n\n return navigationService;\n }\n );\n\n services.AddSingleton<\n IParameterSerializer,\n Winhance.Infrastructure.Features.Common.Services.JsonParameterSerializer\n >();\n\n // Register ThemeManager with navigation service dependency\n services.AddSingleton(\n provider => new Features.Common.Resources.Theme.ThemeManager(\n provider.GetRequiredService()\n )\n );\n\n // Register design-time data service\n services.AddSingleton<\n Features.Common.Services.IDesignTimeDataService,\n Features.Common.Services.DesignTimeDataService\n >();\n\n // Register ViewModels with explicit factory methods for all view models\n services.AddSingleton(provider => new MainViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton(provider => new WindowsAppsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton(provider => new ExternalAppsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n // Register UacSettingsService\n services.AddSingleton(\n provider => new UacSettingsService(\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // Register child ViewModels for OptimizeViewModel\n services.AddSingleton(\n provider => new WindowsSecurityOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new PrivacyOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new GamingandPerformanceOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new UpdateOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new PowerOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // ViewModels are registered above\n\n services.AddSingleton(provider => new OptimizeViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n // Register child ViewModels for CustomizeViewModel\n services.AddSingleton(\n provider => new TaskbarCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new StartMenuCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new ExplorerCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new ExplorerOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new NotificationOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new SoundOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new WindowsThemeCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(provider => new CustomizeViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton(provider => new SoftwareAppsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider\n ));\n\n // Register Views\n services.AddTransient(provider => new MainWindow(\n provider.GetRequiredService(),\n provider,\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n\n // Register version service\n services.AddSingleton();\n services.AddSingleton();\n\n // Register ApplicationCloseService\n services.AddSingleton();\n\n // Register logging service\n services.AddHostedService();\n\n LogStartupError(\"Service configuration complete\");\n }\n catch (Exception ex)\n {\n LogStartupError(\"Error during service configuration\", ex);\n throw;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Resources/Theme/ThemeManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Reflection;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Media;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Properties;\n\nnamespace Winhance.WPF.Features.Common.Resources.Theme\n{\n public partial class ThemeManager : ObservableObject, IThemeManager, IDisposable\n {\n private bool _isDarkTheme = true;\n\n public bool IsDarkTheme\n {\n get => _isDarkTheme;\n set\n {\n if (_isDarkTheme != value)\n {\n _isDarkTheme = value;\n OnPropertyChanged(nameof(IsDarkTheme));\n\n // Update the application resource\n Application.Current.Resources[\"IsDarkTheme\"] = _isDarkTheme;\n }\n }\n }\n\n private readonly INavigationService _navigationService;\n\n // Dictionary with default color values for each theme\n private static readonly Dictionary DarkThemeColors = new()\n {\n { \"PrimaryTextColor\", Color.FromRgb(255, 255, 255) },\n { \"SecondaryTextColor\", Color.FromRgb(170, 170, 170) },\n { \"TertiaryTextColor\", Color.FromRgb(128, 128, 128) },\n { \"HelpIconColor\", Color.FromRgb(255, 255, 255) },\n { \"TooltipBackgroundColor\", Color.FromRgb(43, 45, 48) },\n { \"TooltipForegroundColor\", Color.FromRgb(255, 255, 255) },\n { \"TooltipBorderColor\", Color.FromRgb(255, 222, 0) },\n { \"ControlForegroundColor\", Color.FromRgb(255, 255, 255) },\n { \"ControlFillColor\", Color.FromRgb(255, 255, 255) },\n { \"ControlBorderColor\", Color.FromRgb(255, 222, 0) },\n { \"ToggleKnobColor\", Color.FromRgb(255, 255, 255) },\n { \"ToggleKnobCheckedColor\", Color.FromRgb(255, 222, 0) },\n { \"ContentSectionBorderColor\", Color.FromRgb(31, 32, 34) },\n { \"MainContainerBorderColor\", Color.FromRgb(43, 45, 48) },\n { \"PrimaryButtonForegroundColor\", Color.FromRgb(255, 255, 255) },\n { \"AccentColor\", Color.FromRgb(255, 222, 0) },\n { \"ButtonHoverTextColor\", Color.FromRgb(32, 33, 36) },\n { \"ButtonDisabledForegroundColor\", Color.FromRgb(153, 163, 164) },\n { \"ButtonDisabledBorderColor\", Color.FromRgb(43, 45, 48) },\n { \"NavigationButtonBackgroundColor\", Color.FromRgb(31, 32, 34) },\n { \"NavigationButtonForegroundColor\", Color.FromRgb(255, 255, 255) },\n { \"SliderTrackColor\", Color.FromRgb(64, 64, 64) },\n { \"BackgroundColor\", Color.FromRgb(32, 32, 32) },\n { \"ContentSectionBackgroundColor\", Color.FromRgb(31, 32, 34) },\n { \"ScrollBarThumbColor\", Color.FromRgb(255, 222, 0) },\n { \"ScrollBarThumbHoverColor\", Color.FromRgb(255, 233, 76) },\n { \"ScrollBarThumbPressedColor\", Color.FromRgb(255, 240, 102) },\n };\n\n private static readonly Dictionary LightThemeColors = new()\n {\n { \"PrimaryTextColor\", Color.FromRgb(32, 33, 36) },\n { \"SecondaryTextColor\", Color.FromRgb(102, 102, 102) },\n { \"TertiaryTextColor\", Color.FromRgb(153, 153, 153) },\n { \"HelpIconColor\", Color.FromRgb(32, 33, 36) },\n { \"TooltipBackgroundColor\", Color.FromRgb(255, 255, 255) },\n { \"TooltipForegroundColor\", Color.FromRgb(32, 33, 36) },\n { \"TooltipBorderColor\", Color.FromRgb(66, 66, 66) },\n { \"ControlForegroundColor\", Color.FromRgb(32, 33, 36) },\n { \"ControlFillColor\", Color.FromRgb(66, 66, 66) },\n { \"ControlBorderColor\", Color.FromRgb(66, 66, 66) },\n { \"ToggleKnobColor\", Color.FromRgb(255, 255, 255) },\n { \"ToggleKnobCheckedColor\", Color.FromRgb(66, 66, 66) },\n { \"ContentSectionBorderColor\", Color.FromRgb(246, 248, 252) },\n { \"MainContainerBorderColor\", Color.FromRgb(255, 255, 255) },\n { \"PrimaryButtonForegroundColor\", Color.FromRgb(32, 33, 36) },\n { \"AccentColor\", Color.FromRgb(66, 66, 66) },\n { \"ButtonHoverTextColor\", Color.FromRgb(255, 255, 255) },\n { \"ButtonDisabledForegroundColor\", Color.FromRgb(204, 204, 204) },\n { \"ButtonDisabledBorderColor\", Color.FromRgb(238, 238, 238) },\n { \"NavigationButtonBackgroundColor\", Color.FromRgb(255, 255, 255) },\n { \"NavigationButtonForegroundColor\", Color.FromRgb(32, 33, 36) },\n { \"SliderTrackColor\", Color.FromRgb(204, 204, 204) },\n { \"BackgroundColor\", Color.FromRgb(246, 248, 252) },\n { \"ContentSectionBackgroundColor\", Color.FromRgb(240, 240, 240) },\n { \"ScrollBarThumbColor\", Color.FromRgb(66, 66, 66) },\n { \"ScrollBarThumbHoverColor\", Color.FromRgb(102, 102, 102) },\n { \"ScrollBarThumbPressedColor\", Color.FromRgb(34, 34, 34) },\n };\n\n public ThemeManager(INavigationService navigationService)\n {\n _navigationService = navigationService ?? throw new ArgumentNullException(nameof(navigationService));\n\n // Subscribe to navigation events to update toggle switches when navigating between views\n _navigationService.Navigated += NavigationService_Navigated;\n\n LoadThemePreference();\n ApplyTheme();\n }\n\n private void NavigationService_Navigated(object sender, NavigationEventArgs e)\n {\n // We no longer need to update toggle switches on navigation\n // as they will automatically pick up the correct theme from the application resources\n }\n\n public void ToggleTheme()\n {\n IsDarkTheme = !IsDarkTheme;\n ApplyTheme();\n\n // Ensure the window icons are updated when toggling the theme\n NotifyWindowsOfThemeChange();\n }\n\n public void ApplyTheme()\n {\n try\n {\n var themeColors = IsDarkTheme ? DarkThemeColors : LightThemeColors;\n\n // We no longer need to explicitly update toggle switches\n // as they will automatically pick up the theme from application resources\n\n // Create brushes for all UI elements\n var brushes = new List<(string key, SolidColorBrush brush)>\n {\n (\"WindowBackground\", new SolidColorBrush(themeColors[\"BackgroundColor\"])),\n (\"PrimaryTextColor\", new SolidColorBrush(themeColors[\"PrimaryTextColor\"])),\n (\"SecondaryTextColor\", new SolidColorBrush(themeColors[\"SecondaryTextColor\"])),\n (\"TertiaryTextColor\", new SolidColorBrush(themeColors[\"TertiaryTextColor\"])),\n (\"SubTextColor\", new SolidColorBrush(themeColors[\"SecondaryTextColor\"])),\n (\"HelpIconForeground\", new SolidColorBrush(themeColors[\"HelpIconColor\"])),\n (\n \"ContentSectionBackground\",\n new SolidColorBrush(themeColors[\"ContentSectionBackgroundColor\"])\n ),\n (\n \"ContentSectionBorderBrush\",\n new SolidColorBrush(themeColors[\"ContentSectionBorderColor\"])\n ),\n (\n \"MainContainerBorderBrush\",\n new SolidColorBrush(themeColors[\"MainContainerBorderColor\"])\n ),\n (\n \"NavigationButtonBackground\",\n new SolidColorBrush(themeColors[\"NavigationButtonBackgroundColor\"])\n ),\n (\n \"NavigationButtonForeground\",\n new SolidColorBrush(themeColors[\"NavigationButtonForegroundColor\"])\n ),\n (\"ButtonBorderBrush\", new SolidColorBrush(themeColors[\"AccentColor\"])),\n (\"ButtonHoverBackground\", new SolidColorBrush(themeColors[\"AccentColor\"])),\n (\n \"ButtonHoverTextColor\",\n new SolidColorBrush(themeColors[\"ButtonHoverTextColor\"])\n ),\n (\n \"PrimaryButtonForeground\",\n new SolidColorBrush(themeColors[\"PrimaryButtonForegroundColor\"])\n ),\n (\n \"ButtonDisabledForeground\",\n new SolidColorBrush(themeColors[\"ButtonDisabledForegroundColor\"])\n ),\n (\n \"ButtonDisabledBorderBrush\",\n new SolidColorBrush(themeColors[\"ButtonDisabledBorderColor\"])\n ),\n (\n \"ButtonDisabledHoverBackground\",\n new SolidColorBrush(themeColors[\"ButtonDisabledBorderColor\"])\n ),\n (\n \"ButtonDisabledHoverForeground\",\n new SolidColorBrush(themeColors[\"ButtonDisabledForegroundColor\"])\n ),\n (\n \"TooltipBackground\",\n new SolidColorBrush(themeColors[\"TooltipBackgroundColor\"])\n ),\n (\n \"TooltipForeground\",\n new SolidColorBrush(themeColors[\"TooltipForegroundColor\"])\n ),\n (\"TooltipBorderBrush\", new SolidColorBrush(themeColors[\"TooltipBorderColor\"])),\n (\n \"ControlForeground\",\n new SolidColorBrush(themeColors[\"ControlForegroundColor\"])\n ),\n (\"ControlFillColor\", new SolidColorBrush(themeColors[\"ControlFillColor\"])),\n (\n \"ControlBorderBrush\",\n new SolidColorBrush(themeColors[\"ControlBorderColor\"])\n ),\n (\n \"ToggleKnobBrush\",\n new SolidColorBrush(themeColors[\"ToggleKnobColor\"])\n ),\n (\n \"ToggleKnobCheckedBrush\",\n new SolidColorBrush(themeColors[\"ToggleKnobCheckedColor\"])\n ),\n (\"SliderTrackBackground\", new SolidColorBrush(themeColors[\"SliderTrackColor\"])),\n // Special handling for slider thumb in light mode to make them more visible\n (\n \"SliderAccentColor\",\n new SolidColorBrush(\n IsDarkTheme ? themeColors[\"AccentColor\"] : Color.FromRgb(240, 240, 240)\n )\n ),\n (\"TickBarForeground\", new SolidColorBrush(themeColors[\"PrimaryTextColor\"])),\n (\n \"ScrollBarThumbBrush\",\n new SolidColorBrush(themeColors[\"ScrollBarThumbColor\"])\n ),\n (\n \"ScrollBarThumbHoverBrush\",\n new SolidColorBrush(themeColors[\"ScrollBarThumbHoverColor\"])\n ),\n (\n \"ScrollBarThumbPressedBrush\",\n new SolidColorBrush(themeColors[\"ScrollBarThumbPressedColor\"])\n ),\n };\n\n var resources = Application.Current.Resources;\n\n // Update all brushes in the application resources\n foreach (var (key, brush) in brushes)\n {\n // Freeze for better performance\n brush.Freeze();\n\n // Update in main resources dictionary\n resources[key] = brush;\n }\n\n // Notify the ViewNameToBackgroundConverter that the theme has changed\n try\n {\n Winhance.WPF.Features.Common.Converters.ViewNameToBackgroundConverter.Instance.NotifyThemeChanged();\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error notifying ViewNameToBackgroundConverter: {ex.Message}\");\n }\n\n // Attempt to force a visual refresh of the main window\n var mainWindow = Application.Current.MainWindow;\n if (mainWindow != null)\n {\n // Force a layout update\n mainWindow.InvalidateVisual();\n\n // Directly update the navigation buttons and toggle switches\n Application.Current.Dispatcher.Invoke(() =>\n {\n try\n {\n // Find the navigation buttons by name\n var softwareAppsButton = FindChildByName(\n mainWindow,\n \"SoftwareAppsButton\"\n );\n var optimizeButton = FindChildByName(mainWindow, \"OptimizeButton\");\n var customizeButton = FindChildByName(mainWindow, \"CustomizeButton\");\n var aboutButton = FindChildByName(mainWindow, \"AboutButton\");\n\n // Get the current view name from the main view model\n string currentViewName = string.Empty;\n if (mainWindow.DataContext != null)\n {\n var mainViewModel = mainWindow.DataContext as dynamic;\n currentViewName = mainViewModel.CurrentViewName;\n }\n\n // Update each button's background if not null\n if (softwareAppsButton != null)\n UpdateButtonBackground(\n softwareAppsButton,\n \"SoftwareApps\",\n currentViewName\n );\n if (optimizeButton != null)\n UpdateButtonBackground(optimizeButton, \"Optimize\", currentViewName);\n if (customizeButton != null)\n UpdateButtonBackground(\n customizeButton,\n \"Customize\",\n currentViewName\n );\n if (aboutButton != null)\n UpdateButtonBackground(aboutButton, \"About\", currentViewName);\n\n // We no longer need to explicitly update toggle switches\n // as they will automatically pick up the theme from application resources\n\n // Force a more thorough refresh of the UI\n mainWindow.UpdateLayout();\n\n // Update theme-dependent icons\n NotifyWindowsOfThemeChange();\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error updating UI elements: {ex.Message}\");\n }\n });\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error applying theme: {ex.Message}\");\n Debug.WriteLine(ex.StackTrace);\n }\n\n // Save theme preference\n SaveThemePreference();\n }\n\n private void SaveThemePreference()\n {\n try\n {\n Settings.Default.IsDarkTheme = IsDarkTheme;\n Settings.Default.Save();\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Failed to save theme preference: {ex.Message}\");\n }\n }\n\n public void LoadThemePreference()\n {\n try\n {\n IsDarkTheme = Settings.Default.IsDarkTheme;\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Failed to load theme preference: {ex.Message}\");\n // Keep default value if loading fails\n }\n }\n\n // Clean up event subscriptions\n public void Dispose()\n {\n try\n {\n if (_navigationService != null)\n {\n _navigationService.Navigated -= NavigationService_Navigated;\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error cleaning up ThemeManager: {ex.Message}\");\n }\n }\n\n public void ResetThemePreference()\n {\n try\n {\n Settings.Default.Reset();\n LoadThemePreference();\n ApplyTheme();\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Failed to reset theme preference: {ex.Message}\");\n }\n }\n\n // Helper method to find a child element by name\n private static System.Windows.Controls.Button? FindChildByName(\n DependencyObject parent,\n string name\n )\n {\n if (parent == null)\n return null;\n\n // Check if the current element is the one we're looking for\n if (\n parent is FrameworkElement element\n && element.Name == name\n && element is System.Windows.Controls.Button button\n )\n {\n return button;\n }\n\n // Get the number of children\n int childCount = VisualTreeHelper.GetChildrenCount(parent);\n\n // Recursively search through all children\n for (int i = 0; i < childCount; i++)\n {\n var child = VisualTreeHelper.GetChild(parent, i);\n var result = FindChildByName(child, name);\n if (result != null)\n {\n return result;\n }\n }\n\n return null;\n }\n\n // Helper method to update a button's background based on whether it's selected\n private void UpdateButtonBackground(\n System.Windows.Controls.Button button,\n string buttonViewName,\n string currentViewName\n )\n {\n if (button == null)\n return;\n\n var themeColors = IsDarkTheme ? DarkThemeColors : LightThemeColors;\n\n // Determine if this button is for the currently selected view\n bool isSelected = string.Equals(\n buttonViewName,\n currentViewName,\n StringComparison.OrdinalIgnoreCase\n );\n\n // Set the appropriate background color\n if (isSelected)\n {\n button.Background = new SolidColorBrush(themeColors[\"MainContainerBorderColor\"]);\n }\n else\n {\n button.Background = new SolidColorBrush(\n themeColors[\"NavigationButtonBackgroundColor\"]\n );\n }\n\n // Update the foreground color for the button's content\n button.Foreground = new SolidColorBrush(themeColors[\"NavigationButtonForegroundColor\"]);\n }\n\n // Method to update all toggle switches in all open windows\n private void UpdateAllToggleSwitches()\n {\n try\n {\n // Update toggle switches in all open windows\n foreach (Window window in Application.Current.Windows)\n {\n UpdateToggleSwitches(window);\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error updating toggle switches: {ex.Message}\");\n Debug.WriteLine(ex.StackTrace);\n }\n }\n\n // Method to notify windows about theme changes\n private void NotifyWindowsOfThemeChange()\n {\n try\n {\n Debug.WriteLine($\"NotifyWindowsOfThemeChange called. Current theme: {(IsDarkTheme ? \"Dark\" : \"Light\")}\");\n\n // Notify all open windows about theme changes\n foreach (Window window in Application.Current.Windows)\n {\n Debug.WriteLine($\"Processing window: {window.GetType().Name}\");\n\n // Check if the window is a MainWindow or LoadingWindow\n if (window is MainWindow mainWindow)\n {\n // Call the UpdateThemeIcon method using reflection\n try\n {\n Debug.WriteLine(\"Attempting to update MainWindow icon\");\n var method = mainWindow.GetType().GetMethod(\"UpdateThemeIcon\", BindingFlags.Instance | BindingFlags.NonPublic);\n if (method != null)\n {\n // Use the dispatcher to ensure UI updates happen on the UI thread\n mainWindow.Dispatcher.Invoke(() =>\n {\n method.Invoke(mainWindow, null);\n });\n Debug.WriteLine(\"Updated theme icon in MainWindow\");\n }\n else\n {\n Debug.WriteLine(\"UpdateThemeIcon method not found in MainWindow\");\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error updating theme icon in MainWindow: {ex.Message}\");\n Debug.WriteLine(ex.StackTrace);\n }\n }\n else if (window is LoadingWindow loadingWindow)\n {\n // Call the UpdateThemeIcon method using reflection\n try\n {\n Debug.WriteLine(\"Attempting to update LoadingWindow icon\");\n var method = loadingWindow.GetType().GetMethod(\"UpdateThemeIcon\", BindingFlags.Instance | BindingFlags.NonPublic);\n if (method != null)\n {\n // Use the dispatcher to ensure UI updates happen on the UI thread\n loadingWindow.Dispatcher.Invoke(() =>\n {\n method.Invoke(loadingWindow, null);\n });\n Debug.WriteLine(\"Updated theme icon in LoadingWindow\");\n }\n else\n {\n Debug.WriteLine(\"UpdateThemeIcon method not found in LoadingWindow\");\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error updating theme icon in LoadingWindow: {ex.Message}\");\n Debug.WriteLine(ex.StackTrace);\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error notifying windows of theme change: {ex.Message}\");\n Debug.WriteLine(ex.StackTrace);\n }\n }\n\n // Helper method to update all toggle switches in the visual tree\n private void UpdateToggleSwitches(DependencyObject parent)\n {\n if (parent == null)\n return;\n\n // Check if the current element is a ToggleButton\n if (parent is ToggleButton toggleButton)\n {\n try\n {\n // Always set the Tag property for all toggle buttons\n toggleButton.Tag = IsDarkTheme ? \"Dark\" : \"Light\";\n\n // Force a visual refresh for all toggle buttons\n toggleButton.InvalidateVisual();\n\n // Force a more thorough refresh\n if (toggleButton.Parent is FrameworkElement parentElement)\n {\n parentElement.InvalidateVisual();\n parentElement.UpdateLayout();\n }\n\n // Ensure the toggle button is enabled and clickable if it should be\n if (!toggleButton.IsEnabled && toggleButton.IsEnabled != false)\n {\n toggleButton.IsEnabled = true;\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error updating toggle button: {ex.Message}\");\n }\n }\n\n // Get the number of children\n int childCount = VisualTreeHelper.GetChildrenCount(parent);\n\n // Recursively search through all children\n for (int i = 0; i < childCount; i++)\n {\n var child = VisualTreeHelper.GetChild(parent, i);\n UpdateToggleSwitches(child);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/UnifiedConfigurationDialog.xaml.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Windows;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Interaction logic for UnifiedConfigurationDialog.xaml\n /// \n public partial class UnifiedConfigurationDialog : Window\n {\n private readonly UnifiedConfigurationDialogViewModel _viewModel;\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The title of the dialog.\n /// The description of the dialog.\n /// The dictionary of section names, their availability, and item counts.\n /// Whether this is a save dialog (true) or an import dialog (false).\n public UnifiedConfigurationDialog(\n string title,\n string description,\n Dictionary sections,\n bool isSaveDialog)\n {\n try\n {\n InitializeComponent();\n\n // Try to get the log service from the application using reflection\n try\n {\n if (Application.Current is App appInstance)\n {\n // Use reflection to access the _host.Services property\n var hostField = appInstance.GetType().GetField(\"_host\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (hostField != null)\n {\n var host = hostField.GetValue(appInstance);\n var servicesProperty = host.GetType().GetProperty(\"Services\");\n if (servicesProperty != null)\n {\n var services = servicesProperty.GetValue(host);\n var getServiceMethod = services.GetType().GetMethod(\"GetService\", new[] { typeof(Type) });\n if (getServiceMethod != null)\n {\n _logService = getServiceMethod.Invoke(services, new object[] { typeof(ILogService) }) as ILogService;\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error getting log service: {ex.Message}\");\n // Continue without logging\n }\n \n LogInfo($\"Creating {(isSaveDialog ? \"save\" : \"import\")} dialog with title: {title}\");\n LogInfo($\"Sections: {string.Join(\", \", sections.Keys)}\");\n\n // Create the view model\n _viewModel = new UnifiedConfigurationDialogViewModel(title, description, sections, isSaveDialog);\n \n // Set the data context\n DataContext = _viewModel;\n\n // Set the window title\n this.Title = title;\n \n // Ensure the dialog is shown as a modal dialog\n this.WindowStartupLocation = WindowStartupLocation.CenterOwner;\n this.ResizeMode = ResizeMode.NoResize;\n this.ShowInTaskbar = false;\n \n // Handle the OK and Cancel commands directly\n _viewModel.OkCommand = new RelayCommand(() =>\n {\n // Validate that at least one section is selected\n if (_viewModel.Sections.Any(s => s.IsSelected))\n {\n LogInfo(\"OK button clicked, at least one section selected\");\n this.DialogResult = true;\n }\n else\n {\n LogInfo(\"OK button clicked, but no sections selected\");\n MessageBox.Show(\n \"Please select at least one section to continue.\",\n \"No Sections Selected\",\n MessageBoxButton.OK,\n MessageBoxImage.Warning);\n }\n });\n \n _viewModel.CancelCommand = new RelayCommand(() =>\n {\n LogInfo(\"Cancel button clicked\");\n this.DialogResult = false;\n });\n \n LogInfo(\"Dialog initialization completed\");\n }\n catch (Exception ex)\n {\n LogError($\"Error initializing dialog: {ex.Message}\");\n Debug.WriteLine($\"Error initializing dialog: {ex}\");\n \n // Show error message\n MessageBox.Show($\"Error initializing dialog: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n \n // Set dialog result to false\n DialogResult = false;\n }\n }\n\n /// \n /// Gets the result of the dialog as a dictionary of section names and their selection state.\n /// \n /// A dictionary of section names and their selection state.\n public Dictionary GetResult()\n {\n try\n {\n var result = _viewModel.GetResult();\n LogInfo($\"GetResult called, returning {result.Count} sections\");\n return result;\n }\n catch (Exception ex)\n {\n LogError($\"Error getting result: {ex.Message}\");\n return new Dictionary();\n }\n }\n \n private void LogInfo(string message)\n {\n _logService?.Log(LogLevel.Info, $\"UnifiedConfigurationDialog: {message}\");\n Debug.WriteLine($\"UnifiedConfigurationDialog: {message}\");\n }\n \n private void LogError(string message)\n {\n _logService?.Log(LogLevel.Error, $\"UnifiedConfigurationDialog: {message}\");\n Debug.WriteLine($\"UnifiedConfigurationDialog ERROR: {message}\");\n }\n \n /// \n /// Handles the mouse left button down event on the title bar to enable window dragging.\n /// \n private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n if (e.ChangedButton == MouseButton.Left)\n {\n this.DragMove();\n }\n }\n \n /// \n /// Handles the close button click event.\n /// \n private void CloseButton_Click(object sender, RoutedEventArgs e)\n {\n LogInfo(\"Close button clicked\");\n this.DialogResult = false;\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Customize/ViewModels/CustomizeViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Optimize.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.Common.Messages;\n\nnamespace Winhance.WPF.Features.Customize.ViewModels\n{\n /// \n /// ViewModel for the Customize view.\n /// \n public partial class CustomizeViewModel : SearchableViewModel\n {\n // Store a backup of all items for state recovery\n private List _allItemsBackup = new List();\n private bool _isInitialSearchDone = false;\n\n // Tracks if search has any results\n [ObservableProperty]\n private bool _hasSearchResults = true;\n private readonly ISystemServices _windowsService;\n private readonly IDialogService _dialogService;\n private readonly IThemeManager _themeManager;\n private readonly IConfigurationService _configurationService;\n private readonly IMessengerService _messengerService;\n private readonly ILogService _logService;\n\n /// \n /// Gets the messenger service.\n /// \n public IMessengerService MessengerService => _messengerService;\n\n // Flag to prevent cascading checkbox updates\n private bool _updatingCheckboxes = false;\n /// \n /// Gets or sets a value indicating whether dark mode is enabled.\n /// \n [ObservableProperty]\n private bool _isDarkModeEnabled;\n\n /// \n /// Gets or sets a value indicating whether all settings are selected.\n /// \n [ObservableProperty]\n private bool _isSelectAllSelected;\n\n /// \n /// Gets or sets a value indicating whether settings are being loaded.\n /// \n [ObservableProperty]\n private bool _isLoading;\n\n /// \n /// Gets or sets the status text.\n /// \n [ObservableProperty]\n private string _statusText = \"Customize Your Windows Appearance and Behaviour\";\n \n // Override the SearchText property to add explicit notification and direct control over the search flow\n private string _searchTextOverride = string.Empty;\n public override string SearchText\n {\n get => _searchTextOverride;\n set\n {\n if (_searchTextOverride != value)\n {\n _searchTextOverride = value;\n OnPropertyChanged(nameof(SearchText));\n LogInfo($\"CustomizeViewModel: SearchText changed to: '{value}'\");\n \n // Explicitly update IsSearchActive and call ApplySearch\n IsSearchActive = !string.IsNullOrWhiteSpace(value);\n ApplySearch();\n \n // Update status text based on search results\n if (IsSearchActive)\n {\n StatusText = $\"Found {Items.Count} settings matching '{value}'\";\n }\n else\n {\n StatusText = \"Customize Your Windows Appearance and Behaviour\";\n }\n }\n }\n }\n \n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n\n /// \n /// Gets the collection of customization items.\n /// \n public ObservableCollection CustomizationItems { get; } = new();\n\n /// \n /// Gets or sets the taskbar settings view model.\n /// \n [ObservableProperty]\n private TaskbarCustomizationsViewModel _taskbarSettings;\n\n /// \n /// Gets or sets the start menu settings view model.\n /// \n [ObservableProperty]\n private StartMenuCustomizationsViewModel _startMenuSettings;\n\n /// \n /// Gets or sets the explorer customizations view model.\n /// \n [ObservableProperty]\n private ExplorerCustomizationsViewModel _explorerSettings;\n\n /// \n /// Gets or sets the Windows theme customizations view model.\n /// \n [ObservableProperty]\n private WindowsThemeCustomizationsViewModel _windowsThemeSettings;\n\n /// \n /// Gets a value indicating whether the view model is initialized.\n /// \n public bool IsInitialized { get; private set; }\n\n /// \n /// Gets the initialize command.\n /// \n public AsyncRelayCommand InitializeCommand { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The Windows service.\n /// The log service.\n /// The dialog service.\n /// The theme manager.\n /// The search service.\n /// The configuration service.\n /// The taskbar customizations view model.\n /// The start menu customizations view model.\n /// The explorer settings view model.\n /// The Windows theme customizations view model.\n /// The messenger service.\n public CustomizeViewModel(\n ITaskProgressService progressService,\n ISystemServices windowsService,\n ILogService logService,\n IDialogService dialogService,\n IThemeManager themeManager,\n ISearchService searchService,\n IConfigurationService configurationService,\n TaskbarCustomizationsViewModel taskbarSettings,\n StartMenuCustomizationsViewModel startMenuSettings,\n ExplorerCustomizationsViewModel explorerSettings,\n WindowsThemeCustomizationsViewModel windowsThemeSettings,\n IMessengerService messengerService)\n : base(progressService, searchService, null)\n {\n _windowsService = windowsService ?? throw new ArgumentNullException(nameof(windowsService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));\n _messengerService = messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n\n TaskbarSettings = taskbarSettings ?? throw new ArgumentNullException(nameof(taskbarSettings));\n StartMenuSettings = startMenuSettings ?? throw new ArgumentNullException(nameof(startMenuSettings));\n ExplorerSettings = explorerSettings ?? throw new ArgumentNullException(nameof(explorerSettings));\n WindowsThemeSettings = windowsThemeSettings ?? throw new ArgumentNullException(nameof(windowsThemeSettings));\n\n InitializeCustomizationItems();\n \n // Sync with WindowsThemeSettings\n IsDarkModeEnabled = WindowsThemeSettings.IsDarkModeEnabled;\n \n // Subscribe to WindowsThemeSettings property changes\n WindowsThemeSettings.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(WindowsThemeSettings.IsDarkModeEnabled))\n {\n // Sync dark mode state with WindowsThemeSettings\n IsDarkModeEnabled = WindowsThemeSettings.IsDarkModeEnabled;\n }\n };\n\n // Create initialize command\n InitializeCommand = new AsyncRelayCommand(InitializeAsync);\n \n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n }\n\n /// \n /// Initializes a new instance of the class for design-time use.\n /// \n public CustomizeViewModel()\n : base(\n new Winhance.Infrastructure.Features.Common.Services.TaskProgressService(new Core.Features.Common.Services.LogService()),\n new Winhance.Infrastructure.Features.Common.Services.SearchService())\n {\n // Default constructor for design-time use\n CustomizationItems = new ObservableCollection();\n InitializeCustomizationItems();\n IsDarkModeEnabled = true; // Default to dark mode for design-time\n }\n\n /// \n /// Called when the view model is navigated to.\n /// \n /// The navigation parameter.\n public override void OnNavigatedTo(object parameter)\n {\n LogInfo(\"CustomizeViewModel.OnNavigatedTo called\");\n \n // Ensure the status text is set to the default value\n StatusText = \"Customize Your Windows Appearance and Behaviour\";\n\n // If not already initialized, initialize now\n if (!IsInitialized)\n {\n InitializeCommand.Execute(null);\n }\n }\n\n /// \n /// Initializes the view model asynchronously.\n /// \n /// The cancellation token.\n /// A task representing the asynchronous operation.\n private async Task InitializeAsync(CancellationToken cancellationToken)\n {\n if (IsInitialized)\n return;\n\n try\n {\n IsLoading = true;\n LogInfo(\"Initializing CustomizeViewModel\");\n\n // Report progress\n ProgressService.UpdateProgress(0, \"Loading customization settings...\");\n\n // Load settings for each category\n LogInfo(\"CustomizeViewModel.InitializeAsync: Loading Taskbar settings\");\n ProgressService.UpdateProgress(10, \"Loading taskbar settings...\");\n await TaskbarSettings.LoadSettingsAsync();\n await TaskbarSettings.CheckSettingStatusesAsync();\n\n LogInfo(\"CustomizeViewModel.InitializeAsync: Loading Start Menu settings\");\n ProgressService.UpdateProgress(30, \"Loading Start Menu settings...\");\n await StartMenuSettings.LoadSettingsAsync();\n await StartMenuSettings.CheckSettingStatusesAsync();\n\n LogInfo(\"CustomizeViewModel.InitializeAsync: Loading Explorer settings\");\n ProgressService.UpdateProgress(50, \"Loading Explorer settings...\");\n await ExplorerSettings.LoadSettingsAsync();\n await ExplorerSettings.CheckSettingStatusesAsync();\n\n // Load Windows Theme settings if available\n if (WindowsThemeSettings != null)\n {\n LogInfo(\"CustomizeViewModel.InitializeAsync: Loading Windows Theme settings\");\n ProgressService.UpdateProgress(70, \"Loading Windows Theme settings...\");\n await WindowsThemeSettings.LoadSettingsAsync();\n await WindowsThemeSettings.CheckSettingStatusesAsync();\n }\n\n // Progress is now complete\n ProgressService.UpdateProgress(90, \"Finalizing...\");\n\n LogInfo(\"CustomizeViewModel.InitializeAsync: All settings loaded\");\n ProgressService.UpdateProgress(100, \"Initialization complete\");\n\n // Set up property change handlers\n SetupPropertyChangeHandlers();\n\n // Update selection states\n UpdateSelectAllState();\n\n // Load all settings for search functionality\n await LoadItemsAsync();\n \n // Ensure Windows Theme settings are properly loaded for search\n if (WindowsThemeSettings != null && WindowsThemeSettings.Settings.Count == 0)\n {\n LogInfo(\"CustomizeViewModel: Reloading Windows Theme settings for search\");\n await WindowsThemeSettings.LoadSettingsAsync();\n }\n \n // Mark as initialized\n IsInitialized = true;\n\n LogInfo(\"CustomizeViewModel initialized successfully\");\n }\n catch (Exception ex)\n {\n LogError($\"Error initializing customization settings: {ex.Message}\");\n throw; // Rethrow to ensure the caller knows initialization failed\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Initializes the customization items.\n /// \n private void InitializeCustomizationItems()\n {\n CustomizationItems.Clear();\n\n // Taskbar customization\n var taskbarItem = new ApplicationSettingGroup\n {\n Name = \"Taskbar\",\n Description = \"Customize taskbar appearance and behavior\",\n IsSelected = false\n };\n CustomizationItems.Add(taskbarItem);\n\n // Start Menu customization\n var startMenuItem = new ApplicationSettingGroup\n {\n Name = \"Start Menu\",\n Description = \"Modify Start Menu layout and settings\",\n IsSelected = false\n };\n CustomizationItems.Add(startMenuItem);\n\n // Explorer customization\n var explorerItem = new ApplicationSettingGroup\n {\n Name = \"Explorer\",\n Description = \"Adjust File Explorer settings and appearance\",\n IsSelected = false\n };\n CustomizationItems.Add(explorerItem);\n\n // Windows Theme customization\n var windowsThemeItem = new ApplicationSettingGroup\n {\n Name = \"Windows Theme\",\n Description = \"Customize Windows appearance themes\",\n IsSelected = false\n };\n CustomizationItems.Add(windowsThemeItem);\n }\n\n /// \n /// Sets up property change handlers.\n /// \n private void SetupPropertyChangeHandlers()\n {\n // Set up property change handlers for all settings\n foreach (var item in CustomizationItems)\n {\n // Add property changed handler for the category itself\n item.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingGroup.IsSelected) && !_updatingCheckboxes)\n {\n _updatingCheckboxes = true;\n try\n {\n // Update all settings in this category\n UpdateCategorySettings(item);\n\n // Update the global state\n UpdateSelectAllState();\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n };\n }\n }\n\n /// \n /// Updates the settings for a category.\n /// \n /// The category.\n private void UpdateCategorySettings(ApplicationSettingGroup category)\n {\n if (category == null) return;\n\n // Get the IsSelected property from ISettingItem interface\n PropertyInfo isSelectedProp = typeof(ISettingItem).GetProperty(\"IsSelected\");\n if (isSelectedProp == null) return;\n\n switch (category.Name)\n {\n case \"Taskbar\":\n foreach (var setting in TaskbarSettings.Settings)\n {\n isSelectedProp.SetValue(setting, category.IsSelected);\n }\n break;\n case \"Start Menu\":\n foreach (var setting in StartMenuSettings.Settings)\n {\n isSelectedProp.SetValue(setting, category.IsSelected);\n }\n break;\n case \"Explorer\":\n foreach (var setting in ExplorerSettings.Settings)\n {\n isSelectedProp.SetValue(setting, category.IsSelected);\n }\n break;\n case \"Windows Theme\":\n if (WindowsThemeSettings != null && WindowsThemeSettings.Settings.Count > 0)\n {\n foreach (var setting in WindowsThemeSettings.Settings)\n {\n isSelectedProp.SetValue(setting, category.IsSelected);\n }\n }\n break;\n }\n }\n\n /// \n /// Updates the category selection state.\n /// \n /// The category name.\n private void UpdateCategorySelectionState(string categoryName)\n {\n // Skip if we're already in an update operation\n if (_updatingCheckboxes)\n return;\n\n _updatingCheckboxes = true;\n\n try\n {\n var category = CustomizationItems.FirstOrDefault(c => c.Name == categoryName);\n if (category == null) return;\n\n bool allSelected = false;\n\n // Get the IsSelected property from ISettingItem interface\n PropertyInfo isSelectedProp = typeof(ISettingItem).GetProperty(\"IsSelected\");\n if (isSelectedProp == null) return;\n\n switch (categoryName)\n {\n case \"Taskbar\":\n allSelected = TaskbarSettings.Settings.Count > 0 &&\n TaskbarSettings.Settings.All(s => (bool)isSelectedProp.GetValue(s));\n break;\n case \"Start Menu\":\n allSelected = StartMenuSettings.Settings.Count > 0 &&\n StartMenuSettings.Settings.All(s => (bool)isSelectedProp.GetValue(s));\n break;\n case \"Explorer\":\n allSelected = ExplorerSettings.Settings.Count > 0 &&\n ExplorerSettings.Settings.All(s => (bool)isSelectedProp.GetValue(s));\n break;\n case \"Windows Theme\":\n allSelected = WindowsThemeSettings != null && \n WindowsThemeSettings.Settings.Count > 0 &&\n WindowsThemeSettings.Settings.All(s => (bool)isSelectedProp.GetValue(s));\n break;\n // Removed Notifications and Sound cases\n }\n\n category.IsSelected = allSelected;\n\n // Update global state\n UpdateSelectAllState();\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Updates the select all state.\n /// \n private void UpdateSelectAllState()\n {\n // Skip if we're already in an update operation\n if (_updatingCheckboxes)\n return;\n\n _updatingCheckboxes = true;\n\n try\n {\n // Skip if no customization items\n if (CustomizationItems.Count == 0)\n return;\n\n // Update global \"Select All\" checkbox based on all categories\n IsSelectAllSelected = CustomizationItems.All(c => c.IsSelected);\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n\n /// \n /// Refreshes the Windows GUI.\n /// \n /// A task representing the asynchronous operation.\n private async Task RefreshWindowsGUI()\n {\n try\n {\n // Use the Windows service to refresh the GUI without restarting explorer\n await _windowsService.RefreshWindowsGUI(false);\n\n LogInfo(\"Windows GUI refresh completed\");\n }\n catch (Exception ex)\n {\n LogError($\"Error refreshing Windows GUI: {ex.Message}\");\n }\n }\n\n /// \n /// Toggles the select all state.\n /// \n [RelayCommand]\n private void ToggleSelectAll()\n {\n bool newState = !IsSelectAllSelected;\n IsSelectAllSelected = newState;\n\n _updatingCheckboxes = true;\n\n try\n {\n foreach (var item in CustomizationItems)\n {\n item.IsSelected = newState;\n UpdateCategorySettings(item);\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n // Note: ApplyCustomizationsCommand has been removed as settings are now applied immediately when toggled\n // Note: RestoreDefaultsCommand has been removed as settings are now applied immediately when toggled\n\n /// \n /// Executes a customization action.\n /// \n /// The action to execute.\n [RelayCommand]\n private async Task ExecuteAction(ApplicationAction? action)\n {\n if (action == null) return;\n\n try\n {\n IsLoading = true;\n StatusText = $\"Executing action: {action.Name}...\";\n\n // Execute the action through the appropriate view model\n if (action.GroupName == \"Taskbar\" && TaskbarSettings != null)\n {\n await TaskbarSettings.ExecuteActionAsync(action);\n }\n else if (action.GroupName == \"Start Menu\" && StartMenuSettings != null)\n {\n await StartMenuSettings.ExecuteActionAsync(action);\n }\n else if (action.GroupName == \"Explorer\" && ExplorerSettings != null)\n {\n await ExplorerSettings.ExecuteActionAsync(action);\n }\n else if (action.GroupName == \"Windows Theme\" && WindowsThemeSettings != null)\n {\n await WindowsThemeSettings.ExecuteActionAsync(action);\n }\n\n StatusText = $\"Action '{action.Name}' executed successfully\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Error executing action: {ex.Message}\";\n LogError($\"Error executing action '{action?.Name}': {ex.Message}\");\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Toggles a category.\n /// \n /// The category to toggle.\n [RelayCommand]\n private void ToggleCategory(ApplicationSettingGroup? category)\n {\n if (category == null) return;\n\n // Skip if we're already in an update operation\n if (_updatingCheckboxes)\n return;\n\n _updatingCheckboxes = true;\n\n try\n {\n switch (category.Name)\n {\n case \"Taskbar\":\n foreach (var setting in TaskbarSettings.Settings)\n {\n setting.IsSelected = category.IsSelected;\n }\n break;\n case \"Start Menu\":\n foreach (var setting in StartMenuSettings.Settings)\n {\n setting.IsSelected = category.IsSelected;\n }\n break;\n case \"Explorer\":\n foreach (var setting in ExplorerSettings.Settings)\n {\n setting.IsSelected = category.IsSelected;\n }\n break;\n case \"Windows Theme\":\n if (WindowsThemeSettings != null && WindowsThemeSettings.Settings.Count > 0)\n {\n foreach (var setting in WindowsThemeSettings.Settings)\n {\n setting.IsSelected = category.IsSelected;\n }\n }\n break;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n \n /// \n /// Loads items asynchronously.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadItemsAsync()\n {\n try\n {\n IsLoading = true;\n StatusText = \"Loading customization settings...\";\n\n // Clear the items collection\n Items.Clear();\n\n // Collect all settings from the various view models\n var allSettings = new List();\n\n // Add settings from each category\n if (TaskbarSettings != null && TaskbarSettings.Settings != null)\n {\n foreach (var setting in TaskbarSettings.Settings)\n {\n if (setting is ApplicationSettingItem applicationSetting)\n {\n allSettings.Add(applicationSetting);\n }\n }\n }\n\n if (StartMenuSettings != null && StartMenuSettings.Settings != null)\n {\n foreach (var setting in StartMenuSettings.Settings)\n {\n if (setting is ApplicationSettingItem applicationSetting)\n {\n allSettings.Add(applicationSetting);\n }\n }\n }\n\n if (ExplorerSettings != null && ExplorerSettings.Settings != null)\n {\n foreach (var setting in ExplorerSettings.Settings)\n {\n if (setting is ApplicationSettingItem applicationSetting)\n {\n allSettings.Add(applicationSetting);\n }\n }\n }\n\n if (WindowsThemeSettings != null && WindowsThemeSettings.Settings != null)\n {\n foreach (var setting in WindowsThemeSettings.Settings)\n {\n if (setting is ApplicationSettingItem applicationSetting)\n {\n allSettings.Add(applicationSetting);\n }\n }\n }\n\n // Add all settings to the Items collection\n foreach (var setting in allSettings)\n {\n Items.Add(setting);\n }\n\n // Create a backup of all items for state recovery\n _allItemsBackup = new List(Items);\n\n // Only update StatusText if it's currently showing a loading message\n if (StatusText.Contains(\"Loading\"))\n {\n StatusText = \"Customize Your Windows Appearance and Behaviour\";\n }\n }\n catch (Exception ex)\n {\n StatusText = $\"Error loading customization settings: {ex.Message}\";\n LogError($\"Error loading customization settings: {ex.Message}\", ex);\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the installation status of items asynchronously.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckInstallationStatusAsync()\n {\n // This method is not applicable for customization settings\n // but we need to implement it to satisfy the interface\n await Task.CompletedTask;\n }\n\n /// \n /// Restores all items visibility to their original state.\n /// \n private void RestoreAllItemsVisibility()\n {\n // Make all settings visible in each category\n if (TaskbarSettings?.Settings != null)\n {\n foreach (var setting in TaskbarSettings.Settings)\n {\n setting.IsVisible = true;\n }\n TaskbarSettings.HasVisibleSettings = TaskbarSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Restored visibility for {TaskbarSettings.Settings.Count} Taskbar settings\");\n }\n \n if (StartMenuSettings?.Settings != null)\n {\n foreach (var setting in StartMenuSettings.Settings)\n {\n setting.IsVisible = true;\n }\n StartMenuSettings.HasVisibleSettings = StartMenuSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Restored visibility for {StartMenuSettings.Settings.Count} Start Menu settings\");\n }\n \n if (ExplorerSettings?.Settings != null)\n {\n foreach (var setting in ExplorerSettings.Settings)\n {\n setting.IsVisible = true;\n }\n ExplorerSettings.HasVisibleSettings = ExplorerSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Restored visibility for {ExplorerSettings.Settings.Count} Explorer settings\");\n }\n \n if (WindowsThemeSettings?.Settings != null)\n {\n foreach (var setting in WindowsThemeSettings.Settings)\n {\n setting.IsVisible = true;\n }\n WindowsThemeSettings.HasVisibleSettings = WindowsThemeSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Restored visibility for {WindowsThemeSettings.Settings.Count} Windows Theme settings, HasVisibleSettings={WindowsThemeSettings.HasVisibleSettings}\");\n }\n \n // Make all customization items visible\n foreach (var item in CustomizationItems)\n {\n item.IsVisible = true;\n LogInfo($\"CustomizeViewModel: Restored visibility for CustomizationItem '{item.Name}'\");\n }\n \n // Always ensure HasSearchResults is true when restoring visibility\n HasSearchResults = true;\n \n // Send a message to notify the view to reset section expansion states\n _messengerService.Send(new ResetExpansionStateMessage());\n \n LogInfo(\"CustomizeViewModel: RestoreAllItemsVisibility has reset all UI elements to visible state\");\n }\n \n /// \n /// Applies the current search text to filter items.\n /// \n protected override void ApplySearch()\n {\n LogInfo($\"CustomizeViewModel: ApplySearch called with SearchText: '{SearchText}'\");\n \n // If we have no items yet, there's nothing to filter\n if (Items == null)\n return;\n \n // If this is our first time running a search and the backup isn't created yet, create it\n if (!_isInitialSearchDone && Items.Count > 0)\n {\n _allItemsBackup = new List(Items);\n _isInitialSearchDone = true;\n LogInfo($\"CustomizeViewModel: Created backup of all items ({_allItemsBackup.Count} items)\");\n }\n\n // If search is empty, restore all items visibility and the original items collection\n if (string.IsNullOrWhiteSpace(SearchText))\n {\n LogInfo(\"CustomizeViewModel: Empty search, restoring all items visibility\");\n \n // Restore visibility of UI elements first\n RestoreAllItemsVisibility();\n \n // Use the backup to restore all items\n if (_allItemsBackup.Count > 0)\n {\n LogInfo($\"CustomizeViewModel: Restoring {_allItemsBackup.Count} items from backup\");\n Items.Clear();\n foreach (var item in _allItemsBackup)\n {\n Items.Add(item);\n }\n }\n else if (Items.Count == 0)\n {\n // If we don't have a backup and Items is empty (which could happen after a no-results search),\n // try to reload items\n LogInfo(\"CustomizeViewModel: No backup available and Items is empty, attempting to reload\");\n _ = LoadItemsAsync();\n }\n \n // Always set HasSearchResults to true when search is cleared - critical to fix the bug\n HasSearchResults = true;\n \n // Make sure all CustomizationItems are visible\n foreach (var item in CustomizationItems)\n {\n item.IsVisible = true;\n LogInfo($\"CustomizeViewModel: Setting CustomizationItem '{item.Name}' visibility to true\");\n }\n \n // Ensure all sub-view models have HasVisibleSettings set to true\n if (TaskbarSettings != null)\n {\n TaskbarSettings.HasVisibleSettings = TaskbarSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Setting TaskbarSettings.HasVisibleSettings to {TaskbarSettings.HasVisibleSettings}\");\n }\n \n if (StartMenuSettings != null)\n {\n StartMenuSettings.HasVisibleSettings = StartMenuSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Setting StartMenuSettings.HasVisibleSettings to {StartMenuSettings.HasVisibleSettings}\");\n }\n \n if (ExplorerSettings != null)\n {\n ExplorerSettings.HasVisibleSettings = ExplorerSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Setting ExplorerSettings.HasVisibleSettings to {ExplorerSettings.HasVisibleSettings}\");\n }\n \n if (WindowsThemeSettings != null)\n {\n WindowsThemeSettings.HasVisibleSettings = WindowsThemeSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Setting WindowsThemeSettings.HasVisibleSettings to {WindowsThemeSettings.HasVisibleSettings}\");\n }\n \n // Update status text\n StatusText = \"Customize Your Windows Appearance and Behaviour\";\n LogInfo($\"CustomizeViewModel: Restored items, count={Items.Count}\");\n return;\n }\n\n // We're doing an active search, use the backup for filtering if available\n var itemsToFilter = _allItemsBackup.Count > 0 \n ? new ObservableCollection(_allItemsBackup) \n : Items;\n \n // Normalize and clean the search text\n string normalizedSearchText = SearchText.Trim().ToLowerInvariant();\n LogInfo($\"CustomizeViewModel: Normalized search text: '{normalizedSearchText}'\");\n \n // Handle edge case: if search is all whitespace after trimming, treat it as empty\n if (string.IsNullOrEmpty(normalizedSearchText))\n {\n // Same handling as empty search\n RestoreAllItemsVisibility();\n if (_allItemsBackup.Count > 0)\n {\n Items.Clear();\n foreach (var item in _allItemsBackup)\n {\n Items.Add(item);\n }\n }\n HasSearchResults = true;\n StatusText = \"Customize Your Windows Appearance and Behaviour\";\n return;\n }\n \n // Filter items based on search text - ensure we pass normalized text\n var filteredItems = FilterItems(itemsToFilter)\n .Where(item => \n item.Name?.IndexOf(normalizedSearchText, StringComparison.OrdinalIgnoreCase) >= 0 || \n item.Description?.IndexOf(normalizedSearchText, StringComparison.OrdinalIgnoreCase) >= 0)\n .ToList();\n \n // Log the number of filtered items\n int filteredCount = filteredItems.Count;\n LogInfo($\"CustomizeViewModel: Found {filteredCount} matching items\");\n \n // Update HasSearchResults based on filtered count\n HasSearchResults = filteredCount > 0;\n LogInfo($\"CustomizeViewModel: Setting HasSearchResults to {HasSearchResults} based on filtered count {filteredCount}\");\n \n // Create a HashSet of filtered item IDs for efficient lookup\n var filteredItemIds = new HashSet(filteredItems.Select(item => item.Id));\n\n // Update each sub-view model's Settings collection\n UpdateSubViewSettings(TaskbarSettings, filteredItemIds);\n UpdateSubViewSettings(StartMenuSettings, filteredItemIds);\n UpdateSubViewSettings(ExplorerSettings, filteredItemIds);\n UpdateSubViewSettings(WindowsThemeSettings, filteredItemIds);\n\n // Count the actual visible items after filtering\n int visibleItemsCount = 0;\n \n // Count visible items in each category\n if (TaskbarSettings?.Settings != null)\n visibleItemsCount += TaskbarSettings.Settings.Count(s => s is ApplicationSettingItem csItem && csItem.IsVisible);\n \n if (StartMenuSettings?.Settings != null)\n visibleItemsCount += StartMenuSettings.Settings.Count(s => s is ApplicationSettingItem csItem && csItem.IsVisible);\n \n if (ExplorerSettings?.Settings != null)\n visibleItemsCount += ExplorerSettings.Settings.Count(s => s is ApplicationSettingItem csItem && csItem.IsVisible);\n \n if (WindowsThemeSettings?.Settings != null)\n visibleItemsCount += WindowsThemeSettings.Settings.Count(s => s is ApplicationSettingItem csItem && csItem.IsVisible);\n\n // Update the Items collection to match visible items\n Items.Clear();\n foreach (var setting in filteredItems)\n {\n if (setting.IsVisible)\n {\n Items.Add(setting);\n }\n }\n\n // Update status text with correct count\n if (IsSearchActive)\n {\n StatusText = $\"Found {visibleItemsCount} settings matching '{SearchText}'\";\n LogInfo($\"CustomizeViewModel: StatusText updated to: '{StatusText}' with {visibleItemsCount} visible items\");\n }\n else\n {\n StatusText = $\"Showing all {Items.Count} customization settings\";\n LogInfo($\"CustomizeViewModel: StatusText updated to: '{StatusText}'\");\n }\n }\n\n /// \n /// Updates a sub-view model's Settings collection based on filtered items.\n /// \n /// The sub-view model to update.\n /// HashSet of IDs of items that match the search criteria.\n private void UpdateSubViewSettings(BaseSettingsViewModel viewModel, HashSet filteredItemIds)\n {\n if (viewModel == null || viewModel.Settings == null)\n return;\n\n // If not searching, show all settings\n if (!IsSearchActive)\n {\n foreach (var setting in viewModel.Settings)\n {\n setting.IsVisible = true;\n }\n \n // Update the view model's visibility\n viewModel.HasVisibleSettings = viewModel.Settings.Count > 0;\n \n // Update the corresponding CustomizationItem\n var item = CustomizationItems.FirstOrDefault(i => i.Name == viewModel.CategoryName);\n if (item != null)\n {\n item.IsVisible = true;\n }\n \n LogInfo($\"CustomizeViewModel: Set all settings visible in {viewModel.CategoryName}\");\n return;\n }\n\n // When searching, only show settings that match the search criteria\n bool hasVisibleSettings = false;\n int visibleCount = 0;\n \n foreach (var setting in viewModel.Settings)\n {\n // Check if this setting is in the filtered items\n setting.IsVisible = filteredItemIds.Contains(setting.Id);\n \n if (setting.IsVisible)\n {\n hasVisibleSettings = true;\n visibleCount++;\n }\n }\n \n // Update the view model's visibility\n viewModel.HasVisibleSettings = hasVisibleSettings;\n \n // Update the corresponding CustomizationItem - this is critical for proper UI behavior\n var categoryItem = CustomizationItems.FirstOrDefault(i => i.Name == viewModel.CategoryName);\n if (categoryItem != null)\n {\n categoryItem.IsVisible = hasVisibleSettings;\n LogInfo($\"CustomizeViewModel: Setting CustomizationItem '{categoryItem.Name}' visibility to {hasVisibleSettings}\");\n }\n \n LogInfo($\"CustomizeViewModel: {viewModel.CategoryName} has {visibleCount} visible settings, HasVisibleSettings={hasVisibleSettings}\");\n }\n\n // SaveConfig and ImportConfig methods removed as part of unified configuration cleanup\n\n /// \n /// Logs an informational message.\n /// \n /// The message to log.\n private void LogInfo(string message)\n {\n StatusText = message;\n _logService?.Log(LogLevel.Info, message);\n }\n\n /// \n /// Logs an error message.\n /// \n /// The message to log.\n private void LogError(string message)\n {\n StatusText = message;\n _logService?.Log(LogLevel.Error, message);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/WindowsSystemService.cs", "using System;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Services;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.Customize.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Models.Enums;\n\n// We're now using the UacLevel from Models.Enums directly\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Contains detailed information about the Windows version\n /// \n public class WindowsVersionInfo\n {\n /// \n /// The full OS version\n /// \n public Version Version { get; set; }\n\n /// \n /// The major version number\n /// \n public int MajorVersion { get; set; }\n\n /// \n /// The minor version number\n /// \n public int MinorVersion { get; set; }\n\n /// \n /// The build number\n /// \n public int BuildNumber { get; set; }\n\n /// \n /// The product name from registry\n /// \n public string ProductName { get; set; }\n\n /// \n /// Whether this is Windows 11 based on build number\n /// \n public bool IsWindows11ByBuild { get; set; }\n\n /// \n /// Whether this is Windows 11 based on product name\n /// \n public bool IsWindows11ByProductName { get; set; }\n\n /// \n /// Whether this is Windows 11 (combined determination)\n /// \n public bool IsWindows11 { get; set; }\n\n /// \n /// Whether this is Windows 10\n /// \n public bool IsWindows10 { get; set; }\n }\n\n public class WindowsSystemService : ISystemServices\n {\n // Dependencies\n private readonly IRegistryService _registryService;\n private readonly ILogService _logService;\n private readonly IThemeService _themeService;\n private readonly IUacSettingsService _uacSettingsService;\n private readonly IInternetConnectivityService _connectivityService;\n\n public WindowsSystemService(\n IRegistryService registryService,\n ILogService logService,\n IInternetConnectivityService connectivityService,\n IThemeService themeService = null,\n IUacSettingsService uacSettingsService = null\n ) // Optional to maintain backward compatibility\n {\n _registryService =\n registryService ?? throw new ArgumentNullException(nameof(registryService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _connectivityService =\n connectivityService ?? throw new ArgumentNullException(nameof(connectivityService));\n _themeService = themeService; // May be null if not provided\n _uacSettingsService = uacSettingsService; // May be null if not provided\n }\n\n /// \n /// Gets the registry service.\n /// \n public IRegistryService RegistryService => _registryService;\n\n public bool IsAdministrator()\n {\n try\n {\n#if WINDOWS\n WindowsIdentity identity = WindowsIdentity.GetCurrent();\n WindowsPrincipal principal = new WindowsPrincipal(identity);\n bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);\n\n _logService.LogInformation(\n $\"Administrator check completed. Is Administrator: {isAdmin}\"\n );\n return isAdmin;\n#else\n _logService.LogWarning(\"Administrator check is not supported on this platform.\");\n return false;\n#endif\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking administrator status\", ex);\n return false;\n }\n }\n\n /// \n /// Gets detailed Windows version information including build number and product name\n /// \n /// A WindowsVersionInfo object containing detailed version information\n private WindowsVersionInfo GetWindowsVersionInfo()\n {\n var result = new WindowsVersionInfo();\n\n try\n {\n var osVersion = Environment.OSVersion;\n result.Version = osVersion.Version;\n result.MajorVersion = osVersion.Version.Major;\n result.MinorVersion = osVersion.Version.Minor;\n result.BuildNumber = osVersion.Version.Build;\n\n // Check if Windows 11 using build number\n result.IsWindows11ByBuild =\n result.MajorVersion == 10 && result.BuildNumber >= 22000;\n\n // Check registry ProductName for more reliable detection\n try\n {\n using (\n var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(\n @\"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\"\n )\n )\n {\n if (key != null)\n {\n result.ProductName = key.GetValue(\"ProductName\") as string;\n result.IsWindows11ByProductName =\n result.ProductName != null\n && result.ProductName.Contains(\"Windows 11\");\n\n // Log the actual product name for debugging\n _logService.LogInformation(\n $\"Windows registry ProductName: {result.ProductName}\"\n );\n }\n }\n }\n catch (Exception regEx)\n {\n _logService.LogWarning($\"Error reading registry ProductName: {regEx.Message}\");\n }\n\n // Log detailed version information\n _logService.LogInformation(\n $\"Windows build number: {result.BuildNumber}, IsWin11ByBuild: {result.IsWindows11ByBuild}, IsWin11ByProductName: {result.IsWindows11ByProductName}\"\n );\n\n // Determine if this is Windows 11 using both methods, with ProductName taking precedence if available\n result.IsWindows11 =\n result.IsWindows11ByProductName\n || (result.IsWindows11ByBuild && !result.IsWindows11ByProductName == false);\n result.IsWindows10 = result.MajorVersion == 10 && !result.IsWindows11;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error getting Windows version info\", ex);\n }\n\n return result;\n }\n\n public string GetWindowsVersion()\n {\n try\n {\n var versionInfo = GetWindowsVersionInfo();\n string versionString;\n\n if (versionInfo.MajorVersion == 10)\n {\n versionString = versionInfo.IsWindows11 ? \"Windows 11\" : \"Windows 10\";\n }\n else\n {\n versionString = $\"Windows {versionInfo.Version}\";\n }\n\n _logService.LogInformation($\"Detected Windows version: {versionString}\");\n return versionString;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error detecting Windows version\", ex);\n return \"Unknown Windows Version\";\n }\n }\n\n public void RestartExplorer()\n {\n try\n {\n _logService.LogInformation(\"Attempting to restart Explorer\");\n\n // Kill all explorer processes\n var explorerProcesses = Process.GetProcessesByName(\"explorer\");\n foreach (var process in explorerProcesses)\n {\n _logService.LogInformation($\"Killing Explorer process (PID: {process.Id})\");\n process.Kill();\n }\n\n // Wait a moment - using Thread.Sleep since we can't use await anymore\n Thread.Sleep(1000);\n\n // Restart explorer\n Process.Start(\"explorer.exe\");\n\n _logService.LogSuccess(\"Explorer restarted successfully\");\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to restart Explorer\", ex);\n }\n }\n\n public void RefreshDesktop()\n {\n try\n {\n [DllImport(\"user32.dll\", SetLastError = true)]\n static extern bool SystemParametersInfo(\n uint uiAction,\n uint uiParam,\n IntPtr pvParam,\n uint fWinIni\n );\n\n const uint SPI_SETDESKWALLPAPER = 0x0014;\n const uint SPIF_UPDATEINIFILE = 0x01;\n const uint SPIF_SENDCHANGE = 0x02;\n\n _logService.LogInformation(\"Attempting to refresh desktop\");\n SystemParametersInfo(\n SPI_SETDESKWALLPAPER,\n 0,\n IntPtr.Zero,\n SPIF_UPDATEINIFILE | SPIF_SENDCHANGE\n );\n\n _logService.LogSuccess(\"Desktop refreshed successfully\");\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to refresh desktop\", ex);\n }\n }\n\n public bool IsProcessRunning(string processName)\n {\n try\n {\n bool isRunning = Process.GetProcessesByName(processName).Length > 0;\n _logService.LogInformation($\"Process check for {processName}: {isRunning}\");\n return isRunning;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking if process {processName} is running\", ex);\n return false;\n }\n }\n\n public void KillProcess(string processName)\n {\n try\n {\n _logService.LogInformation($\"Attempting to kill process: {processName}\");\n\n var processes = Process.GetProcessesByName(processName);\n foreach (var process in processes)\n {\n _logService.LogInformation(\n $\"Killing process {processName} (PID: {process.Id})\"\n );\n process.Kill();\n }\n\n _logService.LogSuccess($\"Killed all instances of {processName}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to kill process {processName}\", ex);\n }\n }\n\n // IsInternetConnected method has been moved to InternetConnectivityService\n\n // IsInternetConnectedAsync method has been moved to InternetConnectivityService\n\n public bool IsWindows11()\n {\n try\n {\n // Use our centralized version detection method\n var versionInfo = GetWindowsVersionInfo();\n\n _logService.LogInformation(\n $\"Windows 11 check completed. Is Windows 11: {versionInfo.IsWindows11} (By build: {versionInfo.IsWindows11ByBuild}, By ProductName: {versionInfo.IsWindows11ByProductName})\"\n );\n return versionInfo.IsWindows11;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking Windows 11 version\", ex);\n return false;\n }\n }\n\n public bool RequireAdministrator()\n {\n try\n {\n if (!IsAdministrator())\n {\n _logService.LogWarning(\n \"Application requires administrator privileges. Attempting to elevate.\"\n );\n\n ProcessStartInfo startInfo = new ProcessStartInfo\n {\n UseShellExecute = true,\n WorkingDirectory = Environment.CurrentDirectory,\n FileName =\n Process.GetCurrentProcess().MainModule?.FileName\n ?? throw new InvalidOperationException(\"MainModule is null\"),\n Verb = \"runas\",\n };\n\n try\n {\n // Start the elevated process and capture the Process object\n Process elevatedProcess = Process.Start(startInfo);\n\n // If elevatedProcess is null, it means the UAC prompt was canceled or denied\n if (elevatedProcess == null)\n {\n _logService.LogWarning(\n \"User denied UAC elevation. Application will exit.\"\n );\n Environment.Exit(1); // Exit with error code to indicate denial\n return false;\n }\n\n _logService.LogInformation(\n \"Elevation request accepted. Exiting current process.\"\n );\n Environment.Exit(0);\n }\n catch (System.ComponentModel.Win32Exception w32Ex)\n when (w32Ex.NativeErrorCode == 1223)\n {\n // Error code 1223 specifically means \"The operation was canceled by the user\"\n // This happens when the user clicks \"No\" on the UAC prompt\n _logService.LogWarning(\"User denied UAC elevation. Application will exit.\");\n Environment.Exit(1); // Exit with error code to indicate denial\n return false;\n }\n catch (Exception elevationEx)\n {\n _logService.LogError(\"Failed to elevate privileges\", elevationEx);\n Environment.Exit(1); // Exit with error code to indicate failure\n return false;\n }\n }\n\n _logService.LogInformation(\"Application is running with administrator privileges\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Unexpected error during privilege elevation\", ex);\n return false;\n }\n }\n\n public bool IsDarkModeEnabled()\n {\n // Delegate to ThemeService if available, otherwise use legacy implementation\n if (_themeService != null)\n {\n try\n {\n return _themeService.IsDarkModeEnabled();\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Error using ThemeService.IsDarkModeEnabled: {ex.Message}. Falling back to legacy implementation.\"\n );\n // Fall through to legacy implementation\n }\n }\n\n // Legacy implementation\n try\n {\n using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(\n WindowsThemeSettings.Registry.ThemesPersonalizeSubKey\n );\n\n if (key == null)\n {\n _logService.LogWarning(\"Could not open registry key for dark mode check\");\n return false;\n }\n\n var value = key.GetValue(WindowsThemeSettings.Registry.AppsUseLightThemeName);\n bool isDarkMode = value != null && (int)value == 0;\n\n _logService.LogInformation(\n $\"Dark mode check completed. Is Dark Mode: {isDarkMode}\"\n );\n return isDarkMode;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking dark mode status\", ex);\n return false;\n }\n }\n\n public void SetDarkMode(bool enabled)\n {\n // Delegate to ThemeService if available, otherwise use legacy implementation\n if (_themeService != null)\n {\n try\n {\n _themeService.SetThemeMode(enabled);\n return;\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Error using ThemeService.SetThemeMode: {ex.Message}. Falling back to legacy implementation.\"\n );\n // Fall through to legacy implementation\n }\n }\n\n // Legacy implementation\n try\n {\n _logService.LogInformation(\n $\"Attempting to {(enabled ? \"enable\" : \"disable\")} dark mode\"\n );\n\n string[] keys = new[] { WindowsThemeSettings.Registry.ThemesPersonalizeSubKey };\n\n string[] values = new[]\n {\n WindowsThemeSettings.Registry.AppsUseLightThemeName,\n WindowsThemeSettings.Registry.SystemUsesLightThemeName,\n };\n\n foreach (var key in keys)\n {\n using var registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(\n key,\n true\n );\n if (registryKey == null)\n {\n _logService.LogWarning($\"Could not open registry key: {key}\");\n continue;\n }\n\n foreach (var value in values)\n {\n registryKey.SetValue(\n value,\n enabled ? 0 : 1,\n Microsoft.Win32.RegistryValueKind.DWord\n );\n _logService.LogInformation($\"Set {value} to {(enabled ? 0 : 1)}\");\n }\n }\n\n _logService.LogSuccess(\n $\"Dark mode {(enabled ? \"enabled\" : \"disabled\")} successfully\"\n );\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to {(enabled ? \"enable\" : \"disable\")} dark mode\", ex);\n }\n }\n\n public void SetUacLevel(Winhance.Core.Models.Enums.UacLevel level)\n {\n try\n {\n // No need to convert as we're already using the Core UacLevel\n Winhance.Core.Models.Enums.UacLevel coreLevel = level;\n\n // Special handling for Custom UAC level\n if (coreLevel == Winhance.Core.Models.Enums.UacLevel.Custom)\n {\n // For Custom level, try to get the saved custom settings and apply them\n if (_uacSettingsService != null && _uacSettingsService.TryGetCustomUacValues(\n out int customConsentPromptValue, \n out int customSecureDesktopValue))\n {\n _logService.Log(\n LogLevel.Info,\n $\"Applying saved custom UAC settings: ConsentPrompt={customConsentPromptValue}, SecureDesktop={customSecureDesktopValue}\"\n );\n \n string registryPath = $\"HKLM\\\\{UacOptimizations.RegistryPath}\";\n \n // Set the ConsentPromptBehaviorAdmin value\n _registryService.SetValue(\n registryPath,\n UacOptimizations.ConsentPromptName,\n customConsentPromptValue,\n UacOptimizations.ValueKind\n );\n \n // Set the PromptOnSecureDesktop value\n _registryService.SetValue(\n registryPath,\n UacOptimizations.SecureDesktopName,\n customSecureDesktopValue,\n UacOptimizations.ValueKind\n );\n \n return;\n }\n else\n {\n // No saved custom settings found\n _logService.Log(\n LogLevel.Warning,\n \"Custom UAC level selected but no saved settings found - preserving current registry settings\"\n );\n return;\n }\n }\n\n // Get both registry values for the selected UAC level\n if (\n !UacOptimizations.UacLevelToConsentPromptValue.TryGetValue(\n coreLevel,\n out int consentPromptValue\n )\n || !UacOptimizations.UacLevelToSecureDesktopValue.TryGetValue(\n coreLevel,\n out int secureDesktopValue\n )\n )\n {\n throw new ArgumentException($\"Invalid UAC level: {level}\");\n }\n\n string fullPath = $\"HKLM\\\\{UacOptimizations.RegistryPath}\";\n\n bool keyExists = _registryService.KeyExists(fullPath);\n if (!keyExists)\n {\n _logService.Log(\n LogLevel.Info,\n $\"UAC registry key doesn't exist, creating: {fullPath}\"\n );\n _registryService.CreateKey(fullPath);\n }\n\n // Set the ConsentPromptBehaviorAdmin value\n _registryService.SetValue(\n fullPath,\n UacOptimizations.ConsentPromptName,\n consentPromptValue,\n UacOptimizations.ValueKind\n );\n\n // Set the PromptOnSecureDesktop value\n _registryService.SetValue(\n fullPath,\n UacOptimizations.SecureDesktopName,\n secureDesktopValue,\n UacOptimizations.ValueKind\n );\n\n string levelName = UacOptimizations.UacLevelNames.TryGetValue(\n coreLevel,\n out string name\n )\n ? name\n : coreLevel.ToString();\n _logService.Log(\n LogLevel.Info,\n $\"UAC level set to {levelName} (ConsentPrompt: {consentPromptValue}, SecureDesktop: {secureDesktopValue})\"\n );\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting UAC level: {ex.Message}\");\n throw;\n }\n }\n\n public Winhance.Core.Models.Enums.UacLevel GetUacLevel()\n {\n try\n {\n string fullPath = $\"HKLM\\\\{UacOptimizations.RegistryPath}\";\n\n // Get both registry values needed to determine the UAC level\n var consentPromptValue = _registryService.GetValue(\n fullPath,\n UacOptimizations.ConsentPromptName\n );\n var secureDesktopValue = _registryService.GetValue(\n fullPath,\n UacOptimizations.SecureDesktopName\n );\n\n // Convert to integers with appropriate defaults if values are null\n var consentPromptInt = Convert.ToInt32(consentPromptValue ?? 5); // Default to 5 (Notify)\n var secureDesktopInt = Convert.ToInt32(secureDesktopValue ?? 1); // Default to 1 (Enabled)\n\n _logService.Log(\n LogLevel.Info,\n $\"UAC registry values retrieved: ConsentPrompt={consentPromptInt}, SecureDesktop={secureDesktopInt}\"\n );\n\n // Determine the UacLevel from both registry values\n Winhance.Core.Models.Enums.UacLevel coreLevel =\n UacOptimizations.GetUacLevelFromRegistryValues(\n consentPromptInt,\n secureDesktopInt,\n _uacSettingsService\n );\n string levelName = UacOptimizations.UacLevelNames.TryGetValue(\n coreLevel,\n out string name\n )\n ? name\n : coreLevel.ToString();\n\n _logService.Log(LogLevel.Info, $\"UAC level mapped to: {levelName}\");\n\n // Return the Core UacLevel directly\n return coreLevel;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting UAC level: {ex.Message}\");\n return Winhance.Core.Models.Enums.UacLevel.NotifyChangesOnly; // Default value\n }\n }\n\n public async Task RefreshWindowsGUI(bool killExplorer)\n {\n try\n {\n _logService.Log(\n LogLevel.Info,\n $\"Refreshing Windows GUI (killExplorer: {killExplorer})\"\n );\n\n // Define Windows message constants\n const int HWND_BROADCAST = 0xffff;\n const uint WM_SYSCOLORCHANGE = 0x0015;\n const uint WM_SETTINGCHANGE = 0x001A;\n const uint WM_THEMECHANGE = 0x031A;\n\n // Import Windows API functions\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\n static extern IntPtr SendMessage(\n IntPtr hWnd,\n uint Msg,\n IntPtr wParam,\n IntPtr lParam\n );\n\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n static extern IntPtr SendMessageTimeout(\n IntPtr hWnd,\n uint Msg,\n IntPtr wParam,\n IntPtr lParam,\n uint fuFlags,\n uint uTimeout,\n out IntPtr lpdwResult\n );\n\n SendMessage((IntPtr)HWND_BROADCAST, WM_SYSCOLORCHANGE, IntPtr.Zero, IntPtr.Zero);\n SendMessage((IntPtr)HWND_BROADCAST, WM_THEMECHANGE, IntPtr.Zero, IntPtr.Zero);\n\n if (killExplorer)\n {\n _logService.Log(\n LogLevel.Info,\n \"Refreshing Windows GUI by terminating Explorer process\"\n );\n\n await Task.Delay(500);\n\n bool explorerWasRunning = Process.GetProcessesByName(\"explorer\").Length > 0;\n\n if (explorerWasRunning)\n {\n _logService.Log(\n LogLevel.Info,\n \"Terminating Explorer processes - Windows will restart it automatically\"\n );\n\n foreach (var process in Process.GetProcessesByName(\"explorer\"))\n {\n try\n {\n process.Kill();\n _logService.Log(\n LogLevel.Info,\n $\"Killed Explorer process (PID: {process.Id})\"\n );\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to kill Explorer process: {ex.Message}\"\n );\n }\n }\n\n _logService.Log(\n LogLevel.Info,\n \"Waiting for Windows to automatically restart Explorer\"\n );\n\n // Wait for Explorer to be terminated completely\n await Task.Delay(1000);\n\n // Check if Explorer has restarted automatically\n int retryCount = 0;\n const int maxRetries = 5;\n bool explorerRestarted = false;\n\n while (retryCount < maxRetries && !explorerRestarted)\n {\n if (Process.GetProcessesByName(\"explorer\").Length > 0)\n {\n explorerRestarted = true;\n _logService.Log(\n LogLevel.Info,\n \"Explorer process restarted automatically\"\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Explorer not restarted yet, waiting... (Attempt {retryCount + 1}/{maxRetries})\"\n );\n retryCount++;\n await Task.Delay(1000);\n }\n }\n\n // If Explorer didn't restart automatically, start it manually\n if (!explorerRestarted)\n {\n _logService.Log(\n LogLevel.Warning,\n \"Explorer did not restart automatically, starting it manually\"\n );\n try\n {\n Process.Start(\"explorer.exe\");\n _logService.Log(LogLevel.Info, \"Explorer process started manually\");\n\n // Wait for Explorer to initialize\n await Task.Delay(2000);\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Error,\n $\"Failed to start Explorer manually: {ex.Message}\"\n );\n return false;\n }\n }\n }\n }\n else\n {\n _logService.Log(\n LogLevel.Info,\n \"Refreshing Windows GUI without killing Explorer\"\n );\n }\n\n string themeChanged = \"ImmersiveColorSet\";\n IntPtr themeChangedPtr = Marshal.StringToHGlobalUni(themeChanged);\n\n try\n {\n IntPtr result;\n SendMessageTimeout(\n (IntPtr)HWND_BROADCAST,\n WM_SETTINGCHANGE,\n IntPtr.Zero,\n themeChangedPtr,\n 0x0000,\n 1000,\n out result\n );\n\n SendMessage((IntPtr)HWND_BROADCAST, WM_SETTINGCHANGE, IntPtr.Zero, IntPtr.Zero);\n }\n finally\n {\n Marshal.FreeHGlobal(themeChangedPtr);\n }\n\n _logService.Log(LogLevel.Info, \"Windows GUI refresh completed successfully\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error refreshing Windows GUI: {ex.Message}\");\n return false;\n }\n }\n\n public Task RefreshWindowsGUI()\n {\n return RefreshWindowsGUI(true);\n }\n\n /// \n /// Checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// True if internet is connected, false otherwise.\n public bool IsInternetConnected(bool forceCheck = false)\n {\n return _connectivityService.IsInternetConnected(forceCheck);\n }\n\n /// \n /// Asynchronously checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// Cancellation token for the operation.\n /// True if internet is connected, false otherwise.\n public async Task IsInternetConnectedAsync(\n bool forceCheck = false,\n CancellationToken cancellationToken = default,\n bool userInitiatedCancellation = false\n )\n {\n return await _connectivityService.IsInternetConnectedAsync(\n forceCheck,\n cancellationToken,\n userInitiatedCancellation\n );\n }\n\n private async Task RunCommand(string command, string arguments)\n {\n try\n {\n using var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = command,\n Arguments = arguments,\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n },\n };\n\n process.Start();\n await process.WaitForExitAsync();\n\n if (process.ExitCode != 0)\n {\n _logService.Log(LogLevel.Warning, $\"Command failed: {command} {arguments}\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error running command: {ex.Message}\");\n throw;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/ApplicationSettingViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.WPF.Features.Common.Extensions;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// Base view model for application settings.\n /// \n public partial class ApplicationSettingViewModel : ObservableObject, ISettingItem\n {\n protected readonly IRegistryService? _registryService;\n protected readonly IDialogService? _dialogService;\n protected readonly ILogService? _logService;\n protected readonly IDependencyManager? _dependencyManager;\n protected readonly Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService? _powerPlanService;\n protected bool _isUpdatingFromCode;\n\n /// \n /// Gets or sets a value indicating whether the IsSelected property is being updated from code.\n /// This is used to prevent automatic application of settings when loading.\n /// \n public bool IsUpdatingFromCode\n {\n get => _isUpdatingFromCode;\n set => _isUpdatingFromCode = value;\n }\n\n [ObservableProperty]\n private string _id = string.Empty;\n\n [ObservableProperty]\n private string _name = string.Empty;\n\n [ObservableProperty]\n private string _description = string.Empty;\n\n [ObservableProperty]\n private bool _isSelected;\n\n [ObservableProperty]\n private string _groupName = string.Empty;\n\n [ObservableProperty]\n private bool _isGroupHeader;\n\n [ObservableProperty]\n private bool _isGroupedSetting;\n\n [ObservableProperty]\n private bool _isVisible = true;\n\n [ObservableProperty]\n private ObservableCollection _childSettings = new();\n\n [ObservableProperty]\n private ControlType _controlType = ControlType.BinaryToggle;\n\n [ObservableProperty]\n private int? _sliderSteps;\n\n [ObservableProperty]\n private int _sliderValue;\n\n [ObservableProperty]\n private ObservableCollection _sliderLabels = new();\n\n [ObservableProperty]\n private RegistrySettingStatus _status = RegistrySettingStatus.Unknown;\n\n [ObservableProperty]\n private object? _currentValue;\n\n /// \n /// Gets a value indicating whether this setting is command-based rather than registry-based.\n /// \n public bool IsCommandBasedSetting\n {\n get\n {\n // Check if this setting has PowerCfg commands in its CustomProperties\n return CustomProperties != null &&\n CustomProperties.ContainsKey(\"PowerCfgSettings\") &&\n CustomProperties[\"PowerCfgSettings\"] is List powerCfgSettings &&\n powerCfgSettings.Count > 0;\n }\n }\n \n /// \n /// Gets a list of PowerCfg commands for display in tooltips.\n /// \n public ObservableCollection PowerCfgCommands\n {\n get\n {\n var commands = new ObservableCollection();\n \n if (IsCommandBasedSetting &&\n CustomProperties.ContainsKey(\"PowerCfgSettings\") &&\n CustomProperties[\"PowerCfgSettings\"] is List powerCfgSettings)\n {\n foreach (var setting in powerCfgSettings)\n {\n commands.Add(setting.Command);\n }\n }\n \n return commands;\n }\n }\n\n /// \n /// Gets a value indicating whether the registry value is null.\n /// \n public bool IsRegistryValueNull\n {\n get\n {\n // Don't show warning for command-based settings\n if (IsCommandBasedSetting)\n {\n return false;\n }\n \n // Don't show warning for settings with ActionType = Remove\n if (RegistrySetting != null && RegistrySetting.ActionType == RegistryActionType.Remove)\n {\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Returning false because ActionType is Remove\");\n return false;\n }\n \n // Also check linked registry settings for ActionType = Remove\n if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n // If all linked settings have ActionType = Remove, don't show warning\n bool allRemove = LinkedRegistrySettings.Settings.All(s => s.ActionType == RegistryActionType.Remove);\n if (allRemove)\n {\n // For Remove actions, we don't want to show the warning if all values are null (which means keys don't exist)\n bool allNull = LinkedRegistrySettingsWithValues.All(lv => lv.CurrentValue == null);\n if (allNull)\n {\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Returning false because all Remove settings have null values (keys don't exist)\");\n return false;\n }\n \n // If any key exists when it shouldn't, we might want to show a warning\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Continuing because some Remove settings have non-null values (keys exist)\");\n }\n }\n \n // Add debug logging to help diagnose the issue\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': CurrentValue = {(CurrentValue == null ? \"null\" : CurrentValue.ToString())}\");\n \n // Check if the registry value is null or a special value that indicates it doesn't exist\n if (CurrentValue == null)\n {\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Returning true because CurrentValue is null\");\n return true;\n }\n \n // Check if the registry setting exists\n if (RegistrySetting != null)\n {\n // If we have a registry setting but no current value, it might be null\n if (Status == RegistrySettingStatus.Unknown)\n {\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Returning true because Status is Unknown\");\n return true;\n }\n }\n \n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Returning false\");\n return false;\n }\n }\n\n [ObservableProperty]\n private string _statusMessage = string.Empty;\n\n [ObservableProperty]\n private bool _isApplying;\n\n /// \n /// Gets or sets the registry setting associated with this view model.\n /// \n public RegistrySetting? RegistrySetting { get; set; }\n\n /// \n /// Gets or sets the linked registry settings associated with this view model.\n /// \n public LinkedRegistrySettings LinkedRegistrySettings { get; set; } = new LinkedRegistrySettings();\n\n /// \n /// Gets or sets the linked registry settings with their current values for display in tooltips.\n /// \n [ObservableProperty]\n private ObservableCollection _linkedRegistrySettingsWithValues = new();\n\n /// \n /// Gets or sets the dependencies between settings.\n /// \n public List Dependencies { get; set; } = new List();\n\n /// \n /// Gets or sets custom properties for this setting.\n /// This can be used to store additional data specific to certain optimization types,\n /// such as PowerCfg settings.\n /// \n public Dictionary CustomProperties { get; set; } = new Dictionary();\n\n /// \n /// Gets or sets the command to apply the setting.\n /// \n public ICommand ApplySettingCommand { get; set; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n public ApplicationSettingViewModel()\n {\n // Default constructor for design-time use\n ApplySettingCommand = new RelayCommand(async () => await ApplySetting());\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The registry service.\n /// The dialog service.\n /// The log service.\n /// The dependency manager.\n public ApplicationSettingViewModel(\n IRegistryService registryService,\n IDialogService? dialogService,\n ILogService logService,\n IDependencyManager? dependencyManager = null,\n Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService? powerPlanService = null)\n {\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n _dialogService = dialogService; // Allow null for dialogService\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _dependencyManager = dependencyManager; // Allow null for backward compatibility\n _powerPlanService = powerPlanService; // Allow null for backward compatibility\n \n // Initialize the ApplySettingCommand\n ApplySettingCommand = new RelayCommand(async () => await ApplySetting());\n\n // Set up property changed handlers for immediate application\n this.PropertyChanged += (s, e) => {\n if ((e.PropertyName == nameof(IsSelected) || e.PropertyName == nameof(SliderValue)) && !IsUpdatingFromCode)\n {\n _logService?.Log(LogLevel.Info, $\"Property {e.PropertyName} changed for {Name}, applying setting\");\n\n // Check dependencies when enabling a setting\n if (e.PropertyName == nameof(IsSelected))\n {\n if (IsSelected)\n {\n // Check if this setting can be enabled based on its dependencies\n var allSettings = GetAllSettings();\n if (allSettings != null && _dependencyManager != null)\n {\n if (!_dependencyManager.CanEnableSetting(Id, allSettings))\n {\n _logService?.Log(LogLevel.Info, $\"Setting {Name} has unsatisfied dependencies, attempting to enable them\");\n \n // Find the dependencies that need to be enabled\n var unsatisfiedDependencies = new List();\n foreach (var dependency in Dependencies)\n {\n if (dependency.DependencyType == SettingDependencyType.RequiresEnabled)\n {\n var requiredSetting = allSettings.FirstOrDefault(s => s.Id == dependency.RequiredSettingId);\n if (requiredSetting != null && !requiredSetting.IsSelected)\n {\n unsatisfiedDependencies.Add(requiredSetting);\n }\n }\n }\n \n if (unsatisfiedDependencies.Count > 0)\n {\n // Automatically enable the dependencies without asking\n bool enableDependencies = true;\n \n // Log what we're doing\n var dependencyNames = string.Join(\", \", unsatisfiedDependencies.Select(d => $\"'{d.Name}'\"));\n _logService?.Log(LogLevel.Info, $\"'{Name}' requires {dependencyNames} to be enabled. Automatically enabling dependencies.\");\n \n if (enableDependencies)\n {\n // Enable all dependencies\n foreach (var dependency in unsatisfiedDependencies)\n {\n _logService?.Log(LogLevel.Info, $\"Automatically enabling dependency: {dependency.Name}\");\n \n // Enable the dependency\n if (dependency is ApplicationSettingViewModel depViewModel)\n {\n depViewModel.IsUpdatingFromCode = true;\n try\n {\n depViewModel.IsSelected = true;\n }\n finally\n {\n depViewModel.IsUpdatingFromCode = false;\n }\n \n // Apply the setting\n depViewModel.ApplySettingCommand.Execute(null);\n }\n }\n }\n else\n {\n // User chose not to enable dependencies, so don't enable this setting\n IsUpdatingFromCode = true;\n try\n {\n IsSelected = false;\n }\n finally\n {\n IsUpdatingFromCode = false;\n }\n return;\n }\n }\n else\n {\n // No dependencies found, show a generic message\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"'{Name}' cannot be enabled because one of its dependencies is not satisfied.\",\n \"Setting Dependency\");\n }\n \n // Prevent enabling this setting\n IsUpdatingFromCode = true;\n try\n {\n IsSelected = false;\n }\n finally\n {\n IsUpdatingFromCode = false;\n }\n return;\n }\n }\n \n // Automatically enable any required settings\n _dependencyManager.HandleSettingEnabled(Id, allSettings);\n }\n }\n else\n {\n // Handle disabling a setting\n var allSettings = GetAllSettings();\n if (allSettings != null && _dependencyManager != null)\n {\n _dependencyManager.HandleSettingDisabled(Id, allSettings);\n }\n }\n }\n\n ApplySettingCommand.Execute(null);\n }\n else if ((e.PropertyName == nameof(IsSelected) || e.PropertyName == nameof(SliderValue)) && IsUpdatingFromCode)\n {\n _logService?.Log(LogLevel.Info, $\"Property {e.PropertyName} changed for {Name}, but not applying setting because IsUpdatingFromCode is true\");\n }\n };\n }\n\n /// \n /// Called when the IsSelected property changes.\n /// \n /// The new value.\n partial void OnIsSelectedChanged(bool value)\n {\n // If this is a grouped setting, update all child settings\n if (IsGroupedSetting && ChildSettings.Count > 0)\n {\n _isUpdatingFromCode = true;\n try\n {\n foreach (var child in ChildSettings)\n {\n child.IsSelected = value;\n }\n }\n finally\n {\n _isUpdatingFromCode = false;\n }\n }\n }\n\n /// \n /// Applies the setting immediately.\n /// \n protected virtual async Task ApplySetting()\n {\n if (IsApplying || _registryService == null || _logService == null)\n return;\n\n try\n {\n IsApplying = true;\n\n // Check if this is a command-based setting (PowerCfg commands)\n if (IsCommandBasedSetting)\n {\n _logService.Log(LogLevel.Info, $\"Applying command-based setting: {Name}, IsSelected={IsSelected}\");\n \n // Get the PowerPlanService from the application services\n var powerPlanService = GetPowerPlanService();\n if (powerPlanService == null)\n {\n _logService.Log(LogLevel.Error, $\"Cannot apply command-based setting: {Name} - PowerPlanService not found\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = \"Failed to apply setting: PowerPlanService not found\";\n return;\n }\n \n // Get the PowerCfg settings from CustomProperties\n var powerCfgSettings = CustomProperties[\"PowerCfgSettings\"] as List;\n if (powerCfgSettings == null || powerCfgSettings.Count == 0)\n {\n _logService.Log(LogLevel.Error, $\"Cannot apply command-based setting: {Name} - PowerCfgSettings is null or empty\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = \"Failed to apply setting: PowerCfgSettings is null or empty\";\n return;\n }\n \n bool success;\n \n if (IsSelected)\n {\n // Apply the PowerCfg settings when enabling\n _logService.Log(LogLevel.Info, $\"Enabling command-based setting: {Name}\");\n success = await powerPlanService.ApplyPowerCfgSettingsAsync(powerCfgSettings);\n }\n else\n {\n // Apply the disabled values when disabling\n _logService.Log(LogLevel.Info, $\"Disabling command-based setting: {Name}\");\n \n // Create a list of PowerCfgSetting objects with disabled values\n var disabledSettings = new List();\n foreach (var powerCfgSetting in powerCfgSettings)\n {\n if (!string.IsNullOrEmpty(powerCfgSetting.DisabledValue))\n {\n disabledSettings.Add(new Winhance.Core.Features.Optimize.Models.PowerCfgSetting\n {\n Command = powerCfgSetting.DisabledValue.StartsWith(\"powercfg \")\n ? powerCfgSetting.DisabledValue\n : \"powercfg \" + powerCfgSetting.DisabledValue,\n Description = \"Restore default: \" + powerCfgSetting.Description,\n EnabledValue = powerCfgSetting.DisabledValue,\n DisabledValue = powerCfgSetting.EnabledValue\n });\n }\n }\n \n // Apply the disabled settings\n if (disabledSettings.Count > 0)\n {\n success = await powerPlanService.ApplyPowerCfgSettingsAsync(disabledSettings);\n }\n else\n {\n // If no disabled settings are defined, consider it a success\n _logService.Log(LogLevel.Warning, $\"No disabled values defined for command-based setting: {Name}\");\n success = true;\n }\n }\n \n if (success)\n {\n _logService.Log(LogLevel.Info, $\"Successfully applied command-based setting: {Name}\");\n Status = IsSelected ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n StatusMessage = IsSelected ? \"Setting applied successfully\" : \"Setting disabled successfully\";\n \n // Set a dummy current value to prevent warning icon\n CurrentValue = IsSelected ? \"Enabled\" : \"Disabled\";\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to apply command-based setting: {Name}\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = \"Failed to apply setting\";\n }\n \n return;\n }\n\n // Check if we have linked registry settings\n if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Applying linked registry settings for {Name}\");\n var linkedResult = await _registryService.ApplyLinkedSettingsAsync(LinkedRegistrySettings, IsSelected);\n\n if (linkedResult)\n {\n _logService.Log(LogLevel.Info, $\"Successfully applied linked settings for {Name}\");\n Status = RegistrySettingStatus.Applied;\n StatusMessage = \"Settings applied successfully\";\n\n // Update tooltip data for linked settings\n if (_registryService != null && LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n // Update the tooltip data\n LinkedRegistrySettingsWithValues.Clear();\n\n // For linked settings, get fresh values from registry\n foreach (var regSetting in LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = _registryService.GetValue(\n RegistryExtensions.GetRegistryHiveString(regSetting.Hive) + \"\\\\\" + regSetting.SubKey,\n regSetting.Name);\n LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n\n // Update the main current value display with the primary or first setting\n var primarySetting = LinkedRegistrySettings.Settings.FirstOrDefault(s => s.IsPrimary) ??\n LinkedRegistrySettings.Settings.FirstOrDefault();\n if (primarySetting != null)\n {\n var primaryValue = _registryService.GetValue(\n RegistryExtensions.GetRegistryHiveString(primarySetting.Hive) + \"\\\\\" + primarySetting.SubKey,\n primarySetting.Name);\n CurrentValue = primaryValue;\n }\n }\n\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to apply linked settings for {Name}\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = \"Failed to apply settings\";\n }\n return;\n }\n\n // Fall back to single registry setting if no linked settings\n if (RegistrySetting == null)\n {\n _logService.Log(LogLevel.Error, $\"Cannot apply setting: {Name} - Registry setting is null\");\n return;\n }\n\n string valueToSet = string.Empty;\n object valueObject;\n\n // Determine value to set based on control type\n switch (ControlType)\n {\n case ControlType.BinaryToggle:\n if (IsSelected)\n {\n // When toggle is ON, use EnabledValue if available, otherwise fall back to RecommendedValue\n valueObject = RegistrySetting.EnabledValue ?? RegistrySetting.RecommendedValue;\n }\n else\n {\n // When toggle is OFF, use DisabledValue if available, otherwise fall back to DefaultValue\n valueObject = RegistrySetting.DisabledValue ?? RegistrySetting.DefaultValue;\n }\n break;\n\n case ControlType.ThreeStateSlider:\n // Map slider value to appropriate setting value\n valueObject = SliderValue;\n break;\n\n case ControlType.Custom:\n default:\n // Custom handling would go here\n valueObject = IsSelected ?\n (RegistrySetting.EnabledValue ?? RegistrySetting.RecommendedValue) :\n (RegistrySetting.DisabledValue ?? RegistrySetting.DefaultValue);\n break;\n }\n\n // Check if this registry setting requires special handling\n if (RegistrySetting.RequiresSpecialHandling() && \n RegistrySetting.ApplySpecialHandling(_registryService, IsSelected))\n {\n // Special handling was applied successfully\n _logService.Log(LogLevel.Info, $\"Special handling applied for {RegistrySetting.Name}\");\n Status = RegistrySettingStatus.Applied;\n StatusMessage = \"Setting applied successfully\";\n \n // Update current value for tooltip display\n if (_registryService != null)\n {\n // Get the current value after special handling\n var currentValue = _registryService.GetValue(\n RegistryExtensions.GetRegistryHiveString(RegistrySetting.Hive) + \"\\\\\" + RegistrySetting.SubKey,\n RegistrySetting.Name);\n \n CurrentValue = currentValue;\n \n // Update the tooltip data\n LinkedRegistrySettingsWithValues.Clear();\n LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(RegistrySetting, currentValue));\n }\n \n return;\n }\n else\n {\n // Apply the registry change normally\n var result = _registryService.SetValue(\n RegistryExtensions.GetRegistryHiveString(RegistrySetting.Hive) + \"\\\\\" + RegistrySetting.SubKey,\n RegistrySetting.Name,\n valueObject,\n RegistrySetting.ValueType);\n\n if (result)\n {\n _logService.Log(LogLevel.Info, $\"Setting applied: {Name}\");\n Status = RegistrySettingStatus.Applied;\n StatusMessage = \"Setting applied successfully\";\n\n // Update current value for tooltip display\n if (_registryService != null)\n {\n // Update the current value\n CurrentValue = valueObject;\n\n // Update the tooltip data\n LinkedRegistrySettingsWithValues.Clear();\n if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n // For linked settings\n foreach (var regSetting in LinkedRegistrySettings.Settings)\n {\n // For the setting that was just changed, use the new value\n if (regSetting.SubKey == RegistrySetting.SubKey &&\n regSetting.Name == RegistrySetting.Name &&\n regSetting.Hive == RegistrySetting.Hive)\n {\n LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, valueObject));\n }\n else\n {\n // For other linked settings, get the current value from registry\n var regCurrentValue = _registryService.GetValue(\n RegistryExtensions.GetRegistryHiveString(regSetting.Hive) + \"\\\\\" + regSetting.SubKey,\n regSetting.Name);\n LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n }\n }\n else if (RegistrySetting != null)\n {\n // For single setting\n LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(RegistrySetting, valueObject));\n }\n }\n\n // Check if restart is required\n bool requiresRestart = Name.Contains(\"restart\", StringComparison.OrdinalIgnoreCase);\n if (requiresRestart && _dialogService != null)\n {\n _dialogService.ShowMessage(\n \"This change requires a system restart to take effect.\",\n \"Restart Required\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to apply setting: {Name}\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = \"Failed to apply setting\";\n\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"Failed to apply {Name}. This may require administrator privileges.\",\n \"Error\");\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying setting: {ex.Message}\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = $\"Error: {ex.Message}\";\n\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"An error occurred: {ex.Message}\",\n \"Error\");\n }\n }\n finally\n {\n IsApplying = false;\n }\n }\n\n /// \n /// Gets all settings from all view models in the application.\n /// \n /// A list of all settings, or null if none found.\n protected virtual List? GetAllSettings()\n {\n try\n {\n _logService?.Log(LogLevel.Info, $\"Getting all settings for dependency check\");\n \n // Check if we have a dependency manager with a settings registry\n if (_dependencyManager is IDependencyManager dependencyManager && \n dependencyManager.GetType().GetProperty(\"SettingsRegistry\")?.GetValue(dependencyManager) is ISettingsRegistry settingsRegistry)\n {\n var settings = settingsRegistry.GetAllSettings();\n if (settings.Count > 0)\n {\n _logService?.Log(LogLevel.Info, $\"Found {settings.Count} settings in settings registry via dependency manager\");\n return settings;\n }\n }\n \n // If no settings registry is available or it's empty, fall back to the original implementation\n var result = new List();\n var app = System.Windows.Application.Current;\n if (app == null) return null;\n\n // Try to find all settings view models\n foreach (System.Windows.Window window in app.Windows)\n {\n if (window.DataContext != null)\n {\n // Look for view models that have a Settings property\n var settingsProperties = window.DataContext.GetType().GetProperties()\n .Where(p => p.Name == \"Settings\" || p.Name.EndsWith(\"Settings\"));\n\n foreach (var prop in settingsProperties)\n {\n var value = prop.GetValue(window.DataContext);\n if (value is IEnumerable settings)\n {\n result.AddRange(settings);\n _logService?.Log(LogLevel.Info, $\"Found {settings.Count()} settings in {prop.Name}\");\n }\n }\n\n // Also look for view models that might contain other view models with settings\n var viewModelProperties = window.DataContext.GetType().GetProperties()\n .Where(p => p.Name.EndsWith(\"ViewModel\") && p.Name != \"DataContext\");\n\n foreach (var prop in viewModelProperties)\n {\n var viewModel = prop.GetValue(window.DataContext);\n if (viewModel != null)\n {\n var nestedSettingsProps = viewModel.GetType().GetProperties()\n .Where(p => p.Name == \"Settings\" || p.Name.EndsWith(\"Settings\"));\n\n foreach (var nestedProp in nestedSettingsProps)\n {\n var value = nestedProp.GetValue(viewModel);\n if (value is IEnumerable settings)\n {\n result.AddRange(settings);\n _logService?.Log(LogLevel.Info, $\"Found {settings.Count()} settings in {prop.Name}.{nestedProp.Name}\");\n }\n }\n }\n }\n }\n }\n\n // If we found settings, return them\n if (result.Count > 0)\n {\n _logService?.Log(LogLevel.Info, $\"Found a total of {result.Count} settings through property scanning\");\n \n // Log the settings we found\n foreach (var setting in result)\n {\n _logService?.Log(LogLevel.Info, $\"Found setting: {setting.Id} - {setting.Name}\");\n }\n \n // If we found a settings registry earlier, register these settings for future use\n if (_dependencyManager is IDependencyManager dependencyManager2 && \n dependencyManager2.GetType().GetProperty(\"SettingsRegistry\")?.GetValue(dependencyManager2) is ISettingsRegistry settingsRegistry2)\n {\n foreach (var setting in result)\n {\n settingsRegistry2.RegisterSetting(setting);\n }\n _logService?.Log(LogLevel.Info, $\"Registered {result.Count} settings in settings registry for future use\");\n }\n \n return result;\n }\n\n _logService?.Log(LogLevel.Warning, \"Could not find any settings for dependency check\");\n return null;\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Error getting all settings: {ex.Message}\");\n return null;\n }\n }\n \n /// \n /// Gets the PowerPlanService from the application services.\n /// \n /// The PowerPlanService, or null if not found.\n protected Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService? GetPowerPlanService()\n {\n // If we already have a PowerPlanService, return it\n if (_powerPlanService != null)\n {\n return _powerPlanService;\n }\n \n try\n {\n // Try to get the PowerPlanService from the application services\n var app = System.Windows.Application.Current;\n if (app == null) return null;\n \n // Check if the application has a GetService method\n var getServiceMethod = app.GetType().GetMethod(\"GetService\", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);\n if (getServiceMethod != null)\n {\n // Call the GetService method to get the PowerPlanService\n var powerPlanService = getServiceMethod.Invoke(app, new object[] { typeof(Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService) });\n return powerPlanService as Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService;\n }\n \n // If the application doesn't have a GetService method, try to find the PowerPlanService in the application resources\n foreach (System.Windows.Window window in app.Windows)\n {\n if (window.DataContext != null)\n {\n // Look for view models that might have a PowerPlanService property\n var powerPlanServiceProperty = window.DataContext.GetType().GetProperty(\"PowerPlanService\");\n if (powerPlanServiceProperty != null)\n {\n var powerPlanService = powerPlanServiceProperty.GetValue(window.DataContext);\n if (powerPlanService is Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService)\n {\n return powerPlanService as Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService;\n }\n }\n \n // Look for view models that might contain other view models with a PowerPlanService property\n var viewModelProperties = window.DataContext.GetType().GetProperties()\n .Where(p => p.Name.EndsWith(\"ViewModel\") && p.Name != \"DataContext\");\n \n foreach (var prop in viewModelProperties)\n {\n var viewModel = prop.GetValue(window.DataContext);\n if (viewModel != null)\n {\n var nestedPowerPlanServiceProperty = viewModel.GetType().GetProperty(\"PowerPlanService\");\n if (nestedPowerPlanServiceProperty != null)\n {\n var powerPlanService = nestedPowerPlanServiceProperty.GetValue(viewModel);\n if (powerPlanService is Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService)\n {\n return powerPlanService as Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService;\n }\n }\n \n // Check if this view model has a _powerPlanService field\n var powerPlanServiceField = viewModel.GetType().GetField(\"_powerPlanService\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (powerPlanServiceField != null)\n {\n var powerPlanService = powerPlanServiceField.GetValue(viewModel);\n if (powerPlanService is Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService)\n {\n return powerPlanService as Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService;\n }\n }\n }\n }\n }\n }\n \n return null;\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Error getting PowerPlanService: {ex.Message}\");\n return null;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/ConfigurationCoordinatorService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows.Input;\nusing Microsoft.Extensions.DependencyInjection;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Customize.ViewModels;\nusing Winhance.WPF.Features.Optimize.ViewModels;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\nusing Winhance.WPF.Features.SoftwareApps.Models;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for coordinating configuration operations across multiple view models.\n /// \n public class ConfigurationCoordinatorService : IConfigurationCoordinatorService\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly IConfigurationService _configurationService;\n private readonly ILogService _logService;\n private readonly IDialogService _dialogService;\n private readonly IRegistryService _registryService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The configuration service.\n /// The log service.\n /// The dialog service.\n public ConfigurationCoordinatorService(\n IServiceProvider serviceProvider,\n IConfigurationService configurationService,\n ILogService logService,\n IDialogService dialogService,\n IRegistryService registryService)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n }\n\n /// \n /// Creates a unified configuration file containing settings from all view models.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file.\n public async Task CreateUnifiedConfigurationAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Creating unified configuration from all view models\");\n \n // Create a dictionary to hold settings from all sections\n var sectionSettings = new Dictionary>();\n\n // Get all view models from the service provider\n var windowsAppsViewModel = _serviceProvider.GetService();\n var externalAppsViewModel = _serviceProvider.GetService();\n var customizeViewModel = _serviceProvider.GetService();\n var optimizeViewModel = _serviceProvider.GetService();\n\n // Add settings from each view model to the dictionary\n if (windowsAppsViewModel != null)\n {\n _logService.Log(LogLevel.Debug, \"Processing WindowsAppsViewModel\");\n \n // Ensure the view model is initialized\n if (!windowsAppsViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"WindowsAppsViewModel not initialized, loading items\");\n await windowsAppsViewModel.LoadItemsAsync();\n }\n \n // Log the number of items in the view model\n var itemsProperty = windowsAppsViewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(windowsAppsViewModel) as System.Collections.ICollection;\n if (items != null)\n {\n _logService.Log(LogLevel.Debug, $\"WindowsAppsViewModel has {items.Count} items\");\n \n // Log the type of the first item\n if (items.Count > 0)\n {\n var enumerator = items.GetEnumerator();\n enumerator.MoveNext();\n var firstItem = enumerator.Current;\n if (firstItem != null)\n {\n _logService.Log(LogLevel.Debug, $\"First item type: {firstItem.GetType().FullName}\");\n }\n }\n }\n }\n \n // For WindowsAppsViewModel, we need to use SaveConfig to get the settings\n // This is because the Items property is not of type ISettingItem\n // We'll use reflection to call the SaveConfig method\n var saveConfigMethod = windowsAppsViewModel.GetType().GetMethod(\"SaveConfig\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);\n \n // Instead of trying to call SaveConfig, directly access the Items collection\n // and convert them to WindowsAppSettingItems\n var windowsAppsItemsProperty = windowsAppsViewModel.GetType().GetProperty(\"Items\");\n if (windowsAppsItemsProperty != null)\n {\n var items = windowsAppsItemsProperty.GetValue(windowsAppsViewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n _logService.Log(LogLevel.Info, \"Directly accessing Items collection from WindowsAppsViewModel\");\n \n // Convert each WindowsApp to WindowsAppSettingItem\n var windowsAppSettingItems = new List();\n \n foreach (var item in items)\n {\n if (item is Winhance.WPF.Features.SoftwareApps.Models.WindowsApp windowsApp)\n {\n windowsAppSettingItems.Add(new WindowsAppSettingItem(windowsApp));\n _logService.Log(LogLevel.Debug, $\"Added WindowsAppSettingItem for {windowsApp.Name}\");\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Created {windowsAppSettingItems.Count} WindowsAppSettingItems\");\n \n // Always add WindowsApps to sectionSettings, even if empty\n sectionSettings[\"WindowsApps\"] = windowsAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added WindowsApps section with {windowsAppSettingItems.Count} items\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Items collection is null\");\n \n // Create some default WindowsApps\n var defaultApps = new[]\n {\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Microsoft Edge\",\n PackageName = \"Microsoft.MicrosoftEdge\",\n IsSelected = true,\n Description = \"Microsoft Edge browser\"\n },\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Calculator\",\n PackageName = \"Microsoft.WindowsCalculator\",\n IsSelected = true,\n Description = \"Windows Calculator app\"\n },\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Photos\",\n PackageName = \"Microsoft.Windows.Photos\",\n IsSelected = true,\n Description = \"Windows Photos app\"\n }\n };\n \n var defaultWindowsAppSettingItems = new List();\n foreach (var app in defaultApps)\n {\n defaultWindowsAppSettingItems.Add(new WindowsAppSettingItem(app));\n }\n \n // Always add WindowsApps to sectionSettings, even if using defaults\n sectionSettings[\"WindowsApps\"] = defaultWindowsAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added WindowsApps section with {defaultWindowsAppSettingItems.Count} default items\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Error, \"Could not find Items property in WindowsAppsViewModel\");\n \n // Create some default WindowsApps\n var defaultApps = new[]\n {\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Microsoft Edge\",\n PackageName = \"Microsoft.MicrosoftEdge\",\n IsSelected = true,\n Description = \"Microsoft Edge browser\"\n },\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Calculator\",\n PackageName = \"Microsoft.WindowsCalculator\",\n IsSelected = true,\n Description = \"Windows Calculator app\"\n },\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Photos\",\n PackageName = \"Microsoft.Windows.Photos\",\n IsSelected = true,\n Description = \"Windows Photos app\"\n }\n };\n \n var defaultWindowsAppSettingItems = new List();\n foreach (var app in defaultApps)\n {\n defaultWindowsAppSettingItems.Add(new WindowsAppSettingItem(app));\n }\n \n // Always add WindowsApps to sectionSettings, even if using defaults\n sectionSettings[\"WindowsApps\"] = defaultWindowsAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added WindowsApps section with {defaultWindowsAppSettingItems.Count} default items\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"WindowsAppsViewModel is null\");\n }\n\n if (externalAppsViewModel != null)\n {\n // Ensure the view model is initialized\n if (!externalAppsViewModel.IsInitialized)\n {\n await externalAppsViewModel.LoadItemsAsync();\n }\n \n // For ExternalAppsViewModel, we need to get the settings directly\n // This is because the Items property is not of type ISettingItem\n var externalAppsItems = new List();\n \n // Get the Items property\n var itemsProperty = externalAppsViewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(externalAppsViewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n foreach (var item in items)\n {\n if (item is Winhance.WPF.Features.SoftwareApps.Models.ExternalApp externalApp)\n {\n externalAppsItems.Add(new ExternalAppSettingItem(externalApp));\n }\n }\n }\n }\n \n // Add the settings to the dictionary\n sectionSettings[\"ExternalApps\"] = externalAppsItems;\n _logService.Log(LogLevel.Info, $\"Added ExternalApps section with {externalAppsItems.Count} items\");\n }\n\n if (customizeViewModel != null)\n {\n // Ensure the view model is initialized\n if (!customizeViewModel.IsInitialized)\n {\n await customizeViewModel.LoadItemsAsync();\n }\n \n // For CustomizeViewModel, we need to get the settings directly\n var customizeItems = new List();\n \n // Get the Items property\n var itemsProperty = customizeViewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(customizeViewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n foreach (var item in items)\n {\n if (item is ISettingItem settingItem)\n {\n customizeItems.Add(settingItem);\n }\n }\n }\n }\n \n // Add the settings to the dictionary\n sectionSettings[\"Customize\"] = customizeItems;\n _logService.Log(LogLevel.Info, $\"Added Customize section with {customizeItems.Count} items\");\n }\n\n if (optimizeViewModel != null)\n {\n _logService.Log(LogLevel.Debug, \"Processing OptimizeViewModel\");\n \n // Ensure the view model is initialized\n if (!optimizeViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"OptimizeViewModel not initialized, initializing now\");\n await optimizeViewModel.InitializeCommand.ExecuteAsync(null);\n \n // After initialization, ensure items are loaded\n await optimizeViewModel.LoadItemsAsync();\n _logService.Log(LogLevel.Debug, $\"OptimizeViewModel initialized and loaded with {optimizeViewModel.Items?.Count ?? 0} items\");\n }\n else\n {\n _logService.Log(LogLevel.Debug, \"OptimizeViewModel already initialized\");\n \n // Even if initialized, make sure items are loaded\n if (optimizeViewModel.Items == null || optimizeViewModel.Items.Count == 0)\n {\n _logService.Log(LogLevel.Debug, \"OptimizeViewModel items not loaded, loading now\");\n await optimizeViewModel.LoadItemsAsync();\n _logService.Log(LogLevel.Debug, $\"OptimizeViewModel items loaded, count: {optimizeViewModel.Items?.Count ?? 0}\");\n }\n }\n \n // For OptimizeViewModel, we need to get the settings directly\n var optimizeItems = new List();\n \n // Get the Items property\n var itemsProperty = optimizeViewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(optimizeViewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n _logService.Log(LogLevel.Debug, $\"OptimizeViewModel has items collection, enumerating\");\n \n // Log the type of the first item\n var enumerator = items.GetEnumerator();\n if (enumerator.MoveNext() && enumerator.Current != null)\n {\n _logService.Log(LogLevel.Debug, $\"First item type: {enumerator.Current.GetType().FullName}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"OptimizeViewModel items collection is empty or first item is null\");\n }\n \n // Reset the enumerator\n items = itemsProperty.GetValue(optimizeViewModel) as System.Collections.IEnumerable;\n \n foreach (var item in items)\n {\n if (item is Winhance.WPF.Features.Common.Models.ApplicationSettingItem applicationItem)\n {\n optimizeItems.Add(applicationItem);\n _logService.Log(LogLevel.Debug, $\"Added ApplicationSettingItem for {applicationItem.Name}\");\n }\n else if (item is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added generic ISettingItem for {settingItem.Name}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Item of type {item?.GetType().FullName ?? \"null\"} is not an ISettingItem\");\n }\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"OptimizeViewModel items collection is null\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Error, \"Could not find Items property in OptimizeViewModel\");\n }\n \n // If we still don't have any items, collect them directly from the child view models\n // This avoids showing the Optimizations Custom Dialog before the Save Dialog\n if (optimizeItems.Count == 0)\n {\n _logService.Log(LogLevel.Warning, \"No items found in OptimizeViewModel, collecting from child view models\");\n \n // Get all the child view models using reflection\n var childViewModels = new List();\n var properties = optimizeViewModel.GetType().GetProperties();\n \n foreach (var property in properties)\n {\n if (property.Name.EndsWith(\"ViewModel\") &&\n property.Name != \"OptimizeViewModel\" &&\n property.PropertyType.Name.Contains(\"Optimizations\"))\n {\n var childViewModel = property.GetValue(optimizeViewModel);\n if (childViewModel != null)\n {\n childViewModels.Add(childViewModel);\n _logService.Log(LogLevel.Debug, $\"Found child view model: {property.Name}\");\n }\n }\n }\n \n // Collect settings from each child view model\n foreach (var childViewModel in childViewModels)\n {\n var settingsProperty = childViewModel.GetType().GetProperty(\"Settings\");\n if (settingsProperty != null)\n {\n var settings = settingsProperty.GetValue(childViewModel) as System.Collections.IEnumerable;\n if (settings != null)\n {\n foreach (var setting in settings)\n {\n // Use dynamic to avoid type issues\n dynamic settingViewModel = setting;\n try\n {\n // Convert setting to ApplicationSettingItem using dynamic\n var item = new Winhance.WPF.Features.Common.Models.ApplicationSettingItem(_registryService, _dialogService, _logService);\n \n // Copy properties using reflection to avoid type issues\n try { item.Id = settingViewModel.Id; } catch { }\n try { item.Name = settingViewModel.Name; } catch { }\n try { item.Description = settingViewModel.Description; } catch { }\n try { item.IsSelected = settingViewModel.IsSelected; } catch { }\n try { item.GroupName = settingViewModel.GroupName; } catch { }\n try { item.IsVisible = settingViewModel.IsVisible; } catch { }\n try { item.ControlType = settingViewModel.ControlType; } catch { }\n try { item.SliderValue = settingViewModel.SliderValue; } catch { }\n try { item.SliderSteps = settingViewModel.SliderSteps; } catch { }\n try { item.Status = settingViewModel.Status; } catch { }\n try { item.StatusMessage = settingViewModel.StatusMessage; } catch { }\n try { item.RegistrySetting = settingViewModel.RegistrySetting; } catch { }\n \n // Skip LinkedRegistrySettings for now as it's causing issues\n \n optimizeItems.Add(item);\n _logService.Log(LogLevel.Debug, $\"Added setting from {childViewModel.GetType().Name}: {item.Name}\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error converting setting: {ex.Message}\");\n \n // Try to add as generic ISettingItem if possible\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added generic setting from {childViewModel.GetType().Name}: {settingItem.Name}\");\n }\n }\n }\n }\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Collected {optimizeItems.Count} items from child view models\");\n \n // If we still don't have any items, add a placeholder as a last resort\n if (optimizeItems.Count == 0)\n {\n _logService.Log(LogLevel.Warning, \"No items found in child view models, adding placeholder\");\n \n var placeholderItem = new Winhance.WPF.Features.Common.Models.ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = \"OptimizePlaceholder\",\n Name = \"Optimization Settings\",\n Description = \"Default optimization settings\",\n IsSelected = true,\n GroupName = \"Optimizations\"\n };\n \n optimizeItems.Add(placeholderItem);\n _logService.Log(LogLevel.Info, \"Added placeholder item to Optimize section\");\n }\n }\n \n // Add the settings to the dictionary\n sectionSettings[\"Optimize\"] = optimizeItems;\n _logService.Log(LogLevel.Info, $\"Added Optimize section with {optimizeItems.Count} items\");\n }\n\n // Create a list of all available sections - include all sections by default\n var availableSections = new List { \"WindowsApps\", \"ExternalApps\", \"Customize\", \"Optimize\" };\n\n // Create and return the unified configuration\n var unifiedConfig = _configurationService.CreateUnifiedConfiguration(sectionSettings, availableSections);\n \n _logService.Log(LogLevel.Info, \"Successfully created unified configuration from all view models\");\n \n return unifiedConfig;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating unified configuration: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Applies a unified configuration to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n public async Task ApplyUnifiedConfigurationAsync(UnifiedConfigurationFile config, IEnumerable selectedSections)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Applying unified configuration to selected sections: {string.Join(\", \", selectedSections)}\");\n \n // Log the contents of the unified configuration\n _logService.Log(LogLevel.Debug, $\"Unified configuration contains: \" +\n $\"WindowsApps: {config.WindowsApps?.Items?.Count ?? 0} items, \" +\n $\"ExternalApps: {config.ExternalApps?.Items?.Count ?? 0} items, \" +\n $\"Customize: {config.Customize?.Items?.Count ?? 0} items, \" +\n $\"Optimize: {config.Optimize?.Items?.Count ?? 0} items\");\n \n // Validate the configuration\n if (config == null)\n {\n _logService.Log(LogLevel.Error, \"Unified configuration is null\");\n return false;\n }\n \n // Validate the selected sections\n if (selectedSections == null || !selectedSections.Any())\n {\n _logService.Log(LogLevel.Error, \"No sections selected for import\");\n return false;\n }\n \n bool result = true;\n var sectionResults = new Dictionary();\n\n foreach (var section in selectedSections)\n {\n _logService.Log(LogLevel.Info, $\"Processing section: {section}\");\n \n // Extract the section from the unified configuration\n var configFile = _configurationService.ExtractSectionFromUnifiedConfiguration(config, section);\n \n if (configFile == null)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to extract section {section} from unified configuration\");\n sectionResults[section] = false;\n result = false;\n continue;\n }\n \n if (configFile.Items == null || !configFile.Items.Any())\n {\n _logService.Log(LogLevel.Warning, $\"Section {section} is empty or not included in the unified configuration\");\n sectionResults[section] = false;\n continue;\n }\n\n _logService.Log(LogLevel.Info, $\"Extracted section {section} with {configFile.Items.Count} items\");\n \n // Log all items for debugging\n foreach (var item in configFile.Items)\n {\n _logService.Log(LogLevel.Debug, $\"Item in {section}: {item.Name}, IsSelected: {item.IsSelected}, ControlType: {item.ControlType}\");\n }\n\n // Apply the configuration to the appropriate view model\n bool sectionResult = false;\n \n switch (section)\n {\n case \"WindowsApps\":\n _logService.Log(LogLevel.Info, $\"Getting WindowsAppsViewModel from service provider\");\n var windowsAppsViewModel = _serviceProvider.GetService();\n if (windowsAppsViewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"WindowsAppsViewModel found, importing configuration\");\n \n // Ensure the view model is initialized\n if (!windowsAppsViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, $\"WindowsAppsViewModel not initialized, initializing now\");\n await windowsAppsViewModel.LoadItemsAsync();\n }\n \n // Use the view model's own import method\n sectionResult = await ImportWindowsAppsConfig(windowsAppsViewModel, configFile);\n _logService.Log(LogLevel.Info, $\"WindowsApps import result: {sectionResult}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"WindowsAppsViewModel not available\");\n sectionResult = false;\n }\n break;\n\n case \"ExternalApps\":\n _logService.Log(LogLevel.Info, $\"Getting ExternalAppsViewModel from service provider\");\n var externalAppsViewModel = _serviceProvider.GetService();\n if (externalAppsViewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"ExternalAppsViewModel found, importing configuration\");\n \n // Ensure the view model is initialized\n if (!externalAppsViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, $\"ExternalAppsViewModel not initialized, initializing now\");\n await externalAppsViewModel.LoadItemsAsync();\n }\n \n // Use the view model's own import method\n sectionResult = await ImportExternalAppsConfig(externalAppsViewModel, configFile);\n _logService.Log(LogLevel.Info, $\"ExternalApps import result: {sectionResult}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"ExternalAppsViewModel not available\");\n sectionResult = false;\n }\n break;\n\n case \"Customize\":\n _logService.Log(LogLevel.Info, $\"Getting CustomizeViewModel from service provider\");\n var customizeViewModel = _serviceProvider.GetService();\n if (customizeViewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"CustomizeViewModel found, importing configuration\");\n \n // Ensure the view model is initialized\n if (!customizeViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, $\"CustomizeViewModel not initialized, initializing now\");\n await customizeViewModel.InitializeCommand.ExecuteAsync(null);\n }\n \n // Use the view model's own import method\n sectionResult = await ImportCustomizeConfig(customizeViewModel, configFile);\n _logService.Log(LogLevel.Info, $\"Customize import result: {sectionResult}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"CustomizeViewModel not available\");\n sectionResult = false;\n }\n break;\n\n case \"Optimize\":\n _logService.Log(LogLevel.Info, $\"Getting OptimizeViewModel from service provider\");\n var optimizeViewModel = _serviceProvider.GetService();\n if (optimizeViewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"OptimizeViewModel found, importing configuration\");\n \n // Ensure the view model is initialized\n if (!optimizeViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, $\"OptimizeViewModel not initialized, initializing now\");\n await optimizeViewModel.InitializeCommand.ExecuteAsync(null);\n }\n \n // Use the view model's own import method\n sectionResult = await ImportOptimizeConfig(optimizeViewModel, configFile);\n _logService.Log(LogLevel.Info, $\"Optimize import result: {sectionResult}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"OptimizeViewModel not available\");\n sectionResult = false;\n }\n break;\n\n default:\n _logService.Log(LogLevel.Warning, $\"Unknown section: {section}\");\n sectionResult = false;\n break;\n }\n \n sectionResults[section] = sectionResult;\n if (!sectionResult)\n {\n result = false;\n }\n }\n\n // Log the results for each section\n _logService.Log(LogLevel.Info, \"Import results by section:\");\n foreach (var sectionResult in sectionResults)\n {\n _logService.Log(LogLevel.Info, $\" {sectionResult.Key}: {(sectionResult.Value ? \"Success\" : \"Failed\")}\");\n }\n\n _logService.Log(LogLevel.Info, $\"Finished applying unified configuration to selected sections. Overall result: {(result ? \"Success\" : \"Partial failure\")}\");\n return result;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying unified configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false; // Return false instead of throwing to prevent crashing the application\n }\n }\n\n /// \n /// Imports a configuration to a view model using reflection to call its ImportConfig method.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n private async Task ImportConfigToViewModel(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n string viewModelTypeName = viewModel.GetType().Name;\n _logService.Log(LogLevel.Info, $\"Starting to import configuration to {viewModelTypeName}\");\n _logService.Log(LogLevel.Debug, $\"Configuration file has {configFile.Items?.Count ?? 0} items\");\n \n // Log the first few items for debugging\n if (configFile.Items != null && configFile.Items.Any())\n {\n foreach (var item in configFile.Items.Take(5))\n {\n _logService.Log(LogLevel.Debug, $\"Item: {item.Name}, IsSelected: {item.IsSelected}, ControlType: {item.ControlType}\");\n }\n }\n\n // Store the original configuration file\n var originalConfigFile = configFile;\n\n // Create a wrapper for the configuration service\n var configServiceWrapper = new ConfigurationServiceWrapper(_configurationService, originalConfigFile);\n _logService.Log(LogLevel.Debug, \"Created configuration service wrapper\");\n\n // Replace the configuration service in the view model\n var configServiceField = viewModel.GetType().GetField(\"_configurationService\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n\n if (configServiceField != null)\n {\n _logService.Log(LogLevel.Debug, \"Found _configurationService field in view model\");\n \n // Store the original service\n var originalService = configServiceField.GetValue(viewModel);\n _logService.Log(LogLevel.Debug, $\"Original service type: {originalService?.GetType().Name ?? \"null\"}\");\n\n try\n {\n // Replace with our wrapper\n configServiceField.SetValue(viewModel, configServiceWrapper);\n _logService.Log(LogLevel.Debug, \"Replaced configuration service with wrapper\");\n\n // Special handling for different view model types\n bool importResult = false;\n \n if (viewModelTypeName.Contains(\"WindowsApps\"))\n {\n importResult = await ImportWindowsAppsConfig(viewModel, configFile);\n }\n else if (viewModelTypeName.Contains(\"ExternalApps\"))\n {\n importResult = await ImportExternalAppsConfig(viewModel, configFile);\n }\n else if (viewModelTypeName.Contains(\"Customize\"))\n {\n importResult = await ImportCustomizeConfig(viewModel, configFile);\n }\n else if (viewModelTypeName.Contains(\"Optimize\"))\n {\n importResult = await ImportOptimizeConfig(viewModel, configFile);\n }\n else\n {\n // Generic import for other view model types\n importResult = await ImportGenericConfig(viewModel, configFile);\n }\n \n if (importResult)\n {\n _logService.Log(LogLevel.Info, $\"Successfully imported configuration to {viewModelTypeName}\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Failed to import configuration to {viewModelTypeName}\");\n return false;\n }\n }\n finally\n {\n // Restore the original service\n configServiceField.SetValue(viewModel, originalService);\n _logService.Log(LogLevel.Debug, \"Restored original configuration service\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Could not find _configurationService field in {viewModelTypeName}\");\n \n // Try direct application as a fallback\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, $\"Successfully applied configuration directly to {viewModelTypeName}\");\n return true;\n }\n \n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing configuration to {viewModel.GetType().Name}: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Imports configuration to WindowsAppsViewModel.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// True if successful, false otherwise.\n private async Task ImportWindowsAppsConfig(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Importing configuration to WindowsAppsViewModel\");\n \n // First try using the ImportConfigCommand\n var importCommand = viewModel.GetType().GetProperty(\"ImportConfigCommand\")?.GetValue(viewModel) as IAsyncRelayCommand;\n if (importCommand != null)\n {\n _logService.Log(LogLevel.Debug, \"Found ImportConfigCommand, executing...\");\n await importCommand.ExecuteAsync(null);\n \n // Verify that the configuration was applied\n bool configApplied = await VerifyConfigurationApplied(viewModel, configFile);\n \n if (configApplied)\n {\n _logService.Log(LogLevel.Info, \"Successfully imported configuration using ImportConfigCommand\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Configuration may not have been properly applied using ImportConfigCommand\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"ImportConfigCommand not found\");\n }\n \n // If we get here, try direct application\n _logService.Log(LogLevel.Info, \"Falling back to direct application\");\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n \n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, \"Successfully applied configuration directly\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Failed to apply configuration directly\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing WindowsApps configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Imports configuration to ExternalAppsViewModel.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// True if successful, false otherwise.\n private async Task ImportExternalAppsConfig(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Importing configuration to ExternalAppsViewModel\");\n \n // First try using the ImportConfigCommand\n var importCommand = viewModel.GetType().GetProperty(\"ImportConfigCommand\")?.GetValue(viewModel) as IAsyncRelayCommand;\n if (importCommand != null)\n {\n _logService.Log(LogLevel.Debug, \"Found ImportConfigCommand, executing...\");\n await importCommand.ExecuteAsync(null);\n \n // Verify that the configuration was applied\n bool configApplied = await VerifyConfigurationApplied(viewModel, configFile);\n \n if (configApplied)\n {\n _logService.Log(LogLevel.Info, \"Successfully imported configuration using ImportConfigCommand\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Configuration may not have been properly applied using ImportConfigCommand\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"ImportConfigCommand not found\");\n }\n \n // If we get here, try direct application\n _logService.Log(LogLevel.Info, \"Falling back to direct application\");\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n \n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, \"Successfully applied configuration directly\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Failed to apply configuration directly\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing ExternalApps configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Imports configuration to CustomizeViewModel.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// True if successful, false otherwise.\n private async Task ImportCustomizeConfig(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Importing configuration to CustomizeViewModel\");\n \n // First try using the ImportConfigCommand\n var importCommand = viewModel.GetType().GetProperty(\"ImportConfigCommand\")?.GetValue(viewModel) as IAsyncRelayCommand;\n if (importCommand != null)\n {\n _logService.Log(LogLevel.Debug, \"Found ImportConfigCommand, executing...\");\n await importCommand.ExecuteAsync(null);\n \n // Verify that the configuration was applied\n bool configApplied = await VerifyConfigurationApplied(viewModel, configFile);\n \n if (configApplied)\n {\n _logService.Log(LogLevel.Info, \"Successfully imported configuration using ImportConfigCommand\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Configuration may not have been properly applied using ImportConfigCommand\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"ImportConfigCommand not found\");\n }\n \n // If we get here, try direct application\n _logService.Log(LogLevel.Info, \"Falling back to direct application\");\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n \n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, \"Successfully applied configuration directly\");\n \n // For CustomizeViewModel, try to call ApplyCustomizations if available\n var applyCustomizationsMethod = viewModel.GetType().GetMethod(\"ApplyCustomizations\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (applyCustomizationsMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling ApplyCustomizations method\");\n \n // Check if the method takes parameters\n var parameters = applyCustomizationsMethod.GetParameters();\n if (parameters.Length == 0)\n {\n applyCustomizationsMethod.Invoke(viewModel, null);\n }\n else if (parameters.Length == 1 && parameters[0].ParameterType == typeof(bool))\n {\n // If it takes a boolean parameter, pass true to force application\n applyCustomizationsMethod.Invoke(viewModel, new object[] { true });\n }\n }\n \n // Additionally, iterate through all items and ensure their registry settings are applied\n var itemsProperty = viewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(viewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n _logService.Log(LogLevel.Debug, \"Iterating through items to ensure registry settings are applied\");\n foreach (var item in items)\n {\n var applySettingCommand = item.GetType().GetProperty(\"ApplySettingCommand\")?.GetValue(item) as ICommand;\n if (applySettingCommand != null && applySettingCommand.CanExecute(null))\n {\n var nameProperty = item.GetType().GetProperty(\"Name\");\n var name = nameProperty?.GetValue(item)?.ToString() ?? \"unknown\";\n _logService.Log(LogLevel.Debug, $\"Executing ApplySettingCommand for {name}\");\n applySettingCommand.Execute(null);\n }\n }\n }\n }\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Failed to apply configuration directly\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing Customize configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Imports configuration to OptimizeViewModel.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// True if successful, false otherwise.\n private async Task ImportOptimizeConfig(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Importing configuration to OptimizeViewModel\");\n \n // First try using the ImportConfigCommand\n var importCommand = viewModel.GetType().GetProperty(\"ImportConfigCommand\")?.GetValue(viewModel) as IAsyncRelayCommand;\n if (importCommand != null)\n {\n _logService.Log(LogLevel.Debug, \"Found ImportConfigCommand, executing...\");\n await importCommand.ExecuteAsync(null);\n \n // Verify that the configuration was applied\n bool configApplied = await VerifyConfigurationApplied(viewModel, configFile);\n \n if (configApplied)\n {\n _logService.Log(LogLevel.Info, \"Successfully imported configuration using ImportConfigCommand\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Configuration may not have been properly applied using ImportConfigCommand\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"ImportConfigCommand not found\");\n }\n \n // If we get here, try direct application\n _logService.Log(LogLevel.Info, \"Falling back to direct application\");\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n \n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, \"Successfully applied configuration directly\");\n \n // For OptimizeViewModel, try to call ApplyOptimizations if available\n var applyOptimizationsMethod = viewModel.GetType().GetMethod(\"ApplyOptimizations\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (applyOptimizationsMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling ApplyOptimizations method\");\n \n // Check if the method takes parameters\n var parameters = applyOptimizationsMethod.GetParameters();\n if (parameters.Length == 0)\n {\n applyOptimizationsMethod.Invoke(viewModel, null);\n }\n else if (parameters.Length == 1 && parameters[0].ParameterType == typeof(bool))\n {\n // If it takes a boolean parameter, pass true to force application\n applyOptimizationsMethod.Invoke(viewModel, new object[] { true });\n }\n }\n \n // Additionally, iterate through all items and ensure their registry settings are applied\n var itemsProperty = viewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(viewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n _logService.Log(LogLevel.Debug, \"Iterating through items to ensure registry settings are applied\");\n foreach (var item in items)\n {\n var applySettingCommand = item.GetType().GetProperty(\"ApplySettingCommand\")?.GetValue(item) as ICommand;\n if (applySettingCommand != null && applySettingCommand.CanExecute(null))\n {\n var nameProperty = item.GetType().GetProperty(\"Name\");\n var name = nameProperty?.GetValue(item)?.ToString() ?? \"unknown\";\n _logService.Log(LogLevel.Debug, $\"Executing ApplySettingCommand for {name}\");\n applySettingCommand.Execute(null);\n }\n }\n }\n }\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Failed to apply configuration directly\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing Optimize configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Imports configuration to a generic view model.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// True if successful, false otherwise.\n private async Task ImportGenericConfig(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Importing configuration to generic view model\");\n \n // First try using the ImportConfigCommand\n var importCommand = viewModel.GetType().GetProperty(\"ImportConfigCommand\")?.GetValue(viewModel) as IAsyncRelayCommand;\n if (importCommand != null)\n {\n _logService.Log(LogLevel.Debug, \"Found ImportConfigCommand, executing...\");\n await importCommand.ExecuteAsync(null);\n \n // Verify that the configuration was applied\n bool configApplied = await VerifyConfigurationApplied(viewModel, configFile);\n \n if (configApplied)\n {\n _logService.Log(LogLevel.Info, \"Successfully imported configuration using ImportConfigCommand\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Configuration may not have been properly applied using ImportConfigCommand\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"ImportConfigCommand not found\");\n }\n \n // If we get here, try direct application\n _logService.Log(LogLevel.Info, \"Falling back to direct application\");\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n \n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, \"Successfully applied configuration directly\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Failed to apply configuration directly\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing generic configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Verifies that the configuration was properly applied to the view model.\n /// \n /// The view model to verify.\n /// The configuration file that was applied.\n /// True if the configuration was applied, false otherwise.\n private async Task VerifyConfigurationApplied(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Debug, $\"Verifying configuration was applied to {viewModel.GetType().Name}\");\n \n // Get the Items property from the view model\n var itemsProperty = viewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty == null)\n {\n _logService.Log(LogLevel.Warning, $\"Could not find Items property in {viewModel.GetType().Name}\");\n return false;\n }\n \n var items = itemsProperty.GetValue(viewModel) as System.Collections.IEnumerable;\n if (items == null)\n {\n _logService.Log(LogLevel.Warning, $\"Items collection is null in {viewModel.GetType().Name}\");\n return false;\n }\n \n // Check if at least some items have the expected IsSelected state\n int matchCount = 0;\n int totalChecked = 0;\n \n // Create dictionaries of config items by name and ID for faster lookup\n var configItemsByName = new Dictionary(StringComparer.OrdinalIgnoreCase);\n var configItemsById = new Dictionary(StringComparer.OrdinalIgnoreCase);\n \n if (configFile.Items != null)\n {\n foreach (var item in configFile.Items)\n {\n if (!string.IsNullOrEmpty(item.Name) && !configItemsByName.ContainsKey(item.Name))\n {\n configItemsByName.Add(item.Name, item);\n }\n \n if (item.CustomProperties.TryGetValue(\"Id\", out var id) && id != null &&\n !string.IsNullOrEmpty(id.ToString()) && !configItemsById.ContainsKey(id.ToString()))\n {\n configItemsById.Add(id.ToString(), item);\n }\n }\n }\n \n // Get the view model type to determine special handling\n string viewModelTypeName = viewModel.GetType().Name;\n _logService.Log(LogLevel.Debug, $\"Verifying view model of type: {viewModelTypeName}\");\n \n // Check up to 15 items\n foreach (var item in items)\n {\n if (totalChecked >= 15) break;\n \n var nameProperty = item.GetType().GetProperty(\"Name\");\n var idProperty = item.GetType().GetProperty(\"Id\");\n var isSelectedProperty = item.GetType().GetProperty(\"IsSelected\");\n \n if (nameProperty != null && isSelectedProperty != null)\n {\n var name = nameProperty.GetValue(item)?.ToString();\n var id = idProperty?.GetValue(item)?.ToString();\n \n _logService.Log(LogLevel.Debug, $\"Processing item: {name}, Id: {id}\");\n \n ConfigurationItem configItem = null;\n \n // Try to match by ID first\n if (!string.IsNullOrEmpty(id) && configItemsById.TryGetValue(id, out var itemById))\n {\n configItem = itemById;\n }\n // Then try to match by name\n else if (!string.IsNullOrEmpty(name) && configItemsByName.TryGetValue(name, out var itemByName))\n {\n configItem = itemByName;\n }\n \n if (configItem != null)\n {\n totalChecked++;\n bool itemMatches = true;\n \n // Check IsSelected property\n if (isSelectedProperty.GetValue(item) is bool isSelected && isSelected != configItem.IsSelected)\n {\n _logService.Log(LogLevel.Debug, $\"Item {name} has IsSelected={isSelected}, expected {configItem.IsSelected}\");\n itemMatches = false;\n }\n \n // For controls with additional properties, check those too\n if (configItem.ControlType == ControlType.ThreeStateSlider || configItem.ControlType == ControlType.ComboBox)\n {\n var sliderValueProperty = item.GetType().GetProperty(\"SliderValue\");\n if (sliderValueProperty != null && configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int expectedValue = Convert.ToInt32(sliderValue);\n int actualValue = (int)(sliderValueProperty.GetValue(item) ?? 0);\n \n if (actualValue != expectedValue)\n {\n _logService.Log(LogLevel.Debug, $\"Item {name} has SliderValue={actualValue}, expected {expectedValue}\");\n itemMatches = false;\n }\n }\n }\n \n // For ComboBox, check SelectedValue\n if (configItem.ControlType == ControlType.ComboBox)\n {\n var selectedValueProperty = item.GetType().GetProperty(\"SelectedValue\");\n if (selectedValueProperty != null && !string.IsNullOrEmpty(configItem.SelectedValue))\n {\n string expectedValue = configItem.SelectedValue;\n string actualValue = selectedValueProperty.GetValue(item)?.ToString();\n \n if (actualValue != expectedValue)\n {\n _logService.Log(LogLevel.Debug, $\"Item {name} has SelectedValue={actualValue}, expected {expectedValue}\");\n itemMatches = false;\n }\n }\n }\n \n if (itemMatches)\n {\n matchCount++;\n }\n }\n }\n }\n \n _logService.Log(LogLevel.Debug, $\"Verification result: {matchCount} matches out of {totalChecked} checked items\");\n \n // If we checked at least 3 items and at least 50% match, consider it successful\n if (totalChecked >= 3 && (double)matchCount / totalChecked >= 0.5)\n {\n _logService.Log(LogLevel.Info, $\"Configuration verification passed: {matchCount}/{totalChecked} items match\");\n return true;\n }\n else if (totalChecked > 0)\n {\n _logService.Log(LogLevel.Warning, $\"Configuration verification failed: only {matchCount}/{totalChecked} items match\");\n \n // Even if verification fails, we'll try to directly apply the configuration\n _logService.Log(LogLevel.Info, \"Will attempt direct application as fallback\");\n return false;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"No items could be checked for verification\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error verifying configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Directly applies the configuration to the view model without using the ImportConfigCommand.\n /// \n /// The view model to apply the configuration to.\n /// The configuration file to apply.\n /// True if successful, false otherwise.\n private async Task DirectlyApplyConfiguration(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Attempting to directly apply configuration to {viewModel.GetType().Name}\");\n \n // Get the Items property from the view model\n var itemsProperty = viewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty == null)\n {\n _logService.Log(LogLevel.Warning, $\"Could not find Items property in {viewModel.GetType().Name}\");\n return false;\n }\n \n var items = itemsProperty.GetValue(viewModel) as System.Collections.IEnumerable;\n if (items == null)\n {\n _logService.Log(LogLevel.Warning, $\"Items collection is null in {viewModel.GetType().Name}\");\n return false;\n }\n \n // Create dictionaries of config items by name and ID for faster lookup\n var configItemsByName = new Dictionary(StringComparer.OrdinalIgnoreCase);\n var configItemsById = new Dictionary(StringComparer.OrdinalIgnoreCase);\n \n if (configFile.Items != null)\n {\n foreach (var item in configFile.Items)\n {\n if (!string.IsNullOrEmpty(item.Name) && !configItemsByName.ContainsKey(item.Name))\n {\n configItemsByName.Add(item.Name, item);\n }\n \n if (item.CustomProperties.TryGetValue(\"Id\", out var id) && id != null &&\n !string.IsNullOrEmpty(id.ToString()) && !configItemsById.ContainsKey(id.ToString()))\n {\n configItemsById.Add(id.ToString(), item);\n }\n }\n }\n \n // Update the items in the view model\n int updatedCount = 0;\n \n // Determine if we're dealing with a collection that implements INotifyCollectionChanged\n bool isObservableCollection = false;\n var itemsType = items.GetType();\n if (typeof(System.Collections.Specialized.INotifyCollectionChanged).IsAssignableFrom(itemsType))\n {\n isObservableCollection = true;\n _logService.Log(LogLevel.Debug, $\"Items collection is an observable collection\");\n }\n \n // Get the view model type to determine special handling\n string viewModelTypeName = viewModel.GetType().Name;\n _logService.Log(LogLevel.Debug, $\"Processing view model of type: {viewModelTypeName}\");\n \n foreach (var item in items)\n {\n var nameProperty = item.GetType().GetProperty(\"Name\");\n var idProperty = item.GetType().GetProperty(\"Id\");\n var isSelectedProperty = item.GetType().GetProperty(\"IsSelected\");\n var isUpdatingFromCodeProperty = item.GetType().GetProperty(\"IsUpdatingFromCode\");\n \n if (nameProperty != null && isSelectedProperty != null)\n {\n var name = nameProperty.GetValue(item)?.ToString();\n var id = idProperty?.GetValue(item)?.ToString();\n \n _logService.Log(LogLevel.Debug, $\"Processing item: {name}, Id: {id}\");\n \n ConfigurationItem configItem = null;\n \n // Try to match by ID first\n if (!string.IsNullOrEmpty(id) && configItemsById.TryGetValue(id, out var itemById))\n {\n configItem = itemById;\n }\n // Then try to match by name\n else if (!string.IsNullOrEmpty(name) && configItemsByName.TryGetValue(name, out var itemByName))\n {\n configItem = itemByName;\n }\n \n if (configItem != null)\n {\n // Get the current IsSelected value before changing it\n bool currentIsSelected = (bool)(isSelectedProperty.GetValue(item) ?? false);\n \n // Set IsUpdatingFromCode to true before making changes\n if (isUpdatingFromCodeProperty != null)\n {\n isUpdatingFromCodeProperty.SetValue(item, true);\n }\n \n // Update IsSelected\n if (currentIsSelected != configItem.IsSelected)\n {\n _logService.Log(LogLevel.Debug, $\"Updating IsSelected for {name} from {currentIsSelected} to {configItem.IsSelected}\");\n isSelectedProperty.SetValue(item, configItem.IsSelected);\n }\n \n // Update other properties if available\n bool propertiesUpdated = UpdateAdditionalProperties(item, configItem);\n \n // If any property was updated, count it\n if (currentIsSelected != configItem.IsSelected || propertiesUpdated)\n {\n updatedCount++;\n }\n \n // Set IsUpdatingFromCode back to false to allow property change events to trigger\n if (isUpdatingFromCodeProperty != null)\n {\n isUpdatingFromCodeProperty.SetValue(item, false);\n }\n \n // Ensure UI state is properly updated\n TriggerPropertyChangedIfPossible(item);\n \n // Always explicitly call ApplySetting method to ensure registry changes are applied\n // regardless of view model type or IsSelected state\n var applySettingCommand = item.GetType().GetProperty(\"ApplySettingCommand\")?.GetValue(item) as ICommand;\n if (applySettingCommand != null && applySettingCommand.CanExecute(null))\n {\n _logService.Log(LogLevel.Debug, $\"Explicitly executing ApplySettingCommand for {name}\");\n applySettingCommand.Execute(null);\n }\n }\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Directly updated {updatedCount} items in {viewModel.GetType().Name}\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return updatedCount > 0;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error directly applying configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Attempts to trigger property changed notifications on an item if it implements INotifyPropertyChanged.\n /// \n /// The item to trigger property changed on.\n private void TriggerPropertyChangedIfPossible(object item)\n {\n try\n {\n // Check if the item implements INotifyPropertyChanged\n if (item is System.ComponentModel.INotifyPropertyChanged notifyPropertyChanged)\n {\n try\n {\n // Try to find the OnPropertyChanged method with a string parameter\n var onPropertyChangedMethod = item.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(string) },\n null);\n \n if (onPropertyChangedMethod != null)\n {\n // Invoke the method with null string to refresh all properties\n onPropertyChangedMethod.Invoke(item, new object[] { null });\n _logService.Log(LogLevel.Debug, $\"Triggered OnPropertyChanged(string) for {item.GetType().Name}\");\n }\n else\n {\n // Try to find the OnPropertyChanged method with no parameters\n var onPropertyChangedNoParamsMethod = item.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n Type.EmptyTypes,\n null);\n \n if (onPropertyChangedNoParamsMethod != null)\n {\n // Invoke the method with no parameters\n onPropertyChangedNoParamsMethod.Invoke(item, null);\n _logService.Log(LogLevel.Debug, $\"Triggered OnPropertyChanged() for {item.GetType().Name}\");\n }\n else\n {\n // Try to find the RaisePropertyChanged method as an alternative\n var raisePropertyChangedMethod = item.GetType().GetMethod(\"RaisePropertyChanged\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (raisePropertyChangedMethod != null)\n {\n // Invoke with null to refresh all properties\n raisePropertyChangedMethod.Invoke(item, new object[] { null });\n _logService.Log(LogLevel.Debug, $\"Triggered RaisePropertyChanged for {item.GetType().Name}\");\n }\n }\n }\n }\n catch (System.Reflection.AmbiguousMatchException)\n {\n _logService.Log(LogLevel.Debug, $\"Ambiguous match for OnPropertyChanged in {item.GetType().Name}, trying alternative approach\");\n \n // Try to get all methods named OnPropertyChanged\n var methods = item.GetType().GetMethods(System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance)\n .Where(m => m.Name == \"OnPropertyChanged\").ToList();\n \n if (methods.Any())\n {\n // Try to find one that takes a string parameter\n var stringParamMethod = methods.FirstOrDefault(m =>\n {\n var parameters = m.GetParameters();\n return parameters.Length == 1 && parameters[0].ParameterType == typeof(string);\n });\n \n if (stringParamMethod != null)\n {\n stringParamMethod.Invoke(item, new object[] { null });\n _logService.Log(LogLevel.Debug, $\"Triggered OnPropertyChanged using specific method for {item.GetType().Name}\");\n }\n }\n }\n \n // Try to find a method that might trigger property changed\n var refreshMethod = item.GetType().GetMethod(\"Refresh\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);\n \n if (refreshMethod != null)\n {\n refreshMethod.Invoke(item, null);\n _logService.Log(LogLevel.Debug, $\"Called Refresh method for {item.GetType().Name}\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error triggering property changed: {ex.Message}\");\n }\n }\n \n /// \n /// Updates additional properties of an item based on the configuration item.\n /// \n /// The item to update.\n /// The configuration item containing the values to apply.\n /// True if any property was updated, false otherwise.\n private bool UpdateAdditionalProperties(object item, ConfigurationItem configItem)\n {\n try\n {\n bool anyPropertyUpdated = false;\n \n // Get the item type to access its properties\n var itemType = item.GetType();\n \n // Log the control type for debugging\n _logService.Log(LogLevel.Debug, $\"Updating additional properties for {configItem.Name}, ControlType: {configItem.ControlType}\");\n \n // Update SliderValue for ThreeStateSlider or ComboBox\n if (configItem.ControlType == ControlType.ThreeStateSlider || configItem.ControlType == ControlType.ComboBox)\n {\n var sliderValueProperty = itemType.GetProperty(\"SliderValue\");\n if (sliderValueProperty != null && configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int newSliderValue = Convert.ToInt32(sliderValue);\n int currentSliderValue = (int)(sliderValueProperty.GetValue(item) ?? 0);\n \n if (currentSliderValue != newSliderValue)\n {\n _logService.Log(LogLevel.Debug, $\"Updating SliderValue for {configItem.Name} from {currentSliderValue} to {newSliderValue}\");\n sliderValueProperty.SetValue(item, newSliderValue);\n anyPropertyUpdated = true;\n }\n }\n }\n \n // Update SelectedValue for ComboBox\n if (configItem.ControlType == ControlType.ComboBox)\n {\n var selectedValueProperty = itemType.GetProperty(\"SelectedValue\");\n if (selectedValueProperty != null && !string.IsNullOrEmpty(configItem.SelectedValue))\n {\n string currentSelectedValue = selectedValueProperty.GetValue(item)?.ToString();\n \n if (currentSelectedValue != configItem.SelectedValue)\n {\n _logService.Log(LogLevel.Debug, $\"Updating SelectedValue for {configItem.Name} from '{currentSelectedValue}' to '{configItem.SelectedValue}'\");\n selectedValueProperty.SetValue(item, configItem.SelectedValue);\n anyPropertyUpdated = true;\n }\n }\n }\n \n // Update SelectedTheme for theme selector\n if (configItem.Name.Contains(\"Theme\") && configItem.CustomProperties.TryGetValue(\"SelectedTheme\", out var selectedTheme))\n {\n var selectedThemeProperty = itemType.GetProperty(\"SelectedTheme\");\n if (selectedThemeProperty != null && selectedTheme != null)\n {\n string currentSelectedTheme = selectedThemeProperty.GetValue(item)?.ToString();\n string newSelectedTheme = selectedTheme.ToString();\n \n if (currentSelectedTheme != newSelectedTheme)\n {\n _logService.Log(LogLevel.Debug, $\"Updating SelectedTheme for {configItem.Name} from '{currentSelectedTheme}' to '{newSelectedTheme}'\");\n selectedThemeProperty.SetValue(item, newSelectedTheme);\n anyPropertyUpdated = true;\n }\n }\n }\n \n // Update Status for items that have a status property\n var statusProperty = itemType.GetProperty(\"Status\");\n if (statusProperty != null && configItem.CustomProperties.TryGetValue(\"Status\", out var status))\n {\n statusProperty.SetValue(item, status);\n anyPropertyUpdated = true;\n }\n \n // Update StatusMessage for items that have a status message property\n var statusMessageProperty = itemType.GetProperty(\"StatusMessage\");\n if (statusMessageProperty != null && configItem.CustomProperties.TryGetValue(\"StatusMessage\", out var statusMessage))\n {\n statusMessageProperty.SetValue(item, statusMessage?.ToString());\n anyPropertyUpdated = true;\n }\n \n // For toggle switches, ensure IsChecked is synchronized with IsSelected\n var isCheckedProperty = itemType.GetProperty(\"IsChecked\");\n if (isCheckedProperty != null)\n {\n bool currentIsChecked = (bool)(isCheckedProperty.GetValue(item) ?? false);\n \n if (currentIsChecked != configItem.IsSelected)\n {\n _logService.Log(LogLevel.Debug, $\"Updating IsChecked for {configItem.Name} from {currentIsChecked} to {configItem.IsSelected}\");\n isCheckedProperty.SetValue(item, configItem.IsSelected);\n anyPropertyUpdated = true;\n }\n }\n \n // Update CurrentValue property if it exists\n var currentValueProperty = itemType.GetProperty(\"CurrentValue\");\n if (currentValueProperty != null)\n {\n // For toggle buttons, set the current value based on IsSelected\n if (configItem.ControlType == ControlType.BinaryToggle)\n {\n object valueToSet = configItem.IsSelected ? 1 : 0;\n currentValueProperty.SetValue(item, valueToSet);\n _logService.Log(LogLevel.Debug, $\"Setting CurrentValue for {configItem.Name} to {valueToSet}\");\n anyPropertyUpdated = true;\n }\n // For other control types, use the appropriate value\n else if (configItem.ControlType == ControlType.ThreeStateSlider || configItem.ControlType == ControlType.ComboBox)\n {\n if (configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n currentValueProperty.SetValue(item, sliderValue);\n _logService.Log(LogLevel.Debug, $\"Setting CurrentValue for {configItem.Name} to {sliderValue}\");\n anyPropertyUpdated = true;\n }\n }\n }\n \n // Update RegistrySetting property if it exists\n var registrySettingProperty = itemType.GetProperty(\"RegistrySetting\");\n if (registrySettingProperty != null && configItem.CustomProperties.TryGetValue(\"RegistrySetting\", out var registrySetting))\n {\n registrySettingProperty.SetValue(item, registrySetting);\n _logService.Log(LogLevel.Debug, $\"Updated RegistrySetting for {configItem.Name}\");\n anyPropertyUpdated = true;\n }\n \n // Update LinkedRegistrySettings property if it exists\n var linkedRegistrySettingsProperty = itemType.GetProperty(\"LinkedRegistrySettings\");\n if (linkedRegistrySettingsProperty != null && configItem.CustomProperties.TryGetValue(\"LinkedRegistrySettings\", out var linkedRegistrySettings))\n {\n linkedRegistrySettingsProperty.SetValue(item, linkedRegistrySettings);\n _logService.Log(LogLevel.Debug, $\"Updated LinkedRegistrySettings for {configItem.Name}\");\n anyPropertyUpdated = true;\n }\n \n return anyPropertyUpdated;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating additional properties: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Forces a UI refresh if needed for the view model.\n /// \n /// The view model to refresh.\n private async Task RefreshUIIfNeeded(object viewModel)\n {\n try\n {\n _logService.Log(LogLevel.Debug, $\"Refreshing UI for {viewModel.GetType().Name}\");\n bool refreshed = false;\n \n // Get the view model type to determine special handling\n string viewModelTypeName = viewModel.GetType().Name;\n \n // Try multiple refresh methods in order of preference\n \n // 1. First try RefreshCommand if available\n var refreshCommandProperty = viewModel.GetType().GetProperty(\"RefreshCommand\");\n if (refreshCommandProperty != null)\n {\n var refreshCommand = refreshCommandProperty.GetValue(viewModel) as IAsyncRelayCommand;\n if (refreshCommand != null && refreshCommand.CanExecute(null))\n {\n _logService.Log(LogLevel.Debug, \"Executing RefreshCommand\");\n await refreshCommand.ExecuteAsync(null);\n refreshed = true;\n }\n }\n \n // 2. Try RaisePropertyChanged for the Items property if the view model implements INotifyPropertyChanged\n if (!refreshed && viewModel is System.ComponentModel.INotifyPropertyChanged)\n {\n try\n {\n // Try to find the OnPropertyChanged method with a string parameter\n var onPropertyChangedMethod = viewModel.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(string) },\n null);\n \n if (onPropertyChangedMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling OnPropertyChanged(string) for Items property\");\n onPropertyChangedMethod.Invoke(viewModel, new object[] { \"Items\" });\n refreshed = true;\n }\n else\n {\n // Try to find the RaisePropertyChanged method as an alternative\n var raisePropertyChangedMethod = viewModel.GetType().GetMethod(\"RaisePropertyChanged\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (raisePropertyChangedMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling RaisePropertyChanged for Items property\");\n raisePropertyChangedMethod.Invoke(viewModel, new object[] { \"Items\" });\n refreshed = true;\n }\n else\n {\n // Try to find the NotifyPropertyChanged method as another alternative\n var notifyPropertyChangedMethod = viewModel.GetType().GetMethod(\"NotifyPropertyChanged\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (notifyPropertyChangedMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling NotifyPropertyChanged for Items property\");\n notifyPropertyChangedMethod.Invoke(viewModel, new object[] { \"Items\" });\n refreshed = true;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Warning, $\"Error calling property changed method: {ex.Message}\");\n // Continue with other refresh methods\n }\n }\n \n // 3. Try LoadItemsAsync method\n if (!refreshed)\n {\n var loadItemsMethod = viewModel.GetType().GetMethod(\"LoadItemsAsync\");\n if (loadItemsMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling LoadItemsAsync method\");\n await (Task)loadItemsMethod.Invoke(viewModel, null);\n refreshed = true;\n }\n }\n \n // 4. Try ApplySearch method\n if (!refreshed)\n {\n var applySearchMethod = viewModel.GetType().GetMethod(\"ApplySearch\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (applySearchMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling ApplySearch method\");\n applySearchMethod.Invoke(viewModel, null);\n refreshed = true;\n }\n }\n \n // 5. For specific view model types, try additional refresh methods\n if (!refreshed)\n {\n if (viewModelTypeName.Contains(\"Customize\"))\n {\n // Try to refresh the CustomizeViewModel specifically\n var refreshCustomizationsMethod = viewModel.GetType().GetMethod(\"RefreshCustomizations\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (refreshCustomizationsMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling RefreshCustomizations method\");\n refreshCustomizationsMethod.Invoke(viewModel, null);\n refreshed = true;\n }\n }\n else if (viewModelTypeName.Contains(\"Optimize\"))\n {\n // Try to refresh the OptimizeViewModel specifically\n var refreshOptimizationsMethod = viewModel.GetType().GetMethod(\"RefreshOptimizations\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (refreshOptimizationsMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling RefreshOptimizations method\");\n refreshOptimizationsMethod.Invoke(viewModel, null);\n refreshed = true;\n }\n }\n }\n \n // 6. If we still haven't refreshed, try to force a collection refresh\n if (!refreshed)\n {\n // Get the Items property\n var itemsProperty = viewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(viewModel);\n \n // Check if it's an ObservableCollection\n if (items != null && items.GetType().Name.Contains(\"ObservableCollection\"))\n {\n // Try to call a refresh method on the collection\n var refreshMethod = items.GetType().GetMethod(\"Refresh\");\n if (refreshMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling Refresh on ObservableCollection\");\n refreshMethod.Invoke(items, null);\n refreshed = true;\n }\n }\n }\n }\n \n if (!refreshed)\n {\n _logService.Log(LogLevel.Warning, \"Could not find a suitable method to refresh the UI\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error refreshing UI: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n }\n\n /// \n /// A wrapper for the configuration service that returns a specific configuration file.\n /// \n private class ConfigurationServiceWrapper : IConfigurationService\n {\n private readonly IConfigurationService _innerService;\n private readonly ConfigurationFile _configFile;\n private readonly ILogService _logService;\n\n public ConfigurationServiceWrapper(IConfigurationService innerService, ConfigurationFile configFile)\n {\n _innerService = innerService;\n _configFile = configFile;\n \n // Try to get the log service from the inner service using reflection\n try\n {\n var logServiceField = _innerService.GetType().GetField(\"_logService\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (logServiceField != null)\n {\n _logService = logServiceField.GetValue(_innerService) as ILogService;\n }\n }\n catch\n {\n // Ignore any errors, we'll just operate without logging\n }\n }\n\n public Task LoadConfigurationAsync(string configType)\n {\n // Log the operation if possible\n _logService?.Log(LogLevel.Debug, $\"ConfigurationServiceWrapper.LoadConfigurationAsync called with configType: {configType}\");\n _logService?.Log(LogLevel.Debug, $\"Returning config file with {_configFile.Items?.Count ?? 0} items\");\n \n // Always return our config file, but ensure it has the correct configType\n var configFileCopy = new ConfigurationFile\n {\n ConfigType = configType,\n CreatedAt = _configFile.CreatedAt,\n Items = _configFile.Items\n };\n \n return Task.FromResult(configFileCopy);\n }\n\n public Task SaveConfigurationAsync(IEnumerable items, string configType)\n {\n // Log the operation if possible\n _logService?.Log(LogLevel.Debug, $\"ConfigurationServiceWrapper.SaveConfigurationAsync called with configType: {configType}\");\n \n // Delegate to the inner service\n return _innerService.SaveConfigurationAsync(items, configType);\n }\n\n public Task LoadUnifiedConfigurationAsync()\n {\n // Log the operation if possible\n _logService?.Log(LogLevel.Debug, \"ConfigurationServiceWrapper.LoadUnifiedConfigurationAsync called\");\n \n // Delegate to the inner service\n return _innerService.LoadUnifiedConfigurationAsync();\n }\n\n public Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile unifiedConfig)\n {\n return Task.FromResult(true);\n }\n\n public UnifiedConfigurationFile CreateUnifiedConfiguration(Dictionary> sections, IEnumerable includedSections)\n {\n // Log the operation if possible\n _logService?.Log(LogLevel.Debug, \"ConfigurationServiceWrapper.CreateUnifiedConfiguration called\");\n \n // Delegate to the inner service\n return _innerService.CreateUnifiedConfiguration(sections, includedSections);\n }\n\n public ConfigurationFile ExtractSectionFromUnifiedConfiguration(UnifiedConfigurationFile unifiedConfig, string sectionName)\n {\n // Log the operation if possible\n _logService?.Log(LogLevel.Debug, $\"ConfigurationServiceWrapper.ExtractSectionFromUnifiedConfiguration called with sectionName: {sectionName}\");\n \n // Delegate to the inner service\n return _innerService.ExtractSectionFromUnifiedConfiguration(unifiedConfig, sectionName);\n }\n }\n\n /// \n /// A mock configuration service that captures the settings passed to SaveConfigurationAsync.\n /// \n private class MockConfigurationService : IConfigurationService\n {\n // Flag to indicate this is being used for unified configuration\n public bool IsUnifiedConfigurationMode { get; set; } = true;\n \n // Flag to suppress dialogs\n public bool SuppressDialogs { get; set; } = true;\n \n // Captured settings\n public List CapturedSettings { get; } = new List();\n \n // Dialog service for showing messages\n private readonly IDialogService _dialogService;\n \n public MockConfigurationService(IDialogService dialogService = null)\n {\n _dialogService = dialogService;\n }\n\n public Task LoadConfigurationAsync(string configType)\n {\n // Return an empty configuration file\n return Task.FromResult(new ConfigurationFile\n {\n ConfigType = configType,\n CreatedAt = DateTime.UtcNow,\n Items = new List()\n });\n }\n\n public Task SaveConfigurationAsync(IEnumerable items, string configType)\n {\n System.Diagnostics.Debug.WriteLine($\"MockConfigurationService.SaveConfigurationAsync called with configType: {configType}\");\n System.Diagnostics.Debug.WriteLine($\"Generic type T: {typeof(T).FullName}\");\n System.Diagnostics.Debug.WriteLine($\"SuppressDialogs: {SuppressDialogs}, IsUnifiedConfigurationMode: {IsUnifiedConfigurationMode}\");\n \n // Check if items is null or empty\n if (items == null)\n {\n System.Diagnostics.Debug.WriteLine(\"Items collection is null\");\n return Task.FromResult(true);\n }\n \n if (!items.Any())\n {\n System.Diagnostics.Debug.WriteLine(\"Items collection is empty\");\n return Task.FromResult(true);\n }\n \n // Log the count of items\n System.Diagnostics.Debug.WriteLine($\"Items count: {items.Count()}\");\n \n try\n {\n // We no longer need special handling for WindowsApps since we're directly accessing the Items collection\n // Special handling for ExternalApps\n if (configType == \"ExternalApps\")\n {\n System.Diagnostics.Debug.WriteLine(\"Processing ExternalApps configuration\");\n \n // Convert each ExternalApp to ExternalAppSettingItem\n var externalApps = new List();\n \n foreach (var item in items)\n {\n if (item is Winhance.WPF.Features.SoftwareApps.Models.ExternalApp externalApp)\n {\n externalApps.Add(new ExternalAppSettingItem(externalApp));\n System.Diagnostics.Debug.WriteLine($\"Added ExternalAppSettingItem for {externalApp.Name}\");\n }\n }\n \n System.Diagnostics.Debug.WriteLine($\"Created {externalApps.Count} ExternalAppSettingItems\");\n CapturedSettings.AddRange(externalApps);\n System.Diagnostics.Debug.WriteLine($\"Added {externalApps.Count} ExternalAppSettingItems to CapturedSettings\");\n }\n else\n {\n // For other types, try to cast directly to ISettingItem\n try\n {\n var settingItems = items.Cast().ToList();\n System.Diagnostics.Debug.WriteLine($\"Successfully cast to ISettingItem, count: {settingItems.Count}\");\n \n CapturedSettings.AddRange(settingItems);\n System.Diagnostics.Debug.WriteLine($\"Added {settingItems.Count} ISettingItems to CapturedSettings\");\n }\n catch (InvalidCastException ex)\n {\n // Log the error but don't throw it to avoid breaking the configuration process\n System.Diagnostics.Debug.WriteLine($\"Error casting items to ISettingItem: {ex.Message}\");\n \n // Try to convert each item individually\n int convertedCount = 0;\n foreach (var item in items)\n {\n try\n {\n if (item is Winhance.WPF.Features.SoftwareApps.Models.WindowsApp windowsApp)\n {\n CapturedSettings.Add(new WindowsAppSettingItem(windowsApp));\n System.Diagnostics.Debug.WriteLine($\"Added WindowsAppSettingItem for {windowsApp.Name}\");\n convertedCount++;\n }\n else if (item is Winhance.WPF.Features.SoftwareApps.Models.ExternalApp externalApp)\n {\n CapturedSettings.Add(new ExternalAppSettingItem(externalApp));\n System.Diagnostics.Debug.WriteLine($\"Added ExternalAppSettingItem for {externalApp.Name}\");\n convertedCount++;\n }\n else\n {\n System.Diagnostics.Debug.WriteLine($\"Unknown item type: {item?.GetType().FullName ?? \"null\"}\");\n }\n }\n catch (Exception itemEx)\n {\n System.Diagnostics.Debug.WriteLine($\"Error processing individual item: {itemEx.Message}\");\n }\n }\n System.Diagnostics.Debug.WriteLine($\"Converted {convertedCount} items individually\");\n }\n }\n }\n catch (Exception ex)\n {\n System.Diagnostics.Debug.WriteLine($\"Unexpected error in SaveConfigurationAsync: {ex.Message}\");\n }\n \n System.Diagnostics.Debug.WriteLine($\"CapturedSettings count after SaveConfigurationAsync: {CapturedSettings.Count}\");\n \n // Return true without showing any dialogs when in unified configuration mode\n if (SuppressDialogs || IsUnifiedConfigurationMode)\n {\n System.Diagnostics.Debug.WriteLine(\"Suppressing dialogs in unified configuration mode\");\n return Task.FromResult(true);\n }\n \n // Show a success dialog if not in unified configuration mode\n if (_dialogService != null)\n {\n _dialogService.ShowMessage($\"Configuration saved successfully.\", \"Configuration Saved\");\n }\n \n return Task.FromResult(true);\n }\n\n public Task LoadUnifiedConfigurationAsync()\n {\n // Return an empty unified configuration file\n return Task.FromResult(new UnifiedConfigurationFile\n {\n CreatedAt = DateTime.UtcNow,\n WindowsApps = new ConfigSection(),\n ExternalApps = new ConfigSection(),\n Customize = new ConfigSection(),\n Optimize = new ConfigSection()\n });\n }\n\n public Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile unifiedConfig)\n {\n return Task.FromResult(true);\n }\n\n public UnifiedConfigurationFile CreateUnifiedConfiguration(Dictionary> sections, IEnumerable includedSections)\n {\n // Create a unified configuration file with all sections included\n var unifiedConfig = new UnifiedConfigurationFile\n {\n CreatedAt = DateTime.UtcNow,\n WindowsApps = new ConfigSection(),\n ExternalApps = new ConfigSection(),\n Customize = new ConfigSection(),\n Optimize = new ConfigSection()\n };\n\n // Set the IsIncluded flag for each section based on whether it's in the includedSections list\n // and whether it has any items\n if (sections.TryGetValue(\"WindowsApps\", out var windowsApps) && windowsApps.Any())\n {\n unifiedConfig.WindowsApps.IsIncluded = true;\n unifiedConfig.WindowsApps.Items = ConvertToConfigurationItems(windowsApps);\n }\n\n if (sections.TryGetValue(\"ExternalApps\", out var externalApps) && externalApps.Any())\n {\n unifiedConfig.ExternalApps.IsIncluded = true;\n unifiedConfig.ExternalApps.Items = ConvertToConfigurationItems(externalApps);\n }\n\n if (sections.TryGetValue(\"Customize\", out var customize) && customize.Any())\n {\n unifiedConfig.Customize.IsIncluded = true;\n unifiedConfig.Customize.Items = ConvertToConfigurationItems(customize);\n }\n\n if (sections.TryGetValue(\"Optimize\", out var optimize) && optimize.Any())\n {\n unifiedConfig.Optimize.IsIncluded = true;\n unifiedConfig.Optimize.Items = ConvertToConfigurationItems(optimize);\n }\n\n return unifiedConfig;\n }\n\n // Helper method to convert ISettingItem objects to ConfigurationItem objects\n private List ConvertToConfigurationItems(IEnumerable items)\n {\n var result = new List();\n \n foreach (var item in items)\n {\n var configItem = new ConfigurationItem\n {\n Name = item.Name,\n IsSelected = item.IsSelected,\n ControlType = item.ControlType\n };\n \n // Add Id to custom properties\n if (!string.IsNullOrEmpty(item.Id))\n {\n configItem.CustomProperties[\"Id\"] = item.Id;\n }\n \n // Add GroupName to custom properties\n if (!string.IsNullOrEmpty(item.GroupName))\n {\n configItem.CustomProperties[\"GroupName\"] = item.GroupName;\n }\n \n // Add Description to custom properties\n if (!string.IsNullOrEmpty(item.Description))\n {\n configItem.CustomProperties[\"Description\"] = item.Description;\n }\n \n // Ensure SelectedValue is set for ComboBox controls\n configItem.EnsureSelectedValueIsSet();\n \n result.Add(configItem);\n }\n \n return result;\n }\n\n public ConfigurationFile ExtractSectionFromUnifiedConfiguration(UnifiedConfigurationFile unifiedConfig, string sectionName)\n {\n // Return an empty configuration file\n return new ConfigurationFile\n {\n ConfigType = sectionName,\n CreatedAt = DateTime.UtcNow,\n Items = new List()\n };\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/OptimizeViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Linq;\nusing System.Windows.Controls;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.Customize.Enums;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.Common.Messages;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for the OptimizeView that manages system optimization settings.\n /// \n public partial class OptimizeViewModel : SearchableViewModel\n {\n private readonly IRegistryService _registryService;\n private readonly IDialogService _dialogService;\n private readonly ILogService _logService;\n private readonly IConfigurationService _configurationService;\n private readonly IMessengerService _messengerService;\n private List _allItemsBackup = new List();\n private bool _updatingCheckboxes;\n private bool _isInitialSearchDone = false;\n \n /// \n /// Gets or sets a value indicating whether the view model is initialized.\n /// \n [ObservableProperty]\n private bool _isInitialized;\n \n /// \n /// Gets or sets a value indicating whether search has any results.\n /// \n [ObservableProperty]\n private bool _hasSearchResults = true;\n \n /// \n /// Gets or sets the status text.\n /// \n [ObservableProperty]\n private string _statusText = \"Optimize Your Windows Settings and Performance\";\n \n // Override the SearchText property to add explicit notification and direct control over the search flow\n private string _searchTextOverride = string.Empty;\n public override string SearchText\n {\n get => _searchTextOverride;\n set\n {\n if (_searchTextOverride != value)\n {\n _searchTextOverride = value;\n OnPropertyChanged(nameof(SearchText));\n LogInfo($\"OptimizeViewModel: SearchText changed to: '{value}'\");\n \n // Explicitly update IsSearchActive and call ApplySearch\n IsSearchActive = !string.IsNullOrWhiteSpace(value);\n ApplySearch();\n \n // Update status text based on search results\n if (IsSearchActive)\n {\n StatusText = $\"Found {Items.Count} settings matching '{value}'\";\n }\n else\n {\n StatusText = \"Optimize Your Windows Settings and Performance\";\n }\n }\n }\n }\n\n /// \n /// Gets the messenger service.\n /// \n public IMessengerService MessengerService => _messengerService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The registry service for interacting with the Windows Registry.\n /// The dialog service for showing dialogs.\n /// The logging service.\n /// The progress service.\n /// The search service.\n /// The configuration service.\n /// The gaming settings view model.\n /// The privacy optimizations view model.\n /// The update optimizations view model.\n /// The power settings view model.\n /// The Windows security optimizations view model.\n /// The explorer optimizations view model.\n /// The notification optimizations view model.\n /// The sound optimizations view model.\n /// The messenger service.\n\n public OptimizeViewModel(\n IRegistryService registryService,\n IDialogService dialogService,\n ILogService logService,\n ITaskProgressService progressService,\n ISearchService searchService,\n IConfigurationService configurationService,\n GamingandPerformanceOptimizationsViewModel gamingSettings,\n PrivacyOptimizationsViewModel privacySettings,\n UpdateOptimizationsViewModel updateSettings,\n PowerOptimizationsViewModel powerSettings,\n WindowsSecurityOptimizationsViewModel windowsSecuritySettings,\n ExplorerOptimizationsViewModel explorerSettings,\n NotificationOptimizationsViewModel notificationSettings,\n SoundOptimizationsViewModel soundSettings,\n IMessengerService messengerService)\n : base(progressService, searchService, null)\n {\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _messengerService = messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n\n // Set specialized view models\n GamingandPerformanceOptimizationsViewModel = gamingSettings ?? throw new ArgumentNullException(nameof(gamingSettings));\n PrivacyOptimizationsViewModel = privacySettings ?? throw new ArgumentNullException(nameof(privacySettings));\n UpdateOptimizationsViewModel = updateSettings ?? throw new ArgumentNullException(nameof(updateSettings));\n PowerSettingsViewModel = powerSettings ?? throw new ArgumentNullException(nameof(powerSettings));\n WindowsSecuritySettingsViewModel = windowsSecuritySettings ?? throw new ArgumentNullException(nameof(windowsSecuritySettings));\n ExplorerOptimizationsViewModel = explorerSettings ?? throw new ArgumentNullException(nameof(explorerSettings));\n NotificationOptimizationsViewModel = notificationSettings ?? throw new ArgumentNullException(nameof(notificationSettings));\n SoundOptimizationsViewModel = soundSettings ?? throw new ArgumentNullException(nameof(soundSettings));\n\n // Store the configuration service\n _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));\n\n // Create initialize command\n InitializeCommand = new AsyncRelayCommand(InitializeAsync);\n\n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n\n // We'll initialize when explicitly called, not automatically\n // This ensures the loading screen stays visible until initialization is complete\n\n }\n\n /// \n /// Gets the command to initialize the view model.\n /// \n public IAsyncRelayCommand InitializeCommand { get; }\n\n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n\n /// \n /// Gets the gaming settings view model.\n /// \n public GamingandPerformanceOptimizationsViewModel GamingandPerformanceOptimizationsViewModel { get; }\n\n /// \n /// Gets the privacy optimizations view model.\n /// \n public PrivacyOptimizationsViewModel PrivacyOptimizationsViewModel { get; }\n\n /// \n /// Gets the updates optimizations view model.\n /// \n public UpdateOptimizationsViewModel UpdateOptimizationsViewModel { get; }\n\n /// \n /// Gets the power settings view model.\n /// \n public PowerOptimizationsViewModel PowerSettingsViewModel { get; }\n\n /// \n /// Gets the Windows security optimizations view model.\n /// \n public WindowsSecurityOptimizationsViewModel WindowsSecuritySettingsViewModel { get; }\n\n /// \n /// Gets the explorer optimizations view model.\n /// \n public ExplorerOptimizationsViewModel ExplorerOptimizationsViewModel { get; }\n\n /// \n /// Gets the notification optimizations view model.\n /// \n public NotificationOptimizationsViewModel NotificationOptimizationsViewModel { get; }\n\n /// \n /// Gets the sound optimizations view model.\n /// \n public SoundOptimizationsViewModel SoundOptimizationsViewModel { get; }\n\n /// \n /// Toggles the selection state of all gaming settings.\n /// \n [RelayCommand]\n private void ToggleGaming()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n GamingandPerformanceOptimizationsViewModel.IsSelected = !GamingandPerformanceOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in GamingandPerformanceOptimizationsViewModel.Settings)\n {\n setting.IsSelected = GamingandPerformanceOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all privacy settings.\n /// \n [RelayCommand]\n private void TogglePrivacy()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n PrivacyOptimizationsViewModel.IsSelected = !PrivacyOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in PrivacyOptimizationsViewModel.Settings)\n {\n setting.IsSelected = PrivacyOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all update settings.\n /// \n [RelayCommand]\n private void ToggleUpdates()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n UpdateOptimizationsViewModel.IsSelected = !UpdateOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in UpdateOptimizationsViewModel.Settings)\n {\n setting.IsSelected = UpdateOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all power settings.\n /// \n [RelayCommand]\n private void TogglePowerSettings()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n PowerSettingsViewModel.IsSelected = !PowerSettingsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in PowerSettingsViewModel.Settings)\n {\n setting.IsSelected = PowerSettingsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of Windows Security settings.\n /// \n [RelayCommand]\n private void ToggleWindowsSecurity()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n WindowsSecuritySettingsViewModel.IsSelected = !WindowsSecuritySettingsViewModel.IsSelected;\n\n // Windows Security only has the UAC notification level, no individual settings to update\n // This is primarily for UI consistency with other sections\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all explorer settings.\n /// \n [RelayCommand]\n private void ToggleExplorer()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n ExplorerOptimizationsViewModel.IsSelected = !ExplorerOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in ExplorerOptimizationsViewModel.Settings)\n {\n setting.IsSelected = ExplorerOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all notification settings.\n /// \n [RelayCommand]\n private void ToggleNotifications()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n NotificationOptimizationsViewModel.IsSelected = !NotificationOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in NotificationOptimizationsViewModel.Settings)\n {\n setting.IsSelected = NotificationOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all sound settings.\n /// \n [RelayCommand]\n private void ToggleSound()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n SoundOptimizationsViewModel.IsSelected = !SoundOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in SoundOptimizationsViewModel.Settings)\n {\n setting.IsSelected = SoundOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Loads items asynchronously.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadItemsAsync()\n {\n try\n {\n IsLoading = true;\n StatusText = \"Loading optimization settings...\";\n\n // Clear the items collection\n Items.Clear();\n\n // Collect all settings from the various view models\n var allSettings = new List();\n \n // Ensure all child view models are initialized and have loaded their settings\n await EnsureChildViewModelsInitialized();\n\n // Add settings from each category - convert from OptimizationSettingViewModel to OptimizationSettingItem\n if (WindowsSecuritySettingsViewModel != null && WindowsSecuritySettingsViewModel.Settings != null)\n {\n _logService.Log(LogLevel.Debug, $\"Loading {WindowsSecuritySettingsViewModel.Settings.Count} settings from WindowsSecuritySettingsViewModel\");\n foreach (var setting in WindowsSecuritySettingsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n \n // For UAC slider, add the slider labels\n if (item.Id == \"UACSlider\" && item.ControlType == ControlType.ThreeStateSlider)\n {\n item.SliderLabels.Clear();\n item.SliderLabels.Add(\"Low\");\n item.SliderLabels.Add(\"Moderate\");\n item.SliderLabels.Add(\"High\");\n }\n \n allSettings.Add(item);\n }\n }\n\n if (GamingandPerformanceOptimizationsViewModel != null && GamingandPerformanceOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in GamingandPerformanceOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n if (PrivacyOptimizationsViewModel != null && PrivacyOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in PrivacyOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n if (UpdateOptimizationsViewModel != null && UpdateOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in UpdateOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n if (PowerSettingsViewModel != null && PowerSettingsViewModel.Settings != null)\n {\n foreach (var setting in PowerSettingsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n \n // For Power Plan ComboBox, add the ComboBox labels\n if (item.Id == \"PowerPlanComboBox\" && item.ControlType == ControlType.ComboBox)\n {\n item.SliderLabels.Clear();\n // Copy labels from PowerSettingsViewModel\n if (PowerSettingsViewModel.PowerPlanLabels != null)\n {\n foreach (var label in PowerSettingsViewModel.PowerPlanLabels)\n {\n item.SliderLabels.Add(label);\n }\n \n // Set the SliderValue based on the current PowerPlanValue\n if (PowerSettingsViewModel.PowerPlanValue >= 0 &&\n PowerSettingsViewModel.PowerPlanValue < PowerSettingsViewModel.PowerPlanLabels.Count)\n {\n item.SliderValue = PowerSettingsViewModel.PowerPlanValue;\n _logService.Log(LogLevel.Info, $\"Set SliderValue for Power Plan to {item.SliderValue} (label: {PowerSettingsViewModel.PowerPlanLabels[PowerSettingsViewModel.PowerPlanValue]})\");\n }\n }\n else\n {\n // Fallback labels if PowerPlanLabels is null\n item.SliderLabels.Add(\"Balanced\");\n item.SliderLabels.Add(\"High Performance\");\n item.SliderLabels.Add(\"Ultimate Performance\");\n \n // Set the SliderValue based on the current PowerPlanValue\n if (PowerSettingsViewModel.PowerPlanValue >= 0 && PowerSettingsViewModel.PowerPlanValue < 3)\n {\n item.SliderValue = PowerSettingsViewModel.PowerPlanValue;\n string[] defaultLabels = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n _logService.Log(LogLevel.Info, $\"Set SliderValue for Power Plan to {item.SliderValue} (label: {defaultLabels[PowerSettingsViewModel.PowerPlanValue]})\");\n }\n }\n }\n \n allSettings.Add(item);\n }\n }\n\n if (ExplorerOptimizationsViewModel != null && ExplorerOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in ExplorerOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n if (NotificationOptimizationsViewModel != null && NotificationOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in NotificationOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n if (SoundOptimizationsViewModel != null && SoundOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in SoundOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n // Add all settings to the Items collection\n foreach (var setting in allSettings)\n {\n Items.Add(setting);\n }\n\n // Create a backup of all items for state recovery\n _allItemsBackup = new List(Items);\n\n // Only update StatusText if it's currently showing a loading message\n if (StatusText.Contains(\"Loading\"))\n {\n StatusText = \"Optimize Your Windows Settings and Performance\";\n }\n _logService.Log(LogLevel.Info, $\"OptimizeViewModel.LoadItemsAsync completed with {Items.Count} items\");\n }\n catch (Exception ex)\n {\n StatusText = $\"Error loading optimization settings: {ex.Message}\";\n LogError($\"Error loading optimization settings: {ex.Message}\", ex);\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the installation status of items asynchronously.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckInstallationStatusAsync()\n {\n // This method is not applicable for optimization settings\n // but we need to implement it to satisfy the interface\n await Task.CompletedTask;\n }\n\n \n /// \n /// Restores all items visibility to their original state.\n /// \n private void RestoreAllItemsVisibility()\n {\n // Make all settings visible in each category\n if (GamingandPerformanceOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in GamingandPerformanceOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n GamingandPerformanceOptimizationsViewModel.HasVisibleSettings = GamingandPerformanceOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (PrivacyOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in PrivacyOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n PrivacyOptimizationsViewModel.HasVisibleSettings = PrivacyOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (UpdateOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in UpdateOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n UpdateOptimizationsViewModel.HasVisibleSettings = UpdateOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (PowerSettingsViewModel?.Settings != null)\n {\n foreach (var setting in PowerSettingsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n PowerSettingsViewModel.HasVisibleSettings = PowerSettingsViewModel.Settings.Count > 0;\n }\n \n if (ExplorerOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in ExplorerOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n ExplorerOptimizationsViewModel.HasVisibleSettings = ExplorerOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (NotificationOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in NotificationOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n NotificationOptimizationsViewModel.HasVisibleSettings = NotificationOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (SoundOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in SoundOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n SoundOptimizationsViewModel.HasVisibleSettings = SoundOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (WindowsSecuritySettingsViewModel?.Settings != null)\n {\n foreach (var setting in WindowsSecuritySettingsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n WindowsSecuritySettingsViewModel.HasVisibleSettings = WindowsSecuritySettingsViewModel.Settings.Count > 0;\n }\n \n // Always ensure HasSearchResults is true when restoring visibility\n HasSearchResults = true;\n \n // Send a message to notify the view to reset section expansion states\n _messengerService.Send(new ResetExpansionStateMessage());\n \n LogInfo(\"OptimizeViewModel: RestoreAllItemsVisibility has reset all UI elements to visible state\");\n }\n \n /// \n /// Applies the current search text to filter items.\n /// \n protected override void ApplySearch()\n {\n LogInfo($\"OptimizeViewModel: ApplySearch called with SearchText: '{SearchText}'\");\n \n // If we have no items yet, there's nothing to filter\n if (Items == null)\n return;\n \n // If this is our first time running a search and the backup isn't created yet, create it\n if (!_isInitialSearchDone && Items.Count > 0)\n {\n _allItemsBackup = new List(Items);\n _isInitialSearchDone = true;\n LogInfo($\"OptimizeViewModel: Created backup of all items ({_allItemsBackup.Count} items)\");\n }\n\n // If search is empty, restore all items visibility and the original items collection\n if (string.IsNullOrWhiteSpace(SearchText))\n {\n LogInfo(\"OptimizeViewModel: Empty search, restoring all items visibility\");\n \n // Restore visibility of UI elements first\n RestoreAllItemsVisibility();\n \n // Use the backup to restore all items\n if (_allItemsBackup.Count > 0)\n {\n LogInfo($\"OptimizeViewModel: Restoring {_allItemsBackup.Count} items from backup\");\n Items.Clear();\n foreach (var item in _allItemsBackup)\n {\n Items.Add(item);\n }\n }\n else if (Items.Count == 0)\n {\n // If we don't have a backup and Items is empty (which could happen after a no-results search),\n // try to reload items\n LogInfo(\"OptimizeViewModel: No backup available and Items is empty, attempting to reload\");\n _ = LoadItemsAsync();\n }\n \n // Always set HasSearchResults to true when search is cleared\n HasSearchResults = true;\n \n // Update status text\n StatusText = \"Optimize Your Windows Settings and Performance\";\n LogInfo($\"OptimizeViewModel: Restored items, count={Items.Count}\");\n return;\n }\n\n // We're doing an active search, use the backup for filtering if available\n var itemsToFilter = _allItemsBackup.Count > 0\n ? new ObservableCollection(_allItemsBackup)\n : Items;\n \n // Normalize and clean the search text - convert to lowercase for consistent case-insensitive matching\n string normalizedSearchText = SearchText.Trim().ToLowerInvariant();\n LogInfo($\"OptimizeViewModel: Normalized search text: '{normalizedSearchText}'\");\n \n // Handle edge case: if search is empty after normalization, treat it as empty\n if (string.IsNullOrEmpty(normalizedSearchText))\n {\n // Same handling as empty search\n RestoreAllItemsVisibility();\n if (_allItemsBackup.Count > 0)\n {\n Items.Clear();\n foreach (var item in _allItemsBackup)\n {\n Items.Add(item);\n }\n }\n HasSearchResults = true;\n StatusText = \"Optimize Your Windows Settings and Performance\";\n return;\n }\n \n // Add additional logging to help diagnose search issues\n LogInfo($\"OptimizeViewModel: Starting search with term '{normalizedSearchText}'\");\n \n // Filter items based on search text - ensure we pass normalized text\n // Don't convert to lowercase here - we'll handle case insensitivity in the MatchesSearch method\n var filteredItems = FilterItems(itemsToFilter).ToList();\n \n // Log each filtered item for debugging\n foreach (var item in filteredItems)\n {\n LogInfo($\"OptimizeViewModel: Filtered item: '{item.Name}' (ID: {item.Id})\");\n }\n \n // Log the number of filtered items\n int filteredCount = filteredItems.Count;\n LogInfo($\"OptimizeViewModel: Found {filteredCount} matching items\");\n \n // Log the filtered count for debugging\n LogInfo($\"OptimizeViewModel: Initial filtered count: {filteredCount}\");\n \n // We'll update HasSearchResults after counting the actual visible items\n // This is just an initial value\n bool initialHasResults = filteredCount > 0;\n LogInfo($\"OptimizeViewModel: Initial HasSearchResults: {initialHasResults}\");\n \n // Log the filtered items for debugging\n LogInfo($\"OptimizeViewModel: Filtered items: {string.Join(\", \", filteredItems.Select(item => item.Name))}\");\n\n // Update each sub-view model's Settings collection with the normalized search text\n UpdateSubViewSettings(GamingandPerformanceOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(PrivacyOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(UpdateOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(PowerSettingsViewModel, normalizedSearchText);\n UpdateSubViewSettings(ExplorerOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(NotificationOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(SoundOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(WindowsSecuritySettingsViewModel, normalizedSearchText);\n\n // Count the actual visible items after filtering\n int visibleItemsCount = 0;\n \n // Count visible items in each category\n if (GamingandPerformanceOptimizationsViewModel?.Settings != null)\n visibleItemsCount += GamingandPerformanceOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (PrivacyOptimizationsViewModel?.Settings != null)\n visibleItemsCount += PrivacyOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (UpdateOptimizationsViewModel?.Settings != null)\n visibleItemsCount += UpdateOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (PowerSettingsViewModel?.Settings != null)\n visibleItemsCount += PowerSettingsViewModel.Settings.Count(s => s.IsVisible);\n \n if (ExplorerOptimizationsViewModel?.Settings != null)\n visibleItemsCount += ExplorerOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (NotificationOptimizationsViewModel?.Settings != null)\n visibleItemsCount += NotificationOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (SoundOptimizationsViewModel?.Settings != null)\n visibleItemsCount += SoundOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (WindowsSecuritySettingsViewModel?.Settings != null)\n visibleItemsCount += WindowsSecuritySettingsViewModel.Settings.Count(s => s.IsVisible);\n\n // Update the Items collection to match visible items\n Items.Clear();\n foreach (var setting in filteredItems)\n {\n if (setting.IsVisible)\n {\n Items.Add(setting);\n }\n }\n \n // Now update HasSearchResults based on the ACTUAL visible items count\n // This is more accurate than using the filtered count\n HasSearchResults = visibleItemsCount > 0;\n LogInfo($\"OptimizeViewModel: Final HasSearchResults: {HasSearchResults} (visibleItemsCount: {visibleItemsCount})\");\n\n // Update status text with correct count\n if (IsSearchActive)\n {\n StatusText = $\"Found {visibleItemsCount} settings matching '{SearchText}'\";\n LogInfo($\"OptimizeViewModel: StatusText updated to: '{StatusText}' with {visibleItemsCount} visible items\");\n }\n else\n {\n StatusText = $\"Showing all {Items.Count} optimization settings\";\n LogInfo($\"OptimizeViewModel: StatusText updated to: '{StatusText}'\");\n }\n }\n\n /// \n /// Updates a sub-view model's Settings collection based on search text.\n /// \n /// The sub-view model to update.\n /// The normalized search text to match against.\n private void UpdateSubViewSettings(object viewModel, string searchText)\n {\n if (viewModel == null)\n return;\n\n // Use dynamic to access properties without knowing the exact type\n dynamic dynamicViewModel = viewModel;\n \n if (dynamicViewModel.Settings == null)\n return;\n\n // If not searching, show all settings\n if (!IsSearchActive)\n {\n foreach (var setting in dynamicViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n \n // Update the view model's visibility\n dynamicViewModel.HasVisibleSettings = dynamicViewModel.Settings.Count > 0;\n \n LogInfo($\"OptimizeViewModel: Set all settings visible in {dynamicViewModel.GetType().Name}\");\n return;\n }\n\n // When searching, only show settings that match the search criteria\n bool hasVisibleSettings = false;\n int visibleCount = 0;\n \n foreach (var setting in dynamicViewModel.Settings)\n {\n // Use partial matching instead of exact name matching\n // This matches the same logic used in OptimizationSettingItem.MatchesSearch()\n bool matchesName = setting.Name != null &&\n setting.Name.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0;\n bool matchesDescription = setting.Description != null &&\n setting.Description.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0;\n bool matchesGroupName = setting.GroupName != null &&\n setting.GroupName.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0;\n \n // Set visibility based on any match\n setting.IsVisible = matchesName || matchesDescription || matchesGroupName;\n \n // Log when we find a match for debugging\n if (setting.IsVisible)\n {\n LogInfo($\"OptimizeViewModel: Setting '{setting.Name}' is visible in {viewModel.GetType().Name}\");\n }\n \n if (setting.IsVisible)\n {\n hasVisibleSettings = true;\n visibleCount++;\n }\n }\n \n // Update the view model's visibility\n dynamicViewModel.HasVisibleSettings = hasVisibleSettings;\n \n LogInfo($\"OptimizeViewModel: {dynamicViewModel.GetType().Name} has {visibleCount} visible settings, HasVisibleSettings={hasVisibleSettings}\");\n }\n\n // SaveConfig and ImportConfig methods removed as part of unified configuration cleanup\n\n /// \n /// Gets the name of the UAC level.\n /// \n /// The UAC level (0=Low, 1=Moderate, 2=High).\n /// The name of the UAC level.\n private string GetUacLevelName(int level)\n {\n return level switch\n {\n 0 => \"Low\",\n 1 => \"Moderate\",\n 2 => \"High\",\n _ => \"Unknown\"\n };\n }\n\n /// \n /// Called when the view model is navigated to.\n /// \n /// The navigation parameter.\n public override async void OnNavigatedTo(object parameter)\n {\n LogInfo(\"OptimizeViewModel.OnNavigatedTo called\");\n\n try\n {\n // If not already initialized, initialize now\n if (!IsInitialized)\n {\n await InitializeAsync(CancellationToken.None);\n }\n else\n {\n // Just refresh the settings status\n await RefreshSettingsStatusAsync();\n }\n }\n catch (Exception ex)\n {\n LogError($\"Error in OptimizeViewModel.OnNavigatedTo: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Initializes the view model asynchronously.\n /// \n /// A cancellation token that can be used to cancel the operation.\n /// A task representing the asynchronous operation.\n private async Task InitializeAsync(CancellationToken cancellationToken)\n {\n if (IsInitialized)\n return;\n\n try\n {\n IsLoading = true;\n LogInfo(\"Initializing OptimizeViewModel\");\n\n // Create a progress reporter\n var progress = new Progress(detail => {\n // Report progress through the task progress service\n int progress = detail.Progress.HasValue ? (int)detail.Progress.Value : 0;\n ProgressService.UpdateProgress(progress, detail.StatusText);\n });\n\n // Initialize settings sequentially to provide better progress reporting\n ProgressService.UpdateProgress(0, \"Loading Windows security settings...\");\n await WindowsSecuritySettingsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(10, \"Loading gaming settings...\");\n await GamingandPerformanceOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(25, \"Loading privacy settings...\");\n await PrivacyOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(40, \"Loading update settings...\");\n await UpdateOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(55, \"Loading power settings...\");\n await PowerSettingsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(70, \"Loading explorer settings...\");\n await ExplorerOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(80, \"Loading notification settings...\");\n await NotificationOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(90, \"Loading sound settings...\");\n await SoundOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(100, \"Initialization complete\");\n\n // Mark as initialized\n IsInitialized = true;\n\n LogInfo(\"OptimizeViewModel initialized successfully\");\n }\n catch (Exception ex)\n {\n LogError($\"Error initializing OptimizeViewModel: {ex.Message}\", ex);\n throw; // Rethrow to ensure the caller knows initialization failed\n }\n finally\n {\n IsLoading = false;\n }\n }\n \n /// \n /// Ensures all child view models are initialized and have loaded their settings.\n /// \n private async Task EnsureChildViewModelsInitialized()\n {\n _logService.Log(LogLevel.Debug, \"Ensuring all child view models are initialized\");\n \n // Create a list of tasks to initialize all child view models\n var initializationTasks = new List();\n \n // Windows Security Settings\n if (WindowsSecuritySettingsViewModel != null && WindowsSecuritySettingsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading WindowsSecuritySettingsViewModel settings\");\n initializationTasks.Add(WindowsSecuritySettingsViewModel.LoadSettingsAsync());\n }\n \n // Gaming and Performance Settings\n if (GamingandPerformanceOptimizationsViewModel != null && GamingandPerformanceOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading GamingandPerformanceOptimizationsViewModel settings\");\n initializationTasks.Add(GamingandPerformanceOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Privacy Settings\n if (PrivacyOptimizationsViewModel != null && PrivacyOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading PrivacyOptimizationsViewModel settings\");\n initializationTasks.Add(PrivacyOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Update Settings\n if (UpdateOptimizationsViewModel != null && UpdateOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading UpdateOptimizationsViewModel settings\");\n initializationTasks.Add(UpdateOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Power Settings\n if (PowerSettingsViewModel != null && PowerSettingsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading PowerSettingsViewModel settings\");\n initializationTasks.Add(PowerSettingsViewModel.LoadSettingsAsync());\n }\n \n // Explorer Settings\n if (ExplorerOptimizationsViewModel != null && ExplorerOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading ExplorerOptimizationsViewModel settings\");\n initializationTasks.Add(ExplorerOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Notification Settings\n if (NotificationOptimizationsViewModel != null && NotificationOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading NotificationOptimizationsViewModel settings\");\n initializationTasks.Add(NotificationOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Sound Settings\n if (SoundOptimizationsViewModel != null && SoundOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading SoundOptimizationsViewModel settings\");\n initializationTasks.Add(SoundOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Wait for all initialization tasks to complete\n if (initializationTasks.Count > 0)\n {\n _logService.Log(LogLevel.Debug, $\"Waiting for {initializationTasks.Count} child view models to initialize\");\n await Task.WhenAll(initializationTasks);\n _logService.Log(LogLevel.Debug, \"All child view models initialized\");\n }\n else\n {\n _logService.Log(LogLevel.Debug, \"All child view models were already initialized\");\n }\n }\n\n /// \n /// Refreshes the status of all settings.\n /// \n /// A task representing the asynchronous operation.\n private async Task RefreshSettingsStatusAsync()\n {\n try\n {\n IsLoading = true;\n LogInfo(\"Refreshing settings status\");\n\n // Refresh all settings view models\n var refreshTasks = new List\n {\n WindowsSecuritySettingsViewModel.CheckSettingStatusesAsync(),\n GamingandPerformanceOptimizationsViewModel.CheckSettingStatusesAsync(),\n PrivacyOptimizationsViewModel.CheckSettingStatusesAsync(),\n UpdateOptimizationsViewModel.CheckSettingStatusesAsync(),\n PowerSettingsViewModel.CheckSettingStatusesAsync(),\n ExplorerOptimizationsViewModel.CheckSettingStatusesAsync(),\n NotificationOptimizationsViewModel.CheckSettingStatusesAsync(),\n SoundOptimizationsViewModel.CheckSettingStatusesAsync()\n };\n\n // Wait for all refresh tasks to complete\n await Task.WhenAll(refreshTasks);\n\n LogInfo(\"Settings status refreshed successfully\");\n }\n catch (Exception ex)\n {\n LogError($\"Error refreshing settings status: {ex.Message}\", ex);\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Handles the checkbox state changed event for optimization settings.\n /// \n /// The setting that was changed.\n [RelayCommand]\n private void SettingChanged(Winhance.WPF.Features.Common.Models.ApplicationSettingItem setting)\n {\n if (_updatingCheckboxes)\n return;\n\n try\n {\n _updatingCheckboxes = true;\n\n if (setting.RegistrySetting?.Category == \"PowerPlan\")\n {\n // Handle power plan changes separately\n // This would call a method to change the power plan\n LogInfo($\"Power plan setting changed: {setting.Name} to {setting.IsSelected}\");\n }\n else\n {\n // Apply registry change\n if (setting.RegistrySetting != null)\n {\n // Use EnabledValue/DisabledValue if available, otherwise fall back to RecommendedValue/DefaultValue\n string valueToSet;\n if (setting.IsSelected)\n {\n var enabledValue = setting.RegistrySetting.EnabledValue ?? setting.RegistrySetting.RecommendedValue;\n valueToSet = enabledValue.ToString();\n }\n else\n {\n var disabledValue = setting.RegistrySetting.DisabledValue ?? setting.RegistrySetting.DefaultValue;\n valueToSet = disabledValue?.ToString() ?? \"\";\n }\n\n var result = _registryService.SetValue(\n setting.RegistrySetting.Hive + \"\\\\\" + setting.RegistrySetting.SubKey,\n setting.RegistrySetting.Name,\n valueToSet,\n setting.RegistrySetting.ValueType);\n\n if (result)\n {\n LogInfo($\"Setting applied: {setting.Name}\");\n\n // Check if restart is required based on setting category or name\n bool requiresRestart = setting.Name.Contains(\"restart\", StringComparison.OrdinalIgnoreCase);\n\n if (requiresRestart)\n {\n _dialogService.ShowMessage(\n \"Some changes require a system restart to take effect.\",\n \"Restart Required\");\n }\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Failed to apply setting: {setting.Name}\");\n\n // Revert the checkbox state\n setting.IsSelected = !setting.IsSelected;\n\n _dialogService.ShowMessage(\n $\"Failed to apply the setting: {setting.Name}. This may require administrator privileges.\",\n \"Error\");\n }\n }\n }\n catch (Exception ex)\n {\n LogError($\"Error applying setting: {ex.Message}\", ex);\n\n // Revert the checkbox state\n setting.IsSelected = !setting.IsSelected;\n\n _dialogService.ShowMessage(\n $\"An error occurred: {ex.Message}\",\n \"Error\");\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n // Note: ApplyOptimizationsCommand has been removed as settings are now applied immediately when toggled\n \n // The CreateOptimizationSettingItem method has been removed as it's no longer needed\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Implementations/WinGetInstaller.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.Logging;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Verification;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.Extensions;\nusing Winhance.Infrastructure.Features.Common.Utilities;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Utilities;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Implementations\n{\n /// \n /// Implements the interface for managing packages with WinGet.\n /// \n public class WinGetInstaller : IWinGetInstaller\n {\n private const string WinGetExe = \"winget.exe\";\n private readonly IPowerShellExecutionService _powerShellService;\n private readonly ITaskProgressService _taskProgressService;\n private readonly IInstallationVerifier _installationVerifier;\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The PowerShell factory for executing commands.\n /// The task progress service for reporting progress.\n /// The installation verifier to check if packages are installed.\n /// The logging service for logging messages.\n public WinGetInstaller(\n IPowerShellExecutionService powerShellService,\n ITaskProgressService taskProgressService,\n IInstallationVerifier installationVerifier = null,\n ILogService logService = null\n )\n {\n _powerShellService =\n powerShellService ?? throw new ArgumentNullException(nameof(powerShellService));\n _taskProgressService =\n taskProgressService ?? throw new ArgumentNullException(nameof(taskProgressService));\n _installationVerifier =\n installationVerifier\n ?? new CompositeInstallationVerifier(GetDefaultVerificationMethods());\n _logService = logService;\n }\n\n /// \n public async Task InstallPackageAsync(\n string packageId,\n InstallationOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n options ??= new InstallationOptions();\n var arguments = new StringBuilder(\n $\"install --id {EscapeArgument(packageId)} --accept-package-agreements --accept-source-agreements --disable-interactivity --silent --force\"\n );\n\n if (!string.IsNullOrWhiteSpace(options.Version))\n arguments.Append($\" --version {EscapeArgument(options.Version)}\");\n\n // Force parameter is now always included\n // Interactive is disabled with --disable-interactivity\n // Silent is now always included\n\n try\n {\n // Create a wrapper function that will be passed to the extension method\n Func, Task> operation = async (\n progress\n ) =>\n {\n var commandResult = await ExecuteWinGetCommandAsync(\n WinGetExe,\n arguments.ToString(),\n progress,\n cancellationToken\n )\n .ConfigureAwait(false);\n\n // Convert the command result to an InstallationResult\n return new InstallationResult\n {\n Success = commandResult.ExitCode == 0,\n Message =\n commandResult.ExitCode == 0\n ? $\"Successfully installed {packageId}\"\n : $\"Failed to install {packageId}. Exit code: {commandResult.ExitCode}. Error: {commandResult.Error}\",\n PackageId = packageId,\n Version = options?.Version,\n };\n };\n\n // Use the display name if provided, otherwise use packageId\n string nameToDisplay = displayName ?? packageId;\n\n // Use the extension method to track progress\n var result = await _taskProgressService\n .TrackWinGetInstallationAsync(operation, nameToDisplay, cancellationToken)\n .ConfigureAwait(false);\n\n if (result.ExitCode != 0)\n {\n return new InstallationResult\n {\n Success = false,\n Message =\n $\"Failed to install {packageId}. Exit code: {result.ExitCode}. Error: {result.Error}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n\n // For Microsoft Store apps, trust the WinGet exit code as the primary indicator of success\n bool isMicrosoftStoreApp =\n packageId.All(char.IsLetterOrDigit) && !packageId.Contains('.');\n\n if (isMicrosoftStoreApp)\n {\n _logService?.LogInformation(\n $\"Microsoft Store app detected: {packageId}. Using WinGet exit code for success determination.\"\n );\n\n // For Microsoft Store apps, trust the exit code\n return new InstallationResult\n {\n Success = true, // WinGet command succeeded, so consider the installation successful\n Message = $\"Successfully installed {packageId} {options.Version}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n\n // For regular apps, try verification with a longer delay\n try\n {\n // Add a longer delay for verification to allow Windows to complete registration\n await Task.Delay(TimeSpan.FromSeconds(3), cancellationToken)\n .ConfigureAwait(false);\n\n var verification = await _installationVerifier\n .VerifyInstallationAsync(packageId, options.Version, cancellationToken)\n .ConfigureAwait(false);\n\n // If verification succeeds, great! If not, but WinGet reported success, trust WinGet\n bool success = verification.IsVerified || result.ExitCode == 0;\n\n return new InstallationResult\n {\n Success = success,\n Message = success\n ? $\"Successfully installed {packageId} {options.Version}\"\n : $\"Installation may have failed: {verification.Message}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n catch (Exception ex)\n {\n _logService?.LogWarning(\n $\"Verification failed with error: {ex.Message}. Using WinGet exit code for success determination.\"\n );\n\n // If verification throws an exception, trust the WinGet exit code\n return new InstallationResult\n {\n Success = true, // WinGet command succeeded, so consider the installation successful\n Message =\n $\"Successfully installed {packageId} {options.Version} (verification skipped due to error)\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n return new InstallationResult\n {\n Success = false,\n Message = $\"Error installing {packageId}: {ex.Message}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n }\n\n /// \n public async Task UpgradePackageAsync(\n string packageId,\n UpgradeOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n options ??= new UpgradeOptions();\n var arguments = new StringBuilder(\n $\"upgrade --id {EscapeArgument(packageId)} --accept-package-agreements --accept-source-agreements --disable-interactivity --silent --force\"\n );\n\n // Force parameter is now always included\n // Interactive is disabled with --disable-interactivity\n // Silent is now always included\n\n try\n {\n // Create a wrapper function that will be passed to the extension method\n Func, Task> operation = async (\n progress\n ) =>\n {\n // Create an adapter since ExecuteWinGetCommandAsync expects InstallationProgress\n var progressAdapter = new Progress(p =>\n {\n // Convert InstallationProgress to UpgradeProgress\n progress.Report(\n new UpgradeProgress\n {\n Percentage = p.Percentage,\n Status = p.Status,\n IsIndeterminate = p.IsIndeterminate,\n }\n );\n });\n\n var commandResult = await ExecuteWinGetCommandAsync(\n WinGetExe,\n arguments.ToString(),\n progressAdapter,\n cancellationToken\n )\n .ConfigureAwait(false);\n\n // Convert the command result to an UpgradeResult\n return new UpgradeResult\n {\n Success = commandResult.ExitCode == 0,\n Message =\n commandResult.ExitCode == 0\n ? $\"Successfully upgraded {packageId}\"\n : $\"Failed to upgrade {packageId}. Exit code: {commandResult.ExitCode}. Error: {commandResult.Error}\",\n PackageId = packageId,\n Version = options?.Version,\n };\n };\n\n // Use the display name if provided, otherwise use packageId\n string nameToDisplay = displayName ?? packageId;\n\n // Use the extension method to track progress\n var result = await _taskProgressService\n .TrackWinGetUpgradeAsync(operation, nameToDisplay, cancellationToken)\n .ConfigureAwait(false);\n\n if (result.ExitCode != 0)\n {\n return new UpgradeResult\n {\n Success = false,\n Message =\n $\"Failed to upgrade {packageId}. Exit code: {result.ExitCode}. Error: {result.Error}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n\n // For Microsoft Store apps, trust the WinGet exit code as the primary indicator of success\n bool isMicrosoftStoreApp =\n packageId.All(char.IsLetterOrDigit) && !packageId.Contains('.');\n\n if (isMicrosoftStoreApp)\n {\n _logService?.LogInformation(\n $\"Microsoft Store app detected: {packageId}. Using WinGet exit code for success determination.\"\n );\n\n // For Microsoft Store apps, trust the exit code\n return new UpgradeResult\n {\n Success = true, // WinGet command succeeded, so consider the upgrade successful\n Message = $\"Successfully upgraded {packageId} to {options.Version}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n\n // For regular apps, try verification with a longer delay\n try\n {\n // Add a longer delay for verification to allow Windows to complete registration\n await Task.Delay(TimeSpan.FromSeconds(3), cancellationToken)\n .ConfigureAwait(false);\n\n var verificationResult = await _installationVerifier\n .VerifyInstallationAsync(packageId, options.Version, cancellationToken)\n .ConfigureAwait(false);\n\n // If verification succeeds, great! If not, but WinGet reported success, trust WinGet\n bool success = verificationResult.IsVerified || result.ExitCode == 0;\n\n return new UpgradeResult\n {\n Success = success,\n Message = success\n ? $\"Successfully upgraded {packageId} to {options.Version}\"\n : $\"Upgrade may have failed: {verificationResult.Message}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n catch (Exception ex)\n {\n _logService?.LogWarning(\n $\"Verification failed with error: {ex.Message}. Using WinGet exit code for success determination.\"\n );\n\n // If verification throws an exception, trust the WinGet exit code\n return new UpgradeResult\n {\n Success = true, // WinGet command succeeded, so consider the upgrade successful\n Message =\n $\"Successfully upgraded {packageId} to {options.Version} (verification skipped due to error)\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n }\n catch (Exception ex)\n {\n return new UpgradeResult\n {\n Success = false,\n Message = $\"Error upgrading {packageId}: {ex.Message}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n }\n\n /// \n public async Task UninstallPackageAsync(\n string packageId,\n UninstallationOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n options ??= new UninstallationOptions();\n var arguments = new StringBuilder(\n $\"uninstall --id {EscapeArgument(packageId)} --accept-package-agreements --accept-source-agreements --disable-interactivity --silent --force\"\n );\n\n // Force parameter is now always included\n // Interactive is disabled with --disable-interactivity\n // Silent is now always included\n\n try\n {\n // Create a wrapper function that will be passed to the extension method\n Func, Task> operation =\n async (progress) =>\n {\n // Create an adapter since ExecuteWinGetCommandAsync expects InstallationProgress\n var progressAdapter = new Progress(p =>\n {\n // Convert InstallationProgress to UninstallationProgress\n progress.Report(\n new UninstallationProgress\n {\n Percentage = p.Percentage,\n Status = p.Status,\n IsIndeterminate = p.IsIndeterminate,\n }\n );\n });\n\n var commandResult = await ExecuteWinGetCommandAsync(\n WinGetExe,\n arguments.ToString(),\n progressAdapter,\n cancellationToken\n )\n .ConfigureAwait(false);\n\n // Convert the command result to an UninstallationResult\n return new UninstallationResult\n {\n Success = commandResult.ExitCode == 0,\n Message =\n commandResult.ExitCode == 0\n ? $\"Successfully uninstalled {packageId}\"\n : $\"Failed to uninstall {packageId}. Exit code: {commandResult.ExitCode}. Error: {commandResult.Error}\",\n PackageId = packageId,\n };\n };\n\n // Use the display name if provided, otherwise use packageId\n string nameToDisplay = displayName ?? packageId;\n\n // Use the extension method to track progress\n var result = await _taskProgressService\n .TrackWinGetUninstallationAsync(operation, nameToDisplay, cancellationToken)\n .ConfigureAwait(false);\n\n if (result.ExitCode != 0)\n {\n return new UninstallationResult\n {\n Success = false,\n Message =\n $\"Failed to uninstall {packageId}. Exit code: {result.ExitCode}. Error: {result.Error}\",\n PackageId = packageId,\n };\n }\n\n // Verify uninstallation (should return false if successfully uninstalled)\n var verification = await _installationVerifier\n .VerifyInstallationAsync(packageId, null, cancellationToken)\n .ConfigureAwait(false);\n\n return new UninstallationResult\n {\n Success = !verification.IsVerified,\n Message = !verification.IsVerified\n ? $\"Successfully uninstalled {packageId}\"\n : $\"Uninstallation may have failed: {verification.Message}\",\n PackageId = packageId,\n };\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n return new UninstallationResult\n {\n Success = false,\n Message = $\"Error uninstalling {packageId}: {ex.Message}\",\n PackageId = packageId,\n };\n }\n }\n\n /// \n public async Task GetPackageInfoAsync(\n string packageId,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n try\n {\n var arguments = $\"show --id {EscapeArgument(packageId)} --accept-source-agreements\";\n var result = await ExecuteWinGetCommandAsync(\n WinGetExe,\n arguments,\n null,\n cancellationToken\n )\n .ConfigureAwait(false);\n\n if (result.ExitCode != 0)\n {\n return null;\n }\n\n return ParsePackageInfo(result.Output);\n }\n catch (Exception)\n {\n return null;\n }\n }\n\n /// \n public async Task> SearchPackagesAsync(\n string query,\n SearchOptions options = null,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(query))\n throw new ArgumentException(\n \"Search query cannot be null or whitespace.\",\n nameof(query)\n );\n\n options ??= new SearchOptions();\n var arguments = new StringBuilder(\n $\"search {EscapeArgument(query)} --accept-source-agreements\"\n );\n\n if (options.IncludeAvailable)\n arguments.Append(\" --available\");\n\n if (options.Count > 0)\n arguments.Append($\" --max {options.Count}\");\n\n try\n {\n var result = await ExecuteWinGetCommandAsync(\n WinGetExe,\n arguments.ToString(),\n null,\n cancellationToken\n )\n .ConfigureAwait(false);\n\n if (result.ExitCode != 0)\n {\n return Enumerable.Empty();\n }\n\n return ParsePackageList(result.Output);\n }\n catch (Exception)\n {\n return Enumerable.Empty();\n }\n }\n\n private IEnumerable GetDefaultVerificationMethods()\n {\n return new IVerificationMethod[]\n {\n new WinGetVerificationMethod(),\n new AppxPackageVerificationMethod(),\n new RegistryVerificationMethod(),\n new FileSystemVerificationMethod(),\n };\n }\n\n /// \n /// Checks if WinGet is available in the PATH.\n /// \n /// True if WinGet is in the PATH, false otherwise.\n private bool IsWinGetInPath()\n {\n var pathEnv = Environment.GetEnvironmentVariable(\"PATH\") ?? string.Empty;\n return pathEnv\n .Split(Path.PathSeparator)\n .Any(p => !string.IsNullOrEmpty(p) && File.Exists(Path.Combine(p, WinGetExe)));\n }\n \n /// \n /// Tries to verify WinGet is working by running a simple command (winget -v)\n /// \n /// True if WinGet command works, false otherwise\n private bool TryVerifyWinGetCommand()\n {\n try\n {\n _logService?.LogInformation(\"Verifying WinGet by running 'winget -v' command\");\n \n // Create a process to run WinGet version command\n var processStartInfo = new ProcessStartInfo\n {\n FileName = WinGetExe,\n Arguments = \"-v\",\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n UseShellExecute = false,\n CreateNoWindow = true,\n };\n \n using (var process = new Process { StartInfo = processStartInfo })\n {\n try\n {\n if (process.Start())\n {\n // Wait for the process to exit with a timeout\n if (process.WaitForExit(5000)) // 5 second timeout\n {\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n \n // If we got output and no error, WinGet is working\n if (!string.IsNullOrWhiteSpace(output) && string.IsNullOrWhiteSpace(error))\n {\n _logService?.LogInformation($\"WinGet command verification successful, version: {output.Trim()}\");\n return true;\n }\n else if (!string.IsNullOrWhiteSpace(error))\n {\n _logService?.LogWarning($\"WinGet command verification failed with error: {error.Trim()}\");\n }\n }\n else\n {\n // Process didn't exit within timeout\n _logService?.LogWarning(\"WinGet command verification timed out\");\n try { process.Kill(); } catch { }\n }\n }\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error verifying WinGet command: {ex.Message}\");\n }\n }\n \n // Try an alternative approach - using WindowsApps path directly\n string windowsAppsPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Microsoft\\\\WindowsApps\"\n );\n \n if (Directory.Exists(windowsAppsPath))\n {\n processStartInfo.FileName = Path.Combine(windowsAppsPath, WinGetExe);\n _logService?.LogInformation($\"Trying alternative WinGet path: {processStartInfo.FileName}\");\n \n if (File.Exists(processStartInfo.FileName))\n {\n using (var process = new Process { StartInfo = processStartInfo })\n {\n try\n {\n if (process.Start())\n {\n if (process.WaitForExit(5000))\n {\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n \n if (!string.IsNullOrWhiteSpace(output) && string.IsNullOrWhiteSpace(error))\n {\n _logService?.LogInformation($\"Alternative WinGet path verification successful, version: {output.Trim()}\");\n return true;\n }\n }\n }\n }\n catch { }\n }\n }\n }\n \n return false;\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error in TryVerifyWinGetCommand: {ex.Message}\", ex);\n return false;\n }\n }\n\n private async Task TryInstallWinGetAsync(CancellationToken cancellationToken)\n {\n try\n {\n _logService?.LogInformation(\"WinGet not found. Attempting to install WinGet...\");\n\n // Create a progress adapter for the task progress service\n var progressAdapter = new Progress(progress =>\n {\n _taskProgressService?.UpdateDetailedProgress(progress);\n });\n\n // Use the WinGetInstallationScript to install WinGet\n var result = await WinGetInstallationScript.InstallWinGetAsync(\n progressAdapter,\n _logService,\n cancellationToken\n );\n\n bool success = result.Success;\n string message = result.Message;\n\n if (success)\n {\n _logService?.LogInformation(\"WinGet was successfully installed.\");\n return true;\n }\n else\n {\n _logService?.LogError($\"Failed to install WinGet: {message}\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error installing WinGet: {ex.Message}\", ex);\n return false;\n }\n }\n\n private async Task<(string WinGetPath, bool JustInstalled)> FindWinGetPathAsync(\n CancellationToken cancellationToken = default\n )\n {\n // First try to verify WinGet by running a command\n if (TryVerifyWinGetCommand())\n {\n _logService?.LogInformation(\"WinGet command verified and working\");\n return (WinGetExe, false);\n }\n\n // Check if winget is in the PATH\n if (IsWinGetInPath())\n {\n return (WinGetExe, false);\n }\n\n // Check common installation paths\n var possiblePaths = new[]\n {\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n @\"Microsoft\\WindowsApps\\winget.exe\"\n ),\n @\"C:\\Program Files\\WindowsApps\\Microsoft.DesktopAppInstaller_*\\winget.exe\",\n };\n\n // Try to find WinGet in common locations\n string foundPath = null;\n foreach (var pathPattern in possiblePaths)\n {\n if (pathPattern.Contains(\"*\"))\n {\n // Handle wildcard paths\n var directory = Path.GetDirectoryName(pathPattern);\n var filePattern = Path.GetFileName(pathPattern);\n \n if (Directory.Exists(directory))\n {\n var matchingFiles = Directory.GetFiles(directory, filePattern, SearchOption.AllDirectories);\n if (matchingFiles.Length > 0)\n {\n foundPath = matchingFiles[0];\n _logService?.LogInformation($\"Found WinGet at: {foundPath}\");\n return (foundPath, false);\n }\n }\n }\n else if (File.Exists(pathPattern))\n {\n foundPath = pathPattern;\n _logService?.LogInformation($\"Found WinGet at: {foundPath}\");\n return (foundPath, false);\n }\n }\n\n // If WinGet is not found, try to install it\n if (await TryInstallWinGetAsync(cancellationToken))\n {\n _logService?.LogInformation(\"WinGet installation completed, verifying installation\");\n \n // First try to verify WinGet by running a command after installation\n if (TryVerifyWinGetCommand())\n {\n _logService?.LogInformation(\"WinGet command verified and working after installation\");\n return (WinGetExe, true);\n }\n \n // After installation, check if it's now in the PATH\n if (IsWinGetInPath())\n {\n return (WinGetExe, true);\n }\n\n // Check the common paths again\n foreach (var pathPattern in possiblePaths)\n {\n if (pathPattern.Contains(\"*\"))\n {\n // Handle wildcard paths\n var directory = Path.GetDirectoryName(pathPattern);\n var filePattern = Path.GetFileName(pathPattern);\n \n if (Directory.Exists(directory))\n {\n var matchingFiles = Directory.GetFiles(directory, filePattern, SearchOption.AllDirectories);\n if (matchingFiles.Length > 0)\n {\n foundPath = matchingFiles[0];\n _logService?.LogInformation($\"Found WinGet at: {foundPath}\");\n return (foundPath, true);\n }\n }\n }\n else if (File.Exists(pathPattern))\n {\n foundPath = pathPattern;\n _logService?.LogInformation($\"Found WinGet at: {foundPath}\");\n return (foundPath, true);\n }\n }\n }\n\n // If we still can't find it, throw an exception\n throw new InvalidOperationException(\"WinGet not found and installation failed.\");\n }\n\n private string FindWinGetPath()\n {\n try\n {\n // Call the async method synchronously\n var result = FindWinGetPathAsync().GetAwaiter().GetResult();\n return result.WinGetPath;\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error finding WinGet: {ex.Message}\", ex);\n throw;\n }\n }\n\n // Installation states have been moved to WinGetOutputParser.InstallationState\n\n private async Task<(int ExitCode, string Output, string Error)> ExecuteWinGetCommandAsync(\n string command,\n string arguments,\n IProgress progressAdapter = null,\n CancellationToken cancellationToken = default\n )\n {\n var commandLine = $\"{command} {arguments}\";\n _logService?.LogInformation($\"Executing WinGet command: {commandLine}\");\n\n try\n {\n // Find WinGet path or install it if not found\n string winGetPath;\n bool justInstalled = false;\n try\n {\n (winGetPath, justInstalled) = await FindWinGetPathAsync(cancellationToken);\n }\n catch (InvalidOperationException ex)\n {\n _logService?.LogError($\"WinGet error: {ex.Message}\");\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = $\"Error: {ex.Message}\",\n Percentage = 0,\n IsIndeterminate = false,\n }\n );\n return (1, string.Empty, ex.Message);\n }\n \n // If WinGet was just installed, we might need to wait a moment for permissions to be set up\n // This is especially important on LTSC editions where there can be a delay\n if (justInstalled)\n {\n _logService?.LogInformation(\"WinGet was just installed. Waiting briefly before proceeding...\");\n await Task.Delay(2000, cancellationToken); // Wait 2 seconds\n \n // Notify the user that WinGet was installed and we're continuing with the app installation\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"WinGet was successfully installed. Continuing with application installation...\",\n Percentage = 30,\n IsIndeterminate = false,\n }\n );\n \n // For LTSC editions, we need to use a different approach after installation\n // Try to use the full path to WinGet if it's not just \"winget.exe\"\n if (!string.Equals(winGetPath, WinGetExe, StringComparison.OrdinalIgnoreCase))\n {\n _logService?.LogInformation($\"Using full path to WinGet: {winGetPath}\");\n \n // Check if the file exists and is accessible\n if (File.Exists(winGetPath))\n {\n try\n {\n // Test file access permissions\n using (File.OpenRead(winGetPath)) { }\n _logService?.LogInformation(\"Successfully verified file access to WinGet executable\");\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Access issue with WinGet executable: {ex.Message}\");\n _logService?.LogInformation(\"Falling back to using 'winget.exe' command\");\n winGetPath = WinGetExe; // Fall back to using just the command name\n }\n }\n }\n }\n\n // Create a process to run WinGet directly\n var processStartInfo = new ProcessStartInfo\n {\n FileName = winGetPath,\n Arguments = arguments,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n UseShellExecute = false,\n CreateNoWindow = true,\n };\n\n _logService?.LogInformation(\n $\"Starting process: {processStartInfo.FileName} {processStartInfo.Arguments}\"\n );\n\n var process = new Process\n {\n StartInfo = processStartInfo,\n EnableRaisingEvents = true,\n };\n\n var outputBuilder = new StringBuilder();\n var errorBuilder = new StringBuilder();\n\n // Progress tracking is now handled by WinGetOutputParser\n\n // Create an output parser for processing WinGet output\n var outputParser = new WinGetOutputParser(_logService);\n \n // Report initial progress with more detailed status\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Searching for package...\",\n Percentage = 5,\n IsIndeterminate = false,\n }\n );\n\n process.OutputDataReceived += (sender, e) =>\n {\n if (e.Data != null)\n {\n outputBuilder.AppendLine(e.Data);\n \n // Parse the output line and get progress update\n var progress = outputParser.ParseOutputLine(e.Data);\n \n // Report progress if available\n if (progress != null)\n {\n progressAdapter?.Report(progress);\n }\n }\n };\n \n // The parsing functionality has been moved to WinGetOutputParser\n\n process.ErrorDataReceived += (sender, e) =>\n {\n if (e.Data != null)\n {\n errorBuilder.AppendLine(e.Data);\n _logService?.LogError($\"WinGet error: {e.Data}\");\n }\n };\n\n // Start the process\n if (!process.Start())\n {\n _logService?.LogError(\"Failed to start WinGet process\");\n return (1, string.Empty, \"Failed to start WinGet process\");\n }\n\n // Begin reading output and error streams\n process.BeginOutputReadLine();\n process.BeginErrorReadLine();\n\n // Create a task that completes when the process exits\n var processExitTask = Task.Run(\n () =>\n {\n process.WaitForExit();\n return process.ExitCode;\n },\n cancellationToken\n );\n\n // Wait for the process to exit or cancellation\n int exitCode;\n try\n {\n // Create a flag to track whether cancellation was due to user action or connectivity issues\n bool isCancellationDueToConnectivity = false;\n \n // Register cancellation callback to kill the process when cancellation is requested\n using var cancelRegistration = cancellationToken.Register(() =>\n {\n _logService?.LogWarning(\"Cancellation requested, attempting to kill WinGet process\");\n try\n {\n // Check if cancellation is due to connectivity issues\n // This is determined by examining the cancellation token's source\n // The AppInstallationCoordinatorService will set this flag when cancelling due to connectivity\n if (cancellationToken.IsCancellationRequested)\n {\n // We can't directly check the reason for cancellation from the token itself,\n // but the AppInstallationCoordinatorService will handle this distinction\n _logService?.LogWarning(\"WinGet process cancellation requested\");\n }\n \n if (!process.HasExited)\n {\n // Report cancellation progress immediately\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Cancelling installation...\",\n Percentage = 0,\n IsIndeterminate = true,\n IsCancelled = true\n }\n );\n \n // Kill the process and all child processes in a background task\n // to prevent UI stalling\n Task.Run(() => \n {\n try \n {\n KillProcessAndChildren(process.Id);\n _logService?.LogWarning(\"WinGet process and all child processes were killed due to cancellation\");\n \n // Update progress after killing processes\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Installation was cancelled\",\n Percentage = 0,\n IsIndeterminate = false,\n IsCancelled = true\n }\n );\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error killing processes: {ex.Message}\");\n }\n });\n }\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error killing WinGet process: {ex.Message}\");\n }\n });\n \n exitCode = await processExitTask;\n _logService?.LogInformation($\"WinGet process exited with code: {exitCode}\");\n\n // Report completion progress\n if (exitCode == 0)\n {\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Installation completed successfully\",\n Percentage = 100,\n IsIndeterminate = false,\n }\n );\n }\n else\n {\n // Report failure progress\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = $\"Installation failed with exit code: {exitCode}\",\n Percentage = 100,\n IsIndeterminate = false,\n IsError = true\n }\n );\n }\n }\n catch (OperationCanceledException)\n {\n _logService?.LogWarning(\"WinGet process execution was cancelled\");\n\n // Try to kill the process if it's still running\n if (!process.HasExited)\n {\n try\n {\n // Report cancellation progress immediately\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Cancelling installation...\",\n Percentage = 0,\n IsIndeterminate = true,\n IsCancelled = true\n }\n );\n \n // Kill the process and all child processes in a background task\n Task.Run(() => \n {\n try \n {\n KillProcessAndChildren(process.Id);\n _logService?.LogWarning(\n \"WinGet process and all child processes were killed due to cancellation\"\n );\n \n // Update progress after killing processes\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Installation was cancelled\",\n Percentage = 0,\n IsIndeterminate = false,\n IsCancelled = true\n }\n );\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error killing processes: {ex.Message}\");\n }\n });\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error killing WinGet process: {ex.Message}\");\n }\n }\n \n // Report cancellation progress\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Installation was cancelled\",\n Percentage = 0,\n IsIndeterminate = false,\n IsCancelled = true\n }\n );\n\n throw;\n }\n\n string output = outputBuilder.ToString();\n string error = errorBuilder.ToString();\n\n return (exitCode, output, error);\n }\n catch (Exception ex) when (!(ex is OperationCanceledException))\n {\n _logService?.LogError($\"Error executing WinGet command: {ex.Message}\", ex);\n\n // Report error progress\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = $\"Error: {ex.Message}\",\n Percentage = 0,\n IsIndeterminate = false,\n }\n );\n\n return (1, string.Empty, ex.Message);\n }\n }\n\n // These methods have been moved to WinGetOutputParser class:\n // - DetermineInstallationState\n // - CalculateProgressPercentage\n // - GetStatusMessage\n\n // Original FindWinGetPath method removed to avoid duplication\n\n /// \n /// Kills a process and all of its children recursively with optimizations to prevent UI stalling.\n /// \n /// The process ID to kill.\n private void KillProcessAndChildren(int pid)\n {\n try\n {\n // First, directly kill any Windows Store processes that might be related to the installation\n // This is a more direct approach to ensure the installation is cancelled\n KillWindowsStoreProcesses();\n \n // Get the process by ID\n Process process = null;\n try\n {\n process = Process.GetProcessById(pid);\n }\n catch (ArgumentException)\n {\n _logService?.LogWarning($\"Process with ID {pid} not found\");\n return;\n }\n \n // Use a more efficient approach to kill the process and its children\n // with a timeout to prevent hanging\n using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)))\n {\n try\n {\n // Kill the process directly first\n if (!process.HasExited)\n {\n try\n {\n process.Kill(true); // true = kill entire process tree (Windows 10 1809+)\n _logService?.LogInformation($\"Killed process tree {process.ProcessName} (ID: {pid})\");\n return; // If this works, we're done\n }\n catch (PlatformNotSupportedException)\n {\n // Process.Kill(true) is not supported on this platform, continue with fallback\n _logService?.LogInformation(\"Process.Kill(true) not supported, using fallback method\");\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error killing process tree: {ex.Message}, using fallback method\");\n }\n }\n \n // Fallback: Kill the process and its children manually\n KillProcessTree(pid, cts.Token);\n }\n catch (OperationCanceledException)\n {\n _logService?.LogWarning(\"Process killing operation timed out\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error in KillProcessAndChildren for PID {pid}: {ex.Message}\");\n }\n }\n \n /// \n /// Kills the Windows Store processes that might be related to the installation.\n /// \n private void KillWindowsStoreProcesses()\n {\n try\n {\n // Target specific processes known to be related to Windows Store installations\n string[] targetProcessNames = new[] { \n \"WinStore.App\", \n \"WinStore.Mobile\", \n \"WindowsPackageManagerServer\", \n \"AppInstaller\",\n \"Microsoft.WindowsStore\"\n };\n \n foreach (var processName in targetProcessNames)\n {\n try\n {\n var processes = Process.GetProcessesByName(processName);\n foreach (var process in processes)\n {\n try\n {\n if (!process.HasExited)\n {\n process.Kill();\n _logService?.LogInformation($\"Killed Windows Store process: {processName}\");\n }\n }\n finally\n {\n process.Dispose();\n }\n }\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error killing Windows Store process {processName}: {ex.Message}\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error killing Windows Store processes: {ex.Message}\");\n }\n }\n \n /// \n /// Kills a process tree efficiently with cancellation support.\n /// \n /// The process ID to kill.\n /// Cancellation token to prevent hanging.\n private void KillProcessTree(int pid, CancellationToken cancellationToken)\n {\n try\n {\n // Get direct child processes using a more efficient method\n var childProcessIds = GetChildProcessIds(pid);\n \n // Kill child processes first\n foreach (var childPid in childProcessIds)\n {\n cancellationToken.ThrowIfCancellationRequested();\n \n try\n {\n // Recursively kill child process trees\n KillProcessTree(childPid, cancellationToken);\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error killing child process {childPid}: {ex.Message}\");\n }\n }\n \n // Kill the parent process\n try\n {\n var process = Process.GetProcessById(pid);\n if (!process.HasExited)\n {\n process.Kill();\n _logService?.LogInformation($\"Killed process {process.ProcessName} (ID: {pid})\");\n }\n process.Dispose();\n }\n catch (ArgumentException)\n {\n // Process already exited\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error killing process {pid}: {ex.Message}\");\n }\n }\n catch (OperationCanceledException)\n {\n throw; // Rethrow to be handled by the caller\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error in KillProcessTree for PID {pid}: {ex.Message}\");\n }\n }\n \n /// \n /// Gets the child process IDs for a given process ID efficiently.\n /// \n /// The parent process ID.\n /// A list of child process IDs.\n private List GetChildProcessIds(int parentId)\n {\n var result = new List();\n \n try\n {\n // Use a more efficient query that only gets the data we need\n using (var searcher = new System.Management.ManagementObjectSearcher(\n $\"SELECT ProcessId FROM Win32_Process WHERE ParentProcessId = {parentId}\"))\n {\n searcher.Options.Timeout = TimeSpan.FromSeconds(1); // Set a timeout to prevent hanging\n \n foreach (var obj in searcher.Get())\n {\n try\n {\n result.Add(Convert.ToInt32(obj[\"ProcessId\"]));\n }\n catch\n {\n // Skip this entry if conversion fails\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error getting child process IDs: {ex.Message}\");\n }\n \n return result;\n }\n \n private string EscapeArgument(string arg)\n {\n if (string.IsNullOrEmpty(arg))\n return \"\\\"\\\"\";\n\n // Escape any double quotes\n arg = arg.Replace(\"\\\"\", \"\\\\\\\"\");\n\n // Surround with quotes if it contains spaces\n if (arg.Contains(\" \"))\n arg = $\"\\\"{arg}\\\"\";\n\n return arg;\n }\n\n private PackageInfo ParsePackageInfo(string output)\n {\n if (string.IsNullOrWhiteSpace(output))\n return null;\n\n var info = new PackageInfo();\n var lines = output.Split(\n new[] { \"\\r\\n\", \"\\r\", \"\\n\" },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n foreach (var line in lines)\n {\n if (!line.Contains(\":\"))\n continue;\n\n var parts = line.Split(new[] { ':' }, 2);\n if (parts.Length != 2)\n continue;\n\n var key = parts[0].Trim().ToLowerInvariant();\n var value = parts[1].Trim();\n\n switch (key)\n {\n case \"id\":\n info.Id = value;\n break;\n case \"name\":\n info.Name = value;\n break;\n case \"version\":\n info.Version = value;\n break;\n // Description property doesn't exist in PackageInfo\n case \"description\":\n // info.Description = value;\n break;\n }\n }\n\n return info;\n }\n\n private IEnumerable ParsePackageList(string output)\n {\n if (string.IsNullOrWhiteSpace(output))\n yield break;\n\n var lines = output.Split(\n new[] { \"\\r\\n\", \"\\r\", \"\\n\" },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n // Skip header lines\n bool headerPassed = false;\n for (int i = 0; i < lines.Length; i++)\n {\n var line = lines[i].Trim();\n\n // Skip empty lines\n if (string.IsNullOrWhiteSpace(line))\n continue;\n\n // Skip until we find a line with dashes (header separator)\n if (!headerPassed)\n {\n if (line.Contains(\"---\"))\n {\n headerPassed = true;\n }\n continue;\n }\n\n // Parse package info from the line\n var parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (parts.Length < 3)\n continue;\n\n yield return new PackageInfo\n {\n Name = parts[0],\n Id = parts[1],\n Version = parts[2],\n Source = parts.Length > 3 ? parts[3] : string.Empty,\n IsInstalled = line.Contains(\"[Installed]\"),\n };\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/UpdateDialog.xaml.cs", "using System;\nusing System.Diagnostics;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media.Imaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Resources.Theme;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Update dialog that shows when a new version is available\n /// \n public partial class UpdateDialog : Window, System.ComponentModel.INotifyPropertyChanged\n {\n private readonly VersionInfo _currentVersion;\n private readonly VersionInfo _latestVersion;\n private readonly Func _downloadAndInstallAction;\n \n // Add a property for theme binding that defaults to dark theme\n private bool _isThemeDark = true;\n public bool IsThemeDark\n {\n get => _isThemeDark;\n set\n {\n if (_isThemeDark != value)\n {\n _isThemeDark = value;\n OnPropertyChanged(nameof(IsThemeDark));\n }\n }\n }\n \n public bool IsDownloading { get; private set; }\n\n // Implement INotifyPropertyChanged\n public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\n \n protected virtual void OnPropertyChanged(string propertyName)\n {\n PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\n }\n \n private UpdateDialog(string title, string message, VersionInfo currentVersion, VersionInfo latestVersion, Func downloadAndInstallAction)\n {\n InitializeComponent();\n DataContext = this;\n \n _currentVersion = currentVersion;\n _latestVersion = latestVersion;\n _downloadAndInstallAction = downloadAndInstallAction;\n \n // Try to determine the Winhance theme\n try\n {\n // First check if the theme is stored in Application.Current.Resources\n if (Application.Current.Resources.Contains(\"IsDarkTheme\"))\n {\n IsThemeDark = (bool)Application.Current.Resources[\"IsDarkTheme\"];\n }\n else\n {\n // Fall back to system theme if Winhance theme is not available\n bool systemUsesLightTheme = false;\n \n try\n {\n // Try to read the Windows registry to determine the system theme\n using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@\"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\"))\n {\n if (key != null)\n {\n var value = key.GetValue(\"AppsUseLightTheme\");\n if (value != null)\n {\n systemUsesLightTheme = Convert.ToInt32(value) == 1;\n }\n }\n }\n }\n catch (Exception)\n {\n // Ignore errors reading the registry\n }\n \n // Set the IsThemeDark property based on the system theme\n IsThemeDark = !systemUsesLightTheme;\n }\n }\n catch (Exception)\n {\n // Default to dark theme if we can't determine the theme\n IsThemeDark = true;\n }\n \n // Set up a handler to listen for theme changes\n this.Loaded += (sender, e) =>\n {\n // Listen for resource dictionary changes that might affect the theme\n if (Application.Current.Resources is System.Windows.ResourceDictionary resourceDictionary)\n {\n // Use reflection to get the event\n var eventInfo = resourceDictionary.GetType().GetEvent(\"ResourceDictionaryChanged\");\n if (eventInfo != null)\n {\n // Create a handler for the event\n EventHandler resourceChangedHandler = (s, args) =>\n {\n if (Application.Current.Resources.Contains(\"IsDarkTheme\"))\n {\n bool newIsDarkTheme = (bool)Application.Current.Resources[\"IsDarkTheme\"];\n if (IsThemeDark != newIsDarkTheme)\n {\n IsThemeDark = newIsDarkTheme;\n }\n }\n };\n \n // Add the handler to the event\n eventInfo.AddEventHandler(resourceDictionary, resourceChangedHandler);\n }\n }\n };\n \n Title = title;\n HeaderText.Text = title;\n MessageText.Text = message;\n \n // Ensure version text is properly displayed\n CurrentVersionText.Text = currentVersion.Version;\n LatestVersionText.Text = latestVersion.Version;\n \n // Make sure the footer text is visible\n FooterText.Visibility = Visibility.Visible;\n }\n \n private async void PrimaryButton_Click(object sender, RoutedEventArgs e)\n {\n try\n {\n // Disable buttons during download\n PrimaryButton.IsEnabled = false;\n SecondaryButton.IsEnabled = false;\n \n // Show progress indicator\n IsDownloading = true;\n OnPropertyChanged(nameof(IsDownloading));\n DownloadProgress.Visibility = Visibility.Visible;\n StatusText.Text = \"Downloading update...\";\n \n // Hide the footer text during download\n FooterText.Visibility = Visibility.Collapsed;\n \n // Execute the download and install action\n await _downloadAndInstallAction();\n \n // Set dialog result and close\n DialogResult = true;\n Close();\n }\n catch (Exception ex)\n {\n // Re-enable buttons\n PrimaryButton.IsEnabled = true;\n SecondaryButton.IsEnabled = true;\n \n // Hide progress indicator\n IsDownloading = false;\n OnPropertyChanged(nameof(IsDownloading));\n DownloadProgress.Visibility = Visibility.Collapsed;\n \n // Show error message\n StatusText.Text = $\"Error downloading update: {ex.Message}\";\n \n // Show the footer text again\n FooterText.Visibility = Visibility.Visible;\n }\n }\n\n private void SecondaryButton_Click(object sender, RoutedEventArgs e)\n {\n // User chose to be reminded later\n DialogResult = false;\n Close();\n }\n \n /// \n /// Shows an update dialog with the specified parameters\n /// \n /// The title of the dialog\n /// The message to display\n /// The current version information\n /// The latest version information\n /// The action to execute when the user clicks Download & Install\n /// True if the user chose to download and install, false otherwise\n public static async Task ShowAsync(\n string title, \n string message, \n VersionInfo currentVersion, \n VersionInfo latestVersion, \n Func downloadAndInstallAction)\n {\n try\n {\n var dialog = new UpdateDialog(title, message, currentVersion, latestVersion, downloadAndInstallAction)\n {\n WindowStartupLocation = WindowStartupLocation.CenterScreen,\n ShowInTaskbar = false,\n Topmost = true\n };\n \n // Set the owner to the main window to ensure it appears on top\n if (Application.Current.MainWindow != null && Application.Current.MainWindow != dialog)\n {\n dialog.Owner = Application.Current.MainWindow;\n }\n else\n {\n // Try to find the main window another way\n foreach (Window window in Application.Current.Windows)\n {\n if (window != dialog && window.IsVisible)\n {\n dialog.Owner = window;\n break;\n }\n }\n }\n \n // Show the dialog and wait for the result\n return await Task.Run(() =>\n {\n return Application.Current.Dispatcher.Invoke(() =>\n {\n try\n {\n return dialog.ShowDialog() ?? false;\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error showing dialog: {ex.Message}\");\n return false;\n }\n });\n });\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error in ShowAsync: {ex.Message}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/OptimizeView.xaml.cs", "using System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing MaterialDesignThemes.Wpf;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Messages;\nusing Winhance.WPF.Features.Optimize.ViewModels;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n public partial class OptimizeView : UserControl\n {\n private IMessengerService? _messengerService; // Changed from readonly to allow assignment\n \n // References to the child views\n private UIElement _windowsSecurityOptimizationsView;\n private UIElement _privacySettingsView;\n private UIElement _gamingandPerformanceOptimizationsView;\n private UIElement _updateOptimizationsView;\n private UIElement _powerSettingsView;\n private UIElement _explorerOptimizationsView;\n private UIElement _notificationOptimizationsView;\n private UIElement _soundOptimizationsView;\n\n public OptimizeView()\n {\n InitializeComponent();\n Loaded += OptimizeView_Loaded;\n\n // Initialize section visibility and click handlers - all visible by default\n // WindowsSecurityContent will be initialized in the Loaded event\n\n // Add click handlers to the header border elements\n WindowsSecurityHeaderBorder.MouseDown += WindowsSecurityHeader_MouseDown;\n PrivacyHeaderBorder.MouseDown += PrivacyHeader_MouseDown;\n GamingHeaderBorder.MouseDown += GamingHeader_MouseDown;\n UpdatesHeaderBorder.MouseDown += UpdatesHeader_MouseDown;\n PowerHeaderBorder.MouseDown += PowerHeader_MouseDown;\n ExplorerHeaderBorder.MouseDown += ExplorerHeader_MouseDown;\n NotificationHeaderBorder.MouseDown += NotificationHeader_MouseDown;\n SoundHeaderBorder.MouseDown += SoundHeader_MouseDown;\n \n // Subscribe to DataContextChanged event to get the messenger service\n DataContextChanged += OptimizeView_DataContextChanged;\n }\n \n private void OptimizeView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n // Unregister from old messenger service if exists\n if (_messengerService != null)\n {\n _messengerService.Unregister(this);\n _messengerService = null;\n }\n\n // Register with new messenger service if available\n if (e.NewValue is OptimizeViewModel viewModel &&\n viewModel.MessengerService is IMessengerService messengerService)\n {\n _messengerService = messengerService;\n \n // Subscribe to the message that signals resetting expansion states\n _messengerService.Register(this, OnResetExpansionState);\n }\n }\n \n private void OnResetExpansionState(ResetExpansionStateMessage message)\n {\n // Reset all section expansion states to expanded\n if (_windowsSecurityOptimizationsView != null)\n {\n _windowsSecurityOptimizationsView.Visibility = Visibility.Visible;\n WindowsSecurityHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_privacySettingsView != null)\n {\n _privacySettingsView.Visibility = Visibility.Visible;\n PrivacyHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_gamingandPerformanceOptimizationsView != null)\n {\n _gamingandPerformanceOptimizationsView.Visibility = Visibility.Visible;\n GamingHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_updateOptimizationsView != null)\n {\n _updateOptimizationsView.Visibility = Visibility.Visible;\n UpdatesHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_powerSettingsView != null)\n {\n _powerSettingsView.Visibility = Visibility.Visible;\n PowerHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_explorerOptimizationsView != null)\n {\n _explorerOptimizationsView.Visibility = Visibility.Visible;\n ExplorerHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_notificationOptimizationsView != null)\n {\n _notificationOptimizationsView.Visibility = Visibility.Visible;\n NotificationHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_soundOptimizationsView != null)\n {\n _soundOptimizationsView.Visibility = Visibility.Visible;\n SoundHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n }\n\n private async void OptimizeView_Loaded(object sender, RoutedEventArgs e)\n {\n if (DataContext is Winhance.WPF.Features.Optimize.ViewModels.OptimizeViewModel viewModel)\n {\n try\n {\n // Find the child views\n _windowsSecurityOptimizationsView = FindChildByType(this);\n _privacySettingsView = FindChildByType(this);\n _gamingandPerformanceOptimizationsView = FindChildByType(this);\n _updateOptimizationsView = FindChildByType(this);\n _powerSettingsView = FindChildByType(this);\n _explorerOptimizationsView = FindChildByType(this);\n _notificationOptimizationsView = FindChildByType(this);\n _soundOptimizationsView = FindChildByType(this);\n\n // Set initial visibility\n if (_windowsSecurityOptimizationsView != null) _windowsSecurityOptimizationsView.Visibility = Visibility.Visible;\n if (_privacySettingsView != null) _privacySettingsView.Visibility = Visibility.Visible;\n if (_gamingandPerformanceOptimizationsView != null) _gamingandPerformanceOptimizationsView.Visibility = Visibility.Visible;\n if (_updateOptimizationsView != null) _updateOptimizationsView.Visibility = Visibility.Visible;\n if (_powerSettingsView != null) _powerSettingsView.Visibility = Visibility.Visible;\n if (_explorerOptimizationsView != null) _explorerOptimizationsView.Visibility = Visibility.Visible;\n if (_notificationOptimizationsView != null) _notificationOptimizationsView.Visibility = Visibility.Visible;\n if (_soundOptimizationsView != null) _soundOptimizationsView.Visibility = Visibility.Visible;\n\n // Set header icons\n WindowsSecurityHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n PrivacyHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n GamingHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n UpdatesHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n PowerHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n ExplorerHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n NotificationHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n SoundHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n\n // Initialize data if needed\n if (viewModel.InitializeCommand != null)\n {\n Console.WriteLine(\"OptimizeView: Executing InitializeCommand\");\n await viewModel.InitializeCommand.ExecuteAsync(null);\n Console.WriteLine(\"OptimizeView: InitializeCommand completed successfully\");\n }\n else\n {\n MessageBox.Show(\"InitializeCommand is null in OptimizeViewModel\",\n \"Initialization Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error);\n }\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"OptimizeView: Error initializing - {ex.Message}\");\n MessageBox.Show($\"Error initializing Optimize view: {ex.Message}\",\n \"Initialization Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error);\n }\n }\n else\n {\n Console.WriteLine(\"OptimizeView: DataContext is not OptimizeViewModel\");\n MessageBox.Show(\"DataContext is not OptimizeViewModel\",\n \"Initialization Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error);\n }\n }\n\n private void WindowsSecurityHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n try\n {\n // Toggle section visibility\n ToggleSectionVisibility(_windowsSecurityOptimizationsView, WindowsSecurityHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n WindowsSecurityToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true; // Mark as handled to prevent the event from bubbling up\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Error toggling Windows Security Settings section: {ex.Message}\",\n \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n }\n }\n\n private void PrivacyHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n try\n {\n // Toggle section visibility\n ToggleSectionVisibility(_privacySettingsView, PrivacyHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n PrivacyToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true; // Mark as handled to prevent the event from bubbling up\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Error toggling Privacy Settings section: {ex.Message}\",\n \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n }\n }\n\n private void GamingHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_gamingandPerformanceOptimizationsView, GamingHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n GamingToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void UpdatesHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_updateOptimizationsView, UpdatesHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n UpdatesToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void PowerHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_powerSettingsView, PowerHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n PowerToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void ExplorerHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_explorerOptimizationsView, ExplorerHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n ExplorerToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void NotificationHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_notificationOptimizationsView, NotificationHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n NotificationToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void SoundHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_soundOptimizationsView, SoundHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n SoundToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void ToggleSectionVisibility(UIElement content, PackIcon icon)\n {\n if (content == null) return;\n\n if (content.Visibility == Visibility.Collapsed)\n {\n content.Visibility = Visibility.Visible;\n icon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n }\n else\n {\n content.Visibility = Visibility.Collapsed;\n icon.Kind = PackIconKind.ChevronDown; // Downward arrow for collapsed state\n }\n }\n\n /// \n /// Finds a child element of the specified type in the visual tree.\n /// \n /// The type of element to find.\n /// The parent element to search in.\n /// The first child element of the specified type, or null if not found.\n private T FindChildByType(DependencyObject parent) where T : DependencyObject\n {\n // Confirm parent and type are valid\n if (parent == null) return null;\n\n // Get child count\n int childCount = VisualTreeHelper.GetChildrenCount(parent);\n\n // Check all children\n for (int i = 0; i < childCount; i++)\n {\n var child = VisualTreeHelper.GetChild(parent, i);\n\n // If the child is the type we're looking for, return it\n if (child is T typedChild)\n {\n return typedChild;\n }\n\n // Otherwise, recursively check this child's children\n var result = FindChildByType(child);\n if (result != null)\n {\n return result;\n }\n }\n\n // If we get here, we didn't find a match\n return null;\n }\n }\n\n // Extension method to check if a visual element is a descendant of another\n public static class VisualExtensions\n {\n public static bool IsDescendantOf(this System.Windows.DependencyObject element, System.Windows.DependencyObject parent)\n {\n if (element == parent)\n return true;\n\n var currentParent = System.Windows.Media.VisualTreeHelper.GetParent(element);\n while (currentParent != null)\n {\n if (currentParent == parent)\n return true;\n currentParent = System.Windows.Media.VisualTreeHelper.GetParent(currentParent);\n }\n\n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ConfigurationPropertyUpdater.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for updating properties of configuration items.\n /// \n public class ConfigurationPropertyUpdater : IConfigurationPropertyUpdater\n {\n private readonly ILogService _logService;\n private readonly IRegistryService _registryService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The registry service.\n public ConfigurationPropertyUpdater(\n ILogService logService,\n IRegistryService registryService\n )\n {\n _logService = logService;\n _registryService = registryService;\n }\n\n /// \n /// Updates properties of items based on the configuration.\n /// \n /// The items to update.\n /// The configuration file containing the updates.\n /// The number of items that were updated.\n public async Task UpdateItemsAsync(\n IEnumerable items,\n ConfigurationFile configFile\n )\n {\n int updatedCount = 0;\n\n // Create dictionaries of config items by name and ID for faster lookup\n var configItemsByName = new Dictionary(\n StringComparer.OrdinalIgnoreCase\n );\n var configItemsById = new Dictionary(\n StringComparer.OrdinalIgnoreCase\n );\n\n if (configFile.Items != null)\n {\n foreach (var item in configFile.Items)\n {\n if (\n !string.IsNullOrEmpty(item.Name)\n && !configItemsByName.ContainsKey(item.Name)\n )\n {\n configItemsByName.Add(item.Name, item);\n }\n\n if (\n item.CustomProperties.TryGetValue(\"Id\", out var id)\n && id != null\n && !string.IsNullOrEmpty(id.ToString())\n && !configItemsById.ContainsKey(id.ToString())\n )\n {\n configItemsById.Add(id.ToString(), item);\n }\n }\n }\n\n // Update the items\n foreach (var item in items)\n {\n try\n {\n var nameProperty = item.GetType().GetProperty(\"Name\");\n var idProperty = item.GetType().GetProperty(\"Id\");\n var isSelectedProperty = item.GetType().GetProperty(\"IsSelected\");\n\n if (nameProperty != null && isSelectedProperty != null)\n {\n var name = nameProperty.GetValue(item)?.ToString();\n var id = idProperty?.GetValue(item)?.ToString();\n\n ConfigurationItem configItem = null;\n\n // Try to match by ID first\n if (\n !string.IsNullOrEmpty(id)\n && configItemsById.TryGetValue(id, out var itemById)\n )\n {\n configItem = itemById;\n }\n // Then try to match by name\n else if (\n !string.IsNullOrEmpty(name)\n && configItemsByName.TryGetValue(name, out var itemByName)\n )\n {\n configItem = itemByName;\n }\n\n if (configItem != null)\n {\n bool anyPropertyUpdated = false;\n\n // Update IsSelected - Always apply regardless of current state\n bool currentIsSelected = (bool)(\n isSelectedProperty.GetValue(item) ?? false\n );\n\n // Always set the value and apply registry settings, even if it hasn't changed\n isSelectedProperty.SetValue(item, configItem.IsSelected);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Info,\n $\"Updated IsSelected for item {name} (ID: {id}) to {configItem.IsSelected}\"\n );\n\n // Always apply registry settings for this item during import\n await ApplyRegistrySettingsAsync(item, configItem.IsSelected);\n\n // Update additional properties\n if (UpdateAdditionalProperties(item, configItem))\n {\n anyPropertyUpdated = true;\n }\n\n if (anyPropertyUpdated)\n {\n updatedCount++;\n TriggerPropertyChangedIfPossible(item);\n }\n }\n }\n }\n catch (Exception ex)\n {\n // Log the error but continue processing other items\n _logService.Log(\n LogLevel.Debug,\n $\"Error applying configuration to item: {ex.Message}\"\n );\n }\n }\n\n return updatedCount;\n }\n\n /// \n /// Updates additional properties of an item based on the configuration.\n /// \n /// The item to update.\n /// The configuration item containing the updates.\n /// True if any properties were updated, false otherwise.\n public bool UpdateAdditionalProperties(object item, ConfigurationItem configItem)\n {\n bool anyPropertyUpdated = false;\n\n try\n {\n // Get the item type to access its properties\n var itemType = item.GetType();\n var itemName =\n itemType.GetProperty(\"Name\")?.GetValue(item)?.ToString() ?? \"Unknown\";\n var itemId = itemType.GetProperty(\"Id\")?.GetValue(item)?.ToString() ?? \"\";\n\n // Check if this is a special item that needs special handling\n bool isUacSlider =\n itemName.Contains(\"User Account Control\") || itemId == \"UACSlider\";\n bool isPowerPlan = itemName.Contains(\"Power Plan\") || itemId == \"PowerPlanComboBox\";\n bool isThemeSelector =\n itemName.Contains(\"Windows Theme\")\n || itemName.Contains(\"Theme Selector\")\n || itemName.Contains(\"Choose Your Mode\");\n\n // Special handling for Windows Theme Selector\n if (isThemeSelector)\n {\n // For Windows Theme Selector, prioritize using SelectedValue or SelectedTheme\n var selectedValueProperty = itemType.GetProperty(\"SelectedValue\");\n if (selectedValueProperty != null)\n {\n try\n {\n string currentSelectedValue = selectedValueProperty\n .GetValue(item)\n ?.ToString();\n string newSelectedValue = null;\n\n // First try to get the value from CustomProperties.SelectedTheme (preferred method)\n if (\n configItem.CustomProperties.TryGetValue(\n \"SelectedTheme\",\n out var selectedTheme\n )\n && selectedTheme != null\n )\n {\n newSelectedValue = selectedTheme.ToString();\n _logService.Log(\n LogLevel.Info,\n $\"Found SelectedTheme in CustomProperties: {newSelectedValue} for item {itemName}\"\n );\n }\n // Then try to get the value directly from configItem.SelectedValue\n else if (!string.IsNullOrEmpty(configItem.SelectedValue))\n {\n newSelectedValue = configItem.SelectedValue;\n _logService.Log(\n LogLevel.Info,\n $\"Found SelectedValue in config: {newSelectedValue} for item {itemName}\"\n );\n }\n // As a last resort, try to derive it from SliderValue (for backward compatibility)\n else if (\n configItem.CustomProperties.TryGetValue(\n \"SliderValue\",\n out var sliderValue\n )\n )\n {\n int sliderValueInt = Convert.ToInt32(sliderValue);\n newSelectedValue = sliderValueInt == 1 ? \"Dark Mode\" : \"Light Mode\";\n _logService.Log(\n LogLevel.Info,\n $\"Derived SelectedValue from SliderValue {sliderValueInt}: {newSelectedValue} for item {itemName}\"\n );\n }\n\n if (\n !string.IsNullOrEmpty(newSelectedValue)\n && currentSelectedValue != newSelectedValue\n )\n {\n selectedValueProperty.SetValue(item, newSelectedValue);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Info,\n $\"Updated SelectedValue for item {itemName} from {currentSelectedValue} to {newSelectedValue}\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating SelectedValue for item {itemName}: {ex.Message}\"\n );\n }\n }\n\n // Also update SelectedTheme property if it exists\n var selectedThemeProperty = itemType.GetProperty(\"SelectedTheme\");\n if (selectedThemeProperty != null)\n {\n try\n {\n string currentSelectedTheme = selectedThemeProperty\n .GetValue(item)\n ?.ToString();\n string newSelectedTheme = null;\n\n // Try to get SelectedTheme from CustomProperties first (preferred method)\n if (\n configItem.CustomProperties.TryGetValue(\n \"SelectedTheme\",\n out var selectedTheme\n )\n && selectedTheme != null\n )\n {\n newSelectedTheme = selectedTheme.ToString();\n }\n // Then try to use SelectedValue directly\n else if (!string.IsNullOrEmpty(configItem.SelectedValue))\n {\n newSelectedTheme = configItem.SelectedValue;\n }\n // As a last resort, try to derive it from SliderValue (for backward compatibility)\n else if (\n configItem.CustomProperties.TryGetValue(\n \"SliderValue\",\n out var themeSliderValue\n )\n )\n {\n int sliderValueInt = Convert.ToInt32(themeSliderValue);\n newSelectedTheme = sliderValueInt == 1 ? \"Dark Mode\" : \"Light Mode\";\n }\n\n if (\n !string.IsNullOrEmpty(newSelectedTheme)\n && currentSelectedTheme != newSelectedTheme\n )\n {\n selectedThemeProperty.SetValue(item, newSelectedTheme);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Debug,\n $\"Updated SelectedTheme for item {itemName} to {newSelectedTheme}\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating SelectedTheme for item {itemName}: {ex.Message}\"\n );\n }\n }\n }\n // For non-theme items, handle SliderValue for ThreeStateSlider or ComboBox\n else if (\n configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue)\n )\n {\n var sliderValueProperty = itemType.GetProperty(\"SliderValue\");\n if (sliderValueProperty != null)\n {\n try\n {\n int newSliderValue = Convert.ToInt32(sliderValue);\n int currentSliderValue = (int)(sliderValueProperty.GetValue(item) ?? 0);\n\n if (currentSliderValue != newSliderValue)\n {\n _logService.Log(\n LogLevel.Info,\n $\"About to update SliderValue for item {itemName} from {currentSliderValue} to {newSliderValue}\"\n );\n sliderValueProperty.SetValue(item, newSliderValue);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Info,\n $\"Updated SliderValue for item {itemName} to {newSliderValue}\"\n );\n\n // Get the control type\n var controlTypeProperty = itemType.GetProperty(\"ControlType\");\n if (controlTypeProperty != null)\n {\n var controlType = controlTypeProperty.GetValue(item);\n _logService.Log(\n LogLevel.Info,\n $\"Item {itemName} has ControlType: {controlType}\"\n );\n\n // If this is a ComboBox, also update the SelectedValue property if available\n if (controlType?.ToString() == \"ComboBox\")\n {\n _logService.Log(\n LogLevel.Info,\n $\"Item {itemName} is a ComboBox, checking for SelectedValue property\"\n );\n var comboBoxSelectedValueProperty = itemType.GetProperty(\n \"SelectedValue\"\n );\n if (comboBoxSelectedValueProperty != null)\n {\n // First try to get the value directly from configItem.SelectedValue\n if (!string.IsNullOrEmpty(configItem.SelectedValue))\n {\n _logService.Log(\n LogLevel.Info,\n $\"Setting SelectedValue to {configItem.SelectedValue} from config for ComboBox {itemName}\"\n );\n comboBoxSelectedValueProperty.SetValue(\n item,\n configItem.SelectedValue\n );\n anyPropertyUpdated = true;\n }\n // Then try to get the value from CustomProperties.SelectedTheme\n else if (\n configItem.CustomProperties.TryGetValue(\n \"SelectedTheme\",\n out var selectedTheme\n )\n && selectedTheme != null\n )\n {\n _logService.Log(\n LogLevel.Info,\n $\"Setting SelectedValue to {selectedTheme} from CustomProperties.SelectedTheme for ComboBox {itemName}\"\n );\n comboBoxSelectedValueProperty.SetValue(\n item,\n selectedTheme.ToString()\n );\n anyPropertyUpdated = true;\n }\n // Finally try to map from SliderValue using SliderLabels\n else\n {\n // Try to get the SliderLabels collection to map the index to a value\n var sliderLabelsProperty = itemType.GetProperty(\n \"SliderLabels\"\n );\n if (sliderLabelsProperty != null)\n {\n var sliderLabels =\n sliderLabelsProperty.GetValue(item)\n as System.Collections.IList;\n if (\n sliderLabels != null\n && newSliderValue < sliderLabels.Count\n )\n {\n var selectedValue = sliderLabels[\n newSliderValue\n ]\n ?.ToString();\n if (!string.IsNullOrEmpty(selectedValue))\n {\n _logService.Log(\n LogLevel.Info,\n $\"Setting SelectedValue to {selectedValue} from SliderLabels for ComboBox {itemName}\"\n );\n comboBoxSelectedValueProperty.SetValue(\n item,\n selectedValue\n );\n anyPropertyUpdated = true;\n }\n }\n }\n }\n }\n }\n }\n\n // Also update specific properties based on the item identification\n if (isPowerPlan)\n {\n // Update PowerPlanValue property\n var powerPlanValueProperty = itemType.GetProperty(\n \"PowerPlanValue\"\n );\n if (powerPlanValueProperty != null)\n {\n int currentPowerPlanValue = (int)(\n powerPlanValueProperty.GetValue(item) ?? 0\n );\n if (currentPowerPlanValue != newSliderValue)\n {\n powerPlanValueProperty.SetValue(item, newSliderValue);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Info,\n $\"Updated PowerPlanValue for item {itemName} from {currentPowerPlanValue} to {newSliderValue}\"\n );\n\n // Try to call OnPowerPlanValueChanged method to apply the power plan\n try\n {\n var onPowerPlanValueChangedMethod =\n itemType.GetMethod(\n \"OnPowerPlanValueChanged\",\n System.Reflection.BindingFlags.NonPublic\n | System\n .Reflection\n .BindingFlags\n .Instance\n );\n\n if (onPowerPlanValueChangedMethod != null)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Calling OnPowerPlanValueChanged method with value {newSliderValue}\"\n );\n onPowerPlanValueChangedMethod.Invoke(\n item,\n new object[] { newSliderValue }\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Debug,\n \"OnPowerPlanValueChanged method not found\"\n );\n\n // Try to find ApplyPowerPlanCommand\n var applyPowerPlanCommandProperty =\n itemType.GetProperty(\n \"ApplyPowerPlanCommand\"\n );\n if (applyPowerPlanCommandProperty != null)\n {\n var command =\n applyPowerPlanCommandProperty.GetValue(\n item\n ) as System.Windows.Input.ICommand;\n if (\n command != null\n && command.CanExecute(newSliderValue)\n )\n {\n _logService.Log(\n LogLevel.Info,\n $\"Executing ApplyPowerPlanCommand with value {newSliderValue}\"\n );\n command.Execute(newSliderValue);\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Error calling power plan methods: {ex.Message}\"\n );\n }\n }\n }\n\n // Also update any ComboBox in the Settings collection\n try\n {\n var settingsProperty = itemType.GetProperty(\"Settings\");\n if (settingsProperty != null)\n {\n var settings =\n settingsProperty.GetValue(item)\n as System.Collections.IEnumerable;\n if (settings != null)\n {\n foreach (var setting in settings)\n {\n var settingType = setting.GetType();\n var settingIdProperty = settingType.GetProperty(\n \"Id\"\n );\n var settingNameProperty =\n settingType.GetProperty(\"Name\");\n\n string settingId = settingIdProperty\n ?.GetValue(setting)\n ?.ToString();\n string settingName = settingNameProperty\n ?.GetValue(setting)\n ?.ToString();\n\n bool isPowerPlanSetting =\n settingId == \"PowerPlanComboBox\"\n || (\n settingName != null\n && settingName.Contains(\"Power Plan\")\n );\n\n if (isPowerPlanSetting)\n {\n var settingSliderValueProperty =\n settingType.GetProperty(\"SliderValue\");\n if (settingSliderValueProperty != null)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Updating SliderValue for Power Plan setting to {newSliderValue}\"\n );\n settingSliderValueProperty.SetValue(\n setting,\n newSliderValue\n );\n }\n\n var selectedValueProperty =\n settingType.GetProperty(\n \"SelectedValue\"\n );\n if (selectedValueProperty != null)\n {\n // First try to get the value from PowerPlanOptions in the configItem\n if (\n configItem.CustomProperties.TryGetValue(\n \"PowerPlanOptions\",\n out var powerPlanOptions\n )\n )\n {\n // Handle different types of PowerPlanOptions\n if (\n powerPlanOptions\n is List options\n && newSliderValue >= 0\n && newSliderValue\n < options.Count\n )\n {\n string powerPlanLabel = options[\n newSliderValue\n ];\n _logService.Log(\n LogLevel.Info,\n $\"Updating SelectedValue for Power Plan setting to {powerPlanLabel} from configItem.PowerPlanOptions\"\n );\n selectedValueProperty.SetValue(\n setting,\n powerPlanLabel\n );\n }\n else if (\n powerPlanOptions\n is Newtonsoft.Json.Linq.JArray jArray\n && newSliderValue >= 0\n && newSliderValue < jArray.Count\n )\n {\n string powerPlanLabel = jArray[\n newSliderValue\n ]\n ?.ToString();\n _logService.Log(\n LogLevel.Info,\n $\"Updating SelectedValue for Power Plan setting to {powerPlanLabel} from configItem.PowerPlanOptions (JArray)\"\n );\n selectedValueProperty.SetValue(\n setting,\n powerPlanLabel\n );\n }\n else\n {\n // Fall back to SliderLabels\n TryUpdateFromSliderLabels(\n settingType,\n setting,\n selectedValueProperty,\n newSliderValue\n );\n }\n }\n // Then try to get it from the setting's SliderLabels\n else\n {\n TryUpdateFromSliderLabels(\n settingType,\n setting,\n selectedValueProperty,\n newSliderValue\n );\n }\n }\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating Power Plan settings: {ex.Message}\"\n );\n }\n }\n else if (isUacSlider)\n {\n var uacLevelProperty = itemType.GetProperty(\"SelectedUacLevel\");\n if (uacLevelProperty != null)\n {\n uacLevelProperty.SetValue(item, newSliderValue);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Debug,\n $\"Updated SelectedUacLevel for item {itemName} to {newSliderValue}\"\n );\n\n // Force the correct ControlType\n if (controlTypeProperty != null)\n {\n controlTypeProperty.SetValue(\n item,\n ControlType.ThreeStateSlider\n );\n _logService.Log(\n LogLevel.Debug,\n $\"Forced ControlType to ThreeStateSlider for item {itemName}\"\n );\n }\n }\n\n // Also try to update the parent view model's UacLevel property\n try\n {\n // Try to get the parent view model\n var viewModelProperty = itemType.GetProperty(\"ViewModel\");\n if (viewModelProperty != null)\n {\n var viewModel = viewModelProperty.GetValue(item);\n if (viewModel != null)\n {\n var viewModelType = viewModel.GetType();\n var viewModelUacLevelProperty =\n viewModelType.GetProperty(\"SelectedUacLevel\");\n if (viewModelUacLevelProperty != null)\n {\n viewModelUacLevelProperty.SetValue(\n viewModel,\n newSliderValue\n );\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Debug,\n $\"Updated SelectedUacLevel on parent view model to {newSliderValue}\"\n );\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating parent view model UacLevel: {ex.Message}\"\n );\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating SliderValue for item {itemName}: {ex.Message}\"\n );\n }\n }\n }\n\n // For non-theme items, also check for SelectedValue property\n if (!isThemeSelector)\n {\n var selectedValueProperty = itemType.GetProperty(\"SelectedValue\");\n if (selectedValueProperty != null)\n {\n try\n {\n string currentSelectedValue = selectedValueProperty\n .GetValue(item)\n ?.ToString();\n string newSelectedValue = null;\n\n // First try to get the value directly from configItem.SelectedValue\n if (!string.IsNullOrEmpty(configItem.SelectedValue))\n {\n newSelectedValue = configItem.SelectedValue;\n _logService.Log(\n LogLevel.Info,\n $\"Found SelectedValue in config: {newSelectedValue} for item {itemName}\"\n );\n }\n // Then try to get the value from CustomProperties.SelectedTheme\n else if (\n configItem.CustomProperties.TryGetValue(\n \"SelectedTheme\",\n out var selectedTheme\n )\n && selectedTheme != null\n )\n {\n newSelectedValue = selectedTheme.ToString();\n _logService.Log(\n LogLevel.Info,\n $\"Found SelectedTheme in CustomProperties: {newSelectedValue} for item {itemName}\"\n );\n }\n // Finally try to map from SliderValue using SliderLabels\n else if (\n configItem.CustomProperties.TryGetValue(\n \"SliderValue\",\n out var configSliderValueForMapping\n )\n )\n {\n var sliderLabelsProperty = itemType.GetProperty(\"SliderLabels\");\n if (sliderLabelsProperty != null)\n {\n var sliderLabels =\n sliderLabelsProperty.GetValue(item)\n as System.Collections.IList;\n int sliderValueInt = Convert.ToInt32(\n configSliderValueForMapping\n );\n if (sliderLabels != null && sliderValueInt < sliderLabels.Count)\n {\n newSelectedValue = sliderLabels[sliderValueInt]?.ToString();\n _logService.Log(\n LogLevel.Info,\n $\"Mapped SliderValue {sliderValueInt} to SelectedValue {newSelectedValue} for item {itemName}\"\n );\n }\n }\n }\n\n if (\n !string.IsNullOrEmpty(newSelectedValue)\n && currentSelectedValue != newSelectedValue\n )\n {\n selectedValueProperty.SetValue(item, newSelectedValue);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Info,\n $\"Updated SelectedValue for item {itemName} from {currentSelectedValue} to {newSelectedValue}\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating SelectedValue for item {itemName}: {ex.Message}\"\n );\n }\n }\n }\n\n // For toggle switches, ensure IsChecked is synchronized with IsSelected\n var isCheckedProperty = itemType.GetProperty(\"IsChecked\");\n if (isCheckedProperty != null)\n {\n try\n {\n bool currentIsChecked = (bool)(isCheckedProperty.GetValue(item) ?? false);\n\n if (currentIsChecked != configItem.IsSelected)\n {\n isCheckedProperty.SetValue(item, configItem.IsSelected);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Debug,\n $\"Updated IsChecked for item {itemName} to {configItem.IsSelected}\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating IsChecked for item {itemName}: {ex.Message}\"\n );\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error in UpdateAdditionalProperties: {ex.Message}\"\n );\n }\n\n return anyPropertyUpdated;\n }\n\n /// \n /// Helper method to try updating SelectedValue from SliderLabels.\n /// \n /// The type of the setting.\n /// The setting object.\n /// The SelectedValue property.\n /// The new slider value.\n private void TryUpdateFromSliderLabels(\n Type settingType,\n object setting,\n System.Reflection.PropertyInfo selectedValueProperty,\n int newSliderValue\n )\n {\n // Try to get the power plan label from SliderLabels\n var sliderLabelsProperty = settingType.GetProperty(\"SliderLabels\");\n if (sliderLabelsProperty != null)\n {\n var sliderLabels =\n sliderLabelsProperty.GetValue(setting) as System.Collections.IList;\n if (\n sliderLabels != null\n && newSliderValue >= 0\n && newSliderValue < sliderLabels.Count\n )\n {\n string powerPlanLabel = sliderLabels[newSliderValue]?.ToString();\n if (!string.IsNullOrEmpty(powerPlanLabel))\n {\n _logService.Log(\n LogLevel.Info,\n $\"Updating SelectedValue for Power Plan setting to {powerPlanLabel} from SliderLabels\"\n );\n selectedValueProperty.SetValue(setting, powerPlanLabel);\n }\n }\n else\n {\n // Fall back to default values\n string[] defaultLabels =\n {\n \"Balanced\",\n \"High Performance\",\n \"Ultimate Performance\",\n };\n if (newSliderValue >= 0 && newSliderValue < defaultLabels.Length)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Updating SelectedValue for Power Plan setting to {defaultLabels[newSliderValue]} from default labels\"\n );\n selectedValueProperty.SetValue(setting, defaultLabels[newSliderValue]);\n }\n }\n }\n }\n\n private void TriggerPropertyChangedIfPossible(object item)\n {\n try\n {\n // Check if the item implements INotifyPropertyChanged\n if (item is System.ComponentModel.INotifyPropertyChanged)\n {\n try\n {\n // Use a safer approach to find property changed methods\n var methods = item.GetType()\n .GetMethods(\n System.Reflection.BindingFlags.Public\n | System.Reflection.BindingFlags.NonPublic\n | System.Reflection.BindingFlags.Instance\n )\n .Where(m =>\n (m.Name == \"RaisePropertyChanged\" || m.Name == \"OnPropertyChanged\")\n && m.GetParameters().Length == 1\n && m.GetParameters()[0].ParameterType == typeof(string)\n )\n .ToList();\n\n if (methods.Any())\n {\n var method = methods.First();\n // Invoke the method with null string to refresh all properties\n method.Invoke(item, new object[] { null });\n return;\n }\n\n // If no method with string parameter is found, try to find a method that takes PropertyChangedEventArgs\n var eventArgsMethods = item.GetType()\n .GetMethods(\n System.Reflection.BindingFlags.Public\n | System.Reflection.BindingFlags.NonPublic\n | System.Reflection.BindingFlags.Instance\n )\n .Where(m =>\n (m.Name == \"OnPropertyChanged\")\n && m.GetParameters().Length == 1\n && m.GetParameters()[0].ParameterType.Name\n == \"PropertyChangedEventArgs\"\n )\n .ToList();\n\n if (eventArgsMethods.Any())\n {\n // Create PropertyChangedEventArgs with null property name to refresh all properties\n var eventArgsType = eventArgsMethods\n .First()\n .GetParameters()[0]\n .ParameterType;\n var eventArgs = Activator.CreateInstance(\n eventArgsType,\n new object[] { null }\n );\n eventArgsMethods.First().Invoke(item, new[] { eventArgs });\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error finding property changed method: {ex.Message}\"\n );\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error triggering property changed: {ex.Message}\");\n }\n }\n\n /// \n /// Applies registry settings for an item based on its IsSelected state.\n /// \n /// The item to apply registry settings for.\n /// Whether the setting is selected (enabled) or not.\n /// A task representing the asynchronous operation.\n private async Task ApplyRegistrySettingsAsync(object item, bool isSelected)\n {\n try\n {\n // Check if this is an ApplicationSettingItem\n if (item is ApplicationSettingItem settingItem)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Applying registry settings for {settingItem.Name}, IsSelected={isSelected}\"\n );\n\n // Apply registry setting if present\n if (settingItem.RegistrySetting != null)\n {\n string hiveString = GetRegistryHiveString(settingItem.RegistrySetting.Hive);\n object valueToApply = isSelected\n ? settingItem.RegistrySetting.EnabledValue\n ?? settingItem.RegistrySetting.RecommendedValue\n : settingItem.RegistrySetting.DisabledValue\n ?? settingItem.RegistrySetting.DefaultValue;\n\n // Ensure the key exists and set the value\n string keyPath = $\"{hiveString}\\\\{settingItem.RegistrySetting.SubKey}\";\n\n // First ensure the key exists\n bool keyExists = _registryService.KeyExists(keyPath);\n if (!keyExists)\n {\n _logService.Log(LogLevel.Info, $\"Creating registry key: {keyPath}\");\n bool keyCreated = _registryService.CreateKeyIfNotExists(keyPath);\n if (!keyCreated)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to create registry key: {keyPath}, trying direct registry access\"\n );\n\n // Try direct registry access to create the key\n try\n {\n RegistryKey rootKey = GetRegistryRootKey(\n settingItem.RegistrySetting.Hive\n );\n if (rootKey != null)\n {\n rootKey.CreateSubKey(\n settingItem.RegistrySetting.SubKey,\n true\n );\n _logService.Log(\n LogLevel.Success,\n $\"Successfully created registry key using direct access: {keyPath}\"\n );\n keyCreated = true;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to create registry key using direct access: {keyPath}, Error: {ex.Message}\"\n );\n }\n\n // If direct access failed, try using PowerShell\n if (!keyCreated)\n {\n try\n {\n string psCommand =\n $\"$ErrorActionPreference = 'Stop'; try {{ if (-not (Test-Path -Path '{keyPath.Replace(\"HKLM\", \"HKLM:\")}')) {{ New-Item -Path '{keyPath.Replace(\"HKLM\", \"HKLM:\")}' -Force | Out-Null; Write-Output 'Key created successfully' }} }} catch {{ Write-Error $_.Exception.Message; exit 1 }}\";\n\n _logService.Log(\n LogLevel.Info,\n $\"Attempting to create registry key using PowerShell: {keyPath}\"\n );\n\n // Execute PowerShell command\n var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-Command \\\"{psCommand}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n },\n };\n\n process.Start();\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n process.WaitForExit();\n\n if (process.ExitCode == 0)\n {\n _logService.Log(\n LogLevel.Success,\n $\"Successfully created registry key using PowerShell: {keyPath}\"\n );\n keyCreated = true;\n }\n else\n {\n _logService.Log(\n LogLevel.Error,\n $\"Failed to create registry key using PowerShell: {keyPath}, Error: {error}\"\n );\n }\n }\n catch (Exception psEx)\n {\n _logService.Log(\n LogLevel.Error,\n $\"PowerShell execution failed: {psEx.Message}\"\n );\n }\n }\n }\n }\n\n // Now set the value - always attempt to set the value even if key creation failed\n // This is important for configuration import to ensure values are applied\n bool success = false;\n\n // First try using the registry service\n success = _registryService.SetValue(\n keyPath,\n settingItem.RegistrySetting.Name,\n valueToApply,\n settingItem.RegistrySetting.ValueType\n );\n\n if (success)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Applied registry setting for {settingItem.Name}: {(isSelected ? \"Enabled\" : \"Disabled\")}\"\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to apply registry setting for {settingItem.Name}, trying direct registry access\"\n );\n\n // Try direct registry access as a fallback\n try\n {\n RegistryKey rootKey = GetRegistryRootKey(\n settingItem.RegistrySetting.Hive\n );\n if (rootKey != null)\n {\n using (\n RegistryKey regKey = rootKey.CreateSubKey(\n settingItem.RegistrySetting.SubKey,\n true\n )\n )\n {\n if (regKey != null)\n {\n regKey.SetValue(\n settingItem.RegistrySetting.Name,\n valueToApply,\n (RegistryValueKind)\n settingItem.RegistrySetting.ValueType\n );\n _logService.Log(\n LogLevel.Success,\n $\"Successfully applied registry setting using direct access: {keyPath}\\\\{settingItem.RegistrySetting.Name}\"\n );\n success = true;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Error,\n $\"Failed to apply registry setting using direct access: {ex.Message}\"\n );\n }\n\n // If direct access failed, try using PowerShell\n if (!success)\n {\n try\n {\n string psCommand =\n $\"$ErrorActionPreference = 'Stop'; try {{ if (-not (Test-Path -Path '{keyPath.Replace(\"HKLM\", \"HKLM:\")}')) {{ New-Item -Path '{keyPath.Replace(\"HKLM\", \"HKLM:\")}' -Force | Out-Null; }} Set-ItemProperty -Path '{keyPath.Replace(\"HKLM\", \"HKLM:\")}' -Name '{settingItem.RegistrySetting.Name}' -Value {valueToApply} -Type {settingItem.RegistrySetting.ValueType} -Force; }} catch {{ Write-Error $_.Exception.Message; exit 1 }}\";\n\n _logService.Log(\n LogLevel.Info,\n $\"Attempting to set registry value using PowerShell: {keyPath}\\\\{settingItem.RegistrySetting.Name}\"\n );\n\n // Execute PowerShell command\n var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-Command \\\"{psCommand}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n },\n };\n\n process.Start();\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n process.WaitForExit();\n\n if (process.ExitCode == 0)\n {\n _logService.Log(\n LogLevel.Success,\n $\"Successfully set registry value using PowerShell: {keyPath}\\\\{settingItem.RegistrySetting.Name}\"\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Error,\n $\"Failed to set registry value using PowerShell: {keyPath}\\\\{settingItem.RegistrySetting.Name}, Error: {error}\"\n );\n }\n }\n catch (Exception psEx)\n {\n _logService.Log(\n LogLevel.Error,\n $\"PowerShell execution failed: {psEx.Message}\"\n );\n }\n }\n }\n }\n // Apply linked registry settings if present\n else if (\n settingItem.LinkedRegistrySettings != null\n && settingItem.LinkedRegistrySettings.Settings.Count > 0\n )\n {\n _logService.Log(\n LogLevel.Info,\n $\"Applying linked registry settings for {settingItem.Name}, IsSelected={isSelected}\"\n );\n\n // Use the registry service to apply linked settings\n bool success = await _registryService.ApplyLinkedSettingsAsync(\n settingItem.LinkedRegistrySettings,\n isSelected\n );\n\n if (success)\n {\n _logService.Log(\n LogLevel.Success,\n $\"Successfully applied all linked registry settings for {settingItem.Name}\"\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Some linked registry settings for {settingItem.Name} failed to apply\"\n );\n }\n }\n\n // Refresh the status of the setting after applying changes\n await settingItem.RefreshStatus();\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying registry settings: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n }\n\n /// \n /// Gets the registry root key for a given hive.\n /// \n /// The registry hive.\n /// The registry root key.\n private RegistryKey GetRegistryRootKey(RegistryHive hive)\n {\n switch (hive)\n {\n case RegistryHive.ClassesRoot:\n return Registry.ClassesRoot;\n case RegistryHive.CurrentUser:\n return Registry.CurrentUser;\n case RegistryHive.LocalMachine:\n return Registry.LocalMachine;\n case RegistryHive.Users:\n return Registry.Users;\n case RegistryHive.CurrentConfig:\n return Registry.CurrentConfig;\n default:\n return null;\n }\n }\n\n /// \n /// Gets the registry hive string.\n /// \n /// The registry hive.\n /// The registry hive string.\n private string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => throw new ArgumentOutOfRangeException(nameof(hive), hive, null),\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/MoreMenuViewModel.cs", "using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Runtime.CompilerServices;\nusing System.Windows;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// ViewModel for the More menu functionality\n /// \n public class MoreMenuViewModel : ObservableObject\n {\n private readonly ILogService _logService;\n private readonly IVersionService _versionService;\n private readonly IMessengerService _messengerService;\n private readonly IApplicationCloseService _applicationCloseService;\n private readonly IDialogService _dialogService;\n\n private string _versionInfo;\n\n /// \n /// Gets or sets the version information text displayed in the menu\n /// \n public string VersionInfo\n {\n get => _versionInfo;\n set => SetProperty(ref _versionInfo, value);\n }\n\n /// \n /// Command to check for application updates\n /// \n public ICommand CheckForUpdatesCommand { get; }\n\n /// \n /// Command to open the logs folder\n /// \n public ICommand OpenLogsCommand { get; }\n\n /// \n /// Command to open the scripts folder\n /// \n public ICommand OpenScriptsCommand { get; }\n\n /// \n /// Command to close the application\n /// \n public ICommand CloseApplicationCommand { get; }\n\n /// \n /// Constructor with dependency injection\n /// \n /// Service for logging\n /// Service for version information and updates\n /// Service for messaging between components\n public MoreMenuViewModel(\n ILogService logService,\n IVersionService versionService,\n IMessengerService messengerService,\n IApplicationCloseService applicationCloseService,\n IDialogService dialogService\n )\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _versionService =\n versionService ?? throw new ArgumentNullException(nameof(versionService));\n _messengerService =\n messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n _applicationCloseService =\n applicationCloseService\n ?? throw new ArgumentNullException(nameof(applicationCloseService));\n _dialogService =\n dialogService\n ?? throw new ArgumentNullException(nameof(dialogService));\n\n // Initialize version info\n UpdateVersionInfo();\n\n // Initialize commands with explicit execute and canExecute methods\n CheckForUpdatesCommand = new RelayCommand(\n execute: () =>\n {\n _logService.LogInformation(\"CheckForUpdatesCommand executed\");\n CheckForUpdatesAsync();\n },\n canExecute: () => true\n );\n\n OpenLogsCommand = new RelayCommand(\n execute: () =>\n {\n _logService.LogInformation(\"OpenLogsCommand executed\");\n OpenLogs();\n },\n canExecute: () => true\n );\n\n OpenScriptsCommand = new RelayCommand(\n execute: () =>\n {\n _logService.LogInformation(\"OpenScriptsCommand executed\");\n OpenScripts();\n },\n canExecute: () => true\n );\n\n CloseApplicationCommand = new RelayCommand(\n execute: () =>\n {\n _logService.LogInformation(\"CloseApplicationCommand executed\");\n CloseApplication();\n },\n canExecute: () => true\n );\n }\n\n /// \n /// Updates the version information text\n /// \n private void UpdateVersionInfo()\n {\n try\n {\n // Get the current version from the version service\n VersionInfo versionInfo = _versionService.GetCurrentVersion();\n\n // Format the version text\n VersionInfo = $\"Winhance Version {versionInfo.Version}\";\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating version info: {ex.Message}\", ex);\n\n // Set a default version text in case of error\n VersionInfo = \"Winhance Version\";\n }\n }\n\n /// \n /// Checks for updates and shows appropriate dialog\n /// \n private async void CheckForUpdatesAsync()\n {\n try\n {\n _logService.LogInformation(\"Checking for updates from MoreMenu\");\n\n // Get the current version\n VersionInfo currentVersion = _versionService.GetCurrentVersion();\n _logService.LogInformation($\"Current version: {currentVersion.Version}\");\n\n // Check for updates\n VersionInfo latestVersion = await _versionService.CheckForUpdateAsync();\n _logService.LogInformation(\n $\"Latest version: {latestVersion.Version}, Update available: {latestVersion.IsUpdateAvailable}\"\n );\n\n if (latestVersion.IsUpdateAvailable)\n {\n // Show update dialog\n string title = \"Update Available\";\n string message = \"Good News! A New Version of Winhance is available.\";\n\n _logService.LogInformation(\"Showing update dialog\");\n // Show the update dialog\n await UpdateDialog.ShowAsync(\n title,\n message,\n currentVersion,\n latestVersion,\n async () =>\n {\n _logService.LogInformation(\n \"User initiated update download and installation\"\n );\n await _versionService.DownloadAndInstallUpdateAsync();\n }\n );\n }\n else\n {\n _logService.LogInformation(\"No updates available\");\n // Show a message that no update is available\n _dialogService.ShowInformationAsync(\n \"You have the latest version of Winhance.\",\n \"No Updates Available\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking for updates: {ex.Message}\", ex);\n\n // Show an error message\n _dialogService.ShowErrorAsync(\n $\"An error occurred while checking for updates: {ex.Message}\",\n \"Update Check Error\"\n );\n }\n }\n\n /// \n /// Opens the logs folder\n /// \n private void OpenLogs()\n {\n try\n {\n // Get the logs folder path\n string logsFolder = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\"\n );\n\n // Create the folder if it doesn't exist\n if (!Directory.Exists(logsFolder))\n {\n Directory.CreateDirectory(logsFolder);\n }\n\n // Open the logs folder using ProcessStartInfo with UseShellExecute=true\n var psi = new ProcessStartInfo\n {\n FileName = \"explorer.exe\",\n Arguments = logsFolder,\n UseShellExecute = true,\n };\n Process.Start(psi);\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error opening logs folder: {ex.Message}\", ex);\n\n // Show an error message\n _dialogService.ShowErrorAsync(\n $\"An error occurred while opening the logs folder: {ex.Message}\",\n \"Logs Folder Error\"\n );\n }\n }\n\n /// \n /// Opens the scripts folder\n /// \n private void OpenScripts()\n {\n try\n {\n // Get the scripts folder path\n string scriptsFolder = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n \"Winhance\",\n \"Scripts\"\n );\n\n // Create the folder if it doesn't exist\n if (!Directory.Exists(scriptsFolder))\n {\n Directory.CreateDirectory(scriptsFolder);\n }\n\n // Open the scripts folder using ProcessStartInfo with UseShellExecute=true\n var psi = new ProcessStartInfo\n {\n FileName = \"explorer.exe\",\n Arguments = scriptsFolder,\n UseShellExecute = true,\n };\n Process.Start(psi);\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error opening scripts folder: {ex.Message}\", ex);\n\n // Show an error message\n _dialogService.ShowErrorAsync(\n $\"An error occurred while opening the scripts folder: {ex.Message}\",\n \"Scripts Folder Error\"\n );\n }\n }\n\n /// \n /// Closes the application using the same behavior as the normal close button\n /// \n private async void CloseApplication()\n {\n try\n {\n _logService.LogInformation(\n \"Closing application from MoreMenu, delegating to ApplicationCloseService\"\n );\n await _applicationCloseService.CloseApplicationWithSupportDialogAsync();\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error closing application: {ex.Message}\", ex);\n\n // Fallback to direct application shutdown if everything else fails\n try\n {\n _logService.LogInformation(\"Falling back to Application.Current.Shutdown()\");\n Application.Current.Dispatcher.Invoke(() => Application.Current.Shutdown());\n }\n catch (Exception shutdownEx)\n {\n _logService.LogError(\n $\"Error shutting down application: {shutdownEx.Message}\",\n shutdownEx\n );\n\n // Last resort\n Environment.Exit(0);\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/Views/CustomizeView.xaml.cs", "using System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing MaterialDesignThemes.Wpf;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Messages;\nusing Winhance.WPF.Features.Customize.ViewModels;\n\nnamespace Winhance.WPF.Features.Customize.Views\n{\n /// \n /// Interaction logic for CustomizeView.xaml\n /// \n public partial class CustomizeView : UserControl\n {\n private IMessengerService? _messengerService; // Changed from readonly to allow assignment\n \n public CustomizeView()\n {\n InitializeComponent();\n Loaded += CustomizeView_Loaded;\n \n // Get messenger service from DataContext when it's set\n DataContextChanged += (s, e) => \n {\n if (e.NewValue is CustomizeViewModel viewModel && \n viewModel.MessengerService is IMessengerService messengerService)\n {\n _messengerService = messengerService;\n SubscribeToMessages();\n }\n };\n }\n \n private void SubscribeToMessages()\n {\n if (_messengerService == null)\n return;\n \n // Subscribe to the message that signals resetting expansion states\n _messengerService.Register(this, OnResetExpansionState);\n }\n \n private void OnResetExpansionState(ResetExpansionStateMessage message)\n {\n // Reset all sections to be expanded\n ResetAllExpansionStates();\n }\n \n /// \n /// Resets all section expansion states to expanded\n /// \n private void ResetAllExpansionStates()\n {\n // Ensure all content is visible\n TaskbarContent.Visibility = Visibility.Visible;\n StartMenuContent.Visibility = Visibility.Visible;\n ExplorerContent.Visibility = Visibility.Visible;\n WindowsThemeContent.Visibility = Visibility.Visible;\n \n // Set all arrow icons to up (expanded state)\n TaskbarHeaderIcon.Kind = PackIconKind.ChevronUp;\n StartMenuHeaderIcon.Kind = PackIconKind.ChevronUp;\n ExplorerHeaderIcon.Kind = PackIconKind.ChevronUp;\n WindowsThemeHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n\n private void CustomizeView_Loaded(object sender, RoutedEventArgs e)\n {\n // Initialize sections to be expanded by default\n TaskbarContent.Visibility = Visibility.Visible;\n StartMenuContent.Visibility = Visibility.Visible;\n ExplorerContent.Visibility = Visibility.Visible;\n WindowsThemeContent.Visibility = Visibility.Visible;\n\n // Set arrow icons to up arrow\n TaskbarHeaderIcon.Kind = PackIconKind.ChevronUp; // Up arrow\n StartMenuHeaderIcon.Kind = PackIconKind.ChevronUp; // Up arrow\n ExplorerHeaderIcon.Kind = PackIconKind.ChevronUp; // Up arrow\n WindowsThemeHeaderIcon.Kind = PackIconKind.ChevronUp; // Up arrow\n\n // Remove all existing event handlers from all border elements\n foreach (var element in this.FindVisualChildren(this))\n {\n if (element?.Tag != null && element.Tag is string tag)\n {\n // Remove any existing MouseLeftButtonDown handlers\n element.MouseLeftButtonDown -= HeaderBorder_MouseLeftButtonDown;\n\n // Add our new handler\n element.PreviewMouseDown += Element_PreviewMouseDown;\n }\n }\n }\n\n private void Element_PreviewMouseDown(object sender, MouseButtonEventArgs e)\n {\n // If we clicked on a Button, don't handle it here\n if (e.OriginalSource is Button)\n {\n return;\n }\n\n if (sender is Border border && border.Tag is string tag)\n {\n try\n {\n // Toggle visibility and selection based on tag\n switch (tag)\n {\n case \"0\":\n ToggleSectionVisibility(TaskbarContent, TaskbarHeaderIcon);\n TaskbarToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n break;\n case \"1\":\n ToggleSectionVisibility(StartMenuContent, StartMenuHeaderIcon);\n StartMenuToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n break;\n case \"2\":\n ToggleSectionVisibility(ExplorerContent, ExplorerHeaderIcon);\n ExplorerToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n break;\n case \"3\":\n ToggleSectionVisibility(WindowsThemeContent, WindowsThemeHeaderIcon);\n WindowsThemeToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n break;\n }\n\n // Mark event as handled so it won't bubble up\n e.Handled = true;\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Error handling header click: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n }\n }\n }\n\n // This method is no longer needed since we're not checking for checkboxes anymore\n\n private void ToggleSectionVisibility(UIElement content, PackIcon icon)\n {\n if (content.Visibility == Visibility.Collapsed)\n {\n content.Visibility = Visibility.Visible;\n icon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n }\n else\n {\n content.Visibility = Visibility.Collapsed;\n icon.Kind = PackIconKind.ChevronDown; // Downward arrow for collapsed state\n }\n }\n\n // This is defined in the XAML, so we need to keep it to avoid errors\n private void HeaderBorder_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n // This no longer does anything because we're using PreviewMouseDown now\n // We'll just mark it as handled to prevent unexpected behavior\n e.Handled = true;\n }\n\n // Helper method to find visual children of a specific type\n private System.Collections.Generic.IEnumerable FindVisualChildren(DependencyObject parent) where T : DependencyObject\n {\n int childrenCount = VisualTreeHelper.GetChildrenCount(parent);\n for (int i = 0; i < childrenCount; i++)\n {\n DependencyObject child = VisualTreeHelper.GetChild(parent, i);\n\n if (child is T childOfType)\n yield return childOfType;\n\n foreach (T childOfChild in FindVisualChildren(child))\n yield return childOfChild;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/PowerOptimizationsViewModel.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Reflection;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Interfaces;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Infrastructure.Features.Common.Registry;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for power optimizations.\n /// \n public partial class PowerOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IPowerPlanService _powerPlanService;\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n [ObservableProperty]\n private int _powerPlanValue;\n\n [ObservableProperty]\n private bool _isApplyingPowerPlan;\n\n [ObservableProperty]\n private string _statusText = \"Power settings\";\n\n [ObservableProperty]\n private ObservableCollection _powerPlanLabels = new()\n {\n \"Balanced\",\n \"High Performance\",\n \"Ultimate Performance\"\n };\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The power plan service.\n /// The view model locator.\n /// The settings registry.\n public PowerOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IPowerPlanService powerPlanService,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService));\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n }\n\n /// \n /// Loads the power settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, \"Loading power settings\");\n\n // Initialize Power settings from PowerOptimizations.GetPowerOptimizations()\n Settings.Clear();\n\n // The Power Plan ComboBox is already defined in the XAML, so we don't need to add it to the Settings collection\n _logService.Log(LogLevel.Info, \"Power Plan ComboBox is defined in XAML\");\n\n // Get power optimizations from the new method\n var powerOptimizations = PowerOptimizations.GetPowerOptimizations();\n \n // Add items for each optimization setting\n foreach (var setting in powerOptimizations.Settings)\n {\n // Skip settings that use PowerCfg commands\n if (setting.CustomProperties != null &&\n setting.CustomProperties.ContainsKey(\"PowerCfgSettings\"))\n {\n _logService.Log(LogLevel.Info, $\"Skipping PowerCfg setting: {setting.Name} - hiding from UI\");\n continue; // Skip this setting\n }\n \n // Create a view model for each setting\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsUpdatingFromCode = true, // Set this to true to allow RefreshStatus to set the correct state\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = setting.ControlType\n };\n \n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Register the setting in the settings registry if available\n if (_settingsRegistry != null && !string.IsNullOrEmpty(settingItem.Id))\n {\n _settingsRegistry.RegisterSetting(settingItem);\n _logService.Log(LogLevel.Info, $\"Registered setting {settingItem.Id} in settings registry during creation\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Refresh status for all settings to populate LinkedRegistrySettingsWithValues\n foreach (var setting in Settings)\n {\n await setting.RefreshStatus();\n }\n\n // Set up power plan ComboBox\n await LoadCurrentPowerPlanAsync();\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading power settings: {ex.Message}\");\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Loads the current power plan and sets the ComboBox value accordingly.\n /// \n private async Task LoadCurrentPowerPlanAsync()\n {\n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));\n var cancellationToken = cancellationTokenSource.Token;\n \n try\n {\n _logService.Log(LogLevel.Info, \"Starting to load current power plan\");\n \n // Get the current active power plan GUID using the service with timeout\n var getPlanTask = _powerPlanService.GetActivePowerPlanGuidAsync();\n await Task.WhenAny(getPlanTask, Task.Delay(5000, cancellationToken));\n \n string activePlanGuid;\n if (getPlanTask.IsCompleted)\n {\n activePlanGuid = await getPlanTask;\n _logService.Log(LogLevel.Info, $\"Active power plan GUID: {activePlanGuid}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"GetActivePowerPlanGuidAsync timed out, defaulting to Balanced\");\n activePlanGuid = PowerOptimizations.PowerPlans.Balanced.Guid;\n cancellationTokenSource.Cancel();\n }\n \n // Get the Ultimate Performance GUID from the service\n string ultimatePerformanceGuid;\n var field = typeof(Winhance.Infrastructure.Features.Optimize.Services.PowerPlanService)\n .GetField(\"ULTIMATE_PERFORMANCE_PLAN_GUID\", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);\n \n if (field != null)\n {\n ultimatePerformanceGuid = (string)field.GetValue(null);\n _logService.Log(LogLevel.Info, $\"Ultimate Performance GUID from service: {ultimatePerformanceGuid}\");\n }\n else\n {\n ultimatePerformanceGuid = PowerOptimizations.PowerPlans.UltimatePerformance.Guid;\n _logService.Log(LogLevel.Warning, $\"Could not get Ultimate Performance GUID from service, using value from PowerOptimizations: {ultimatePerformanceGuid}\");\n }\n \n // Set the slider value based on the active plan\n if (activePlanGuid == PowerOptimizations.PowerPlans.Balanced.Guid)\n {\n // Use IsApplyingPowerPlan to prevent triggering ApplyPowerPlanAsync\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 0; // Balanced\n IsApplyingPowerPlan = wasApplying;\n _logService.Log(LogLevel.Info, \"Detected Balanced power plan\");\n }\n else if (activePlanGuid == PowerOptimizations.PowerPlans.HighPerformance.Guid)\n {\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 1; // High Performance\n IsApplyingPowerPlan = wasApplying;\n _logService.Log(LogLevel.Info, \"Detected High Performance power plan\");\n }\n else if (activePlanGuid == ultimatePerformanceGuid)\n {\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 2; // Ultimate Performance\n IsApplyingPowerPlan = wasApplying;\n _logService.Log(LogLevel.Info, \"Detected Ultimate Performance power plan\");\n }\n else\n {\n // Check if the active plan name contains \"Ultimate Performance\"\n var getPlansTask = _powerPlanService.GetAvailablePowerPlansAsync();\n await Task.WhenAny(getPlansTask, Task.Delay(5000, cancellationToken));\n \n if (getPlansTask.IsCompleted)\n {\n var allPlans = await getPlansTask;\n var activePlan = allPlans.FirstOrDefault(p => p.Guid == activePlanGuid);\n \n if (activePlan != null && activePlan.Name.Contains(\"Ultimate Performance\", StringComparison.OrdinalIgnoreCase))\n {\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 2; // Ultimate Performance\n IsApplyingPowerPlan = wasApplying;\n _logService.Log(LogLevel.Info, $\"Detected Ultimate Performance power plan by name: {activePlan.Name}\");\n \n // Update the static GUID for future reference\n if (field != null)\n {\n field.SetValue(null, activePlanGuid);\n _logService.Log(LogLevel.Info, $\"Updated Ultimate Performance GUID to: {activePlanGuid}\");\n }\n }\n else\n {\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 0; // Default to Balanced if unknown\n IsApplyingPowerPlan = wasApplying;\n _logService.Log(LogLevel.Warning, $\"Unknown power plan GUID: {activePlanGuid}, defaulting to Balanced\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"GetAvailablePowerPlansAsync timed out, defaulting to Balanced\");\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 0; // Default to Balanced\n IsApplyingPowerPlan = wasApplying;\n cancellationTokenSource.Cancel();\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Current power plan: {PowerPlanLabels[PowerPlanValue]} (Value: {PowerPlanValue})\");\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"Power plan loading was canceled due to timeout\");\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 0; // Default to Balanced on timeout\n IsApplyingPowerPlan = wasApplying;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading current power plan: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 0; // Default to Balanced on error\n IsApplyingPowerPlan = wasApplying;\n }\n }\n\n /// \n /// Called when the PowerPlanValue property changes.\n /// \n /// The new value.\n partial void OnPowerPlanValueChanged(int value)\n {\n // Only apply the power plan when not in the middle of applying a power plan\n // This prevents recursive calls and allows for importing without applying\n if (!IsApplyingPowerPlan)\n {\n _logService.Log(LogLevel.Info, $\"PowerPlanValue changed to {value}, applying power plan\");\n try\n {\n // Use ConfigureAwait(false) to avoid deadlocks\n ApplyPowerPlanAsync(value).ConfigureAwait(false);\n _logService.Log(LogLevel.Info, $\"Successfully initiated power plan change to {value}\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error initiating power plan change: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Info, $\"PowerPlanValue changed to {value}, but not applying because IsApplyingPowerPlan is true\");\n _logService.Log(LogLevel.Debug, $\"Stack trace at PowerPlanValue change: {Environment.StackTrace}\");\n }\n }\n\n /// \n /// Applies the selected power plan.\n /// \n /// The power plan index (0=Balanced, 1=High Performance, 2=Ultimate Performance).\n /// A task representing the asynchronous operation.\n [RelayCommand]\n private async Task ApplyPowerPlanAsync(int planIndex)\n {\n // Double-check to prevent recursive calls\n if (IsApplyingPowerPlan)\n {\n _logService.Log(LogLevel.Warning, $\"ApplyPowerPlanAsync called while IsApplyingPowerPlan is true, ignoring\");\n return;\n }\n \n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(15));\n var cancellationToken = cancellationTokenSource.Token;\n \n try\n {\n IsApplyingPowerPlan = true;\n StatusText = $\"Applying {PowerPlanLabels[planIndex]} power plan...\";\n \n // Get the appropriate GUID based on the selected plan\n string planGuid;\n \n // Special handling for Ultimate Performance plan\n if (planIndex == 2) // Ultimate Performance\n {\n // Get the GUID from the service directly\n // This ensures we're using the most up-to-date GUID that might have been created dynamically\n var field = typeof(Winhance.Infrastructure.Features.Optimize.Services.PowerPlanService)\n .GetField(\"ULTIMATE_PERFORMANCE_PLAN_GUID\", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);\n \n if (field != null)\n {\n planGuid = (string)field.GetValue(null);\n _logService.Log(LogLevel.Info, $\"Using Ultimate Performance GUID from service: {planGuid}\");\n }\n else\n {\n // Fallback to the value from PowerOptimizations\n planGuid = PowerOptimizations.PowerPlans.UltimatePerformance.Guid;\n _logService.Log(LogLevel.Warning, $\"Could not get GUID from service, using value from PowerOptimizations: {planGuid}\");\n }\n }\n else\n {\n // For other plans, use the standard GUIDs\n planGuid = planIndex switch\n {\n 0 => PowerOptimizations.PowerPlans.Balanced.Guid,\n 1 => PowerOptimizations.PowerPlans.HighPerformance.Guid,\n _ => PowerOptimizations.PowerPlans.Balanced.Guid // Default to Balanced\n };\n }\n \n _logService.Log(LogLevel.Info, $\"Applying power plan: {PowerPlanLabels[planIndex]} with GUID: {planGuid}\");\n \n // Use the service to set the power plan with timeout\n var setPlanTask = _powerPlanService.SetPowerPlanAsync(planGuid);\n var timeoutTask = Task.Delay(10000, cancellationToken); // 10 second timeout\n \n await Task.WhenAny(setPlanTask, timeoutTask);\n \n if (setPlanTask.IsCompleted)\n {\n bool success = await setPlanTask;\n \n if (success)\n {\n _logService.Log(LogLevel.Info, $\"Power plan set to {PowerPlanLabels[planIndex]} ({planGuid})\");\n StatusText = $\"{PowerPlanLabels[planIndex]} power plan applied\";\n \n // Refresh the current power plan to ensure the UI is updated correctly\n var loadTask = LoadCurrentPowerPlanAsync();\n await Task.WhenAny(loadTask, Task.Delay(5000, cancellationToken));\n \n if (!loadTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"LoadCurrentPowerPlanAsync timed out, continuing anyway\");\n }\n \n // Refresh all PowerCfg settings to reflect the new power plan\n _logService.Log(LogLevel.Info, \"Refreshing PowerCfg settings after power plan change\");\n var checkTask = CheckSettingStatusesAsync();\n await Task.WhenAny(checkTask, Task.Delay(5000, cancellationToken));\n \n if (!checkTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"CheckSettingStatusesAsync timed out, continuing anyway\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Failed to set power plan to {PowerPlanLabels[planIndex]} ({planGuid})\");\n StatusText = $\"Failed to apply {PowerPlanLabels[planIndex]} power plan\";\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Setting power plan timed out after 10 seconds\");\n StatusText = $\"Timeout while applying {PowerPlanLabels[planIndex]} power plan\";\n \n // Cancel the operation\n cancellationTokenSource.Cancel();\n }\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"Power plan application was canceled due to timeout\");\n StatusText = \"Power plan application timed out\";\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying power plan: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n StatusText = $\"Error applying power plan: {ex.Message}\";\n }\n finally\n {\n // Make sure we always reset IsApplyingPowerPlan to false when done\n IsApplyingPowerPlan = false;\n _logService.Log(LogLevel.Info, \"Reset IsApplyingPowerPlan to false in ApplyPowerPlanAsync\");\n }\n }\n\n /// \n /// Checks the status of all power settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, $\"Checking status for {Settings.Count} power settings\");\n\n foreach (var setting in Settings)\n {\n try\n {\n // Check if this is a command-based setting with PowerCfg settings\n bool isCommandBasedSetting = setting.CustomProperties != null &&\n setting.CustomProperties.ContainsKey(\"PowerCfgSettings\") &&\n setting.CustomProperties[\"PowerCfgSettings\"] is List;\n\n if (isCommandBasedSetting)\n {\n _logService.Log(LogLevel.Info, $\"Checking command-based setting status for: {setting.Name}\");\n \n // Get PowerCfg settings from CustomProperties\n var powerCfgSettings = setting.CustomProperties[\"PowerCfgSettings\"] as List;\n \n try\n {\n // Special handling for Desktop Slideshow setting\n bool isDesktopSlideshowSetting = setting.Name.Contains(\"Desktop Slideshow\", StringComparison.OrdinalIgnoreCase);\n \n // Check if all PowerCfg settings are applied\n bool allApplied = await _powerPlanService.AreAllPowerCfgSettingsAppliedAsync(powerCfgSettings);\n \n // Update setting status based on PowerCfg settings\n setting.Status = allApplied ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n \n // Set a more descriptive current value\n if (isDesktopSlideshowSetting)\n {\n // For Desktop Slideshow, the value is counter-intuitive\n // When enabled (IsSelected=true), the slideshow is \"Available\" (value=0)\n // When disabled (IsSelected=false), the slideshow is \"Paused\" (value=1)\n setting.CurrentValue = allApplied ? \"Available\" : \"Paused\";\n }\n else\n {\n setting.CurrentValue = allApplied ? \"Enabled\" : \"Disabled\";\n }\n \n // Set status message with more detailed information\n setting.StatusMessage = allApplied\n ? \"This setting is currently applied.\"\n : \"This setting is not currently applied.\";\n \n _logService.Log(LogLevel.Info, $\"Command-based setting {setting.Name} status: {setting.Status}, isApplied={allApplied}, currentValue={setting.CurrentValue}\");\n \n // Update IsSelected to match the detected state\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = allApplied;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking PowerCfg setting status for {setting.Name}: {ex.Message}\");\n \n // On error, assume the setting is in its default state\n setting.Status = RegistrySettingStatus.NotApplied;\n setting.CurrentValue = \"Unknown\";\n setting.StatusMessage = \"Could not determine the current status of this setting.\";\n }\n }\n else if (setting.RegistrySetting != null)\n {\n _logService.Log(LogLevel.Info, $\"Checking registry-based setting status for: {setting.Name}\");\n\n // Get the status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // Get the current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name}: {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n setting.LinkedRegistrySettingsWithValues.Clear();\n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Checking linked registry settings status for: {setting.Name} with {setting.LinkedRegistrySettings.Settings.Count} registry entries\");\n\n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(regSetting.Hive);\n string fullPath = $\"{hiveString}\\\\{regSetting.SubKey}\";\n _logService.Log(LogLevel.Info, $\"Registry entry: {fullPath}\\\\{regSetting.Name}, EnabledValue={regSetting.EnabledValue}, DisabledValue={regSetting.DisabledValue}\");\n\n // Check if the key exists\n bool keyExists = _registryService.KeyExists(fullPath);\n _logService.Log(LogLevel.Info, $\"Key exists: {keyExists}\");\n\n if (keyExists)\n {\n // Check if the value exists and get its current value\n var currentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value: {currentValue ?? \"null\"}\");\n }\n }\n\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n _logService.Log(LogLevel.Info, $\"Combined status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name} (first entry): {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value for linked setting {regSetting.Name}: {regCurrentValue ?? \"null\"}\");\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry setting or command-based setting found for {setting.Name}\");\n setting.Status = RegistrySettingStatus.Unknown;\n setting.StatusMessage = \"Setting information is missing\";\n }\n\n // If this is a grouped setting, update child settings too\n if (setting.IsGroupedSetting && setting.ChildSettings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Updating {setting.ChildSettings.Count} child settings for {setting.Name}\");\n foreach (var childSetting in setting.ChildSettings)\n {\n // Check if this is a command-based child setting\n bool isCommandBasedChildSetting = childSetting.CustomProperties != null &&\n childSetting.CustomProperties.ContainsKey(\"PowerCfgSettings\") &&\n childSetting.CustomProperties[\"PowerCfgSettings\"] is List;\n\n if (isCommandBasedChildSetting)\n {\n try\n {\n var powerCfgSettings = childSetting.CustomProperties[\"PowerCfgSettings\"] as List;\n \n // Special handling for Desktop Slideshow setting\n bool isDesktopSlideshowSetting = childSetting.Name.Contains(\"Desktop Slideshow\", StringComparison.OrdinalIgnoreCase);\n \n bool allApplied = await _powerPlanService.AreAllPowerCfgSettingsAppliedAsync(powerCfgSettings);\n \n childSetting.Status = allApplied ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n \n // Set a more descriptive current value\n if (isDesktopSlideshowSetting)\n {\n childSetting.CurrentValue = allApplied ? \"Available\" : \"Paused\";\n }\n else\n {\n childSetting.CurrentValue = allApplied ? \"Enabled\" : \"Disabled\";\n }\n \n childSetting.StatusMessage = allApplied\n ? \"This setting is currently applied.\"\n : \"This setting is not currently applied.\";\n \n // Update IsSelected based on status\n childSetting.IsUpdatingFromCode = true;\n try\n {\n childSetting.IsSelected = allApplied;\n }\n finally\n {\n childSetting.IsUpdatingFromCode = false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking PowerCfg setting status for child setting {childSetting.Name}: {ex.Message}\");\n \n // On error, assume the setting is in its default state\n childSetting.Status = RegistrySettingStatus.NotApplied;\n childSetting.CurrentValue = \"Unknown\";\n childSetting.StatusMessage = \"Could not determine the current status of this setting.\";\n }\n }\n else if (childSetting.RegistrySetting != null)\n {\n var status = await _registryService.GetSettingStatusAsync(childSetting.RegistrySetting);\n childSetting.Status = status;\n\n var currentValue = await _registryService.GetCurrentValueAsync(childSetting.RegistrySetting);\n childSetting.CurrentValue = currentValue;\n\n childSetting.StatusMessage = GetStatusMessage(childSetting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Child setting {childSetting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n childSetting.IsUpdatingFromCode = true;\n try\n {\n childSetting.IsSelected = shouldBeSelected;\n }\n finally\n {\n childSetting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating status for setting {setting.Name}: {ex.Message}\");\n setting.Status = RegistrySettingStatus.Error;\n setting.StatusMessage = $\"Error: {ex.Message}\";\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking power setting statuses: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0)\n return;\n\n var selectedCount = Settings.Count(setting => setting.IsSelected);\n IsSelected = selectedCount == Settings.Count;\n }\n\n /// \n /// Applies a registry setting with the specified value.\n /// \n /// The registry setting to apply.\n /// The value to set.\n /// A task representing the asynchronous operation.\n private async Task ApplyRegistrySetting(RegistrySetting registrySetting, object value)\n {\n string hiveString = registrySetting.Hive.ToString();\n if (hiveString == \"LocalMachine\") hiveString = \"HKLM\";\n else if (hiveString == \"CurrentUser\") hiveString = \"HKCU\";\n else if (hiveString == \"ClassesRoot\") hiveString = \"HKCR\";\n else if (hiveString == \"Users\") hiveString = \"HKU\";\n else if (hiveString == \"CurrentConfig\") hiveString = \"HKCC\";\n\n string fullPath = $\"{hiveString}\\\\{registrySetting.SubKey}\";\n \n if (value == null)\n {\n await _registryService.DeleteValue(registrySetting.Hive, registrySetting.SubKey, registrySetting.Name);\n }\n else\n {\n _registryService.SetValue(fullPath, registrySetting.Name, value, registrySetting.ValueType);\n }\n }\n\n /// \n /// Gets a user-friendly status message for a setting.\n /// \n /// The setting to get the status message for.\n /// A user-friendly status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied =>\n \"This setting is already applied with the recommended value.\",\n\n RegistrySettingStatus.NotApplied =>\n setting.CurrentValue == null\n ? \"This setting is not applied (registry value does not exist).\"\n : \"This setting is using the default value.\",\n\n RegistrySettingStatus.Modified =>\n \"This setting has a custom value that differs from the recommended value.\",\n\n RegistrySettingStatus.Error =>\n \"An error occurred while checking this setting's status.\",\n\n _ => \"The status of this setting is unknown.\"\n };\n }\n\n /// \n /// Converts a tuple to a RegistrySetting object.\n /// \n /// The key for the setting.\n /// The tuple containing the setting information.\n /// A RegistrySetting object.\n private RegistrySetting ConvertToRegistrySetting(string key, (string Path, string Name, object Value, Microsoft.Win32.RegistryValueKind ValueKind) settingTuple)\n {\n // Determine the registry hive from the path\n RegistryHive hive = RegistryHive.LocalMachine; // Default to HKLM\n if (settingTuple.Path.StartsWith(\"HKEY_CURRENT_USER\") || settingTuple.Path.StartsWith(\"HKCU\") || settingTuple.Path.StartsWith(\"Software\\\\\"))\n {\n hive = RegistryHive.CurrentUser;\n }\n else if (settingTuple.Path.StartsWith(\"HKEY_LOCAL_MACHINE\") || settingTuple.Path.StartsWith(\"HKLM\"))\n {\n hive = RegistryHive.LocalMachine;\n }\n else if (settingTuple.Path.StartsWith(\"HKEY_CLASSES_ROOT\") || settingTuple.Path.StartsWith(\"HKCR\"))\n {\n hive = RegistryHive.ClassesRoot;\n }\n else if (settingTuple.Path.StartsWith(\"HKEY_USERS\") || settingTuple.Path.StartsWith(\"HKU\"))\n {\n hive = RegistryHive.Users;\n }\n else if (settingTuple.Path.StartsWith(\"HKEY_CURRENT_CONFIG\") || settingTuple.Path.StartsWith(\"HKCC\"))\n {\n hive = RegistryHive.CurrentConfig;\n }\n\n // Clean up the path to remove any hive prefix\n string subKey = settingTuple.Path;\n if (subKey.StartsWith(\"HKEY_CURRENT_USER\\\\\") || subKey.StartsWith(\"HKCU\\\\\"))\n {\n subKey = subKey.Replace(\"HKEY_CURRENT_USER\\\\\", \"\").Replace(\"HKCU\\\\\", \"\");\n }\n else if (subKey.StartsWith(\"HKEY_LOCAL_MACHINE\\\\\") || subKey.StartsWith(\"HKLM\\\\\"))\n {\n subKey = subKey.Replace(\"HKEY_LOCAL_MACHINE\\\\\", \"\").Replace(\"HKLM\\\\\", \"\");\n }\n else if (subKey.StartsWith(\"HKEY_CLASSES_ROOT\\\\\") || subKey.StartsWith(\"HKCR\\\\\"))\n {\n subKey = subKey.Replace(\"HKEY_CLASSES_ROOT\\\\\", \"\").Replace(\"HKCR\\\\\", \"\");\n }\n else if (subKey.StartsWith(\"HKEY_USERS\\\\\") || subKey.StartsWith(\"HKU\\\\\"))\n {\n subKey = subKey.Replace(\"HKEY_USERS\\\\\", \"\").Replace(\"HKU\\\\\", \"\");\n }\n else if (subKey.StartsWith(\"HKEY_CURRENT_CONFIG\\\\\") || subKey.StartsWith(\"HKCC\\\\\"))\n {\n subKey = subKey.Replace(\"HKEY_CURRENT_CONFIG\\\\\", \"\").Replace(\"HKCC\\\\\", \"\");\n }\n\n // Create and return the RegistrySetting object\n var registrySetting = new RegistrySetting\n {\n Category = \"Power\",\n Hive = hive,\n SubKey = subKey,\n Name = settingTuple.Name,\n EnabledValue = settingTuple.Value, // Recommended value becomes EnabledValue\n DisabledValue = settingTuple.Value,\n ValueType = settingTuple.ValueKind,\n // Keep these for backward compatibility\n RecommendedValue = settingTuple.Value,\n DefaultValue = settingTuple.Value,\n Description = $\"Power setting: {key}\"\n };\n\n return registrySetting;\n }\n\n /// \n /// Gets a friendly name for a power setting.\n /// \n /// The power setting key.\n /// A user-friendly name for the power setting.\n private string GetFriendlyNameForPowerSetting(string key)\n {\n return key switch\n {\n \"HibernateEnabled\" => \"Disable Hibernate\",\n \"HibernateEnabledDefault\" => \"Disable Hibernate by Default\",\n \"VideoQuality\" => \"High Video Quality on Battery\",\n \"LockOption\" => \"Hide Lock Option\",\n \"FastBoot\" => \"Disable Fast Boot\",\n \"CpuUnpark\" => \"CPU Core Unparking\",\n \"PowerThrottling\" => \"Disable Power Throttling\",\n _ => key\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/PrivacyOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for privacy optimizations.\n /// \n public partial class PrivacyOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDependencyManager _dependencyManager;\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dependency manager.\n /// The view model locator.\n /// The settings registry.\n public PrivacyOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDependencyManager dependencyManager,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _dependencyManager = dependencyManager ?? throw new ArgumentNullException(nameof(dependencyManager));\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n _logService.Log(LogLevel.Info, \"PrivacyOptimizationsViewModel instance created\");\n }\n\n /// \n /// Loads the privacy settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, \"Loading privacy settings\");\n\n // Initialize privacy settings from PrivacyOptimizations.cs\n var privacyOptimizations = Core.Features.Optimize.Models.PrivacyOptimizations.GetPrivacyOptimizations();\n if (privacyOptimizations?.Settings != null)\n {\n Settings.Clear();\n\n // Process each setting\n foreach (var setting in privacyOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = false, // Always initialize as unchecked\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n\n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Register the setting in the settings registry if available\n if (_settingsRegistry != null && !string.IsNullOrEmpty(settingItem.Id))\n {\n _settingsRegistry.RegisterSetting(settingItem);\n _logService.Log(LogLevel.Info, $\"Registered setting {settingItem.Id} in settings registry during creation\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for checkboxes\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n await CheckSettingStatusesAsync();\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading privacy settings: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all privacy settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, $\"Checking status for {Settings.Count} privacy settings\");\n\n // Clear registry caches to ensure fresh reads\n _registryService.ClearRegistryCaches();\n\n // Create a list of tasks to check all settings in parallel\n var tasks = Settings.Select(async setting => {\n try\n {\n // Check if we have linked registry settings\n if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Checking status for linked setting: {setting.Name} with {setting.LinkedRegistrySettings.Settings.Count} registry entries\");\n\n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(regSetting.Hive);\n string fullPath = $\"{hiveString}\\\\{regSetting.SubKey}\";\n _logService.Log(LogLevel.Info, $\"Registry entry: {fullPath}\\\\{regSetting.Name}, EnabledValue={regSetting.EnabledValue}, DisabledValue={regSetting.DisabledValue}\");\n\n // Check if the key exists\n bool keyExists = _registryService.KeyExists(fullPath);\n _logService.Log(LogLevel.Info, $\"Key exists: {keyExists}\");\n\n if (keyExists)\n {\n // Check if the value exists and get its current value\n var currentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value: {currentValue ?? \"null\"}\");\n }\n }\n\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n _logService.Log(LogLevel.Info, $\"Combined status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name} (first entry): {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value for linked setting {regSetting.Name}: {regCurrentValue ?? \"null\"}\");\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n // Fall back to single registry setting\n else if (setting.RegistrySetting != null)\n {\n _logService.Log(LogLevel.Info, $\"Checking status for setting: {setting.Name}\");\n\n // Log details about the registry entry for debugging\n string hiveString = RegistryExtensions.GetRegistryHiveString(setting.RegistrySetting.Hive);\n string fullPath = $\"{hiveString}\\\\{setting.RegistrySetting.SubKey}\";\n _logService.Log(LogLevel.Info, $\"Registry entry: {fullPath}\\\\{setting.RegistrySetting.Name}, EnabledValue={setting.RegistrySetting.EnabledValue}, DisabledValue={setting.RegistrySetting.DisabledValue}\");\n\n // Check if the key exists\n bool keyExists = _registryService.KeyExists(fullPath);\n _logService.Log(LogLevel.Info, $\"Key exists: {keyExists}\");\n\n // Get the status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // Get the current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name}: {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n \n // Set IsRegistryValueNull for single registry setting\n setting.IsRegistryValueNull = currentValue == null;\n\n // Add to LinkedRegistrySettingsWithValues for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings available for {setting.Name}\");\n setting.Status = RegistrySettingStatus.Unknown;\n setting.StatusMessage = \"Registry setting information is missing\";\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating status for setting {setting.Name}: {ex.Message}\");\n setting.Status = RegistrySettingStatus.Error;\n setting.StatusMessage = $\"Error: {ex.Message}\";\n }\n }).ToList();\n\n // Wait for all tasks to complete\n await Task.WhenAll(tasks);\n\n // Now handle any grouped settings\n foreach (var setting in Settings.Where(s => s.IsGroupedSetting && s.ChildSettings.Count > 0))\n {\n _logService.Log(LogLevel.Info, $\"Updating {setting.ChildSettings.Count} child settings for {setting.Name}\");\n foreach (var childSetting in setting.ChildSettings)\n {\n if (childSetting.RegistrySetting != null)\n {\n var status = await _registryService.GetSettingStatusAsync(childSetting.RegistrySetting);\n childSetting.Status = status;\n\n var currentValue = await _registryService.GetCurrentValueAsync(childSetting.RegistrySetting);\n childSetting.CurrentValue = currentValue;\n\n childSetting.StatusMessage = GetStatusMessage(childSetting);\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking privacy setting statuses: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n // ApplySelectedSettingsAsync and RestoreDefaultsAsync methods removed as part of the refactoring\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0)\n return;\n\n var selectedCount = Settings.Count(setting => setting.IsSelected);\n IsSelected = selectedCount == Settings.Count;\n }\n\n /// \n /// Gets a user-friendly status message for a setting.\n /// \n /// The setting to get the status message for.\n /// A user-friendly status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied =>\n \"This setting is enabled (toggle is ON).\",\n\n RegistrySettingStatus.NotApplied =>\n setting.CurrentValue == null\n ? \"This setting is not applied (registry value does not exist).\"\n : \"This setting is disabled (toggle is OFF).\",\n\n RegistrySettingStatus.Modified =>\n \"This setting has a custom value that differs from both enabled and disabled values.\",\n\n RegistrySettingStatus.Error =>\n \"An error occurred while checking this setting's status.\",\n\n _ => \"The status of this setting is unknown.\"\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/ExternalAppsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.SoftwareApps.Models;\nusing ToastType = Winhance.Core.Features.UI.Interfaces.ToastType;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n public partial class ExternalAppsViewModel : BaseInstallationViewModel\n {\n [ObservableProperty]\n private bool _isInitialized = false;\n\n private readonly IAppInstallationService _appInstallationService;\n private readonly IAppService _appDiscoveryService;\n private readonly IConfigurationService _configurationService;\n\n [ObservableProperty]\n private string _statusText = \"Ready\";\n\n // ObservableCollection to store category view models\n private ObservableCollection _categories = new();\n\n // Public property to expose the categories\n public ObservableCollection Categories => _categories;\n\n public ExternalAppsViewModel(\n ITaskProgressService progressService,\n ISearchService searchService,\n IPackageManager packageManager,\n IAppInstallationService appInstallationService,\n IAppService appDiscoveryService,\n IConfigurationService configurationService,\n Services.SoftwareAppsDialogService dialogService,\n IInternetConnectivityService connectivityService,\n IAppInstallationCoordinatorService appInstallationCoordinatorService\n )\n : base(\n progressService,\n searchService,\n packageManager,\n appInstallationService,\n appInstallationCoordinatorService,\n connectivityService,\n dialogService\n )\n {\n _appInstallationService = appInstallationService;\n _appDiscoveryService = appDiscoveryService;\n _configurationService = configurationService;\n }\n\n // SaveConfig and ImportConfig methods removed as part of unified configuration cleanup\n\n /// \n /// Applies the current search text to filter items.\n /// \n protected override void ApplySearch()\n {\n if (Items == null || Items.Count == 0)\n return;\n\n // Filter items based on search text\n var filteredItems = FilterItems(Items);\n\n // Clear all categories\n foreach (var category in Categories)\n {\n category.Apps.Clear();\n }\n\n // Group filtered items by category\n var appsByCategory = new Dictionary>();\n\n foreach (var app in filteredItems)\n {\n string category = app.Category;\n if (string.IsNullOrEmpty(category))\n {\n category = \"Other\";\n }\n\n if (!appsByCategory.ContainsKey(category))\n {\n appsByCategory[category] = new List();\n }\n\n appsByCategory[category].Add(app);\n }\n\n // Update categories with filtered items\n foreach (var category in Categories)\n {\n if (appsByCategory.TryGetValue(category.Name, out var apps))\n {\n // Sort apps alphabetically within the category\n var sortedApps = apps.OrderBy(a => a.Name);\n\n foreach (var app in sortedApps)\n {\n category.Apps.Add(app);\n }\n }\n }\n\n // Hide empty categories if search is active\n if (IsSearchActive)\n {\n foreach (var category in Categories)\n {\n category.IsExpanded = category.Apps.Count > 0;\n }\n }\n }\n\n public override async Task LoadItemsAsync()\n {\n if (_packageManager == null)\n return;\n\n IsLoading = true;\n StatusText = \"Loading external apps...\";\n\n try\n {\n Items.Clear();\n _categories.Clear();\n\n var apps = await _packageManager.GetInstallableAppsAsync();\n\n // Group apps by category\n var appsByCategory = new Dictionary>();\n\n foreach (var app in apps)\n {\n var externalApp = ExternalApp.FromAppInfo(app);\n Items.Add(externalApp);\n\n // Group by category\n string category = app.Category;\n if (string.IsNullOrEmpty(category))\n {\n category = \"Other\";\n }\n\n if (!appsByCategory.ContainsKey(category))\n {\n appsByCategory[category] = new List();\n }\n\n appsByCategory[category].Add(externalApp);\n }\n\n // Sort categories alphabetically\n var sortedCategories = appsByCategory.Keys.OrderBy(c => c).ToList();\n\n // Create category view models with sorted apps\n foreach (var categoryName in sortedCategories)\n {\n // Sort apps alphabetically within the category\n var sortedApps = appsByCategory[categoryName].OrderBy(a => a.Name).ToList();\n\n // Create observable collection for the category\n var appsCollection = new ObservableCollection(sortedApps);\n\n // Create and add the category view model\n _categories.Add(\n new ExternalAppsCategoryViewModel(categoryName, appsCollection)\n );\n }\n\n StatusText = $\"Loaded {Items.Count} external apps\";\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error loading external apps: {ex.Message}\";\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n public override async Task CheckInstallationStatusAsync()\n {\n if (_appDiscoveryService == null)\n return;\n\n IsLoading = true;\n StatusText = \"Checking installation status...\";\n\n try\n {\n var statusResults = await _appDiscoveryService.GetBatchInstallStatusAsync(\n Items.Select(a => a.PackageName)\n );\n\n foreach (var app in Items)\n {\n if (statusResults.TryGetValue(app.PackageName, out bool isInstalled))\n {\n app.IsInstalled = isInstalled;\n }\n }\n StatusText = \"Installation status check complete\";\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error checking installation status: {ex.Message}\";\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n [RelayCommand]\n public async Task InstallApp(ExternalApp app)\n {\n if (app == null || _appInstallationService == null)\n return;\n\n // Check for internet connectivity before starting installation\n bool isInternetConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(true);\n if (!isInternetConnected)\n {\n StatusText = \"No internet connection available. Installation cannot proceed.\";\n\n // Show dialog informing the user about the connectivity issue\n await ShowNoInternetConnectionDialogAsync();\n return;\n }\n\n IsLoading = true;\n StatusText = $\"Installing {app.Name}...\";\n\n // Setup cancellation for the installation process\n using var cts = new System.Threading.CancellationTokenSource();\n var cancellationToken = cts.Token;\n\n // Start a background task to periodically check internet connectivity during installation\n var connectivityCheckTask = StartPeriodicConnectivityCheck(app.Name, cts);\n\n try\n {\n var progress = _progressService.CreateDetailedProgress();\n\n try\n {\n var operationResult = await _appInstallationService.InstallAppAsync(\n app.ToAppInfo(),\n progress,\n cancellationToken\n );\n\n // Cancel the connectivity check task as installation is complete\n cts.Cancel();\n\n // Wait for the connectivity check task to complete\n try\n {\n await connectivityCheckTask;\n }\n catch (OperationCanceledException)\n { /* Expected when we cancel */\n }\n\n if (operationResult.Success)\n {\n app.IsInstalled = true;\n StatusText = $\"Successfully installed {app.Name}\";\n\n // Show success dialog\n _dialogService.ShowInformationAsync(\n \"Installation Complete\",\n $\"{app.Name} was successfully installed.\",\n new[] { app.Name },\n \"The application has been installed successfully.\"\n );\n }\n else\n {\n string errorMessage =\n operationResult.ErrorMessage\n ?? $\"Failed to install {app.Name}. Please try again.\";\n StatusText = errorMessage;\n\n // Store the error message for later reference\n app.LastOperationError = errorMessage;\n\n // Show error dialog\n _dialogService.ShowInformationAsync(\n \"Installation Failed\",\n $\"Failed to install {app.Name}.\",\n new[] { $\"{app.Name}: {errorMessage}\" },\n \"There was an error during installation. Please try again later.\"\n );\n }\n }\n catch (OperationCanceledException)\n {\n // Set cancellation reason to UserCancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n \n // Cancel the connectivity check task\n cts.Cancel();\n\n // Wait for the connectivity check task to complete\n try\n {\n await connectivityCheckTask;\n }\n catch (OperationCanceledException)\n { /* Expected when we cancel */\n }\n \n // For single app installations, use the ShowCancellationDialogAsync method directly\n // which will use CustomDialog with a simpler message\n await ShowCancellationDialogAsync(true, false); // User-initiated cancellation\n \n // Reset cancellation reason after showing dialog\n CurrentCancellationReason = CancellationReason.None;\n \n StatusText = $\"Installation of {app.Name} was cancelled\";\n }\n catch (System.Exception ex)\n {\n // Cancel the connectivity check task\n cts.Cancel();\n\n // Wait for the connectivity check task to complete\n try\n {\n await connectivityCheckTask;\n }\n catch (OperationCanceledException)\n { /* Expected when we cancel */\n }\n\n // Check if the exception is related to internet connectivity\n bool isConnectivityIssue =\n ex.Message.Contains(\"internet\", StringComparison.OrdinalIgnoreCase)\n || ex.Message.Contains(\"connection\", StringComparison.OrdinalIgnoreCase)\n || ex.Message.Contains(\"network\", StringComparison.OrdinalIgnoreCase)\n || ex.Message.Contains(\"pipeline has been stopped\", StringComparison.OrdinalIgnoreCase);\n\n if (isConnectivityIssue && CurrentCancellationReason == CancellationReason.None)\n {\n // Use the centralized cancellation handling for connectivity issues\n await HandleCancellationAsync(true); // Connectivity-related cancellation\n }\n \n string errorMessage = isConnectivityIssue\n ? \"Internet connection lost during installation. Please check your network connection and try again.\"\n : ex.Message;\n\n // Store the error message for later reference\n app.LastOperationError = errorMessage;\n\n StatusText = $\"Error installing {app.Name}: {errorMessage}\";\n\n // Only show error dialog if it's not a connectivity issue (which is already handled by HandleCancellationAsync)\n if (!isConnectivityIssue)\n {\n _dialogService.ShowInformationAsync(\n \"Installation Failed\",\n $\"Failed to install {app.Name}.\",\n new[] { $\"{app.Name}: {errorMessage}\" },\n \"There was an error during installation. Please try again later.\"\n );\n }\n }\n }\n catch (System.Exception ex)\n {\n // This is a fallback catch-all to ensure the application doesn't crash\n // Cancel the connectivity check task\n cts.Cancel();\n\n // Wait for the connectivity check task to complete\n try\n {\n await connectivityCheckTask;\n }\n catch (OperationCanceledException)\n { /* Expected when we cancel */\n }\n\n // Store the error message for later reference\n app.LastOperationError = ex.Message;\n\n StatusText = $\"Error installing {app.Name}: {ex.Message}\";\n\n // Show error dialog\n _dialogService.ShowInformationAsync(\n \"Installation Failed\",\n $\"Failed to install {app.Name}.\",\n new[] { $\"{app.Name}: {ex.Message}\" },\n \"There was an error during installation. Please try again later.\"\n );\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Starts a periodic check for internet connectivity during installation.\n /// \n /// The name of the app being installed\n /// Cancellation token source to cancel the task\n /// A task that completes when the installation is done or cancelled\n private async Task StartPeriodicConnectivityCheck(\n string appName,\n System.Threading.CancellationTokenSource cts\n )\n {\n try\n {\n // Check connectivity every 5 seconds during installation\n while (!cts.Token.IsCancellationRequested)\n {\n await Task.Delay(5000, cts.Token); // 5 seconds delay between checks\n\n if (cts.Token.IsCancellationRequested)\n break;\n\n bool isConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(\n false,\n cts.Token\n );\n\n if (!isConnected)\n {\n // Only set connectivity loss if no other cancellation reason is set\n if (CurrentCancellationReason == CancellationReason.None)\n {\n // Update status to inform user about connectivity issue\n StatusText =\n $\"Error: Internet connection lost while installing {appName}. Installation stopped.\";\n\n // Show a non-blocking toast notification\n if (_packageManager.NotificationService != null)\n {\n _packageManager.NotificationService.ShowToast(\n \"Internet Connection Lost\",\n \"Internet connection has been lost during installation. Installation has been stopped.\",\n ToastType.Error\n );\n }\n\n // Use the centralized cancellation handling instead of showing dialog directly\n await HandleCancellationAsync(true); // Connectivity-related cancellation\n }\n \n // Cancel the installation process\n cts.Cancel();\n break;\n }\n }\n }\n catch (OperationCanceledException)\n {\n // Task was cancelled, which is expected when installation completes or is stopped\n }\n catch (Exception ex)\n {\n // Log any unexpected errors but don't disrupt the installation process\n System.Diagnostics.Debug.WriteLine($\"Error in connectivity check: {ex.Message}\");\n }\n }\n\n [RelayCommand]\n public void ClearSelectedItems()\n {\n // Clear all selected items\n foreach (var app in Items)\n {\n app.IsSelected = false;\n }\n\n // Update the UI for all categories\n foreach (var category in Categories)\n {\n foreach (var app in category.Apps)\n {\n app.IsSelected = false;\n }\n }\n\n StatusText = \"All selections cleared\";\n }\n\n [RelayCommand]\n public async Task InstallApps()\n {\n if (_appInstallationService == null)\n return;\n\n // Get all selected apps regardless of installation status\n var selectedApps = Items.Where(a => a.IsSelected).ToList();\n\n if (!selectedApps.Any())\n {\n StatusText = \"No apps selected for installation\";\n await ShowNoItemsSelectedDialogAsync(\"installation\");\n return;\n }\n\n // Check for internet connectivity before starting batch installation\n bool isInternetConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(true);\n if (!isInternetConnected)\n {\n StatusText = \"No internet connection available. Installation cannot proceed.\";\n\n // Show dialog informing the user about the connectivity issue\n await ShowNoInternetConnectionDialogAsync();\n return;\n }\n\n // Show confirmation dialog\n bool? dialogResult = await ShowConfirmItemsDialogAsync(\n \"install\",\n selectedApps.Select(a => a.Name),\n selectedApps.Count\n );\n\n // If user didn't confirm, exit\n if (dialogResult != true)\n {\n return;\n }\n\n // Setup cancellation for the installation process\n using var cts = new System.Threading.CancellationTokenSource();\n\n // Start a background task to periodically check internet connectivity during installation\n var connectivityCheckTask = StartBatchConnectivityCheck(cts);\n\n // Use the ExecuteWithProgressAsync method from BaseViewModel to handle progress reporting\n await ExecuteWithProgressAsync(\n async (progress, cancellationToken) =>\n {\n int successCount = 0;\n int currentItem = 0;\n int totalSelected = selectedApps.Count;\n\n foreach (var app in selectedApps)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n await HandleCancellationAsync(false); // User-initiated cancellation\n cts.Cancel(); // Ensure all tasks are cancelled\n return successCount; // Exit the method immediately\n }\n\n try\n {\n var operationResult = await _appInstallationService.InstallAppAsync(\n app.ToAppInfo(),\n progress,\n cancellationToken\n );\n\n if (operationResult.Success)\n {\n app.IsInstalled = true;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Successfully installed {app.Name}\",\n DetailedMessage = $\"Successfully installed app: {app.Name}\",\n LogLevel = LogLevel.Success,\n AdditionalInfo = new Dictionary\n {\n { \"AppName\", app.Name },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Install\" },\n { \"OperationStatus\", \"Success\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n else\n {\n string errorMessage =\n operationResult.ErrorMessage ?? $\"Failed to install {app.Name}\";\n\n // Store the error message for later reference\n app.LastOperationError = errorMessage;\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Error installing {app.Name}\",\n DetailedMessage = errorMessage,\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppName\", app.Name },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Install\" },\n { \"OperationStatus\", \"Error\" },\n { \"ErrorMessage\", errorMessage },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n catch (OperationCanceledException)\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Installation of {app.Name} was cancelled\",\n DetailedMessage =\n $\"The installation of {app.Name} was cancelled.\",\n LogLevel = LogLevel.Warning,\n AdditionalInfo = new Dictionary\n {\n { \"AppName\", app.Name },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Install\" },\n { \"OperationStatus\", \"Cancelled\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n\n // Use the centralized cancellation handling\n await HandleCancellationAsync(false); // User-initiated cancellation\n cts.Cancel();\n return successCount; // Exit the method immediately\n }\n catch (System.Exception ex)\n {\n // Check if the exception is related to internet connectivity\n bool isConnectivityIssue =\n ex.Message.Contains(\"internet\", StringComparison.OrdinalIgnoreCase) ||\n ex.Message.Contains(\"connection\", StringComparison.OrdinalIgnoreCase) ||\n ex.Message.Contains(\"network\", StringComparison.OrdinalIgnoreCase) ||\n ex.Message.Contains(\"pipeline has been stopped\", StringComparison.OrdinalIgnoreCase);\n\n if (isConnectivityIssue && CurrentCancellationReason == CancellationReason.None)\n {\n // Set the cancellation reason to connectivity issue\n await HandleCancellationAsync(true); // Connectivity-related cancellation\n }\n \n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Error installing {app.Name}\",\n DetailedMessage = $\"Error installing {app.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppName\", app.Name },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Install\" },\n { \"OperationStatus\", \"Error\" },\n { \"ErrorMessage\", ex.Message },\n { \"ErrorType\", ex.GetType().Name },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n { \"IsConnectivityIssue\", isConnectivityIssue.ToString() },\n },\n }\n );\n }\n }\n\n // Cancel the connectivity check task as installation is complete\n cts.Cancel();\n\n // Wait for the connectivity check task to complete\n try\n {\n await connectivityCheckTask;\n }\n catch (OperationCanceledException)\n { /* Expected when we cancel */\n }\n\n // Only proceed with normal completion reporting if not cancelled\n // Final report\n // Check if any failures were due to internet connectivity issues\n bool hasInternetIssues = selectedApps.Any(a =>\n !a.IsInstalled\n && (\n a.LastOperationError?.Contains(\"Internet connection\") == true\n || a.LastOperationError?.Contains(\"No internet\") == true\n )\n );\n\n string statusText =\n successCount == totalSelected\n ? $\"Successfully installed {successCount} of {totalSelected} apps\"\n : hasInternetIssues ? $\"Installation incomplete: Internet connection issues\"\n : $\"Installation incomplete: {successCount} of {totalSelected} apps installed\";\n\n string detailedMessage =\n successCount == totalSelected\n ? $\"Task completed: {successCount} of {totalSelected} apps installed successfully\"\n : hasInternetIssues\n ? $\"Task not completed: {successCount} of {totalSelected} apps installed. Installation failed due to internet connection issues\"\n : $\"Task completed: {successCount} of {totalSelected} apps installed successfully\";\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = statusText,\n DetailedMessage = detailedMessage,\n LogLevel =\n successCount == totalSelected ? LogLevel.Success : LogLevel.Warning,\n AdditionalInfo = new Dictionary\n {\n { \"OperationType\", \"Install\" },\n {\n \"OperationStatus\",\n successCount == totalSelected ? \"Complete\" : \"PartialSuccess\"\n },\n { \"SuccessCount\", successCount.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n { \"SuccessRate\", $\"{(successCount * 100.0 / totalSelected):F1}%\" },\n { \"CompletionTime\", DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\") },\n },\n }\n );\n\n // For normal completion (not cancelled), collect success and failure information\n var successItems = new List();\n var failedItems = new List();\n\n // Add successful items to the list\n foreach (var app in selectedApps.Where(a => a.IsInstalled))\n {\n successItems.Add(app.Name);\n }\n\n // Add failed items to the list\n foreach (var app in selectedApps.Where(a => !a.IsInstalled))\n {\n failedItems.Add(app.Name);\n }\n\n // Check if any failures are due to internet connectivity issues\n bool hasConnectivityIssues = hasInternetIssues;\n bool isFailure = successCount < totalSelected;\n \n // Important: Check if the operation was cancelled by the user\n // This ensures we show the correct dialog even if the cancellation happened in a different part of the code\n if (failedItems != null && failedItems.Any(item => item.Contains(\"cancelled by user\", StringComparison.OrdinalIgnoreCase)))\n {\n // Set the cancellation reason to UserCancelled if it's not already set\n if (CurrentCancellationReason == CancellationReason.None)\n {\n CurrentCancellationReason = CancellationReason.UserCancelled;\n }\n }\n \n // Show result dialog using the base class method which handles cancellation scenarios properly\n ShowOperationResultDialog(\n \"Install\",\n successCount,\n totalSelected,\n successItems,\n failedItems,\n null // no skipped items\n );\n\n return successCount;\n },\n $\"Installing {selectedApps.Count} apps\",\n false\n );\n }\n\n /// \n /// Starts a periodic check for internet connectivity during batch installation.\n /// \n /// Cancellation token source to cancel the task\n /// A task that completes when the installation is done or cancelled\n private async Task StartBatchConnectivityCheck(System.Threading.CancellationTokenSource cts)\n {\n try\n {\n // Check connectivity every 15 seconds during batch installation (reduced frequency)\n while (!cts.Token.IsCancellationRequested)\n {\n await Task.Delay(15000, cts.Token); // 15 seconds delay between checks (increased from 5)\n\n // If cancellation was already requested (e.g., by the user), don't proceed with connectivity check\n if (cts.Token.IsCancellationRequested)\n {\n // Important: Do NOT set cancellation reason here, as it might overwrite UserCancelled\n break;\n }\n\n // Check if user cancellation has already been set\n if (CurrentCancellationReason == CancellationReason.UserCancelled)\n {\n // User already cancelled, don't change the reason\n break;\n }\n\n bool isConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(\n false,\n cts.Token\n );\n\n if (!isConnected)\n {\n // Only set connectivity loss if no other cancellation reason is set\n if (CurrentCancellationReason == CancellationReason.None)\n {\n // Update status to inform user about connectivity issue\n StatusText =\n \"Error: Internet connection lost during installation. Installation stopped.\";\n\n // Show a non-blocking toast notification\n if (_packageManager.NotificationService != null)\n {\n _packageManager.NotificationService.ShowToast(\n \"Internet Connection Lost\",\n \"Internet connection has been lost during installation. Installation has been stopped.\",\n ToastType.Error\n );\n }\n\n // Use the centralized cancellation handling\n await HandleCancellationAsync(true); // Connectivity-related cancellation\n }\n \n cts.Cancel();\n return; // Exit the method immediately\n }\n }\n }\n catch (OperationCanceledException)\n {\n // Task was cancelled, which is expected when installation completes or is stopped\n // Do NOT set cancellation reason here, as it might have been set by the main task\n }\n catch (Exception ex)\n {\n // Log any unexpected errors but don't disrupt the installation process\n System.Diagnostics.Debug.WriteLine(\n $\"Error in batch connectivity check: {ex.Message}\"\n );\n }\n }\n\n public async Task LoadAppsAndCheckInstallationStatusAsync()\n {\n if (IsInitialized)\n {\n System.Diagnostics.Debug.WriteLine(\n \"ExternalAppsViewModel already initialized, skipping LoadAppsAndCheckInstallationStatusAsync\"\n );\n return;\n }\n\n System.Diagnostics.Debug.WriteLine(\n \"Starting ExternalAppsViewModel LoadAppsAndCheckInstallationStatusAsync\"\n );\n await LoadItemsAsync();\n await CheckInstallationStatusAsync();\n\n // Mark as initialized after loading is complete\n IsInitialized = true;\n System.Diagnostics.Debug.WriteLine(\n \"Completed ExternalAppsViewModel LoadAppsAndCheckInstallationStatusAsync\"\n );\n }\n\n public override async void OnNavigatedTo(object parameter)\n {\n try\n {\n // Only load data if not already initialized\n if (!IsInitialized)\n {\n await LoadAppsAndCheckInstallationStatusAsync();\n }\n }\n catch (System.Exception ex)\n {\n // Handle any exceptions\n StatusText = $\"Error loading apps: {ex.Message}\";\n IsLoading = false;\n }\n }\n\n #region BaseInstallationViewModel Abstract Method Implementations\n\n /// \n /// Gets the name of an external app.\n /// \n /// The external app.\n /// The name of the app.\n protected override string GetAppName(ExternalApp app)\n {\n return app.Name;\n }\n\n /// \n /// Converts an external app to an AppInfo object.\n /// \n /// The external app to convert.\n /// The AppInfo object.\n protected override AppInfo ToAppInfo(ExternalApp app)\n {\n return app.ToAppInfo();\n }\n\n /// \n /// Gets the selected external apps.\n /// \n /// The selected external apps.\n protected override IEnumerable GetSelectedApps()\n {\n return Items.Where(a => a.IsSelected);\n }\n\n /// \n /// Sets the installation status of an external app.\n /// \n /// The external app.\n /// Whether the app is installed.\n protected override void SetInstallationStatus(ExternalApp app, bool isInstalled)\n {\n app.IsInstalled = isInstalled;\n }\n\n #endregion\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/ConfigurationService.cs", "using Microsoft.Win32;\nusing Newtonsoft.Json;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service for saving and loading application configuration files.\n /// \n public class ConfigurationService : IConfigurationService\n {\n private const string FileExtension = \".winhance\";\n private const string FileFilter = \"Winhance Configuration Files|*\" + FileExtension;\n private const string UnifiedFileFilter = \"Winhance Unified Configuration Files|*\" + FileExtension;\n private readonly ILogService _logService;\n \n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public ConfigurationService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Saves a configuration file containing the selected items.\n /// \n /// The type of items to save.\n /// The collection of items to save.\n /// The type of configuration being saved.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n public async Task SaveConfigurationAsync(IEnumerable items, string configType)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Starting to save {configType} configuration\");\n // Create a save file dialog\n var saveFileDialog = new SaveFileDialog\n {\n Filter = FileFilter,\n DefaultExt = FileExtension,\n Title = \"Save Configuration\",\n FileName = $\"{configType}_{DateTime.Now:yyyyMMdd}{FileExtension}\"\n };\n\n // Show the save file dialog\n if (saveFileDialog.ShowDialog() != true)\n {\n _logService.Log(LogLevel.Info, \"Save configuration canceled by user\");\n return false;\n }\n \n _logService.Log(LogLevel.Info, $\"Saving configuration to {saveFileDialog.FileName}\");\n\n // Create a configuration file\n var configFile = new ConfigurationFile\n {\n ConfigType = configType,\n CreatedAt = DateTime.UtcNow,\n Items = new List()\n };\n\n // Add selected items to the configuration file\n foreach (var item in items)\n {\n var properties = item.GetType().GetProperties();\n var nameProperty = properties.FirstOrDefault(p => p.Name == \"Name\");\n var packageNameProperty = properties.FirstOrDefault(p => p.Name == \"PackageName\");\n var isSelectedProperty = properties.FirstOrDefault(p => p.Name == \"IsSelected\");\n var controlTypeProperty = properties.FirstOrDefault(p => p.Name == \"ControlType\");\n var registrySettingProperty = properties.FirstOrDefault(p => p.Name == \"RegistrySetting\");\n var idProperty = properties.FirstOrDefault(p => p.Name == \"Id\");\n\n if (nameProperty != null && isSelectedProperty != null)\n {\n var name = nameProperty.GetValue(item)?.ToString();\n var packageName = packageNameProperty?.GetValue(item)?.ToString();\n var isSelected = (bool)(isSelectedProperty.GetValue(item) ?? false);\n \n // Create the configuration item\n var configItem = new ConfigurationItem\n {\n Name = name,\n PackageName = packageName,\n IsSelected = isSelected\n };\n \n // Add control type if available\n if (controlTypeProperty != null)\n {\n var controlType = controlTypeProperty.GetValue(item);\n if (controlType != null)\n {\n configItem.ControlType = (ControlType)controlType;\n }\n }\n \n // Store the Id in CustomProperties if available\n if (idProperty != null)\n {\n var id = idProperty.GetValue(item);\n if (id != null)\n {\n configItem.CustomProperties[\"Id\"] = id.ToString();\n _logService.Log(LogLevel.Info, $\"Stored Id for {configItem.Name}: {id}\");\n }\n }\n \n // Handle ComboBox and ThreeStateSlider control types\n if (configItem.ControlType == ControlType.ComboBox || configItem.ControlType == ControlType.ThreeStateSlider)\n {\n // For ComboBox, get the selected value\n var selectedThemeProperty = properties.FirstOrDefault(p => p.Name == \"SelectedTheme\");\n if (selectedThemeProperty != null)\n {\n configItem.SelectedValue = selectedThemeProperty.GetValue(item)?.ToString();\n _logService.Log(LogLevel.Info, $\"Setting SelectedValue for {configItem.Name} to '{configItem.SelectedValue}'\");\n }\n else\n {\n // Try to get the value from SliderLabels and SliderValue\n var sliderLabelsProperty = properties.FirstOrDefault(p => p.Name == \"SliderLabels\");\n var sliderValueProperty = properties.FirstOrDefault(p => p.Name == \"SliderValue\");\n \n if (sliderLabelsProperty != null && sliderValueProperty != null)\n {\n var sliderLabels = sliderLabelsProperty.GetValue(item) as System.Collections.IList;\n var sliderValue = sliderValueProperty.GetValue(item);\n \n if (sliderLabels != null && sliderValue != null && Convert.ToInt32(sliderValue) < sliderLabels.Count)\n {\n configItem.SelectedValue = sliderLabels[Convert.ToInt32(sliderValue)]?.ToString();\n _logService.Log(LogLevel.Info, $\"Derived SelectedValue for {configItem.Name} from SliderLabels[{sliderValue}]: '{configItem.SelectedValue}'\");\n }\n }\n }\n \n // Store the SliderValue for ComboBox or ThreeStateSlider\n // Note: In this application, ComboBox controls use SliderValue to store the selected index\n if (configItem.ControlType == ControlType.ComboBox || configItem.ControlType == ControlType.ThreeStateSlider)\n {\n var sliderValueProperty = properties.FirstOrDefault(p => p.Name == \"SliderValue\");\n if (sliderValueProperty != null)\n {\n var sliderValue = sliderValueProperty.GetValue(item);\n if (sliderValue != null)\n {\n configItem.CustomProperties[\"SliderValue\"] = sliderValue;\n _logService.Log(LogLevel.Info, $\"Stored SliderValue for {configItem.ControlType} {configItem.Name}: {sliderValue}\");\n }\n }\n \n // Also store SliderLabels if available\n var sliderLabelsProperty = properties.FirstOrDefault(p => p.Name == \"SliderLabels\");\n if (sliderLabelsProperty != null)\n {\n var sliderLabels = sliderLabelsProperty.GetValue(item) as System.Collections.IList;\n if (sliderLabels != null && sliderLabels.Count > 0)\n {\n // Store the labels as a comma-separated string\n var labelsString = string.Join(\",\", sliderLabels.Cast().Select(l => l.ToString()));\n configItem.CustomProperties[\"SliderLabels\"] = labelsString;\n _logService.Log(LogLevel.Info, $\"Stored SliderLabels for {configItem.ControlType} {configItem.Name}: {labelsString}\");\n \n // For Power Plan, also store the labels as PowerPlanOptions\n if (configItem.Name.Contains(\"Power Plan\") ||\n (configItem.CustomProperties.ContainsKey(\"Id\") &&\n configItem.CustomProperties[\"Id\"]?.ToString() == \"PowerPlanComboBox\"))\n {\n // Store the actual list of options\n configItem.CustomProperties[\"PowerPlanOptions\"] = sliderLabels.Cast().Select(l => l.ToString()).ToList();\n _logService.Log(LogLevel.Info, $\"Stored PowerPlanOptions for {configItem.Name}: {labelsString}\");\n }\n }\n }\n }\n }\n \n // Add custom properties from RegistrySetting if available\n if (registrySettingProperty != null)\n {\n var registrySetting = registrySettingProperty.GetValue(item);\n if (registrySetting != null)\n {\n // Get the CustomProperties property from RegistrySetting\n var customPropertiesProperty = registrySetting.GetType().GetProperty(\"CustomProperties\");\n if (customPropertiesProperty != null)\n {\n var customProperties = customPropertiesProperty.GetValue(registrySetting) as Dictionary;\n if (customProperties != null && customProperties.Count > 0)\n {\n // Copy custom properties to the configuration item\n foreach (var kvp in customProperties)\n {\n configItem.CustomProperties[kvp.Key] = kvp.Value;\n }\n }\n }\n }\n }\n \n // Ensure SelectedValue is set for ComboBox controls\n configItem.EnsureSelectedValueIsSet();\n \n // Add the configuration item to the file\n configFile.Items.Add(configItem);\n }\n }\n\n // Serialize the configuration file to JSON\n var json = JsonConvert.SerializeObject(configFile, Formatting.Indented);\n\n // Write the JSON to the file\n await File.WriteAllTextAsync(saveFileDialog.FileName, json);\n \n _logService.Log(LogLevel.Info, $\"Successfully saved {configType} configuration with {configFile.Items.Count} items to {saveFileDialog.FileName}\");\n \n // Log details about ComboBox items if any\n var comboBoxItems = configFile.Items.Where(i => i.ControlType == ControlType.ComboBox).ToList();\n if (comboBoxItems.Any())\n {\n _logService.Log(LogLevel.Info, $\"Saved {comboBoxItems.Count} ComboBox items:\");\n foreach (var item in comboBoxItems)\n {\n _logService.Log(LogLevel.Info, $\" - {item.Name}: SelectedValue={item.SelectedValue}, CustomProperties={string.Join(\", \", item.CustomProperties.Select(kv => $\"{kv.Key}={kv.Value}\"))}\");\n }\n }\n\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving configuration: {ex.Message}\");\n MessageBox.Show($\"Error saving configuration: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n return false;\n }\n }\n\n /// \n /// Loads a configuration file and returns the configuration file.\n /// \n /// The type of configuration being loaded.\n /// A task representing the asynchronous operation. Returns the configuration file if successful, null otherwise.\n public async Task LoadConfigurationAsync(string configType)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Starting to load {configType} configuration\");\n // Create an open file dialog\n var openFileDialog = new OpenFileDialog\n {\n Filter = FileFilter,\n DefaultExt = FileExtension,\n Title = \"Open Configuration\"\n };\n\n // Show the open file dialog\n if (openFileDialog.ShowDialog() != true)\n {\n _logService.Log(LogLevel.Info, \"Load configuration canceled by user\");\n return null;\n }\n \n _logService.Log(LogLevel.Info, $\"Loading configuration from {openFileDialog.FileName}\");\n\n // Read the JSON from the file\n var json = await File.ReadAllTextAsync(openFileDialog.FileName);\n\n // Deserialize the JSON to a configuration file\n var configFile = JsonConvert.DeserializeObject(json);\n \n // Ensure SelectedValue is set for all items\n foreach (var item in configFile.Items)\n {\n item.EnsureSelectedValueIsSet();\n }\n \n // Process the configuration items to ensure SelectedValue is set for ComboBox and ThreeStateSlider items\n foreach (var item in configFile.Items)\n {\n // Handle ComboBox items\n if (item.ControlType == ControlType.ComboBox && string.IsNullOrEmpty(item.SelectedValue))\n {\n // Try to get the SelectedTheme from CustomProperties\n if (item.CustomProperties.TryGetValue(\"SelectedTheme\", out var selectedTheme) && selectedTheme != null)\n {\n item.SelectedValue = selectedTheme.ToString();\n _logService.Log(LogLevel.Info, $\"Set SelectedValue for ComboBox {item.Name} from CustomProperties: {item.SelectedValue}\");\n }\n // If not available, try to derive it from SliderValue\n else if (item.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int sliderValueInt = Convert.ToInt32(sliderValue);\n item.SelectedValue = sliderValueInt == 1 ? \"Dark Mode\" : \"Light Mode\";\n _logService.Log(LogLevel.Info, $\"Derived SelectedValue for ComboBox {item.Name} from SliderValue: {sliderValueInt} -> {item.SelectedValue}\");\n }\n }\n \n // Handle ThreeStateSlider items\n if (item.ControlType == ControlType.ThreeStateSlider)\n {\n // Ensure SliderValue is available in CustomProperties\n if (item.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int sliderValueInt = Convert.ToInt32(sliderValue);\n \n // Try to derive SelectedValue from SliderLabels if available\n if (item.CustomProperties.TryGetValue(\"SliderLabels\", out var sliderLabelsString) &&\n sliderLabelsString != null)\n {\n var labels = sliderLabelsString.ToString().Split(',');\n if (sliderValueInt >= 0 && sliderValueInt < labels.Length)\n {\n item.SelectedValue = labels[sliderValueInt];\n _logService.Log(LogLevel.Info, $\"Derived SelectedValue for ThreeStateSlider {item.Name} from SliderLabels: {sliderValueInt} -> {item.SelectedValue}\");\n }\n }\n // If no labels available, use a generic approach\n else if (string.IsNullOrEmpty(item.SelectedValue))\n {\n // For UAC slider\n if (item.Name.Contains(\"User Account Control\") || item.Name.Contains(\"UAC\"))\n {\n item.SelectedValue = sliderValueInt switch\n {\n 0 => \"Low\",\n 1 => \"Moderate\",\n 2 => \"High\",\n _ => $\"Level {sliderValueInt}\"\n };\n }\n // For Power Plan slider\n else if (item.Name.Contains(\"Power Plan\"))\n {\n // First try to get the value from PowerPlanOptions if available\n if (item.CustomProperties.TryGetValue(\"PowerPlanOptions\", out var powerPlanOptions))\n {\n // Handle different types of PowerPlanOptions\n if (powerPlanOptions is List options && sliderValueInt >= 0 && sliderValueInt < options.Count)\n {\n item.SelectedValue = options[sliderValueInt];\n _logService.Log(LogLevel.Info, $\"Set SelectedValue for Power Plan from PowerPlanOptions (List): {item.SelectedValue}\");\n }\n else if (powerPlanOptions is Newtonsoft.Json.Linq.JArray jArray && sliderValueInt >= 0 && sliderValueInt < jArray.Count)\n {\n item.SelectedValue = jArray[sliderValueInt]?.ToString();\n _logService.Log(LogLevel.Info, $\"Set SelectedValue for Power Plan from PowerPlanOptions (JArray): {item.SelectedValue}\");\n }\n else\n {\n // If PowerPlanOptions exists but we can't use it, log the issue\n _logService.Log(LogLevel.Warning, $\"PowerPlanOptions exists but couldn't be used. Type: {powerPlanOptions?.GetType().Name}, SliderValue: {sliderValueInt}\");\n \n // Fall back to default values\n item.SelectedValue = sliderValueInt switch\n {\n 0 => \"Balanced\",\n 1 => \"High Performance\",\n 2 => \"Ultimate Performance\",\n _ => $\"Plan {sliderValueInt}\"\n };\n _logService.Log(LogLevel.Info, $\"Set SelectedValue for Power Plan from default mapping: {item.SelectedValue}\");\n \n // Add PowerPlanOptions if it doesn't exist in the right format\n string[] defaultOptions = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n item.CustomProperties[\"PowerPlanOptions\"] = new List(defaultOptions);\n _logService.Log(LogLevel.Info, $\"Added default PowerPlanOptions to CustomProperties\");\n }\n }\n else\n {\n // Fall back to default values\n item.SelectedValue = sliderValueInt switch\n {\n 0 => \"Balanced\",\n 1 => \"High Performance\",\n 2 => \"Ultimate Performance\",\n _ => $\"Plan {sliderValueInt}\"\n };\n _logService.Log(LogLevel.Info, $\"Set SelectedValue for Power Plan from default mapping: {item.SelectedValue}\");\n \n // Add PowerPlanOptions if it doesn't exist\n string[] defaultOptions = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n item.CustomProperties[\"PowerPlanOptions\"] = new List(defaultOptions);\n _logService.Log(LogLevel.Info, $\"Added default PowerPlanOptions to CustomProperties\");\n }\n }\n // Generic approach for other sliders\n else\n {\n item.SelectedValue = $\"Level {sliderValueInt}\";\n }\n \n _logService.Log(LogLevel.Info, $\"Set generic SelectedValue for ThreeStateSlider {item.Name}: {item.SelectedValue}\");\n }\n }\n }\n }\n\n // Verify the configuration type\n if (string.IsNullOrEmpty(configFile.ConfigType))\n {\n _logService.Log(LogLevel.Warning, $\"Configuration type is empty, setting it to {configType}\");\n configFile.ConfigType = configType;\n }\n else if (configFile.ConfigType != configType)\n {\n _logService.Log(LogLevel.Warning, $\"Configuration type mismatch. Expected {configType}, but found {configFile.ConfigType}. Proceeding anyway.\");\n // We'll proceed anyway, as this might be a unified configuration file\n }\n\n _logService.Log(LogLevel.Info, $\"Successfully loaded {configType} configuration with {configFile.Items.Count} items from {openFileDialog.FileName}\");\n \n // Log details about ComboBox items if any\n var comboBoxItems = configFile.Items.Where(i => i.ControlType == ControlType.ComboBox).ToList();\n if (comboBoxItems.Any())\n {\n _logService.Log(LogLevel.Info, $\"Loaded {comboBoxItems.Count} ComboBox items:\");\n foreach (var item in comboBoxItems)\n {\n _logService.Log(LogLevel.Info, $\" - {item.Name}: SelectedValue={item.SelectedValue}, CustomProperties={string.Join(\", \", item.CustomProperties.Select(kv => $\"{kv.Key}={kv.Value}\"))}\");\n }\n }\n\n // Return the configuration file directly\n // The ViewModel will handle matching these with existing items\n return configFile;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading configuration: {ex.Message}\");\n MessageBox.Show($\"Error loading configuration: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n return null;\n }\n }\n\n /// \n /// Saves a unified configuration file containing settings for multiple parts of the application.\n /// \n /// The unified configuration to save.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n public async Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile unifiedConfig)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Starting to save unified configuration\");\n \n // Create a save file dialog\n var saveFileDialog = new SaveFileDialog\n {\n Filter = UnifiedFileFilter,\n DefaultExt = FileExtension,\n Title = \"Save Unified Configuration\",\n FileName = $\"Winhance_Unified_Config_{DateTime.Now:yyyyMMdd}{FileExtension}\"\n };\n \n // Show the save file dialog\n if (saveFileDialog.ShowDialog() != true)\n {\n _logService.Log(LogLevel.Info, \"Save unified configuration canceled by user\");\n return false;\n }\n \n _logService.Log(LogLevel.Info, $\"Saving unified configuration to {saveFileDialog.FileName}\");\n \n // Ensure all sections are included by default\n unifiedConfig.WindowsApps.IsIncluded = true;\n unifiedConfig.ExternalApps.IsIncluded = true;\n unifiedConfig.Customize.IsIncluded = true;\n unifiedConfig.Optimize.IsIncluded = true;\n \n if (unifiedConfig.WindowsApps.Items == null)\n {\n unifiedConfig.WindowsApps.Items = new List();\n }\n \n // Serialize the configuration file to JSON\n var json = JsonConvert.SerializeObject(unifiedConfig, Formatting.Indented);\n \n // Write the JSON to the file\n await File.WriteAllTextAsync(saveFileDialog.FileName, json);\n \n _logService.Log(LogLevel.Info, \"Successfully saved unified configuration\");\n \n // Log details about included sections\n var includedSections = new List { \"WindowsApps\", \"ExternalApps\", \"Customize\", \"Optimize\" };\n _logService.Log(LogLevel.Info, $\"Included sections: {string.Join(\", \", includedSections)}\");\n \n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving unified configuration: {ex.Message}\");\n MessageBox.Show($\"Error saving unified configuration: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n return false;\n }\n }\n\n /// \n /// Loads a unified configuration file.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file if successful, null otherwise.\n public async Task LoadUnifiedConfigurationAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Starting to load unified configuration\");\n \n // Create an open file dialog\n var openFileDialog = new OpenFileDialog\n {\n Filter = UnifiedFileFilter,\n DefaultExt = FileExtension,\n Title = \"Open Unified Configuration\"\n };\n \n // Show the open file dialog\n if (openFileDialog.ShowDialog() != true)\n {\n _logService.Log(LogLevel.Info, \"Load unified configuration canceled by user\");\n return null;\n }\n \n _logService.Log(LogLevel.Info, $\"Loading unified configuration from {openFileDialog.FileName}\");\n \n // Read the JSON from the file\n var json = await File.ReadAllTextAsync(openFileDialog.FileName);\n \n // Deserialize the JSON to a unified configuration file\n var unifiedConfig = JsonConvert.DeserializeObject(json);\n \n // Always ensure WindowsApps are included\n unifiedConfig.WindowsApps.IsIncluded = true;\n if (unifiedConfig.WindowsApps.Items == null)\n {\n unifiedConfig.WindowsApps.Items = new List();\n }\n \n // Log details about included sections\n var includedSections = new List();\n if (unifiedConfig.WindowsApps.IsIncluded) includedSections.Add(\"WindowsApps\");\n if (unifiedConfig.ExternalApps.IsIncluded) includedSections.Add(\"ExternalApps\");\n if (unifiedConfig.Customize.IsIncluded) includedSections.Add(\"Customize\");\n if (unifiedConfig.Optimize.IsIncluded) includedSections.Add(\"Optimize\");\n \n _logService.Log(LogLevel.Info, $\"Loaded unified configuration with sections: {string.Join(\", \", includedSections)}\");\n \n return unifiedConfig;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading unified configuration: {ex.Message}\");\n MessageBox.Show($\"Error loading unified configuration: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n return null;\n }\n }\n\n /// \n /// Creates a unified configuration file from individual configuration sections.\n /// \n /// Dictionary of section names and their corresponding configuration items.\n /// List of section names to include in the unified configuration.\n /// A unified configuration file.\n public UnifiedConfigurationFile CreateUnifiedConfiguration(Dictionary> sections, IEnumerable includedSections)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Creating unified configuration\");\n \n var unifiedConfig = new UnifiedConfigurationFile\n {\n CreatedAt = DateTime.UtcNow\n };\n \n // Convert each section to ConfigurationItems and add to the appropriate section\n foreach (var sectionName in includedSections)\n {\n if (!sections.TryGetValue(sectionName, out var items) || items == null)\n {\n _logService.Log(LogLevel.Warning, $\"Section {sectionName} not found or has no items\");\n continue;\n }\n \n var configItems = ConvertToConfigurationItems(items);\n \n switch (sectionName)\n {\n case \"WindowsApps\":\n unifiedConfig.WindowsApps.IsIncluded = true;\n unifiedConfig.WindowsApps.Items = configItems;\n unifiedConfig.WindowsApps.Description = \"Windows built-in applications\";\n break;\n case \"ExternalApps\":\n unifiedConfig.ExternalApps.IsIncluded = true;\n unifiedConfig.ExternalApps.Items = configItems;\n unifiedConfig.ExternalApps.Description = \"Third-party applications\";\n break;\n case \"Customize\":\n unifiedConfig.Customize.IsIncluded = true;\n unifiedConfig.Customize.Items = configItems;\n unifiedConfig.Customize.Description = \"Windows UI customization settings\";\n break;\n case \"Optimize\":\n unifiedConfig.Optimize.IsIncluded = true;\n unifiedConfig.Optimize.Items = configItems;\n unifiedConfig.Optimize.Description = \"Windows optimization settings\";\n break;\n default:\n _logService.Log(LogLevel.Warning, $\"Unknown section name: {sectionName}\");\n break;\n }\n }\n \n // Always ensure WindowsApps are included, even if they weren't in the sections dictionary\n // or if they didn't have any items\n unifiedConfig.WindowsApps.IsIncluded = true;\n if (unifiedConfig.WindowsApps.Items == null)\n {\n unifiedConfig.WindowsApps.Items = new List();\n }\n if (string.IsNullOrEmpty(unifiedConfig.WindowsApps.Description))\n {\n unifiedConfig.WindowsApps.Description = \"Windows built-in applications\";\n }\n \n _logService.Log(LogLevel.Info, \"Successfully created unified configuration\");\n return unifiedConfig;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating unified configuration: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Extracts a specific section from a unified configuration file.\n /// \n /// The unified configuration file.\n /// The name of the section to extract.\n /// A configuration file containing only the specified section.\n public ConfigurationFile ExtractSectionFromUnifiedConfiguration(UnifiedConfigurationFile unifiedConfig, string sectionName)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Extracting section {sectionName} from unified configuration\");\n \n // Validate inputs\n if (unifiedConfig == null)\n {\n _logService.Log(LogLevel.Error, \"Unified configuration is null\");\n throw new ArgumentNullException(nameof(unifiedConfig));\n }\n \n if (string.IsNullOrEmpty(sectionName))\n {\n _logService.Log(LogLevel.Error, \"Section name is null or empty\");\n throw new ArgumentException(\"Section name cannot be null or empty\", nameof(sectionName));\n }\n \n var configFile = new ConfigurationFile\n {\n ConfigType = sectionName,\n CreatedAt = DateTime.UtcNow,\n Items = new List()\n };\n \n // Get the items from the appropriate section\n switch (sectionName)\n {\n case \"WindowsApps\":\n // Always include WindowsApps, regardless of IsIncluded flag\n configFile.Items = unifiedConfig.WindowsApps?.Items ?? new List();\n break;\n case \"ExternalApps\":\n if (unifiedConfig.ExternalApps?.IsIncluded == true)\n {\n configFile.Items = unifiedConfig.ExternalApps.Items ?? new List();\n }\n break;\n case \"Customize\":\n if (unifiedConfig.Customize?.IsIncluded == true)\n {\n configFile.Items = unifiedConfig.Customize.Items ?? new List();\n }\n break;\n case \"Optimize\":\n if (unifiedConfig.Optimize?.IsIncluded == true)\n {\n configFile.Items = unifiedConfig.Optimize.Items ?? new List();\n }\n break;\n default:\n _logService.Log(LogLevel.Warning, $\"Unknown section name: {sectionName}\");\n break;\n }\n \n // Ensure Items is not null\n if (configFile.Items == null)\n {\n configFile.Items = new List();\n }\n \n _logService.Log(LogLevel.Info, $\"Successfully extracted section {sectionName} with {configFile.Items.Count} items\");\n return configFile;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error extracting section from unified configuration: {ex.Message}\");\n \n // Return an empty configuration file instead of throwing\n var emptyConfigFile = new ConfigurationFile\n {\n ConfigType = sectionName,\n CreatedAt = DateTime.UtcNow,\n Items = new List()\n };\n \n _logService.Log(LogLevel.Info, $\"Returning empty configuration file for section {sectionName}\");\n return emptyConfigFile;\n }\n }\n\n /// \n /// Converts a collection of ISettingItem objects to a list of ConfigurationItem objects.\n /// \n /// The collection of ISettingItem objects to convert.\n /// A list of ConfigurationItem objects.\n private List ConvertToConfigurationItems(IEnumerable items)\n {\n var configItems = new List();\n \n foreach (var item in items)\n {\n var configItem = new ConfigurationItem\n {\n Name = item.Name,\n IsSelected = item.IsSelected,\n ControlType = item.ControlType,\n CustomProperties = new Dictionary()\n };\n \n // Add Id to custom properties\n if (!string.IsNullOrEmpty(item.Id))\n {\n configItem.CustomProperties[\"Id\"] = item.Id;\n }\n \n // Add GroupName to custom properties\n if (!string.IsNullOrEmpty(item.GroupName))\n {\n configItem.CustomProperties[\"GroupName\"] = item.GroupName;\n }\n \n // Add Description to custom properties\n if (!string.IsNullOrEmpty(item.Description))\n {\n configItem.CustomProperties[\"Description\"] = item.Description;\n }\n \n // Handle specific properties based on the item's type\n var itemType = item.GetType();\n var properties = itemType.GetProperties();\n \n // Check for PackageName property\n var packageNameProperty = properties.FirstOrDefault(p => p.Name == \"PackageName\");\n if (packageNameProperty != null)\n {\n configItem.PackageName = packageNameProperty.GetValue(item)?.ToString();\n }\n \n // Check for SelectedValue property\n var selectedValueProperty = properties.FirstOrDefault(p => p.Name == \"SelectedValue\");\n if (selectedValueProperty != null)\n {\n configItem.SelectedValue = selectedValueProperty.GetValue(item)?.ToString();\n }\n \n // Check for SliderValue property\n var sliderValueProperty = properties.FirstOrDefault(p => p.Name == \"SliderValue\");\n if (sliderValueProperty != null)\n {\n var sliderValue = sliderValueProperty.GetValue(item);\n if (sliderValue != null)\n {\n configItem.CustomProperties[\"SliderValue\"] = sliderValue;\n }\n }\n \n // Check for SliderLabels property\n var sliderLabelsProperty = properties.FirstOrDefault(p => p.Name == \"SliderLabels\");\n if (sliderLabelsProperty != null)\n {\n var sliderLabels = sliderLabelsProperty.GetValue(item) as System.Collections.IList;\n if (sliderLabels != null && sliderLabels.Count > 0)\n {\n // Store the labels as a comma-separated string\n var labelsString = string.Join(\",\", sliderLabels.Cast().Select(l => l.ToString()));\n configItem.CustomProperties[\"SliderLabels\"] = labelsString;\n \n // For Power Plan, also store the labels as PowerPlanOptions\n if (item.Name.Contains(\"Power Plan\") || item.Id == \"PowerPlanComboBox\")\n {\n // Store the actual list of options\n configItem.CustomProperties[\"PowerPlanOptions\"] = sliderLabels.Cast().Select(l => l.ToString()).ToList();\n }\n }\n }\n \n // Check for RegistrySetting property\n var registrySettingProperty = properties.FirstOrDefault(p => p.Name == \"RegistrySetting\");\n if (registrySettingProperty != null)\n {\n var registrySetting = registrySettingProperty.GetValue(item);\n if (registrySetting != null)\n {\n // Get the CustomProperties property from RegistrySetting\n var customPropertiesProperty = registrySetting.GetType().GetProperty(\"CustomProperties\");\n if (customPropertiesProperty != null)\n {\n var customProperties = customPropertiesProperty.GetValue(registrySetting) as Dictionary;\n if (customProperties != null && customProperties.Count > 0)\n {\n // Copy custom properties to the configuration item\n foreach (var kvp in customProperties)\n {\n configItem.CustomProperties[kvp.Key] = kvp.Value;\n }\n }\n }\n }\n }\n \n // Ensure SelectedValue is set for ComboBox controls\n configItem.EnsureSelectedValueIsSet();\n \n configItems.Add(configItem);\n }\n \n return configItems;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/FrameNavigationService.cs", "using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service for navigating between views in the application using ContentPresenter-based navigation.\n /// \n public class FrameNavigationService\n : Winhance.Core.Features.Common.Interfaces.INavigationService\n {\n private readonly Stack _backStack = new();\n private readonly Stack<(Type ViewModelType, object Parameter)> _forwardStack = new();\n private readonly List _navigationHistory = new();\n private readonly Dictionary _viewMappings =\n new();\n private readonly IServiceProvider _serviceProvider;\n private readonly IParameterSerializer _parameterSerializer;\n private readonly SemaphoreSlim _navigationLock = new(1, 1);\n private readonly ConcurrentQueue<(\n Type ViewType,\n Type ViewModelType,\n object Parameter,\n TaskCompletionSource CompletionSource\n )> _navigationQueue = new();\n private object _currentParameter;\n private string _currentRoute;\n private const int MaxHistorySize = 50;\n private CancellationTokenSource _currentNavigationCts;\n private ICommand _navigateCommand;\n\n /// \n /// Gets the command for navigation.\n /// \n public ICommand NavigateCommand =>\n _navigateCommand ??= new RelayCommand(route => NavigateTo(route));\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The parameter serializer.\n public FrameNavigationService(\n IServiceProvider serviceProvider,\n IParameterSerializer parameterSerializer\n )\n {\n _serviceProvider = serviceProvider;\n _parameterSerializer =\n parameterSerializer ?? throw new ArgumentNullException(nameof(parameterSerializer));\n }\n\n /// \n /// Determines whether navigation back is possible.\n /// \n public bool CanGoBack => _backStack.Count > 1;\n\n /// \n /// Gets a list of navigation history.\n /// \n public IReadOnlyList NavigationHistory => _navigationHistory.AsReadOnly();\n\n /// \n /// Gets the current view name.\n /// \n public string CurrentView => _currentRoute;\n\n /// \n /// Event raised when navigation occurs.\n /// \n public event EventHandler Navigated;\n\n /// \n /// Event raised before navigation occurs.\n /// \n public event EventHandler Navigating;\n\n /// \n /// Event raised when navigation fails.\n /// \n public event EventHandler NavigationFailed;\n\n /// \n /// Initializes the navigation service.\n /// \n public void Initialize()\n {\n // No initialization needed for ContentPresenter-based navigation\n }\n\n /// \n /// Registers a view mapping.\n /// \n /// The route.\n /// The view type.\n /// The view model type.\n public void RegisterViewMapping(string route, Type viewType, Type viewModelType)\n {\n if (string.IsNullOrWhiteSpace(route))\n throw new ArgumentException(\"Route cannot be empty\", nameof(route));\n\n _viewMappings[route] = (viewType, viewModelType);\n }\n\n /// \n /// Checks if navigation to a route is possible.\n /// \n /// The route to check.\n /// True if navigation is possible; otherwise, false.\n public bool CanNavigateTo(string route) => _viewMappings.ContainsKey(route);\n\n /// \n /// Navigates to a view by route.\n /// \n /// The route to navigate to.\n /// True if navigation was successful; otherwise, false.\n public bool NavigateTo(string viewName)\n {\n try\n {\n NavigateToAsync(viewName).GetAwaiter().GetResult();\n return true;\n }\n catch (Exception ex)\n {\n // Log the error\n System.Diagnostics.Debug.WriteLine($\"Navigation error: {ex.Message}\");\n\n var args = new Winhance.Core.Features.Common.Interfaces.NavigationEventArgs(\n CurrentView,\n viewName,\n null,\n false\n );\n NavigationFailed?.Invoke(this, args);\n return false;\n }\n }\n\n /// \n /// Navigates to a view by route with a parameter.\n /// \n /// The route to navigate to.\n /// The navigation parameter.\n /// True if navigation was successful; otherwise, false.\n public bool NavigateTo(string viewName, object parameter)\n {\n try\n {\n NavigateToAsync(viewName, parameter).GetAwaiter().GetResult();\n return true;\n }\n catch (Exception ex)\n {\n // Log the error\n System.Diagnostics.Debug.WriteLine($\"Navigation error: {ex.Message}\");\n\n var args = new Winhance.Core.Features.Common.Interfaces.NavigationEventArgs(\n CurrentView,\n viewName,\n parameter,\n false\n );\n NavigationFailed?.Invoke(this, args);\n return false;\n }\n }\n\n /// \n /// Navigates back to the previous view.\n /// \n /// True if navigation was successful; otherwise, false.\n public bool NavigateBack()\n {\n try\n {\n GoBackAsync().GetAwaiter().GetResult();\n return true;\n }\n catch (Exception ex)\n {\n // Log the error\n System.Diagnostics.Debug.WriteLine($\"Navigation back error: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Navigates to a view model type.\n /// \n /// The view model type.\n /// The navigation parameter.\n /// A task representing the asynchronous operation.\n public async Task NavigateToAsync(object parameter = null)\n where TViewModel : class => await NavigateToAsync(typeof(TViewModel), parameter);\n\n /// \n /// Navigates to a view model type.\n /// \n /// The view model type.\n /// The navigation parameter.\n /// A task representing the asynchronous operation.\n public async Task NavigateToAsync(Type viewModelType, object parameter = null)\n {\n var viewType = GetViewTypeForViewModel(viewModelType);\n var tcs = new TaskCompletionSource();\n _navigationQueue.Enqueue((viewType, viewModelType, parameter, tcs));\n\n await ProcessNavigationQueueAsync();\n await tcs.Task;\n }\n\n /// \n /// Navigates to a route.\n /// \n /// The route to navigate to.\n /// The navigation parameter.\n /// A task representing the asynchronous operation.\n public async Task NavigateToAsync(string route, object parameter = null)\n {\n if (!_viewMappings.TryGetValue(route, out var mapping))\n throw new InvalidOperationException($\"No view mapping found for route: {route}\");\n\n await NavigateInternalAsync(mapping.ViewType, mapping.ViewModelType, parameter);\n }\n\n private async Task ProcessNavigationQueueAsync()\n {\n if (!await _navigationLock.WaitAsync(TimeSpan.FromMilliseconds(100)))\n return;\n\n try\n {\n while (_navigationQueue.TryDequeue(out var navigationRequest))\n {\n _currentNavigationCts?.Cancel();\n _currentNavigationCts = new CancellationTokenSource(TimeSpan.FromSeconds(30));\n\n try\n {\n await NavigateInternalAsync(\n navigationRequest.ViewType,\n navigationRequest.ViewModelType,\n navigationRequest.Parameter,\n _currentNavigationCts.Token\n );\n navigationRequest.CompletionSource.SetResult(true);\n }\n catch (Exception ex)\n {\n navigationRequest.CompletionSource.SetException(ex);\n }\n }\n }\n finally\n {\n _navigationLock.Release();\n }\n }\n\n private async Task NavigateInternalAsync(\n Type viewType,\n Type viewModelType,\n object parameter,\n CancellationToken cancellationToken = default\n )\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n // Find the route for this view/viewmodel for event args\n string route = null;\n foreach (var mapping in _viewMappings)\n {\n if (mapping.Value.ViewType == viewType)\n {\n route = mapping.Key;\n break;\n }\n }\n\n var sourceView = _currentRoute;\n var targetView = route;\n\n var args = new Winhance.Core.Features.Common.Interfaces.NavigationEventArgs(\n sourceView,\n targetView,\n parameter,\n true\n );\n Navigating?.Invoke(this, args);\n\n if (args.Cancel)\n {\n return;\n }\n\n _currentParameter = parameter;\n\n // Get the view model from the service provider - we don't need the view when using ContentPresenter\n object viewModel;\n\n try\n {\n viewModel = _serviceProvider.GetRequiredService(viewModelType);\n if (viewModel == null)\n {\n throw new InvalidOperationException(\n $\"Failed to create view model of type {viewModelType.FullName}. The service provider returned null.\"\n );\n }\n }\n catch (Exception ex)\n {\n throw new InvalidOperationException($\"Error creating view model: {ex.Message}\", ex);\n }\n\n // Update the current route and view model\n _currentRoute = route;\n _currentViewModel = viewModel;\n\n // Update the navigation stacks\n while (_backStack.Count >= MaxHistorySize)\n {\n var tempStack = new Stack(_backStack.Skip(1).Reverse());\n _backStack.Clear();\n foreach (var item in tempStack)\n {\n _backStack.Push(item);\n }\n }\n _backStack.Push(viewModelType);\n\n // Call OnNavigatedTo on the view model if it implements IViewModel\n if (viewModel is IViewModel vm)\n {\n vm.OnNavigatedTo(parameter);\n }\n\n // Update navigation history\n if (!string.IsNullOrEmpty(_currentRoute))\n {\n _navigationHistory.Add(_currentRoute);\n }\n\n // Raise the Navigated event which will update the UI\n var navigatedArgs = new Winhance.Core.Features.Common.Interfaces.NavigationEventArgs(\n sourceView,\n targetView,\n viewModel,\n false\n );\n Navigated?.Invoke(this, navigatedArgs);\n }\n\n /// \n /// Navigates back to the previous view.\n /// \n /// A task representing the asynchronous operation.\n public async Task GoBackAsync()\n {\n if (!CanGoBack)\n return;\n\n var tcs = new TaskCompletionSource();\n _navigationQueue.Enqueue((null, null, null, tcs));\n\n await ProcessNavigationQueueAsync();\n await tcs.Task;\n\n var currentViewModelType = _backStack.Peek();\n\n var currentType = _backStack.Pop();\n _forwardStack.Push((currentType, _currentParameter));\n var previousViewModelType = _backStack.Peek();\n var previousParameter =\n _backStack.Count > 1 ? _backStack.ElementAt(_backStack.Count - 2) : null;\n await NavigateToAsync(previousViewModelType, previousParameter);\n }\n\n /// \n /// Navigates forward to the next view.\n /// \n /// A task representing the asynchronous operation.\n public async Task GoForwardAsync()\n {\n if (_forwardStack.Count == 0)\n return;\n\n var tcs = new TaskCompletionSource();\n _navigationQueue.Enqueue((null, null, null, tcs));\n\n await ProcessNavigationQueueAsync();\n await tcs.Task;\n\n var (nextType, nextParameter) = _forwardStack.Pop();\n\n _backStack.Push(nextType);\n await NavigateToAsync(nextType, nextParameter);\n }\n\n /// \n /// Clears the navigation history.\n /// \n /// A task representing the asynchronous operation.\n public async Task ClearHistoryAsync()\n {\n await _navigationLock.WaitAsync();\n try\n {\n _backStack.Clear();\n _forwardStack.Clear();\n _navigationHistory.Clear();\n }\n finally\n {\n _navigationLock.Release();\n }\n }\n\n /// \n /// Cancels the current navigation.\n /// \n public void CancelCurrentNavigation()\n {\n _currentNavigationCts?.Cancel();\n }\n\n // We track the current view model directly now instead of getting it from the Frame\n private object _currentViewModel;\n\n /// \n /// Gets the current view model.\n /// \n public object CurrentViewModel => _currentViewModel;\n\n private Type GetViewTypeForViewModel(Type viewModelType)\n {\n // First, check if we have a mapping for this view model type\n foreach (var mapping in _viewMappings)\n {\n if (mapping.Value.ViewModelType == viewModelType)\n {\n return mapping.Value.ViewType;\n }\n }\n\n // If no mapping found, try the old way as fallback\n var viewName = viewModelType.FullName.Replace(\"ViewModel\", \"View\");\n var viewType = Type.GetType(viewName);\n\n if (viewType == null)\n {\n // Try to find the view type in the loaded assemblies\n foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())\n {\n viewType = assembly\n .GetTypes()\n .FirstOrDefault(t =>\n t.FullName != null\n && t.FullName.Equals(viewName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (viewType != null)\n break;\n }\n }\n\n return viewType\n ?? throw new InvalidOperationException(\n $\"View type for {viewModelType.FullName} not found. Tried looking for {viewName}\"\n );\n }\n\n private string GetRouteForViewType(Type viewType)\n {\n foreach (var mapping in _viewMappings)\n {\n if (mapping.Value.ViewType == viewType)\n {\n return mapping.Key;\n }\n }\n throw new InvalidOperationException(\n $\"No route found for view type: {viewType.FullName}\"\n );\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/WindowsSecurityOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.Common.ViewModels;\n// Use UacLevel from Core.Models.Enums for the UI\nusing UacLevel = Winhance.Core.Models.Enums.UacLevel;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Windows Security optimizations.\n /// \n public partial class WindowsSecurityOptimizationsViewModel : BaseViewModel\n {\n private readonly IRegistryService _registryService;\n private readonly ILogService _logService;\n private readonly ISystemServices _systemServices;\n private readonly IUacSettingsService _uacSettingsService;\n\n /// \n /// Gets or sets a value indicating whether the view model is selected.\n /// \n [ObservableProperty]\n private bool _isSelected;\n\n /// \n /// Gets or sets the selected UAC level.\n /// \n [ObservableProperty]\n private UacLevel _selectedUacLevel;\n\n /// \n /// Gets or sets a value indicating whether the view model has visible settings.\n /// \n [ObservableProperty]\n private bool _hasVisibleSettings = true;\n\n /// \n /// Gets or sets a value indicating whether the UAC level is being applied.\n /// \n [ObservableProperty]\n private bool _isApplyingUacLevel;\n \n /// \n /// Gets or sets a value indicating whether a custom UAC setting is detected.\n /// \n [ObservableProperty]\n private bool _hasCustomUacSetting;\n\n /// \n /// Gets the collection of available UAC levels with their display names.\n /// \n public ObservableCollection> UacLevelOptions { get; } = new();\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The system services.\n /// The UAC settings service.\n public WindowsSecurityOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n ISystemServices systemServices,\n IUacSettingsService uacSettingsService\n )\n : base(progressService, logService, new Features.Common.Services.MessengerService())\n {\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _systemServices = systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n _uacSettingsService = uacSettingsService ?? throw new ArgumentNullException(nameof(uacSettingsService));\n\n // Initialize UAC level options (excluding Custom initially)\n foreach (var kvp in UacOptimizations.UacLevelNames)\n {\n // Skip the Custom option initially - it will be added dynamically when needed\n if (kvp.Key != UacLevel.Custom)\n {\n UacLevelOptions.Add(new KeyValuePair(kvp.Key, kvp.Value));\n }\n }\n\n // Subscribe to property changes to handle UAC level changes\n this.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(SelectedUacLevel))\n {\n HandleUACLevelChange();\n }\n };\n }\n\n /// \n /// Gets the collection of settings.\n /// \n public ObservableCollection Settings { get; } =\n new ObservableCollection();\n\n /// \n /// Handles changes to the UAC notification level.\n /// \n private void HandleUACLevelChange()\n {\n try\n {\n IsApplyingUacLevel = true;\n \n // Set the UAC level using the system service - no conversion needed\n _systemServices.SetUacLevel(SelectedUacLevel);\n \n string levelName = UacOptimizations.UacLevelNames.TryGetValue(SelectedUacLevel, out string name) ? name : SelectedUacLevel.ToString();\n LogInfo($\"UAC Notification Level set to {levelName}\");\n }\n catch (Exception ex)\n {\n LogError($\"Error setting UAC notification level: {ex.Message}\");\n }\n finally\n {\n IsApplyingUacLevel = false;\n }\n }\n \n // Conversion methods removed as we're now using UacLevel directly\n\n /// \n /// Gets the display name of the UAC level.\n /// \n /// The UAC level.\n /// The display name of the UAC level.\n private string GetUacLevelDisplayName(UacLevel level)\n {\n return UacOptimizations.UacLevelNames.TryGetValue(level, out string name) ? name : level.ToString();\n }\n\n /// \n /// Loads the settings.\n /// \n /// A task representing the asynchronous operation.\n public async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n LogInfo(\"Loading UAC notification level setting\");\n\n // Clear existing settings\n Settings.Clear();\n\n // Add a searchable item for the UAC dropdown\n var uacDropdownItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = \"UACDropdown\",\n Name = \"User Account Control Notification Level\",\n Description = \"Controls when Windows notifies you about changes to your computer\",\n GroupName = \"Windows Security Settings\",\n IsVisible = true,\n ControlType = ControlType.Dropdown,\n };\n Settings.Add(uacDropdownItem);\n LogInfo(\"Added searchable item for UAC dropdown\");\n\n // Load UAC notification level\n try\n {\n // Get the UAC level from the system service (now returns Core UacLevel directly)\n SelectedUacLevel = _systemServices.GetUacLevel();\n \n // Check if we have a custom UAC setting in the registry\n bool hasCustomUacInRegistry = (SelectedUacLevel == UacLevel.Custom);\n \n // Check if we have custom UAC settings saved in preferences (using synchronous method to avoid deadlocks)\n bool hasCustomSettingsInPreferences = _uacSettingsService.TryGetCustomUacValues(out _, out _);\n \n // Set flag if we have custom settings either in registry or preferences\n HasCustomUacSetting = hasCustomUacInRegistry || hasCustomSettingsInPreferences;\n \n // If it's a custom setting, add the Custom option to the dropdown if not already present\n if (HasCustomUacSetting)\n {\n // Check if the Custom option is already in the dropdown\n bool customOptionExists = false;\n foreach (var option in UacLevelOptions)\n {\n if (option.Key == UacLevel.Custom)\n {\n customOptionExists = true;\n break;\n }\n }\n \n // Add the Custom option if it doesn't exist\n if (!customOptionExists)\n {\n UacLevelOptions.Add(new KeyValuePair(\n UacLevel.Custom, \n UacOptimizations.UacLevelNames[UacLevel.Custom]));\n LogInfo(\"Added Custom UAC setting option to dropdown\");\n }\n \n // Log the custom UAC settings values\n if (_uacSettingsService.TryGetCustomUacValues(out int consentPromptValue, out int secureDesktopValue))\n {\n LogInfo($\"Custom UAC setting detected: ConsentPrompt={consentPromptValue}, SecureDesktop={secureDesktopValue}\");\n }\n }\n else\n {\n // If not a custom setting, remove the Custom option if it exists\n for (int i = UacLevelOptions.Count - 1; i >= 0; i--)\n {\n if (UacLevelOptions[i].Key == UacLevel.Custom)\n {\n UacLevelOptions.RemoveAt(i);\n LogInfo(\"Removed Custom UAC setting option from dropdown\");\n break;\n }\n }\n }\n \n string levelName = GetUacLevelDisplayName(SelectedUacLevel);\n LogInfo($\"Loaded UAC Notification Level: {levelName}\");\n }\n catch (Exception ex)\n {\n LogError($\"Error loading UAC notification level: {ex.Message}\");\n SelectedUacLevel = UacLevel.NotifyChangesOnly; // Default to standard notification level if there's an error\n HasCustomUacSetting = false;\n }\n\n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n LogError($\"Error loading Windows security settings: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all settings.\n /// \n /// A task representing the asynchronous operation.\n public async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n LogInfo(\"Checking UAC notification level status\");\n\n // Refresh UAC notification level\n await LoadSettingsAsync();\n\n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n LogError($\"Error checking UAC notification level status: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Applies the selected settings.\n /// \n /// Progress reporter.\n /// A task representing the asynchronous operation.\n public async Task ApplySettingsAsync(\n IProgress progress\n )\n {\n try\n {\n IsLoading = true;\n IsApplyingUacLevel = true;\n \n progress.Report(\n new Winhance.Core.Features.Common.Models.TaskProgressDetail\n {\n StatusText = \"Applying UAC notification level setting...\",\n Progress = 0,\n }\n );\n\n // Apply UAC notification level using the system service directly\n // No conversion needed as we're now using UacLevel directly\n _systemServices.SetUacLevel(SelectedUacLevel);\n \n string levelName = GetUacLevelDisplayName(SelectedUacLevel);\n LogInfo($\"UAC Notification Level set to {levelName}\");\n \n progress.Report(\n new Winhance.Core.Features.Common.Models.TaskProgressDetail\n {\n StatusText = $\"{levelName} UAC notification level applied\",\n Progress = 1.0,\n }\n );\n \n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n LogError($\"Error applying UAC notification level: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n IsApplyingUacLevel = false;\n }\n }\n\n /// \n /// Restores the default settings.\n /// \n /// Progress reporter.\n /// A task representing the asynchronous operation.\n public async Task RestoreDefaultsAsync(\n IProgress progress\n )\n {\n try\n {\n IsLoading = true;\n progress.Report(\n new Winhance.Core.Features.Common.Models.TaskProgressDetail\n {\n StatusText = \"Restoring UAC notification level to default...\",\n Progress = 0,\n }\n );\n\n // Set UAC notification level to default (Notify when apps try to make changes)\n SelectedUacLevel = UacLevel.NotifyChangesOnly;\n progress.Report(\n new Winhance.Core.Features.Common.Models.TaskProgressDetail\n {\n StatusText = \"Applying UAC notification level...\",\n Progress = 0.5,\n }\n );\n\n // Apply the changes\n await ApplySettingsAsync(progress);\n\n progress.Report(\n new Winhance.Core.Features.Common.Models.TaskProgressDetail\n {\n StatusText = \"UAC notification level restored to default\",\n Progress = 1.0,\n }\n );\n }\n catch (Exception ex)\n {\n LogError($\"Error restoring UAC notification level: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/OptimizeConfigurationApplier.cs", "using System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Optimize.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for applying configuration to the Optimize section.\n /// \n public class OptimizeConfigurationApplier : ISectionConfigurationApplier\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n private readonly IViewModelRefresher _viewModelRefresher;\n private readonly IConfigurationPropertyUpdater _propertyUpdater;\n\n /// \n /// Gets the section name that this applier handles.\n /// \n public string SectionName => \"Optimize\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n /// The view model refresher.\n /// The property updater.\n public OptimizeConfigurationApplier(\n IServiceProvider serviceProvider,\n ILogService logService,\n IViewModelRefresher viewModelRefresher,\n IConfigurationPropertyUpdater propertyUpdater)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _viewModelRefresher = viewModelRefresher ?? throw new ArgumentNullException(nameof(viewModelRefresher));\n _propertyUpdater = propertyUpdater ?? throw new ArgumentNullException(nameof(propertyUpdater));\n }\n\n /// \n /// Applies the configuration to the Optimize section.\n /// \n /// The configuration file to apply.\n /// True if any items were updated, false otherwise.\n public async Task ApplyConfigAsync(ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Applying configuration to OptimizeViewModel\");\n \n var viewModel = _serviceProvider.GetService();\n if (viewModel == null)\n {\n _logService.Log(LogLevel.Warning, \"OptimizeViewModel not available\");\n return false;\n }\n \n // Set a timeout for the operation to prevent hanging\n using var cancellationTokenSource = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(45));\n var cancellationToken = cancellationTokenSource.Token;\n \n // Add a log entry to track execution time\n var startTime = DateTime.Now;\n _logService.Log(LogLevel.Info, $\"Starting OptimizeConfigurationApplier.ApplyConfigAsync at {startTime}\");\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, \"OptimizeViewModel not initialized, initializing now\");\n try\n {\n var initializeTask = viewModel.InitializeCommand.ExecuteAsync(null);\n await Task.WhenAny(initializeTask, Task.Delay(10000, cancellationToken)); // 10 second timeout\n \n if (!initializeTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Initialization timed out, proceeding with partial initialization\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error initializing OptimizeViewModel: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n // Continue with the import even if initialization fails\n }\n }\n \n int totalUpdatedCount = 0;\n \n // Apply the configuration directly to the view model's items\n try\n {\n int mainItemsUpdatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Items, configFile);\n totalUpdatedCount += mainItemsUpdatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {mainItemsUpdatedCount} items in OptimizeViewModel.Items\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating main items: {ex.Message}\");\n }\n \n // Also apply to child view models - wrap each in try/catch to ensure one failure doesn't stop others\n \n // Gaming and Performance Settings\n if (viewModel.GamingandPerformanceOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.GamingandPerformanceOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in GamingandPerformanceOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating GamingandPerformanceOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Privacy Settings\n if (viewModel.PrivacyOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.PrivacyOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in PrivacyOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating PrivacyOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Update Settings\n if (viewModel.UpdateOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.UpdateOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in UpdateOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating UpdateOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Power Settings - this is the most likely place for hangs\n if (viewModel.PowerSettingsViewModel?.Settings != null)\n {\n try\n {\n // Use a separate timeout for power settings\n using var powerSettingsCts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(10));\n \n var powerSettingsTask = ApplyPowerSettings(viewModel.PowerSettingsViewModel, configFile);\n await Task.WhenAny(powerSettingsTask, Task.Delay(10000, powerSettingsCts.Token));\n \n if (powerSettingsTask.IsCompleted)\n {\n int updatedCount = await powerSettingsTask;\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in PowerSettingsViewModel\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Power settings update timed out, skipping\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating PowerSettingsViewModel: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n }\n \n // Explorer Settings\n if (viewModel.ExplorerOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.ExplorerOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in ExplorerOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating ExplorerOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Notification Settings\n if (viewModel.NotificationOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.NotificationOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in NotificationOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating NotificationOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Sound Settings\n if (viewModel.SoundOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.SoundOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in SoundOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating SoundOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Windows Security Settings\n _logService.Log(LogLevel.Info, \"Starting to process Windows Security Settings\");\n var securityStartTime = DateTime.Now;\n \n if (viewModel.WindowsSecuritySettingsViewModel?.Settings != null)\n {\n try\n {\n // Use a separate timeout for security settings\n using var securitySettingsCts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(10));\n \n var securitySettingsTask = ApplySecuritySettings(viewModel.WindowsSecuritySettingsViewModel, configFile);\n await Task.WhenAny(securitySettingsTask, Task.Delay(10000, securitySettingsCts.Token));\n \n if (securitySettingsTask.IsCompleted)\n {\n int updatedCount = await securitySettingsTask;\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in WindowsSecuritySettingsViewModel\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Security settings update timed out, skipping\");\n securitySettingsCts.Cancel();\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating WindowsSecuritySettingsViewModel: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n \n var securityEndTime = DateTime.Now;\n var securityExecutionTime = securityEndTime - securityStartTime;\n _logService.Log(LogLevel.Info, $\"Completed Windows Security Settings processing in {securityExecutionTime.TotalSeconds:F2} seconds\");\n }\n \n _logService.Log(LogLevel.Info, $\"Updated a total of {totalUpdatedCount} items in OptimizeViewModel and its child view models\");\n \n // Refresh the UI\n try\n {\n await _viewModelRefresher.RefreshViewModelAsync(viewModel);\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error refreshing view model: {ex.Message}\");\n }\n \n // Skip calling ApplyOptimizations during import to avoid system changes\n // We'll just update the UI to reflect the imported values\n \n // Reload the main Items collection to reflect the changes in child view models\n try\n {\n await viewModel.LoadItemsAsync();\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error reloading items: {ex.Message}\");\n }\n \n // Calculate and log execution time\n var endTime = DateTime.Now;\n var executionTime = endTime - startTime;\n _logService.Log(LogLevel.Info, $\"Completed OptimizeConfigurationApplier.ApplyConfigAsync in {executionTime.TotalSeconds:F2} seconds\");\n \n return totalUpdatedCount > 0;\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"OptimizeConfigurationApplier.ApplyConfigAsync was canceled due to timeout\");\n return false;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying Optimize configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n\n private async Task ApplyPowerSettings(PowerOptimizationsViewModel viewModel, ConfigurationFile configFile)\n {\n int updatedCount = 0;\n \n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(15));\n var cancellationToken = cancellationTokenSource.Token;\n \n // Track execution time\n var startTime = DateTime.Now;\n _logService.Log(LogLevel.Info, $\"Starting ApplyPowerSettings at {startTime}\");\n \n try\n {\n // First, check if there's a Power Plan item in the config file\n var powerPlanItem = configFile.Items?.FirstOrDefault(item =>\n (item.Name?.Contains(\"Power Plan\") == true ||\n (item.CustomProperties.TryGetValue(\"Id\", out var id) && id?.ToString() == \"PowerPlanComboBox\")));\n \n if (powerPlanItem != null)\n {\n _logService.Log(LogLevel.Info, $\"Found Power Plan item in config file: {powerPlanItem.Name}\");\n \n int newPowerPlanValue = -1;\n string selectedPowerPlan = null;\n \n // First try to get the value from SelectedValue by mapping to index (preferred method)\n if (!string.IsNullOrEmpty(powerPlanItem.SelectedValue))\n {\n selectedPowerPlan = powerPlanItem.SelectedValue;\n _logService.Log(LogLevel.Info, $\"Found SelectedValue in config: {selectedPowerPlan}\");\n \n var powerPlanLabels = viewModel.PowerPlanLabels;\n for (int i = 0; i < powerPlanLabels.Count; i++)\n {\n if (string.Equals(powerPlanLabels[i], selectedPowerPlan, StringComparison.OrdinalIgnoreCase))\n {\n newPowerPlanValue = i;\n _logService.Log(LogLevel.Info, $\"Mapped SelectedValue {selectedPowerPlan} to PowerPlanValue: {newPowerPlanValue}\");\n break;\n }\n }\n }\n // Then try to get the value from SliderValue in CustomProperties (fallback)\n else if (powerPlanItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n newPowerPlanValue = Convert.ToInt32(sliderValue);\n _logService.Log(LogLevel.Info, $\"Found PowerPlanValue in CustomProperties.SliderValue: {newPowerPlanValue}\");\n }\n \n // If we still don't have a valid power plan value, try to get it from PowerPlanOptions\n if (newPowerPlanValue < 0 && powerPlanItem.CustomProperties.TryGetValue(\"PowerPlanOptions\", out var powerPlanOptions))\n {\n if (powerPlanOptions is System.Collections.IList optionsList && !string.IsNullOrEmpty(selectedPowerPlan))\n {\n for (int i = 0; i < optionsList.Count; i++)\n {\n if (string.Equals(optionsList[i]?.ToString(), selectedPowerPlan, StringComparison.OrdinalIgnoreCase))\n {\n newPowerPlanValue = i;\n _logService.Log(LogLevel.Info, $\"Mapped SelectedValue {selectedPowerPlan} to PowerPlanValue: {newPowerPlanValue} using PowerPlanOptions\");\n break;\n }\n }\n }\n }\n \n if (newPowerPlanValue >= 0)\n {\n // Update the view model properties without triggering the actual power plan change\n // Store the current value for comparison\n int currentPowerPlanValue = viewModel.PowerPlanValue;\n \n if (currentPowerPlanValue != newPowerPlanValue)\n {\n _logService.Log(LogLevel.Info, $\"About to update PowerPlanValue from {currentPowerPlanValue} to {newPowerPlanValue}\");\n \n // Set IsApplyingPowerPlan to true before updating PowerPlanValue\n viewModel.IsApplyingPowerPlan = true;\n _logService.Log(LogLevel.Info, \"Set IsApplyingPowerPlan to true to prevent auto-application\");\n \n // Add a small delay to ensure IsApplyingPowerPlan takes effect\n await Task.Delay(50);\n \n try\n {\n // Use reflection to directly set the backing field for PowerPlanValue\n // This avoids triggering the property change notification that would call ApplyPowerPlanAsync\n var field = viewModel.GetType().GetField(\"_powerPlanValue\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n \n if (field != null)\n {\n // Set the backing field directly\n field.SetValue(viewModel, newPowerPlanValue);\n _logService.Log(LogLevel.Info, $\"Directly updated _powerPlanValue field to {newPowerPlanValue}\");\n \n // Manually trigger property changed notification\n // Specify the parameter types to avoid ambiguous match error\n var onPropertyChangedMethod = viewModel.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(string) },\n null);\n \n if (onPropertyChangedMethod != null)\n {\n onPropertyChangedMethod.Invoke(viewModel, new object[] { \"PowerPlanValue\" });\n _logService.Log(LogLevel.Info, \"Manually triggered OnPropertyChanged for PowerPlanValue\");\n }\n else\n {\n // Fallback: Try with PropertyChangedEventArgs parameter\n var args = new System.ComponentModel.PropertyChangedEventArgs(\"PowerPlanValue\");\n var altMethod = viewModel.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(System.ComponentModel.PropertyChangedEventArgs) },\n null);\n \n if (altMethod != null)\n {\n altMethod.Invoke(viewModel, new object[] { args });\n _logService.Log(LogLevel.Info, \"Manually triggered OnPropertyChanged with PropertyChangedEventArgs\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not find appropriate OnPropertyChanged method\");\n }\n }\n }\n else\n {\n // Fallback to direct property setting if field not found\n _logService.Log(LogLevel.Warning, \"Could not find _powerPlanValue field, using property setter instead\");\n viewModel.PowerPlanValue = newPowerPlanValue;\n _logService.Log(LogLevel.Info, $\"Updated PowerPlanValue property to {newPowerPlanValue}\");\n }\n \n // Add a small delay to ensure property change notifications are processed\n await Task.Delay(100);\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating power plan value: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n throw; // Rethrow to be caught by outer catch\n }\n \n // Now actually apply the power plan\n try\n {\n // Reset IsApplyingPowerPlan to false so we can apply the power plan\n viewModel.IsApplyingPowerPlan = false;\n _logService.Log(LogLevel.Info, \"Reset IsApplyingPowerPlan to false\");\n \n // Call the method to apply the power plan\n var applyPowerPlanMethod = viewModel.GetType().GetMethod(\"ApplyPowerPlanAsync\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (applyPowerPlanMethod != null)\n {\n _logService.Log(LogLevel.Info, $\"Calling ApplyPowerPlanAsync to apply power plan: {selectedPowerPlan}\");\n await (Task)applyPowerPlanMethod.Invoke(viewModel, new object[] { newPowerPlanValue });\n _logService.Log(LogLevel.Success, $\"Successfully applied power plan: {selectedPowerPlan}\");\n }\n else\n {\n // Try to find a method that takes no parameters\n applyPowerPlanMethod = viewModel.GetType().GetMethod(\"ApplyPowerPlanAsync\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance,\n null,\n Type.EmptyTypes,\n null);\n \n if (applyPowerPlanMethod != null)\n {\n _logService.Log(LogLevel.Info, $\"Calling parameterless ApplyPowerPlanAsync to apply power plan: {selectedPowerPlan}\");\n await (Task)applyPowerPlanMethod.Invoke(viewModel, null);\n _logService.Log(LogLevel.Success, $\"Successfully applied power plan: {selectedPowerPlan}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not find ApplyPowerPlanAsync method\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying power plan: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n finally\n {\n // Make sure IsApplyingPowerPlan is reset to false when done\n if (viewModel.IsApplyingPowerPlan)\n {\n viewModel.IsApplyingPowerPlan = false;\n _logService.Log(LogLevel.Info, \"Reset IsApplyingPowerPlan to false in finally block\");\n }\n }\n \n // Also update the SelectedIndex of the ComboBox if possible\n try\n {\n // Find the ComboBox control in the PowerSettingsViewModel\n var powerPlanComboBox = viewModel.Settings.FirstOrDefault(s =>\n s.Id == \"PowerPlanComboBox\" || s.Name?.Contains(\"Power Plan\") == true);\n \n if (powerPlanComboBox != null)\n {\n var sliderValueProperty = powerPlanComboBox.GetType().GetProperty(\"SliderValue\");\n if (sliderValueProperty != null)\n {\n _logService.Log(LogLevel.Info, $\"Setting SliderValue on PowerPlanComboBox to {newPowerPlanValue}\");\n sliderValueProperty.SetValue(powerPlanComboBox, newPowerPlanValue);\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error updating PowerPlanComboBox: {ex.Message}\");\n }\n \n updatedCount++;\n }\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"No Power Plan item found in config file\");\n \n // Try to find a power plan setting in the Settings collection\n var powerPlanSetting = viewModel.Settings?.FirstOrDefault(s =>\n s.Id == \"PowerPlanComboBox\" || s.Name?.Contains(\"Power Plan\") == true);\n \n if (powerPlanSetting != null)\n {\n _logService.Log(LogLevel.Info, $\"Found Power Plan setting in Settings collection: {powerPlanSetting.Name}\");\n \n // Create a new ConfigurationItem for the power plan\n var newPowerPlanItem = new ConfigurationItem\n {\n Name = powerPlanSetting.Name,\n IsSelected = true,\n ControlType = ControlType.ComboBox,\n CustomProperties = new Dictionary\n {\n { \"Id\", \"PowerPlanComboBox\" },\n { \"GroupName\", \"Power Management\" },\n { \"Description\", \"Select power plan for your system\" },\n { \"SliderValue\", viewModel.PowerPlanValue }\n }\n };\n \n // Set the SelectedValue based on the current PowerPlanValue\n if (viewModel.PowerPlanValue >= 0 && viewModel.PowerPlanValue < viewModel.PowerPlanLabels.Count)\n {\n newPowerPlanItem.SelectedValue = viewModel.PowerPlanLabels[viewModel.PowerPlanValue];\n }\n \n // Add the item to the config file\n if (configFile.Items == null)\n {\n configFile.Items = new List();\n }\n \n configFile.Items.Add(newPowerPlanItem);\n _logService.Log(LogLevel.Info, $\"Added Power Plan item to config file with SelectedValue: {newPowerPlanItem.SelectedValue}\");\n }\n }\n \n // Then apply to the Settings collection as usual\n int settingsUpdatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Settings, configFile);\n updatedCount += settingsUpdatedCount;\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"ApplyPowerSettings was canceled due to timeout\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying power settings: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n \n // Calculate and log execution time\n var endTime = DateTime.Now;\n var executionTime = endTime - startTime;\n _logService.Log(LogLevel.Info, $\"Completed ApplyPowerSettings in {executionTime.TotalSeconds:F2} seconds\");\n \n return updatedCount;\n }\n\n private async Task ApplySecuritySettings(WindowsSecurityOptimizationsViewModel viewModel, ConfigurationFile configFile)\n {\n int updatedCount = 0;\n \n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(15));\n var cancellationToken = cancellationTokenSource.Token;\n \n // Track execution time\n var startTime = DateTime.Now;\n _logService.Log(LogLevel.Info, $\"Starting ApplySecuritySettings at {startTime}\");\n \n try\n {\n // First, check if there's a UAC Slider item in the config file\n var uacSliderItem = configFile.Items?.FirstOrDefault(item =>\n (item.Name?.Contains(\"User Account Control\") == true ||\n (item.CustomProperties.TryGetValue(\"Id\", out var id) && id?.ToString() == \"UACSlider\")));\n\n if (uacSliderItem != null && uacSliderItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n // Check if the SelectedUacLevel property exists\n var selectedUacLevelProperty = viewModel.GetType().GetProperty(\"SelectedUacLevel\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);\n\n if (selectedUacLevelProperty != null)\n {\n // Convert the slider value to the corresponding UacLevel enum value\n int newUacLevelValue = Convert.ToInt32(sliderValue);\n var currentUacLevel = selectedUacLevelProperty.GetValue(viewModel);\n\n // Get the UacLevel enum type\n var uacLevelType = selectedUacLevelProperty.PropertyType;\n\n // Convert the integer to the corresponding UacLevel enum value\n var newUacLevel = (Winhance.Core.Models.Enums.UacLevel)Enum.ToObject(uacLevelType, newUacLevelValue);\n var currentUacLevelTyped = currentUacLevel != null ? (Winhance.Core.Models.Enums.UacLevel)currentUacLevel : Winhance.Core.Models.Enums.UacLevel.NotifyChangesOnly;\n\n if (currentUacLevelTyped != newUacLevel)\n {\n // Define isApplyingProperty at the beginning of the block for proper scope\n var isApplyingProperty = viewModel.GetType().GetProperty(\"IsApplyingUacLevel\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n \n if (isApplyingProperty != null)\n {\n _logService.Log(LogLevel.Info, \"Found IsApplyingUacLevel property, setting to true\");\n isApplyingProperty.SetValue(viewModel, true);\n \n // Add a small delay to ensure the property takes effect\n await Task.Delay(50, cancellationToken);\n }\n \n try\n {\n // Use reflection to set the field directly to avoid triggering HandleUACLevelChange\n var field = viewModel.GetType().GetField(\"_selectedUacLevel\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n \n if (field != null)\n {\n field.SetValue(viewModel, newUacLevel);\n _logService.Log(LogLevel.Info, $\"Directly updated _selectedUacLevel field to {newUacLevel}\");\n \n // Trigger property changed notification without calling HandleUACLevelChange\n // Specify the parameter types to avoid ambiguous match error\n var onPropertyChangedMethod = viewModel.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(string) },\n null);\n \n if (onPropertyChangedMethod != null)\n {\n onPropertyChangedMethod.Invoke(viewModel, new object[] { \"SelectedUacLevel\" });\n _logService.Log(LogLevel.Info, \"Manually triggered OnPropertyChanged for SelectedUacLevel\");\n }\n else\n {\n // Fallback: Try with PropertyChangedEventArgs parameter\n var args = new System.ComponentModel.PropertyChangedEventArgs(\"SelectedUacLevel\");\n var altMethod = viewModel.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(System.ComponentModel.PropertyChangedEventArgs) },\n null);\n \n if (altMethod != null)\n {\n altMethod.Invoke(viewModel, new object[] { args });\n _logService.Log(LogLevel.Info, \"Manually triggered OnPropertyChanged with PropertyChangedEventArgs\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not find appropriate OnPropertyChanged method\");\n }\n }\n \n // Add a small delay to ensure property change notifications are processed\n await Task.Delay(100, cancellationToken);\n }\n else\n {\n // Fallback to direct property setting if field not found\n _logService.Log(LogLevel.Warning, \"Could not find _selectedUacLevel field, using property setter instead\");\n viewModel.SelectedUacLevel = (Winhance.Core.Models.Enums.UacLevel)newUacLevel;\n _logService.Log(LogLevel.Info, $\"Updated SelectedUacLevel property to {newUacLevel}\");\n \n // Add a small delay to ensure property change notifications are processed\n await Task.Delay(100, cancellationToken);\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating UAC level value: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n throw; // Rethrow to be caught by outer catch\n }\n \n // Now actually apply the UAC level\n try\n {\n // Reset IsApplyingUacLevel if it exists\n if (isApplyingProperty != null)\n {\n isApplyingProperty.SetValue(viewModel, false);\n _logService.Log(LogLevel.Info, \"Reset IsApplyingUacLevel to false\");\n }\n \n // Call the method to apply the UAC level\n var handleUacLevelChangeMethod = viewModel.GetType().GetMethod(\"HandleUACLevelChange\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (handleUacLevelChangeMethod != null)\n {\n _logService.Log(LogLevel.Info, $\"Calling HandleUACLevelChange to apply UAC level: {newUacLevel}\");\n // HandleUACLevelChange doesn't take any parameters\n handleUacLevelChangeMethod.Invoke(viewModel, null);\n _logService.Log(LogLevel.Success, $\"Successfully applied UAC level: {newUacLevel}\");\n }\n else\n {\n // Try to find a method that takes no parameters\n handleUacLevelChangeMethod = viewModel.GetType().GetMethod(\"HandleUACLevelChange\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance,\n null,\n Type.EmptyTypes,\n null);\n \n if (handleUacLevelChangeMethod != null)\n {\n _logService.Log(LogLevel.Info, $\"Calling parameterless HandleUACLevelChange to apply UAC level: {newUacLevel}\");\n handleUacLevelChangeMethod.Invoke(viewModel, null);\n _logService.Log(LogLevel.Success, $\"Successfully applied UAC level: {newUacLevel}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not find HandleUACLevelChange method\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying UAC level: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n finally\n {\n // Make sure IsApplyingUacLevel is reset to false when done\n if (isApplyingProperty != null && isApplyingProperty.GetValue(viewModel) is true)\n {\n isApplyingProperty.SetValue(viewModel, false);\n _logService.Log(LogLevel.Info, \"Reset IsApplyingUacLevel to false in finally block\");\n }\n } // End of the if (currentUacLevel != newUacLevel) block\n }\n \n updatedCount++;\n }\n }\n \n // Then apply to the Settings collection as usual\n int settingsUpdatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Settings, configFile);\n updatedCount += settingsUpdatedCount;\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"ApplySecuritySettings was canceled due to timeout\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying security settings: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n \n // Calculate and log execution time\n var endTime = DateTime.Now;\n var executionTime = endTime - startTime;\n _logService.Log(LogLevel.Info, $\"Completed ApplySecuritySettings in {executionTime.TotalSeconds:F2} seconds\");\n \n return updatedCount;\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/ConfigurationCollectorService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Customize.ViewModels;\nusing Winhance.WPF.Features.Optimize.ViewModels;\nusing Winhance.WPF.Features.SoftwareApps.Models;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for collecting configuration settings from different view models.\n /// \n public class ConfigurationCollectorService\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n\n /// \n /// A wrapper class that implements ISettingItem for Power Plan settings\n /// \n private class PowerPlanSettingItem : ISettingItem\n {\n private readonly ConfigurationItem _configItem;\n private readonly object _originalItem;\n private string _id;\n private string _name;\n private string _description;\n private bool _isSelected;\n private string _groupName;\n private bool _isVisible;\n private ControlType _controlType;\n private int _sliderValue;\n\n public PowerPlanSettingItem(ConfigurationItem configItem, object originalItem)\n {\n _configItem = configItem;\n _originalItem = originalItem;\n \n // Initialize properties from the ConfigurationItem\n _id = _configItem.CustomProperties.TryGetValue(\"Id\", out var id) ? id?.ToString() : \"PowerPlanComboBox\";\n _name = _configItem.Name;\n _description = _configItem.CustomProperties.TryGetValue(\"Description\", out var desc) ? desc?.ToString() : \"Power Plan setting\";\n _isSelected = _configItem.IsSelected;\n _groupName = _configItem.CustomProperties.TryGetValue(\"GroupName\", out var group) ? group?.ToString() : \"Power Management\";\n _isVisible = true;\n _controlType = ControlType.ComboBox;\n _sliderValue = _configItem.CustomProperties.TryGetValue(\"SliderValue\", out var value) ? Convert.ToInt32(value) : 0;\n \n // Ensure the ConfigurationItem has the correct format\n // Make sure SelectedValue is set properly\n if (_configItem.SelectedValue == null)\n {\n // Try to get it from PowerPlanOptions if available\n if (_configItem.CustomProperties.TryGetValue(\"PowerPlanOptions\", out var options) &&\n options is List powerPlanOptions &&\n powerPlanOptions.Count > 0 &&\n _configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int index = Convert.ToInt32(sliderValue);\n if (index >= 0 && index < powerPlanOptions.Count)\n {\n _configItem.SelectedValue = powerPlanOptions[index];\n }\n }\n }\n \n // Always ensure SelectedValue is set based on SliderValue if it's still null\n if (_configItem.SelectedValue == null && _configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sv))\n {\n int index = Convert.ToInt32(sv);\n if (_configItem.CustomProperties.TryGetValue(\"PowerPlanOptions\", out var opt) &&\n opt is List planOptions &&\n planOptions.Count > index && index >= 0)\n {\n _configItem.SelectedValue = planOptions[index];\n }\n else\n {\n // Fallback to default power plan names if PowerPlanOptions is not available\n string[] defaultOptions = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n if (index >= 0 && index < defaultOptions.Length)\n {\n _configItem.SelectedValue = defaultOptions[index];\n }\n }\n }\n \n // Initialize other required properties\n Dependencies = new List();\n IsUpdatingFromCode = false;\n ApplySettingCommand = null;\n }\n\n // Properties with getters and setters\n public string Id { get => _id; set => _id = value; }\n public string Name { get => _name; set => _name = value; }\n public string Description { get => _description; set => _description = value; }\n public bool IsSelected { get => _isSelected; set => _isSelected = value; }\n public string GroupName { get => _groupName; set => _groupName = value; }\n public bool IsVisible { get => _isVisible; set => _isVisible = value; }\n public ControlType ControlType { get => _controlType; set => _controlType = value; }\n public int SliderValue { get => _sliderValue; set => _sliderValue = value; }\n \n // Additional required properties\n public List Dependencies { get; set; }\n public bool IsUpdatingFromCode { get; set; }\n public System.Windows.Input.ICommand ApplySettingCommand { get; set; }\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n public ConfigurationCollectorService(\n IServiceProvider serviceProvider,\n ILogService logService)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Collects settings from all view models.\n /// \n /// A dictionary of section names and their settings.\n public async Task>> CollectAllSettingsAsync()\n {\n var sectionSettings = new Dictionary>();\n\n // Get all view models from the service provider\n var windowsAppsViewModel = _serviceProvider.GetService();\n var externalAppsViewModel = _serviceProvider.GetService();\n var customizeViewModel = _serviceProvider.GetService();\n var optimizeViewModel = _serviceProvider.GetService();\n\n // Add settings from WindowsAppsViewModel\n if (windowsAppsViewModel != null)\n {\n await CollectWindowsAppsSettings(windowsAppsViewModel, sectionSettings);\n }\n\n // Add settings from ExternalAppsViewModel\n if (externalAppsViewModel != null)\n {\n await CollectExternalAppsSettings(externalAppsViewModel, sectionSettings);\n }\n\n // Add settings from CustomizeViewModel\n if (customizeViewModel != null)\n {\n await CollectCustomizeSettings(customizeViewModel, sectionSettings);\n }\n\n // Add settings from OptimizeViewModel\n if (optimizeViewModel != null)\n {\n await CollectOptimizeSettings(optimizeViewModel, sectionSettings);\n }\n\n return sectionSettings;\n }\n\n private async Task CollectWindowsAppsSettings(WindowsAppsViewModel viewModel, Dictionary> sectionSettings)\n {\n try\n {\n _logService.Log(LogLevel.Debug, \"Collecting settings from WindowsAppsViewModel\");\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"WindowsAppsViewModel not initialized, loading items\");\n await viewModel.LoadItemsAsync();\n }\n \n // Convert each WindowsApp to WindowsAppSettingItem\n var windowsAppSettingItems = new List();\n \n foreach (var item in viewModel.Items)\n {\n if (item is WindowsApp windowsApp)\n {\n windowsAppSettingItems.Add(new WindowsAppSettingItem(windowsApp));\n _logService.Log(LogLevel.Debug, $\"Added WindowsAppSettingItem for {windowsApp.Name}\");\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Created {windowsAppSettingItems.Count} WindowsAppSettingItems\");\n \n // Always add WindowsApps to sectionSettings, even if empty\n sectionSettings[\"WindowsApps\"] = windowsAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added WindowsApps section with {windowsAppSettingItems.Count} items\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error collecting WindowsApps settings: {ex.Message}\");\n \n // Create some default WindowsApps as fallback\n var defaultApps = new[]\n {\n new WindowsApp\n {\n Name = \"Microsoft Edge\",\n PackageName = \"Microsoft.MicrosoftEdge\",\n IsSelected = true,\n Description = \"Microsoft Edge browser\"\n },\n new WindowsApp\n {\n Name = \"Calculator\",\n PackageName = \"Microsoft.WindowsCalculator\",\n IsSelected = true,\n Description = \"Windows Calculator app\"\n },\n new WindowsApp\n {\n Name = \"Photos\",\n PackageName = \"Microsoft.Windows.Photos\",\n IsSelected = true,\n Description = \"Windows Photos app\"\n }\n };\n \n var defaultWindowsAppSettingItems = new List();\n foreach (var app in defaultApps)\n {\n defaultWindowsAppSettingItems.Add(new WindowsAppSettingItem(app));\n }\n \n // Always add WindowsApps to sectionSettings, even if using defaults\n sectionSettings[\"WindowsApps\"] = defaultWindowsAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added WindowsApps section with {defaultWindowsAppSettingItems.Count} default items\");\n }\n }\n\n private async Task CollectExternalAppsSettings(ExternalAppsViewModel viewModel, Dictionary> sectionSettings)\n {\n try\n {\n _logService.Log(LogLevel.Debug, \"Collecting settings from ExternalAppsViewModel\");\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"ExternalAppsViewModel not initialized, loading items\");\n await viewModel.LoadItemsAsync();\n }\n \n // Convert each ExternalApp to ExternalAppSettingItem\n var externalAppSettingItems = new List();\n \n foreach (var item in viewModel.Items)\n {\n if (item is ExternalApp externalApp)\n {\n externalAppSettingItems.Add(new ExternalAppSettingItem(externalApp));\n _logService.Log(LogLevel.Debug, $\"Added ExternalAppSettingItem for {externalApp.Name}\");\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Created {externalAppSettingItems.Count} ExternalAppSettingItems\");\n \n // Add the settings to the dictionary\n sectionSettings[\"ExternalApps\"] = externalAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added ExternalApps section with {externalAppSettingItems.Count} items\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error collecting ExternalApps settings: {ex.Message}\");\n \n // Add an empty list as fallback\n sectionSettings[\"ExternalApps\"] = new List();\n _logService.Log(LogLevel.Info, \"Added empty ExternalApps section due to error\");\n }\n }\n\n private async Task CollectCustomizeSettings(CustomizeViewModel viewModel, Dictionary> sectionSettings)\n {\n try\n {\n _logService.Log(LogLevel.Debug, \"Collecting settings from CustomizeViewModel\");\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"CustomizeViewModel not initialized, loading items\");\n await viewModel.LoadItemsAsync();\n }\n \n // Collect settings directly\n var customizeItems = new List();\n \n foreach (var item in viewModel.Items)\n {\n if (item is ISettingItem settingItem)\n {\n // Skip the DarkModeToggle item to avoid conflicts with ThemeSelector\n if (settingItem.Id == \"DarkModeToggle\")\n {\n _logService.Log(LogLevel.Debug, $\"Skipping DarkModeToggle item to avoid conflicts with ThemeSelector\");\n continue;\n }\n \n // Special handling for Windows Theme / Choose Your Mode\n if (settingItem.Id == \"ThemeSelector\" ||\n settingItem.Name.Contains(\"Windows Theme\") ||\n settingItem.Name.Contains(\"Theme Selector\") ||\n settingItem.Name.Contains(\"Choose Your Mode\"))\n {\n // Ensure it has the correct ControlType and properties for ComboBox\n if (settingItem is ApplicationSettingItem applicationSetting)\n {\n applicationSetting.ControlType = ControlType.ComboBox;\n \n // Get the SelectedTheme from the RegistrySetting if available\n if (applicationSetting.RegistrySetting?.CustomProperties != null &&\n applicationSetting.RegistrySetting.CustomProperties.ContainsKey(\"SelectedTheme\"))\n {\n var selectedTheme = applicationSetting.RegistrySetting.CustomProperties[\"SelectedTheme\"]?.ToString();\n _logService.Log(LogLevel.Debug, $\"Found SelectedTheme in RegistrySetting: {selectedTheme}\");\n }\n \n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ComboBox for Theme Selector\");\n }\n else if (settingItem is ApplicationSettingViewModel applicationViewModel)\n {\n applicationViewModel.ControlType = ControlType.ComboBox;\n \n // Ensure SelectedValue is set based on SelectedTheme if available\n var selectedThemeProperty = applicationViewModel.GetType().GetProperty(\"SelectedTheme\");\n var selectedValueProperty = applicationViewModel.GetType().GetProperty(\"SelectedValue\");\n \n if (selectedThemeProperty != null && selectedValueProperty != null)\n {\n var selectedTheme = selectedThemeProperty.GetValue(applicationViewModel)?.ToString();\n if (!string.IsNullOrEmpty(selectedTheme))\n {\n selectedValueProperty.SetValue(applicationViewModel, selectedTheme);\n }\n }\n \n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ComboBox for Theme Selector (ViewModel) and ensured SelectedValue is set\");\n }\n else if (settingItem is ApplicationSettingItem customizationSetting)\n {\n customizationSetting.ControlType = ControlType.ComboBox;\n \n // Get the SelectedTheme from the RegistrySetting if available\n if (customizationSetting.RegistrySetting?.CustomProperties != null &&\n customizationSetting.RegistrySetting.CustomProperties.ContainsKey(\"SelectedTheme\"))\n {\n var selectedTheme = customizationSetting.RegistrySetting.CustomProperties[\"SelectedTheme\"]?.ToString();\n _logService.Log(LogLevel.Debug, $\"Found SelectedTheme in RegistrySetting: {selectedTheme}\");\n }\n \n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ComboBox for Theme Selector (CustomizationSetting)\");\n }\n }\n \n customizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item for {settingItem.Name}\");\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Collected {customizeItems.Count} customize items\");\n \n // Add the settings to the dictionary\n sectionSettings[\"Customize\"] = customizeItems;\n _logService.Log(LogLevel.Info, $\"Added Customize section with {customizeItems.Count} items\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error collecting Customize settings: {ex.Message}\");\n \n // Add an empty list as fallback\n sectionSettings[\"Customize\"] = new List();\n _logService.Log(LogLevel.Info, \"Added empty Customize section due to error\");\n }\n }\n\n private async Task CollectOptimizeSettings(OptimizeViewModel viewModel, Dictionary> sectionSettings)\n {\n try\n {\n _logService.Log(LogLevel.Debug, \"Collecting settings from OptimizeViewModel\");\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"OptimizeViewModel not initialized, initializing now\");\n await viewModel.InitializeCommand.ExecuteAsync(null);\n _logService.Log(LogLevel.Debug, \"OptimizeViewModel initialized\");\n }\n \n // Force load items even if already initialized to ensure we have the latest data\n _logService.Log(LogLevel.Debug, \"Loading OptimizeViewModel items\");\n await viewModel.LoadItemsAsync();\n _logService.Log(LogLevel.Debug, $\"OptimizeViewModel items loaded, count: {viewModel.Items?.Count ?? 0}\");\n \n // Collect settings directly\n var optimizeItems = new List();\n \n // First check if Items collection has any settings\n if (viewModel.Items != null && viewModel.Items.Count > 0)\n {\n foreach (var item in viewModel.Items)\n {\n if (item is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Items collection: {settingItem.Name}\");\n }\n }\n }\n \n // If we didn't get any items from the Items collection, try to collect from child view models directly\n if (optimizeItems.Count == 0)\n {\n _logService.Log(LogLevel.Debug, \"No items found in Items collection, collecting from child view models\");\n \n // Collect from GamingandPerformanceOptimizationsViewModel\n if (viewModel.GamingandPerformanceOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.GamingandPerformanceOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Gaming: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from PrivacyOptimizationsViewModel\n if (viewModel.PrivacyOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.PrivacyOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Privacy: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from UpdateOptimizationsViewModel\n if (viewModel.UpdateOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.UpdateOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Updates: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from PowerSettingsViewModel\n if (viewModel.PowerSettingsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.PowerSettingsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n // Special handling for Power Plan\n if (settingItem.Id == \"PowerPlanComboBox\" || settingItem.Name.Contains(\"Power Plan\"))\n {\n // Ensure it has the correct ControlType\n if (settingItem is ApplicationSettingItem applicationSetting)\n {\n applicationSetting.ControlType = ControlType.ComboBox;\n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ComboBox for Power Plan\");\n \n // Get the current power plan value from the view model\n if (viewModel.PowerSettingsViewModel != null)\n {\n // Set the SliderValue to the current power plan index\n int powerPlanIndex = viewModel.PowerSettingsViewModel.PowerPlanValue;\n applicationSetting.SliderValue = powerPlanIndex;\n _logService.Log(LogLevel.Debug, $\"Set SliderValue to {powerPlanIndex} for Power Plan\");\n \n // Instead of replacing the item, update its properties\n applicationSetting.ControlType = ControlType.ComboBox;\n applicationSetting.SliderValue = powerPlanIndex;\n \n // Create a separate ConfigurationItem for the config file\n var configItem = new ConfigurationItem\n {\n Name = \"Power Plan\", // Use a consistent name\n IsSelected = true, // Always enable the Power Plan\n ControlType = ControlType.ComboBox,\n CustomProperties = new Dictionary\n {\n { \"Id\", \"PowerPlanComboBox\" }, // Use a consistent ID\n { \"GroupName\", \"Power Management\" },\n { \"Description\", \"Select power plan for your system\" },\n { \"SliderValue\", powerPlanIndex }\n }\n };\n \n // Set the SelectedValue to the current power plan name\n if (powerPlanIndex >= 0 && powerPlanIndex < viewModel.PowerSettingsViewModel.PowerPlanLabels.Count)\n {\n string powerPlanName = viewModel.PowerSettingsViewModel.PowerPlanLabels[powerPlanIndex];\n \n // Set SelectedValue at the top level (this is what appears in the config file)\n configItem.SelectedValue = powerPlanName;\n \n // Add PowerPlanOptions to CustomProperties (similar to ThemeOptions in Windows Theme)\n configItem.CustomProperties[\"PowerPlanOptions\"] = viewModel.PowerSettingsViewModel.PowerPlanLabels.ToList();\n _logService.Log(LogLevel.Debug, $\"Set SelectedValue to {powerPlanName} for Power Plan ConfigItem\");\n }\n \n // Add this ConfigurationItem directly to the optimizeItems collection\n // We'll create a wrapper that implements ISettingItem\n var powerPlanSettingItem = new PowerPlanSettingItem(configItem, applicationSetting);\n \n // Add it to the collection if it doesn't already exist\n bool exists = false;\n foreach (var item in optimizeItems)\n {\n if (item is PowerPlanSettingItem)\n {\n exists = true;\n break;\n }\n }\n \n if (!exists)\n {\n optimizeItems.Add(powerPlanSettingItem);\n _logService.Log(LogLevel.Debug, $\"Added PowerPlanSettingItem to optimizeItems\");\n }\n }\n }\n else if (settingItem is ApplicationSettingViewModel applicationViewModel)\n {\n applicationViewModel.ControlType = ControlType.ComboBox;\n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ComboBox for Power Plan (ViewModel)\");\n \n // Get the current power plan value from the view model\n if (viewModel.PowerSettingsViewModel != null)\n {\n // Set the SliderValue to the current power plan index\n int powerPlanIndex = viewModel.PowerSettingsViewModel.PowerPlanValue;\n applicationViewModel.SliderValue = powerPlanIndex;\n _logService.Log(LogLevel.Debug, $\"Set SliderValue to {powerPlanIndex} for Power Plan (ViewModel)\");\n \n // Instead of replacing the item, update its properties\n applicationViewModel.ControlType = ControlType.ComboBox;\n applicationViewModel.SliderValue = powerPlanIndex;\n \n // Create a separate ConfigurationItem for the config file\n var configItem = new ConfigurationItem\n {\n Name = \"Power Plan\", // Use a consistent name\n IsSelected = true, // Always enable the Power Plan\n ControlType = ControlType.ComboBox,\n CustomProperties = new Dictionary\n {\n { \"Id\", \"PowerPlanComboBox\" }, // Use a consistent ID\n { \"GroupName\", \"Power Management\" },\n { \"Description\", \"Select power plan for your system\" },\n { \"SliderValue\", powerPlanIndex }\n }\n };\n \n // Set the SelectedValue to the current power plan name\n if (powerPlanIndex >= 0 && powerPlanIndex < viewModel.PowerSettingsViewModel.PowerPlanLabels.Count)\n {\n string powerPlanName = viewModel.PowerSettingsViewModel.PowerPlanLabels[powerPlanIndex];\n \n // Set SelectedValue at the top level (this is what appears in the config file)\n configItem.SelectedValue = powerPlanName;\n \n // Add PowerPlanOptions to CustomProperties (similar to ThemeOptions in Windows Theme)\n configItem.CustomProperties[\"PowerPlanOptions\"] = viewModel.PowerSettingsViewModel.PowerPlanLabels.ToList();\n _logService.Log(LogLevel.Debug, $\"Set SelectedValue to {powerPlanName} for Power Plan ConfigItem (ViewModel)\");\n }\n \n // Add this ConfigurationItem directly to the optimizeItems collection\n // We'll create a wrapper that implements ISettingItem\n var powerPlanSettingItem = new PowerPlanSettingItem(configItem, applicationViewModel);\n \n // Add it to the collection if it doesn't already exist\n bool exists = false;\n foreach (var item in optimizeItems)\n {\n if (item is PowerPlanSettingItem)\n {\n exists = true;\n break;\n }\n }\n \n if (!exists)\n {\n optimizeItems.Add(powerPlanSettingItem);\n _logService.Log(LogLevel.Debug, $\"Added PowerPlanSettingItem to optimizeItems (ViewModel)\");\n }\n }\n }\n }\n \n // Skip adding the original Power Plan item since we've already added our custom PowerPlanSettingItem\n if (!(settingItem.Id == \"PowerPlanComboBox\" || settingItem.Name.Contains(\"Power Plan\")))\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Power: {settingItem.Name}\");\n }\n else\n {\n _logService.Log(LogLevel.Debug, $\"Skipped adding original Power Plan item: {settingItem.Name}\");\n }\n }\n }\n }\n \n // Collect from ExplorerOptimizationsViewModel\n if (viewModel.ExplorerOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.ExplorerOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Explorer: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from NotificationOptimizationsViewModel\n if (viewModel.NotificationOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.NotificationOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Notifications: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from SoundOptimizationsViewModel\n if (viewModel.SoundOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.SoundOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Sound: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from WindowsSecuritySettingsViewModel\n if (viewModel.WindowsSecuritySettingsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.WindowsSecuritySettingsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n // Special handling for UAC Slider\n if (settingItem.Id == \"UACSlider\" || settingItem.Name.Contains(\"User Account Control\"))\n {\n // Ensure it has the correct ControlType\n if (settingItem is ApplicationSettingItem applicationSetting)\n {\n applicationSetting.ControlType = ControlType.ThreeStateSlider;\n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ThreeStateSlider for UAC Slider\");\n }\n else if (settingItem is ApplicationSettingViewModel applicationViewModel)\n {\n applicationViewModel.ControlType = ControlType.ThreeStateSlider;\n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ThreeStateSlider for UAC Slider (ViewModel)\");\n }\n }\n \n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Security: {settingItem.Name}\");\n }\n }\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Collected {optimizeItems.Count} optimize items\");\n \n // Always create a standalone Power Plan item and add it directly to the configuration file\n if (viewModel.PowerSettingsViewModel != null)\n {\n try\n {\n // Get the current power plan index and name\n int powerPlanIndex = viewModel.PowerSettingsViewModel.PowerPlanValue;\n string powerPlanName = null;\n \n if (powerPlanIndex >= 0 && powerPlanIndex < viewModel.PowerSettingsViewModel.PowerPlanLabels.Count)\n {\n powerPlanName = viewModel.PowerSettingsViewModel.PowerPlanLabels[powerPlanIndex];\n }\n \n // Create a ConfigurationItem for the Power Plan\n var configItem = new ConfigurationItem\n {\n Name = \"Power Plan\",\n PackageName = null,\n IsSelected = true,\n ControlType = ControlType.ComboBox,\n SelectedValue = powerPlanName, // Set SelectedValue directly\n CustomProperties = new Dictionary\n {\n { \"Id\", \"PowerPlanComboBox\" },\n { \"GroupName\", \"Power Management\" },\n { \"Description\", \"Select power plan for your system\" },\n { \"SliderValue\", powerPlanIndex },\n { \"PowerPlanOptions\", viewModel.PowerSettingsViewModel.PowerPlanLabels.ToList() }\n }\n };\n \n // Log the configuration item for debugging\n _logService.Log(LogLevel.Info, $\"Created Power Plan configuration item with SelectedValue: {powerPlanName}, SliderValue: {powerPlanIndex}\");\n _logService.Log(LogLevel.Info, $\"PowerPlanOptions: {string.Join(\", \", viewModel.PowerSettingsViewModel.PowerPlanLabels)}\");\n \n // Ensure SelectedValue is not null\n if (string.IsNullOrEmpty(configItem.SelectedValue) &&\n configItem.CustomProperties.ContainsKey(\"PowerPlanOptions\") &&\n configItem.CustomProperties[\"PowerPlanOptions\"] is List options &&\n options.Count > powerPlanIndex && powerPlanIndex >= 0)\n {\n configItem.SelectedValue = options[powerPlanIndex];\n _logService.Log(LogLevel.Info, $\"Set SelectedValue to {configItem.SelectedValue} from PowerPlanOptions\");\n }\n \n // Add the item directly to the configuration file\n var configService = _serviceProvider.GetService();\n if (configService != null)\n {\n // Use reflection to access the ConfigurationFile\n var configFileProperty = configService.GetType().GetProperty(\"CurrentConfiguration\");\n if (configFileProperty != null)\n {\n var configFile = configFileProperty.GetValue(configService) as ConfigurationFile;\n if (configFile != null && configFile.Items != null)\n {\n // Remove any existing Power Plan items\n configFile.Items.RemoveAll(item =>\n item.Name == \"Power Plan\" ||\n (item.CustomProperties != null && item.CustomProperties.TryGetValue(\"Id\", out var id) && id?.ToString() == \"PowerPlanComboBox\"));\n \n // Add the new Power Plan item\n configFile.Items.Add(configItem);\n _logService.Log(LogLevel.Info, $\"Added Power Plan item directly to the configuration file with SelectedValue: {powerPlanName}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not access ConfigurationFile.Items\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not access CurrentConfiguration property\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not get IConfigurationService from service provider\");\n }\n \n // Also create a wrapper that implements ISettingItem for the optimizeItems collection\n var powerPlanSettingItem = new PowerPlanSettingItem(configItem, null);\n \n // Remove any existing Power Plan items from optimizeItems\n optimizeItems.RemoveAll(item =>\n (item is PowerPlanSettingItem) ||\n (item is ApplicationSettingItem settingItem &&\n (settingItem.Id == \"PowerPlanComboBox\" || settingItem.Name.Contains(\"Power Plan\"))));\n \n // Add the new Power Plan item to optimizeItems\n optimizeItems.Add(powerPlanSettingItem);\n _logService.Log(LogLevel.Info, \"Added Power Plan item to optimizeItems\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating Power Plan item: {ex.Message}\");\n }\n }\n \n // Add the settings to the dictionary\n sectionSettings[\"Optimize\"] = optimizeItems;\n _logService.Log(LogLevel.Info, $\"Added Optimize section with {optimizeItems.Count} items\");\n \n // If we still have no items, log a warning\n if (optimizeItems.Count == 0)\n {\n _logService.Log(LogLevel.Warning, \"No optimize items were collected. This may indicate an initialization issue with the OptimizeViewModel or its child view models.\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error collecting Optimize settings: {ex.Message}\");\n \n // Add an empty list as fallback\n sectionSettings[\"Optimize\"] = new List();\n _logService.Log(LogLevel.Info, \"Added empty Optimize section due to error\");\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/UserPreferencesService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading.Tasks;\nusing Newtonsoft.Json;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for managing user preferences\n /// \n public class UserPreferencesService\n {\n private const string PreferencesFileName = \"UserPreferences.json\";\n private readonly ILogService _logService;\n\n public UserPreferencesService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Gets the path to the user preferences file\n /// \n /// The full path to the user preferences file\n private string GetPreferencesFilePath()\n {\n try\n {\n // Get the LocalApplicationData folder (e.g., C:\\Users\\Username\\AppData\\Local)\n string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n \n if (string.IsNullOrEmpty(localAppData))\n {\n _logService.Log(LogLevel.Error, \"LocalApplicationData folder path is empty\");\n // Fallback to a default path\n localAppData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), \"AppData\", \"Local\");\n _logService.Log(LogLevel.Info, $\"Using fallback path: {localAppData}\");\n }\n \n // Combine with Winhance/Config\n string appDataPath = Path.Combine(localAppData, \"Winhance\", \"Config\");\n \n // Log the path\n _logService.Log(LogLevel.Debug, $\"Preferences directory path: {appDataPath}\");\n \n // Ensure the directory exists\n if (!Directory.Exists(appDataPath))\n {\n Directory.CreateDirectory(appDataPath);\n _logService.Log(LogLevel.Info, $\"Created preferences directory: {appDataPath}\");\n }\n \n // Get the full file path\n string filePath = Path.Combine(appDataPath, PreferencesFileName);\n _logService.Log(LogLevel.Debug, $\"Preferences file path: {filePath}\");\n \n return filePath;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting preferences file path: {ex.Message}\");\n \n // Fallback to a temporary file\n string tempPath = Path.Combine(Path.GetTempPath(), \"Winhance\", \"Config\");\n Directory.CreateDirectory(tempPath);\n string tempFilePath = Path.Combine(tempPath, PreferencesFileName);\n \n _logService.Log(LogLevel.Warning, $\"Using fallback temporary path: {tempFilePath}\");\n return tempFilePath;\n }\n }\n\n /// \n /// Gets the user preferences\n /// \n /// A dictionary containing the user preferences\n public async Task> GetPreferencesAsync()\n {\n try\n {\n string filePath = GetPreferencesFilePath();\n \n // Log the file path\n _logService.Log(LogLevel.Debug, $\"Getting preferences from '{filePath}'\");\n \n if (!File.Exists(filePath))\n {\n _logService.Log(LogLevel.Info, $\"User preferences file does not exist at '{filePath}', returning empty preferences\");\n return new Dictionary();\n }\n \n // Read the file\n string json = await File.ReadAllTextAsync(filePath);\n \n // Log a sample of the JSON (first 100 characters)\n if (!string.IsNullOrEmpty(json))\n {\n string sample = json.Length > 100 ? json.Substring(0, 100) + \"...\" : json;\n _logService.Log(LogLevel.Debug, $\"JSON sample: {sample}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Preferences file exists but is empty\");\n return new Dictionary();\n }\n \n // Use more robust deserialization settings\n var settings = new JsonSerializerSettings\n {\n NullValueHandling = NullValueHandling.Include,\n TypeNameHandling = TypeNameHandling.None,\n ReferenceLoopHandling = ReferenceLoopHandling.Ignore\n };\n \n // Use a custom converter to properly handle boolean values\n var preferences = JsonConvert.DeserializeObject>(json, settings);\n \n // Log the raw type of the DontShowSupport value if it exists\n if (preferences != null && preferences.TryGetValue(\"DontShowSupport\", out var dontShowValue))\n {\n _logService.Log(LogLevel.Debug, $\"DontShowSupport raw value type: {dontShowValue?.GetType().FullName}, value: {dontShowValue}\");\n }\n \n if (preferences != null)\n {\n _logService.Log(LogLevel.Info, $\"Successfully loaded {preferences.Count} preferences\");\n \n // Log the keys for debugging\n if (preferences.Count > 0)\n {\n _logService.Log(LogLevel.Debug, $\"Preference keys: {string.Join(\", \", preferences.Keys)}\");\n }\n \n return preferences;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Deserialized preferences is null, returning empty dictionary\");\n return new Dictionary();\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting user preferences: {ex.Message}\");\n if (ex.InnerException != null)\n {\n _logService.Log(LogLevel.Error, $\"Inner exception: {ex.InnerException.Message}\");\n }\n return new Dictionary();\n }\n }\n\n /// \n /// Saves the user preferences\n /// \n /// The preferences to save\n /// True if successful, false otherwise\n public async Task SavePreferencesAsync(Dictionary preferences)\n {\n try\n {\n string filePath = GetPreferencesFilePath();\n \n // Log the file path and preferences count\n _logService.Log(LogLevel.Debug, $\"Saving preferences to '{filePath}', count: {preferences.Count}\");\n \n // Use more robust serialization settings\n var settings = new JsonSerializerSettings\n {\n Formatting = Formatting.Indented,\n NullValueHandling = NullValueHandling.Include,\n TypeNameHandling = TypeNameHandling.None,\n ReferenceLoopHandling = ReferenceLoopHandling.Ignore\n };\n \n string json = JsonConvert.SerializeObject(preferences, settings);\n \n // Log a sample of the JSON (first 100 characters)\n if (json.Length > 0)\n {\n string sample = json.Length > 100 ? json.Substring(0, 100) + \"...\" : json;\n _logService.Log(LogLevel.Debug, $\"JSON sample: {sample}\");\n }\n \n // Ensure the directory exists\n string directory = Path.GetDirectoryName(filePath);\n if (!Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n _logService.Log(LogLevel.Debug, $\"Created directory: {directory}\");\n }\n \n // Write the file\n await File.WriteAllTextAsync(filePath, json);\n \n // Verify the file was written\n if (File.Exists(filePath))\n {\n _logService.Log(LogLevel.Info, $\"User preferences saved successfully to '{filePath}'\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"File not found after writing: '{filePath}'\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving user preferences: {ex.Message}\");\n if (ex.InnerException != null)\n {\n _logService.Log(LogLevel.Error, $\"Inner exception: {ex.InnerException.Message}\");\n }\n return false;\n }\n }\n\n /// \n /// Gets a specific preference value\n /// \n /// The type of the preference value\n /// The preference key\n /// The default value to return if the preference does not exist\n /// The preference value, or the default value if not found\n public async Task GetPreferenceAsync(string key, T defaultValue)\n {\n var preferences = await GetPreferencesAsync();\n \n if (preferences.TryGetValue(key, out var value))\n {\n try\n {\n // Log the actual type and value for debugging\n _logService.Log(LogLevel.Debug, $\"GetPreferenceAsync for key '{key}': value type = {value?.GetType().FullName}, value = {value}\");\n \n // Special case for DontShowSupport boolean preference\n if (key == \"DontShowSupport\" && typeof(T) == typeof(bool))\n {\n // Direct string comparison for known boolean values\n if (value != null)\n {\n string valueStr = value.ToString().ToLowerInvariant();\n if (valueStr == \"true\" || valueStr == \"1\")\n {\n _logService.Log(LogLevel.Debug, $\"DontShowSupport detected as TRUE\");\n return (T)(object)true;\n }\n else if (valueStr == \"false\" || valueStr == \"0\")\n {\n _logService.Log(LogLevel.Debug, $\"DontShowSupport detected as FALSE\");\n return (T)(object)false;\n }\n }\n }\n \n if (value is T typedValue)\n {\n return typedValue;\n }\n \n // Handle JToken conversion for primitive types\n if (value is Newtonsoft.Json.Linq.JToken jToken)\n {\n // For boolean JToken values, handle them explicitly\n if (typeof(T) == typeof(bool))\n {\n if (jToken.Type == Newtonsoft.Json.Linq.JTokenType.Boolean)\n {\n // Use ToObject instead of Value\n bool boolValue = (bool)jToken.ToObject(typeof(bool));\n _logService.Log(LogLevel.Debug, $\"JToken boolean value: {boolValue}\");\n return (T)(object)boolValue;\n }\n else if (jToken.Type == Newtonsoft.Json.Linq.JTokenType.String)\n {\n // Use ToString() instead of Value\n string strValue = jToken.ToString();\n if (bool.TryParse(strValue, out bool boolResult))\n {\n _logService.Log(LogLevel.Debug, $\"JToken string parsed as boolean: {boolResult}\");\n return (T)(object)boolResult;\n }\n }\n else if (jToken.Type == Newtonsoft.Json.Linq.JTokenType.Integer)\n {\n // Use ToObject instead of Value\n int intValue = (int)jToken.ToObject(typeof(int));\n bool boolValue = intValue != 0;\n _logService.Log(LogLevel.Debug, $\"JToken integer converted to boolean: {boolValue}\");\n return (T)(object)boolValue;\n }\n }\n \n var result = jToken.ToObject();\n _logService.Log(LogLevel.Debug, $\"JToken converted to {typeof(T).Name}: {result}\");\n return result;\n }\n \n // Special handling for boolean values\n if (typeof(T) == typeof(bool) && value != null)\n {\n // Handle string representations of boolean values\n if (value is string strValue)\n {\n if (bool.TryParse(strValue, out bool boolResult))\n {\n _logService.Log(LogLevel.Debug, $\"String value '{strValue}' parsed as boolean: {boolResult}\");\n return (T)(object)boolResult;\n }\n \n // Also check for \"1\" and \"0\" string values\n if (strValue == \"1\")\n {\n _logService.Log(LogLevel.Debug, $\"String value '1' converted to boolean: true\");\n return (T)(object)true;\n }\n else if (strValue == \"0\")\n {\n _logService.Log(LogLevel.Debug, $\"String value '0' converted to boolean: false\");\n return (T)(object)false;\n }\n }\n \n // Handle numeric representations (0 = false, non-zero = true)\n if (value is long || value is int || value is double || value is float)\n {\n double numValue = Convert.ToDouble(value);\n bool boolResult2 = numValue != 0; // Renamed to avoid conflict\n _logService.Log(LogLevel.Debug, $\"Numeric value {numValue} converted to boolean: {boolResult2}\");\n return (T)(object)boolResult2;\n }\n \n // Handle direct boolean values\n if (value is bool boolValue)\n {\n _logService.Log(LogLevel.Debug, $\"Direct boolean value: {boolValue}\");\n return (T)(object)boolValue;\n }\n }\n \n // Try to convert the value to the requested type\n var convertedValue = (T)Convert.ChangeType(value, typeof(T));\n _logService.Log(LogLevel.Debug, $\"Converted value to {typeof(T).Name}: {convertedValue}\");\n return convertedValue;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error converting preference value for key '{key}': {ex.Message}\");\n if (ex.InnerException != null)\n {\n _logService.Log(LogLevel.Error, $\"Inner exception: {ex.InnerException.Message}\");\n }\n _logService.Log(LogLevel.Error, $\"Stack trace: {ex.StackTrace}\");\n return defaultValue;\n }\n }\n \n _logService.Log(LogLevel.Debug, $\"Preference '{key}' not found, returning default value: {defaultValue}\");\n return defaultValue;\n }\n\n /// \n /// Sets a specific preference value\n /// \n /// The type of the preference value\n /// The preference key\n /// The preference value\n /// True if successful, false otherwise\n public async Task SetPreferenceAsync(string key, T value)\n {\n try\n {\n var preferences = await GetPreferencesAsync();\n \n // Log the preference being set\n _logService.Log(LogLevel.Debug, $\"Setting preference '{key}' to '{value}'\");\n \n preferences[key] = value;\n \n bool result = await SavePreferencesAsync(preferences);\n \n // Log the result\n if (result)\n {\n _logService.Log(LogLevel.Info, $\"Successfully saved preference '{key}'\");\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to save preference '{key}'\");\n }\n \n return result;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting preference '{key}': {ex.Message}\");\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/WindowsAppsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.SoftwareApps.Models;\nusing ToastType = Winhance.Core.Features.UI.Interfaces.ToastType;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n public partial class WindowsAppsViewModel : BaseInstallationViewModel\n {\n private readonly IAppInstallationService _appInstallationService;\n private readonly ICapabilityInstallationService _capabilityService;\n private readonly IFeatureInstallationService _featureService;\n private readonly IFeatureRemovalService _featureRemovalService;\n private readonly IAppService _appDiscoveryService;\n private readonly IConfigurationService _configurationService;\n private readonly IScriptDetectionService _scriptDetectionService;\n private readonly IInternetConnectivityService _connectivityService;\n private readonly IAppInstallationCoordinatorService _appInstallationCoordinatorService;\n\n [ObservableProperty]\n private string _statusText = \"Ready\";\n\n [ObservableProperty]\n private bool _isRemovingApps;\n\n [ObservableProperty]\n private ObservableCollection _activeScripts = new();\n\n // Flag to prevent duplicate initialization\n [ObservableProperty]\n private bool _isInitialized = false;\n\n // For binding in the WindowsAppsView - filtered collections\n // Standard Windows Apps (Appx packages)\n public System.Collections.ObjectModel.ObservableCollection WindowsApps { get; } =\n new();\n\n // Windows Capabilities\n public System.Collections.ObjectModel.ObservableCollection Capabilities { get; } =\n new();\n\n // Optional Features\n public System.Collections.ObjectModel.ObservableCollection OptionalFeatures { get; } =\n new();\n\n public WindowsAppsViewModel(\n ITaskProgressService progressService,\n ISearchService searchService,\n IPackageManager packageManager,\n IAppInstallationService appInstallationService,\n ICapabilityInstallationService capabilityService,\n IFeatureInstallationService featureService,\n IFeatureRemovalService featureRemovalService,\n IConfigurationService configurationService,\n IScriptDetectionService scriptDetectionService,\n IInternetConnectivityService connectivityService,\n IAppInstallationCoordinatorService appInstallationCoordinatorService,\n Services.SoftwareAppsDialogService dialogService\n )\n : base(\n progressService,\n searchService,\n packageManager,\n appInstallationService,\n appInstallationCoordinatorService,\n connectivityService,\n dialogService\n )\n {\n _appInstallationService = appInstallationService;\n _capabilityService = capabilityService;\n _featureService = featureService;\n _featureRemovalService = featureRemovalService;\n _appDiscoveryService = packageManager?.AppDiscoveryService;\n _configurationService = configurationService;\n _scriptDetectionService = scriptDetectionService;\n _connectivityService = connectivityService;\n _appInstallationCoordinatorService = appInstallationCoordinatorService;\n }\n\n // SaveConfig and ImportConfig methods removed as part of unified configuration cleanup\n\n /// \n /// Applies the current search text to filter items.\n /// \n protected override void ApplySearch()\n {\n if (Items == null || Items.Count == 0)\n return;\n\n // Clear all collections\n WindowsApps.Clear();\n Capabilities.Clear();\n OptionalFeatures.Clear();\n\n // Filter items based on search text\n var filteredItems = FilterItems(Items);\n\n // Add filtered items to their respective collections\n foreach (var app in filteredItems)\n {\n switch (app.AppType)\n {\n case Models.WindowsAppType.StandardApp:\n WindowsApps.Add(app);\n break;\n case Models.WindowsAppType.Capability:\n Capabilities.Add(app);\n break;\n case Models.WindowsAppType.OptionalFeature:\n OptionalFeatures.Add(app);\n break;\n }\n }\n\n // Sort the filtered collections\n SortCollections();\n }\n\n /// \n /// Refreshes the script status information.\n /// \n public void RefreshScriptStatus()\n {\n if (_scriptDetectionService == null)\n return;\n\n IsRemovingApps = _scriptDetectionService.AreRemovalScriptsPresent();\n\n ActiveScripts.Clear();\n foreach (var script in _scriptDetectionService.GetActiveScripts())\n {\n ActiveScripts.Add(script);\n }\n }\n\n public override async Task LoadItemsAsync()\n {\n if (_appDiscoveryService == null)\n return;\n\n IsLoading = true;\n StatusText = \"Loading Windows apps...\";\n\n try\n {\n // Clear all collections\n Items.Clear();\n WindowsApps.Clear();\n Capabilities.Clear();\n OptionalFeatures.Clear();\n\n // Load standard Windows apps (Appx packages)\n var apps = await _appDiscoveryService.GetStandardAppsAsync();\n\n // Load capabilities\n var capabilities = await _appDiscoveryService.GetCapabilitiesAsync();\n\n // Load optional features\n var features = await _appDiscoveryService.GetOptionalFeaturesAsync();\n\n // Convert all to WindowsApp objects and add to the main collection\n foreach (var app in apps)\n {\n var windowsApp = WindowsApp.FromAppInfo(app);\n // AppType is already set in FromAppInfo\n Items.Add(windowsApp);\n WindowsApps.Add(windowsApp);\n }\n\n foreach (var capability in capabilities)\n {\n var windowsApp = WindowsApp.FromCapabilityInfo(capability);\n // AppType is already set in FromCapabilityInfo\n Items.Add(windowsApp);\n Capabilities.Add(windowsApp);\n }\n\n foreach (var feature in features)\n {\n var windowsApp = WindowsApp.FromFeatureInfo(feature);\n // AppType is already set in FromFeatureInfo\n Items.Add(windowsApp);\n OptionalFeatures.Add(windowsApp);\n }\n\n StatusText =\n $\"Loaded {WindowsApps.Count} apps, {Capabilities.Count} capabilities, and {OptionalFeatures.Count} features\";\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error loading Windows apps: {ex.Message}\";\n }\n finally\n {\n IsLoading = false;\n\n // Check script status\n RefreshScriptStatus();\n }\n }\n\n public override async Task CheckInstallationStatusAsync()\n {\n if (_appDiscoveryService == null)\n return;\n\n IsLoading = true;\n StatusText = \"Checking installation status...\";\n\n try\n {\n var statusResults = await _appDiscoveryService.GetBatchInstallStatusAsync(\n Items.Select(a => a.PackageName)\n );\n\n foreach (var app in Items)\n {\n if (statusResults.TryGetValue(app.PackageName, out bool isInstalled))\n {\n app.IsInstalled = isInstalled;\n }\n }\n\n // Sort all collections after we have the installation status\n SortCollections();\n\n StatusText = \"Installation status check complete\";\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error checking installation status: {ex.Message}\";\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n private void SortCollections()\n {\n // Sort apps within each collection by installed status (installed first) then alphabetically\n SortCollection(WindowsApps);\n SortCollection(Capabilities);\n SortCollection(OptionalFeatures);\n }\n\n private void SortCollection(\n System.Collections.ObjectModel.ObservableCollection collection\n )\n {\n var sorted = collection\n .OrderByDescending(app => app.IsInstalled) // Installed first\n .ThenBy(app => app.Name) // Then alphabetically\n .ToList();\n\n collection.Clear();\n foreach (var app in sorted)\n {\n collection.Add(app);\n }\n }\n\n #region Dialog Helper Methods\n\n /// \n /// Gets the past tense form of an operation type\n /// \n /// The operation type (e.g., \"Install\", \"Remove\")\n /// The past tense form of the operation type\n private string GetPastTense(string operationType)\n {\n if (string.IsNullOrEmpty(operationType))\n return string.Empty;\n\n return operationType.Equals(\"Remove\", StringComparison.OrdinalIgnoreCase)\n ? \"removed\"\n : $\"{operationType.ToLower()}ed\";\n }\n\n /// \n /// Shows a confirmation dialog before performing operations.\n /// \n /// Type of operation (Install/Remove)\n /// List of apps selected for the operation\n /// List of apps that will be skipped (optional)\n /// Dialog result (true if confirmed, false if canceled)\n private bool? ShowOperationConfirmationDialog(\n string operationType,\n IEnumerable selectedApps,\n IEnumerable? skippedApps = null\n )\n {\n // Use the base class implementation that uses the dialog service\n var result = ShowOperationConfirmationDialogAsync(\n operationType,\n selectedApps,\n skippedApps\n )\n .GetAwaiter()\n .GetResult();\n return result ? true : (bool?)false;\n }\n\n /// \n /// Shows an operation result dialog after operations complete.\n /// \n /// Type of operation (Install/Remove)\n /// Number of successful operations\n /// Total number of operations attempted\n /// List of successfully processed items\n /// List of failed items (optional)\n /// List of skipped items (optional)\n private void ShowOperationResultDialog(\n string operationType,\n int successCount,\n int totalCount,\n IEnumerable successItems,\n IEnumerable? failedItems = null,\n IEnumerable? skippedItems = null\n )\n {\n // Use the base class implementation that uses the dialog service\n base.ShowOperationResultDialog(\n operationType,\n successCount,\n totalCount,\n successItems,\n failedItems,\n skippedItems\n );\n }\n\n #endregion\n\n public async Task LoadAppsAndCheckInstallationStatusAsync()\n {\n if (IsInitialized)\n {\n System.Diagnostics.Debug.WriteLine(\n \"WindowsAppsViewModel already initialized, skipping LoadAppsAndCheckInstallationStatusAsync\"\n );\n return;\n }\n\n System.Diagnostics.Debug.WriteLine(\"Starting LoadAppsAndCheckInstallationStatusAsync\");\n await LoadItemsAsync();\n await CheckInstallationStatusAsync();\n\n // Set Select All to true by default when view loads\n IsAllSelected = true;\n\n // Mark as initialized after loading is complete\n IsInitialized = true;\n\n // Check script status\n RefreshScriptStatus();\n System.Diagnostics.Debug.WriteLine(\"Completed LoadAppsAndCheckInstallationStatusAsync\");\n }\n\n [RelayCommand]\n public async Task InstallApp(WindowsApp app)\n {\n if (app == null || _appInstallationService == null)\n System.Diagnostics.Debug.WriteLine(\n \"Starting LoadAppsAndCheckInstallationStatusAsync\"\n );\n await LoadItemsAsync();\n await CheckInstallationStatusAsync();\n\n // Set Select All to true by default when view loads\n IsAllSelected = true;\n bool isInternetConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(true);\n if (!isInternetConnected)\n {\n StatusText = \"No internet connection available. Installation cannot proceed.\";\n\n // Show dialog informing the user about the connectivity issue\n await ShowNoInternetConnectionDialogAsync();\n return;\n }\n\n // Show confirmation dialog\n bool? dialogResult = ShowOperationConfirmationDialog(\"Install\", new[] { app });\n\n // If user didn't confirm, exit\n if (dialogResult != true)\n {\n return;\n }\n\n IsLoading = true;\n StatusText = $\"Installing {app.Name}...\";\n\n // Setup cancellation for the installation process\n using var cts = new System.Threading.CancellationTokenSource();\n var cancellationToken = cts.Token;\n\n try\n {\n var progress = _progressService.CreateDetailedProgress();\n\n // Subscribe to installation status changes\n void OnInstallationStatusChanged(\n object sender,\n InstallationStatusChangedEventArgs e\n )\n {\n if (e.AppInfo.PackageID == app.PackageID)\n {\n StatusText = e.StatusMessage;\n }\n }\n\n // Register for status updates\n _appInstallationCoordinatorService.InstallationStatusChanged +=\n OnInstallationStatusChanged;\n\n try\n {\n // Use the coordinator service to handle installation, connectivity monitoring, and status reporting\n var coordinationResult =\n await _appInstallationCoordinatorService.InstallAppAsync(\n app.ToAppInfo(),\n progress,\n cancellationToken\n );\n\n if (coordinationResult.Success)\n {\n app.IsInstalled = true;\n StatusText = $\"Successfully installed {app.Name}\";\n\n // Show result dialog\n ShowOperationResultDialog(\"Install\", 1, 1, new[] { app.Name });\n }\n else\n {\n string errorMessage =\n coordinationResult.ErrorMessage\n ?? $\"Failed to install {app.Name}. Please try again.\";\n StatusText = errorMessage;\n\n // Determine the type of failure for the dialog\n if (coordinationResult.WasCancelled)\n {\n // Show cancellation dialog\n ShowOperationResultDialog(\n \"Install\",\n 0,\n 1,\n Array.Empty(),\n new[] { $\"{app.Name}: Installation was cancelled by user\" }\n );\n }\n else if (coordinationResult.WasConnectivityIssue)\n {\n // Show connectivity issue dialog\n ShowOperationResultDialog(\n \"Install\",\n 0,\n 1,\n Array.Empty(),\n new[]\n {\n $\"{app.Name}: Internet connection lost during installation. Please check your network connection and try again.\",\n }\n );\n }\n else\n {\n // Show general error dialog\n ShowOperationResultDialog(\n \"Install\",\n 0,\n 1,\n Array.Empty(),\n new[] { $\"{app.Name}: {errorMessage}\" }\n );\n }\n }\n }\n finally\n {\n // Always unregister from the event\n _appInstallationCoordinatorService.InstallationStatusChanged -=\n OnInstallationStatusChanged;\n }\n }\n catch (System.Exception ex)\n {\n // This should rarely happen as most exceptions are handled by the coordinator service\n StatusText = $\"Error installing {app.Name}: {ex.Message}\";\n\n // Show error dialog\n ShowOperationResultDialog(\n \"Install\",\n 0,\n 1,\n Array.Empty(),\n new[] { $\"{app.Name}: {ex.Message}\" }\n );\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n // The StartPeriodicConnectivityCheck method has been removed as this functionality is now handled by the AppInstallationCoordinatorService\n\n [RelayCommand]\n public async Task RemoveApp(WindowsApp app)\n {\n if (app == null || _packageManager == null)\n return;\n\n // Show confirmation dialog\n bool? dialogResult = ShowOperationConfirmationDialog(\"Remove\", new[] { app });\n\n // If user didn't confirm, exit\n if (dialogResult != true)\n {\n return;\n }\n\n IsLoading = true;\n StatusText = $\"Removing {app.Name}...\";\n bool success = false;\n\n try\n {\n // Check if this is a special app that requires special handling\n if (app.IsSpecialHandler && !string.IsNullOrEmpty(app.SpecialHandlerType))\n {\n // Use the appropriate special handler method\n switch (app.SpecialHandlerType)\n {\n case \"Edge\":\n success = await _packageManager.RemoveEdgeAsync();\n break;\n case \"OneDrive\":\n success = await _packageManager.RemoveOneDriveAsync();\n break;\n case \"OneNote\":\n success = await _packageManager.RemoveOneNoteAsync();\n break;\n default:\n success = await _packageManager.RemoveSpecialAppAsync(\n app.SpecialHandlerType\n );\n break;\n }\n\n if (success)\n {\n app.IsInstalled = false;\n StatusText = $\"Successfully removed special app: {app.Name}\";\n }\n else\n {\n StatusText = $\"Failed to remove special app: {app.Name}\";\n }\n }\n else\n {\n // Regular app removal\n bool isCapability =\n app.AppType\n == Winhance.WPF.Features.SoftwareApps.Models.WindowsAppType.Capability;\n success = await _packageManager.RemoveAppAsync(app.PackageName, isCapability);\n if (success)\n {\n app.IsInstalled = false;\n StatusText = $\"Successfully removed {app.Name}\";\n }\n else\n {\n StatusText = $\"Failed to remove {app.Name}\";\n }\n }\n\n // Show result dialog\n ShowOperationResultDialog(\n \"Remove\",\n success ? 1 : 0,\n 1,\n success ? new[] { app.Name } : Array.Empty(),\n success ? Array.Empty() : new[] { app.Name }\n );\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error removing {app.Name}: {ex.Message}\";\n\n // Show error dialog\n ShowOperationResultDialog(\n \"Remove\",\n 0,\n 1,\n Array.Empty(),\n new[] { $\"{app.Name}: {ex.Message}\" }\n );\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n public override async void OnNavigatedTo(object parameter)\n {\n try\n {\n // Only load data if not already initialized\n if (!IsInitialized)\n {\n await LoadAppsAndCheckInstallationStatusAsync();\n IsInitialized = true;\n }\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error loading apps: {ex.Message}\";\n IsLoading = false;\n // Log the error or handle it appropriately\n }\n }\n\n // Add IsAllSelected property for the \"Select All\" checkbox\n private bool _isAllSelected;\n public bool IsAllSelected\n {\n get => _isAllSelected;\n set\n {\n if (SetProperty(ref _isAllSelected, value))\n {\n // Apply to all items across all categories\n foreach (var app in WindowsApps)\n {\n app.IsSelected = value;\n }\n\n foreach (var capability in Capabilities)\n {\n capability.IsSelected = value;\n }\n\n foreach (var feature in OptionalFeatures)\n {\n feature.IsSelected = value;\n }\n }\n }\n }\n\n [RelayCommand]\n public async Task RemoveApps()\n {\n if (_packageManager == null)\n return;\n\n // Get selected items from all categories\n var selectedApps = WindowsApps.Where(a => a.IsSelected).ToList();\n var selectedCapabilities = Capabilities.Where(a => a.IsSelected).ToList();\n var selectedFeatures = OptionalFeatures.Where(a => a.IsSelected).ToList();\n\n // Combine all selected items\n var allSelectedItems = selectedApps\n .Concat(selectedCapabilities.Cast())\n .Concat(selectedFeatures.Cast())\n .ToList();\n\n int totalSelected = allSelectedItems.Count;\n\n if (totalSelected == 0)\n {\n StatusText = \"No items selected for removal\";\n return;\n }\n\n // Show confirmation dialog\n bool? dialogResult = ShowOperationConfirmationDialog(\"Remove\", allSelectedItems);\n\n // If user didn't confirm, exit\n if (dialogResult != true)\n {\n return;\n }\n\n // Use the ExecuteWithProgressAsync method from BaseViewModel to handle progress reporting\n await ExecuteWithProgressAsync(\n async (progress, cancellationToken) =>\n {\n int successCount = 0;\n int currentItem = 0;\n\n // Process standard Windows apps\n foreach (var app in selectedApps)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Removing app {app.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage = $\"Removing Windows App: {app.Name}\",\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", app.AppType.ToString() },\n { \"PackageName\", app.PackageName },\n { \"IsSystemProtected\", app.IsSystemProtected.ToString() },\n { \"CanBeReinstalled\", app.CanBeReinstalled.ToString() },\n { \"OperationType\", \"Remove\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n\n try\n {\n // Check if this is a special app that requires special handling\n if (\n app.IsSpecialHandler\n && !string.IsNullOrEmpty(app.SpecialHandlerType)\n )\n {\n // Use the appropriate special handler method\n bool success = false;\n switch (app.SpecialHandlerType)\n {\n case \"Edge\":\n success = await _packageManager.RemoveEdgeAsync();\n break;\n case \"OneDrive\":\n success = await _packageManager.RemoveOneDriveAsync();\n break;\n case \"OneNote\":\n success = await _packageManager.RemoveOneNoteAsync();\n break;\n default:\n success = await _packageManager.RemoveSpecialAppAsync(\n app.SpecialHandlerType\n );\n break;\n }\n\n if (success)\n {\n app.IsInstalled = false;\n successCount++;\n }\n }\n else\n {\n // Regular app removal\n bool success = await _packageManager.RemoveAppAsync(\n app.PackageName,\n false\n );\n if (success)\n {\n app.IsInstalled = false;\n successCount++;\n }\n }\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Successfully removed {app.Name}\",\n DetailedMessage =\n $\"Successfully removed Windows App: {app.Name}\",\n LogLevel = LogLevel.Success,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", app.AppType.ToString() },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Success\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Error removing {app.Name}\",\n DetailedMessage = $\"Error removing {app.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", app.AppType.ToString() },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Error\" },\n { \"ErrorMessage\", ex.Message },\n { \"ErrorType\", ex.GetType().Name },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n\n // Process capabilities\n foreach (var capability in selectedCapabilities)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Removing capability {capability.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage = $\"Removing Windows Capability: {capability.Name}\",\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", capability.AppType.ToString() },\n { \"PackageName\", capability.PackageName },\n {\n \"IsSystemProtected\",\n capability.IsSystemProtected.ToString()\n },\n { \"CanBeReinstalled\", capability.CanBeReinstalled.ToString() },\n { \"OperationType\", \"Remove\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n\n try\n {\n bool success = await _packageManager.RemoveAppAsync(\n capability.PackageName,\n true\n );\n\n if (success)\n {\n capability.IsInstalled = false;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Successfully removed capability {capability.Name}\",\n DetailedMessage =\n $\"Successfully removed Windows Capability: {capability.Name}\",\n LogLevel = LogLevel.Success,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", capability.AppType.ToString() },\n { \"PackageName\", capability.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Success\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n else\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Failed to remove capability {capability.Name}\",\n DetailedMessage =\n $\"Failed to remove Windows Capability: {capability.Name}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", capability.AppType.ToString() },\n { \"PackageName\", capability.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Error\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Error removing capability {capability.Name}\",\n DetailedMessage =\n $\"Error removing capability {capability.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", capability.AppType.ToString() },\n { \"PackageName\", capability.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Error\" },\n { \"ErrorMessage\", ex.Message },\n { \"ErrorType\", ex.GetType().Name },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n\n // Process optional features\n foreach (var feature in selectedFeatures)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Removing feature {feature.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage = $\"Removing Windows Feature: {feature.Name}\",\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", feature.AppType.ToString() },\n { \"PackageName\", feature.PackageName },\n { \"IsSystemProtected\", feature.IsSystemProtected.ToString() },\n { \"CanBeReinstalled\", feature.CanBeReinstalled.ToString() },\n { \"OperationType\", \"Remove\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n\n try\n {\n if (_featureRemovalService != null)\n {\n bool success = await _featureRemovalService.RemoveFeatureAsync(\n feature.ToFeatureInfo()\n );\n if (success)\n {\n feature.IsInstalled = false;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Successfully removed feature {feature.Name}\",\n DetailedMessage =\n $\"Successfully removed Windows Feature: {feature.Name}\",\n LogLevel = LogLevel.Success,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", feature.AppType.ToString() },\n { \"PackageName\", feature.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Success\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n else\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Failed to remove feature {feature.Name}\",\n DetailedMessage =\n $\"Failed to remove Windows Feature: {feature.Name}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", feature.AppType.ToString() },\n { \"PackageName\", feature.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Error\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Error removing feature {feature.Name}\",\n DetailedMessage =\n $\"Error removing feature {feature.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", feature.AppType.ToString() },\n { \"PackageName\", feature.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Error\" },\n { \"ErrorMessage\", ex.Message },\n { \"ErrorType\", ex.GetType().Name },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n\n // Final report\n progress.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText =\n $\"Successfully removed {successCount} of {totalSelected} items\",\n DetailedMessage =\n $\"Task completed: {successCount} of {totalSelected} items removed successfully\",\n LogLevel =\n successCount == totalSelected ? LogLevel.Success : LogLevel.Warning,\n AdditionalInfo = new Dictionary\n {\n { \"OperationType\", \"Remove\" },\n {\n \"OperationStatus\",\n successCount == totalSelected ? \"Complete\" : \"PartialSuccess\"\n },\n { \"SuccessCount\", successCount.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n { \"SuccessRate\", $\"{(successCount * 100.0 / totalSelected):F1}%\" },\n { \"StandardAppsCount\", selectedApps.Count.ToString() },\n { \"CapabilitiesCount\", selectedCapabilities.Count.ToString() },\n { \"FeaturesCount\", selectedFeatures.Count.ToString() },\n {\n \"CompletionTime\",\n System.DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\")\n },\n },\n }\n );\n\n // Refresh the UI\n SortCollections();\n\n // Check if the operation was cancelled by the user or due to connectivity issues\n if (CurrentCancellationReason == CancellationReason.UserCancelled)\n {\n // Log the user cancellation\n System.Diagnostics.Debug.WriteLine(\"[DEBUG] Installation cancelled by user - showing user cancellation dialog\");\n \n // Show the cancellation dialog\n await ShowCancellationDialogAsync(true, false);\n \n // Reset cancellation reason after showing dialog\n CurrentCancellationReason = CancellationReason.None;\n return successCount;\n }\n else if (CurrentCancellationReason == CancellationReason.InternetConnectivityLost)\n {\n // Log the connectivity loss\n System.Diagnostics.Debug.WriteLine(\"[DEBUG] Installation stopped due to connectivity loss - showing connectivity loss dialog\");\n \n // Show the connectivity loss dialog\n await ShowCancellationDialogAsync(false, true);\n \n // Reset cancellation reason after showing dialog\n CurrentCancellationReason = CancellationReason.None;\n return successCount;\n }\n \n // Only proceed with normal completion reporting if not cancelled\n // For normal completion (not cancelled), collect success and failure information\n var successItems = new List();\n var failedItems = new List();\n\n // Add successful items to the list\n foreach (var app in selectedApps.Where(a => !a.IsInstalled))\n {\n successItems.Add(app.Name);\n }\n foreach (var capability in selectedCapabilities.Where(c => !c.IsInstalled))\n {\n successItems.Add(capability.Name);\n }\n foreach (var feature in selectedFeatures.Where(f => !f.IsInstalled))\n {\n successItems.Add(feature.Name);\n }\n\n // Add failed items to the list\n foreach (var app in selectedApps.Where(a => a.IsInstalled))\n {\n failedItems.Add(app.Name);\n }\n foreach (var capability in selectedCapabilities.Where(c => c.IsInstalled))\n {\n failedItems.Add(capability.Name);\n }\n foreach (var feature in selectedFeatures.Where(f => f.IsInstalled))\n {\n failedItems.Add(feature.Name);\n }\n\n // Show result dialog\n ShowOperationResultDialog(\n \"Remove\",\n successCount,\n totalSelected,\n successItems,\n failedItems\n );\n\n return successCount;\n },\n $\"Removing {totalSelected} items\",\n false\n );\n }\n\n [RelayCommand]\n public async Task InstallApps()\n {\n if (\n _packageManager == null\n || _appInstallationService == null\n || _capabilityService == null\n || _featureService == null\n )\n return;\n\n // Get all selected items\n var selectedApps = WindowsApps.Where(a => a.IsSelected).ToList();\n var selectedCapabilities = Capabilities.Where(a => a.IsSelected).ToList();\n var selectedFeatures = OptionalFeatures.Where(a => a.IsSelected).ToList();\n\n // Check if anything is selected at all\n int totalSelected =\n selectedApps.Count + selectedCapabilities.Count + selectedFeatures.Count;\n\n if (totalSelected == 0)\n {\n StatusText = \"No items selected for installation\";\n await ShowNoItemsSelectedDialogAsync(\"installation\");\n return;\n }\n\n // Identify items that cannot be reinstalled\n var nonReinstallableApps = selectedApps.Where(a => !a.CanBeReinstalled).ToList();\n var nonReinstallableCapabilities = selectedCapabilities\n .Where(c => !c.CanBeReinstalled)\n .ToList();\n var nonReinstallableFeatures = selectedFeatures\n .Where(f => !f.CanBeReinstalled)\n .ToList();\n\n var allNonReinstallableItems = nonReinstallableApps\n .Concat(nonReinstallableCapabilities)\n .Concat(nonReinstallableFeatures)\n .ToList();\n\n // Remove non-reinstallable items from the selected items\n var installableApps = selectedApps.Except(nonReinstallableApps).ToList();\n var installableCapabilities = selectedCapabilities\n .Except(nonReinstallableCapabilities)\n .ToList();\n var installableFeatures = selectedFeatures.Except(nonReinstallableFeatures).ToList();\n\n var allInstallableItems = installableApps\n .Concat(installableCapabilities.Cast())\n .Concat(installableFeatures.Cast())\n .ToList();\n\n if (allInstallableItems.Count == 0)\n {\n if (allNonReinstallableItems.Any())\n {\n // Show dialog explaining that all selected items cannot be reinstalled\n await ShowCannotReinstallDialogAsync(\n allNonReinstallableItems.Select(a => a.Name),\n false\n );\n }\n else\n {\n StatusText = \"No items selected for installation\";\n }\n return;\n }\n\n // Show confirmation dialog, including information about skipped items\n // Show confirmation dialog\n bool? dialogResult = await ShowConfirmItemsDialogAsync(\n \"install\",\n allInstallableItems.Select(a => a.Name),\n allInstallableItems.Count\n );\n\n // If user didn't confirm, exit\n if (dialogResult != true)\n {\n return;\n }\n\n // Check for internet connectivity before starting installation\n bool isInternetConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(true);\n if (!isInternetConnected)\n {\n StatusText = \"No internet connection available. Installation cannot proceed.\";\n\n // Show dialog informing the user about the connectivity issue\n await ShowNoInternetConnectionDialogAsync();\n return;\n }\n\n // Use the ExecuteWithProgressAsync method from BaseViewModel to handle progress reporting\n await ExecuteWithProgressAsync(\n async (progress, cancellationToken) =>\n {\n int successCount = 0;\n int currentItem = 0;\n\n // Process standard Windows apps\n foreach (var app in installableApps)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Installing app {app.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage = $\"Installing Windows App: {app.Name}\",\n }\n );\n\n try\n {\n var result = await _appInstallationService.InstallAppAsync(\n app.ToAppInfo(),\n progress,\n cancellationToken\n );\n\n // Only mark as successful if the operation actually succeeded\n if (result.Success && result.Result)\n {\n app.IsInstalled = true;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage = $\"Successfully installed {app.Name}\",\n LogLevel = LogLevel.Success,\n }\n );\n }\n else\n {\n // The operation returned but was not successful\n string errorMessage =\n result.ErrorMessage\n ?? \"Unknown error occurred during installation\";\n\n // Check if it's an internet connectivity issue\n if (\n errorMessage.Contains(\"internet\")\n || errorMessage.Contains(\"connection\")\n )\n {\n errorMessage =\n $\"No internet connection available. Please check your network connection and try again.\";\n }\n\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage =\n $\"Failed to install {app.Name}: {errorMessage}\",\n LogLevel = LogLevel.Error,\n }\n );\n }\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage = $\"Error installing {app.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n }\n }\n\n // Process capabilities\n foreach (var capability in installableCapabilities)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Installing capability {capability.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage =\n $\"Installing Windows Capability: {capability.Name}\",\n }\n );\n\n try\n {\n await _capabilityService.InstallCapabilityAsync(\n capability.ToCapabilityInfo(),\n progress,\n cancellationToken\n );\n capability.IsInstalled = true;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage =\n $\"Successfully installed capability {capability.Name}\",\n LogLevel = LogLevel.Success,\n }\n );\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage =\n $\"Error installing capability {capability.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n }\n }\n\n // Process optional features\n foreach (var feature in installableFeatures)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Installing feature {feature.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage = $\"Installing Windows Feature: {feature.Name}\",\n }\n );\n\n try\n {\n await _featureService.InstallFeatureAsync(\n feature.ToFeatureInfo(),\n progress,\n cancellationToken\n );\n feature.IsInstalled = true;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage =\n $\"Successfully installed feature {feature.Name}\",\n LogLevel = LogLevel.Success,\n }\n );\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage =\n $\"Error installing feature {feature.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n }\n }\n\n // Final report\n progress.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText =\n $\"Successfully installed {successCount} of {totalSelected} items\",\n DetailedMessage =\n $\"Task completed: {successCount} of {totalSelected} items installed successfully\",\n LogLevel =\n successCount == totalSelected ? LogLevel.Success : LogLevel.Warning,\n }\n );\n\n // Refresh the UI\n SortCollections();\n\n // Collect success, failure, and skipped information for the result dialog\n var successItems = new List();\n var failedItems = new List();\n var skippedItems = allNonReinstallableItems.Select(i => i.Name).ToList();\n\n // Add successful items to the list\n foreach (var app in installableApps.Where(a => a.IsInstalled))\n {\n successItems.Add(app.Name);\n }\n foreach (var capability in installableCapabilities.Where(c => c.IsInstalled))\n {\n successItems.Add(capability.Name);\n }\n foreach (var feature in installableFeatures.Where(f => f.IsInstalled))\n {\n successItems.Add(feature.Name);\n }\n\n // Add failed items to the list\n foreach (var app in installableApps.Where(a => !a.IsInstalled))\n {\n failedItems.Add(app.Name);\n }\n foreach (var capability in installableCapabilities.Where(c => !c.IsInstalled))\n {\n failedItems.Add(capability.Name);\n }\n foreach (var feature in installableFeatures.Where(f => !f.IsInstalled))\n {\n failedItems.Add(feature.Name);\n }\n\n // Show result dialog\n ShowOperationResultDialog(\n \"Install\",\n successCount,\n totalSelected + skippedItems.Count,\n successItems,\n failedItems,\n skippedItems\n );\n\n return successCount;\n },\n $\"Installing {totalSelected} items\",\n false\n );\n }\n\n #region BaseInstallationViewModel Abstract Method Implementations\n\n /// \n /// Gets the name of a Windows app.\n /// \n /// The Windows app.\n /// The name of the app.\n protected override string GetAppName(WindowsApp app)\n {\n return app.Name;\n }\n\n /// \n /// Converts a Windows app to an AppInfo object.\n /// \n /// The Windows app to convert.\n /// The AppInfo object.\n protected override AppInfo ToAppInfo(WindowsApp app)\n {\n return app.ToAppInfo();\n }\n\n /// \n /// Gets the selected Windows apps.\n /// \n /// The selected Windows apps.\n protected override IEnumerable GetSelectedApps()\n {\n return Items.Where(a => a.IsSelected);\n }\n\n /// \n /// Sets the installation status of a Windows app.\n /// \n /// The Windows app.\n /// Whether the app is installed.\n protected override void SetInstallationStatus(WindowsApp app, bool isInstalled)\n {\n app.IsInstalled = isInstalled;\n }\n\n #endregion\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/ViewModels/WindowsThemeCustomizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.Customize.Models;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Customize.ViewModels\n{\n /// \n /// ViewModel for Windows Theme customizations.\n /// \n public partial class WindowsThemeCustomizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDialogService _dialogService;\n private readonly IThemeService _themeService;\n private readonly WindowsThemeSettings _themeSettings;\n private readonly IRegistryService _registryService;\n\n // Flags to prevent triggering dark mode action during property change\n private bool _isHandlingDarkModeChange = false;\n private bool _isShowingDialog = false;\n \n // Store the original state before any changes\n private bool _originalDarkModeState;\n private string _originalTheme = string.Empty;\n \n // Store the requested state for the dialog\n private bool _requestedDarkModeState;\n private string _requestedTheme = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether dark mode is enabled.\n /// \n [ObservableProperty]\n private bool _isDarkModeEnabled;\n \n /// \n /// Gets or sets a value indicating whether to change the wallpaper when changing the theme.\n /// \n [ObservableProperty]\n private bool _changeWallpaper;\n\n /// \n /// Gets a value indicating whether theme options are available.\n /// \n public bool HasThemeOptions => true;\n\n /// \n /// Gets the available theme options.\n /// \n public List ThemeOptions => new List { \"Light Mode\", \"Dark Mode\" };\n\n /// \n /// Gets or sets the selected theme.\n /// \n public string SelectedTheme\n {\n get => IsDarkModeEnabled ? \"Dark Mode\" : \"Light Mode\";\n set\n {\n if (value == \"Dark Mode\" && !IsDarkModeEnabled)\n {\n IsDarkModeEnabled = true;\n }\n else if (value == \"Light Mode\" && IsDarkModeEnabled)\n {\n IsDarkModeEnabled = false;\n }\n OnPropertyChanged();\n }\n }\n\n /// \n /// Gets the category name.\n /// \n public string CategoryName => \"Windows Theme\";\n\n /// \n /// Gets the command to apply the theme.\n /// \n public ICommand ApplyThemeCommand { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dialog service.\n /// The theme service.\n public WindowsThemeCustomizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDialogService dialogService,\n IThemeService themeService)\n : base(progressService, registryService, logService)\n {\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _themeService = themeService ?? throw new ArgumentNullException(nameof(themeService));\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n \n // Initialize the theme settings model\n _themeSettings = new WindowsThemeSettings(themeService);\n \n // Load the current theme state\n LoadDarkModeState();\n \n // Initialize commands\n ApplyThemeCommand = new AsyncRelayCommand(ApplyThemeWithConfirmationAsync);\n\n // Subscribe to property changes to handle dark mode toggle and theme selection\n this.PropertyChanged += (s, e) =>\n {\n // Skip if we're already handling a change or showing a dialog\n if (_isHandlingDarkModeChange || _isShowingDialog)\n return;\n \n if (e.PropertyName == nameof(IsDarkModeEnabled))\n {\n HandleDarkModePropertyChange();\n }\n else if (e.PropertyName == nameof(SelectedTheme))\n {\n HandleThemeSelectionChange();\n }\n };\n }\n\n /// \n /// Handles changes to the IsDarkModeEnabled property.\n /// \n private void HandleDarkModePropertyChange()\n {\n // Store the original state before any changes\n _originalDarkModeState = _themeService.IsDarkModeEnabled();\n _originalTheme = _originalDarkModeState ? \"Dark Mode\" : \"Light Mode\";\n \n // Store the requested state\n _requestedDarkModeState = IsDarkModeEnabled;\n _requestedTheme = IsDarkModeEnabled ? \"Dark Mode\" : \"Light Mode\";\n \n // Log the state change\n _logService.Log(LogLevel.Info, $\"Dark mode check completed. Is Dark Mode: {_originalDarkModeState}\");\n \n // Update the selected theme to match the dark mode state\n _isHandlingDarkModeChange = true;\n try\n {\n SelectedTheme = IsDarkModeEnabled ? \"Dark Mode\" : \"Light Mode\";\n \n // Update the theme settings model\n _themeSettings.IsDarkMode = IsDarkModeEnabled;\n \n // Update the theme selector setting if it exists\n UpdateThemeSelectorSetting();\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n \n // Prompt for confirmation\n PromptForThemeChange();\n }\n\n /// \n /// Handles changes to the SelectedTheme property.\n /// \n private void HandleThemeSelectionChange()\n {\n // Store the original state before any changes\n _originalDarkModeState = _themeService.IsDarkModeEnabled();\n _originalTheme = _originalDarkModeState ? \"Dark Mode\" : \"Light Mode\";\n \n // Store the requested state\n _requestedTheme = SelectedTheme;\n _requestedDarkModeState = SelectedTheme == \"Dark Mode\";\n \n // Log the state change\n _logService.Log(LogLevel.Info, $\"Theme mode changed to {SelectedTheme}\");\n \n // Update the dark mode state based on the selected theme\n _isHandlingDarkModeChange = true;\n try\n {\n IsDarkModeEnabled = SelectedTheme == \"Dark Mode\";\n \n // Update the theme settings model\n _themeSettings.IsDarkMode = IsDarkModeEnabled;\n \n // Update the theme selector setting if it exists\n UpdateThemeSelectorSetting();\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n \n // Prompt for confirmation\n PromptForThemeChange();\n }\n\n /// \n /// Loads the dark mode state.\n /// \n private void LoadDarkModeState()\n {\n try\n {\n // Load the current theme settings\n _themeSettings.LoadCurrentSettings();\n \n // Update the view model properties\n _isHandlingDarkModeChange = true;\n try\n {\n IsDarkModeEnabled = _themeSettings.IsDarkMode;\n SelectedTheme = _themeSettings.ThemeName;\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n\n // Store the original state\n _originalDarkModeState = IsDarkModeEnabled;\n _originalTheme = SelectedTheme;\n\n _logService.Log(LogLevel.Info, $\"Loaded theme settings: {SelectedTheme}\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading dark mode state: {ex.Message}\");\n IsDarkModeEnabled = true; // Default to dark mode if there's an error\n SelectedTheme = \"Dark Mode\"; // Set selected theme to match\n \n // Store the original state\n _originalDarkModeState = IsDarkModeEnabled;\n _originalTheme = SelectedTheme;\n }\n }\n\n /// \n /// Prompts the user for theme change confirmation.\n /// \n private async void PromptForThemeChange()\n {\n // Prevent multiple dialogs from being shown at once\n if (_isShowingDialog)\n {\n _logService.Log(LogLevel.Info, \"Dialog already showing, ignoring request\");\n return;\n }\n \n _isShowingDialog = true;\n \n try\n {\n // Store the current UI state before showing the dialog\n bool currentDarkModeState = IsDarkModeEnabled;\n string currentTheme = SelectedTheme;\n \n // Revert to the original state before showing the dialog\n // This ensures that if the user cancels, we're already in the original state\n _isHandlingDarkModeChange = true;\n try\n {\n IsDarkModeEnabled = _originalDarkModeState;\n SelectedTheme = _originalTheme;\n _themeSettings.IsDarkMode = _originalDarkModeState;\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n \n // Prompt user about wallpaper change\n _logService.Log(LogLevel.Info, \"Showing dialog for theme change confirmation\");\n \n // Use the DialogService to show the confirmation dialog\n var result = await _dialogService.ShowYesNoCancelAsync(\n $\"Would you also like to change to the default {(currentDarkModeState ? \"dark\" : \"light\")} theme wallpaper?\",\n \"Windows Theme Change\"\n );\n\n switch (result)\n {\n case true: // Yes - Change theme AND apply wallpaper\n _logService.Log(LogLevel.Info, \"User selected to apply theme with wallpaper\");\n _isHandlingDarkModeChange = true;\n try\n {\n // Apply the requested theme\n IsDarkModeEnabled = _requestedDarkModeState;\n SelectedTheme = _requestedTheme;\n ChangeWallpaper = true; // Store the user's preference\n \n // Update the theme settings model\n _themeSettings.IsDarkMode = _requestedDarkModeState;\n _themeSettings.ChangeWallpaper = true;\n \n // Apply the theme\n await ApplyThemeAsync(true);\n _logService.Log(LogLevel.Info, $\"Theme changed to {(IsDarkModeEnabled ? \"dark\" : \"light\")} mode with wallpaper\");\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n break;\n\n case false: // No - Change theme but DON'T change wallpaper\n _logService.Log(LogLevel.Info, \"User selected to apply theme without wallpaper\");\n _isHandlingDarkModeChange = true;\n try\n {\n // Apply the requested theme\n IsDarkModeEnabled = _requestedDarkModeState;\n SelectedTheme = _requestedTheme;\n ChangeWallpaper = false; // Store the user's preference\n \n // Update the theme settings model\n _themeSettings.IsDarkMode = _requestedDarkModeState;\n _themeSettings.ChangeWallpaper = false;\n \n // Apply the theme\n await ApplyThemeAsync(false);\n _logService.Log(LogLevel.Info, $\"Theme changed to {(IsDarkModeEnabled ? \"dark\" : \"light\")} mode without wallpaper\");\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n break;\n\n case null: // Cancel - Do NOTHING, just close dialog\n _logService.Log(LogLevel.Info, \"User canceled theme change - keeping original state\");\n break;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error toggling dark mode: {ex.Message}\");\n await _dialogService.ShowErrorAsync(\"Theme Error\", $\"Failed to switch themes: {ex.Message}\");\n\n // Revert the toggle and selected theme on error\n _isHandlingDarkModeChange = true;\n try\n {\n // Revert to the original state\n IsDarkModeEnabled = _originalDarkModeState;\n SelectedTheme = _originalTheme;\n _themeSettings.IsDarkMode = _originalDarkModeState;\n \n _logService.Log(LogLevel.Info, \"Reverted to original state after error\");\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n }\n finally\n {\n // Always reset the dialog flag\n _isShowingDialog = false;\n _logService.Log(LogLevel.Info, \"Dialog handling completed\");\n }\n }\n\n /// \n /// Applies the theme with confirmation dialog.\n /// \n /// Whether to change the wallpaper.\n /// A task representing the asynchronous operation.\n private async Task ApplyThemeWithConfirmationAsync(bool changeWallpaper)\n {\n // Store the current state\n bool currentDarkMode = IsDarkModeEnabled;\n \n // Prompt for confirmation\n var result = await _dialogService.ShowConfirmationAsync(\n \"Apply Theme\",\n $\"Are you sure you want to apply the {(currentDarkMode ? \"dark\" : \"light\")} theme?\"\n );\n \n if (result)\n {\n await ApplyThemeAsync(changeWallpaper);\n }\n }\n\n /// \n /// Applies the dark mode setting.\n /// \n /// Whether to change the wallpaper.\n /// A task representing the asynchronous operation.\n public async Task ApplyThemeAsync(bool changeWallpaper)\n {\n try\n {\n // Update the theme settings model\n _themeSettings.IsDarkMode = IsDarkModeEnabled;\n _themeSettings.ChangeWallpaper = changeWallpaper;\n \n // Apply the theme\n bool success = await _themeSettings.ApplyThemeAsync();\n \n if (success)\n {\n _logService.Log(LogLevel.Info, $\"Windows Dark Mode {(IsDarkModeEnabled ? \"enabled\" : \"disabled\")}\");\n }\n else\n {\n _logService.Log(LogLevel.Error, \"Failed to apply theme\");\n }\n \n return success;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying dark mode: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Loads the settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, \"Loading Windows theme settings\");\n\n // Load dark mode state\n LoadDarkModeState();\n \n // Clear existing settings\n Settings.Clear();\n \n // Add a searchable item for the Theme Selector\n var themeItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = \"ThemeSelector\",\n Name = \"Windows Theme\",\n Description = \"Select between light and dark theme for Windows\",\n GroupName = \"Windows Theme\",\n IsVisible = true,\n IsSelected = true, // Always mark as selected so it appears in the config list\n ControlType = ControlType.ComboBox,\n SelectedValue = SelectedTheme, // Store the selected theme directly\n // Create a registry setting for the theme selector\n RegistrySetting = new RegistrySetting\n {\n Category = \"WindowsTheme\",\n Hive = Microsoft.Win32.RegistryHive.CurrentUser,\n SubKey = WindowsThemeSettings.Registry.ThemesPersonalizeSubKey,\n Name = WindowsThemeSettings.Registry.AppsUseLightThemeName,\n RecommendedValue = SelectedTheme == \"Dark Mode\" ? 0 : 1,\n DefaultValue = 1,\n EnabledValue = SelectedTheme == \"Dark Mode\" ? 0 : 1,\n DisabledValue = SelectedTheme == \"Dark Mode\" ? 1 : 0,\n ValueType = Microsoft.Win32.RegistryValueKind.DWord,\n Description = \"Windows Theme Mode\",\n // Store the selected theme and wallpaper preference\n CustomProperties = new Dictionary\n {\n { \"SelectedTheme\", SelectedTheme },\n { \"ChangeWallpaper\", ChangeWallpaper },\n { \"ThemeOptions\", ThemeOptions } // Store available options\n }\n }\n };\n Settings.Add(themeItem);\n \n _logService.Log(LogLevel.Info, $\"Added {Settings.Count} searchable items for Windows Theme settings\");\n\n // Check the status of all settings\n await CheckSettingStatusesAsync();\n\n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading Windows theme settings: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, \"Checking status for Windows theme settings\");\n\n // Refresh dark mode state\n LoadDarkModeState();\n\n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Windows theme settings status: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n // Get status\n var status = setting.Status;\n string message = status switch\n {\n RegistrySettingStatus.Applied => \"Setting is applied with recommended value\",\n RegistrySettingStatus.NotApplied => \"Setting is not applied or using default value\",\n RegistrySettingStatus.Modified => \"Setting has a custom value different from recommended\",\n RegistrySettingStatus.Error => \"Error checking setting status\",\n _ => \"Unknown status\"\n };\n\n return message;\n }\n\n // ApplySelectedSettingsAsync and RestoreDefaultsAsync methods removed as part of the refactoring\n \n /// \n /// Updates the theme selector setting to match the current selected theme.\n /// \n private void UpdateThemeSelectorSetting()\n {\n // Find the theme selector setting\n var themeSelector = Settings.FirstOrDefault(s => s.Id == \"ThemeSelector\");\n if (themeSelector != null)\n {\n themeSelector.IsUpdatingFromCode = true;\n try\n {\n // Update the SelectedValue directly with the current theme\n themeSelector.SelectedValue = SelectedTheme;\n _logService.Log(LogLevel.Info, $\"Updated theme selector setting to {SelectedTheme}\");\n \n // Store the wallpaper preference and selected theme in the setting's additional properties\n // This will be used when saving/loading configurations\n // Create a new RegistrySetting object with updated values\n var customProperties = new Dictionary();\n customProperties[\"ChangeWallpaper\"] = ChangeWallpaper;\n customProperties[\"SelectedTheme\"] = SelectedTheme;\n customProperties[\"ThemeOptions\"] = ThemeOptions; // Store available options\n \n // Create a new RegistrySetting with the updated values\n var newRegistrySetting = new RegistrySetting\n {\n Category = \"WindowsTheme\",\n Hive = Microsoft.Win32.RegistryHive.CurrentUser,\n SubKey = WindowsThemeSettings.Registry.ThemesPersonalizeSubKey,\n Name = WindowsThemeSettings.Registry.AppsUseLightThemeName,\n RecommendedValue = SelectedTheme == \"Dark Mode\" ? 0 : 1,\n DefaultValue = 1,\n EnabledValue = SelectedTheme == \"Dark Mode\" ? 0 : 1,\n DisabledValue = SelectedTheme == \"Dark Mode\" ? 1 : 0,\n ValueType = Microsoft.Win32.RegistryValueKind.DWord,\n Description = \"Windows Theme Mode\",\n CustomProperties = customProperties\n };\n \n // Assign the new RegistrySetting to the theme selector\n themeSelector.RegistrySetting = newRegistrySetting;\n \n _logService.Log(LogLevel.Info, $\"Stored theme preferences: SelectedTheme={SelectedTheme}, ChangeWallpaper={ChangeWallpaper}\");\n }\n finally\n {\n themeSelector.IsUpdatingFromCode = false;\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/GamingandPerformanceOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Infrastructure.Features.Common.Registry;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Gaming and Performance optimizations.\n /// \n public partial class GamingandPerformanceOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n private readonly ICommandService _commandService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The command service.\n /// The view model locator.\n /// The settings registry.\n public GamingandPerformanceOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n ICommandService commandService,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n _commandService = commandService;\n }\n\n /// \n /// Loads the Gaming and Performance optimizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Gaming and Performance optimizations\n var gamingOptimizations = Core.Features.Optimize.Models.GamingandPerformanceOptimizations.GetGamingandPerformanceOptimizations();\n if (gamingOptimizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in gamingOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService, _commandService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsUpdatingFromCode = true, // Set this to true to allow RefreshStatus to set the correct state\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Info, $\"No registry settings found for {setting.Name}\");\n }\n \n // Set up command settings if available\n if (setting.CommandSettings.Count > 0)\n {\n settingItem.CommandSettings = setting.CommandSettings;\n _logService.Log(LogLevel.Info, $\"Setting up command settings for {setting.Name} with {setting.CommandSettings.Count} commands\");\n \n // Log details about each command setting for debugging\n foreach (var cmdSetting in setting.CommandSettings)\n {\n _logService.Log(LogLevel.Info, $\"Command setting: {cmdSetting.Id}, EnabledCommand={cmdSetting.EnabledCommand}, DisabledCommand={cmdSetting.DisabledCommand}, IsPrimary={cmdSetting.IsPrimary}\");\n }\n }\n\n // Add to the settings collection\n Settings.Add(settingItem);\n }\n\n // Register settings with the settings registry if available\n foreach (var setting in Settings)\n {\n if (_settingsRegistry != null && !string.IsNullOrEmpty(setting.Id))\n {\n _settingsRegistry.RegisterSetting(setting);\n _logService.Log(LogLevel.Info, $\"Registered setting {setting.Id} in settings registry during creation\");\n }\n }\n\n // Refresh status for all settings to populate LinkedRegistrySettingsWithValues\n foreach (var setting in Settings)\n {\n await setting.RefreshStatus();\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading Gaming and Performance optimizations: {ex.Message}\");\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all gaming and performance settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, $\"Checking status for {Settings.Count} gaming and performance settings\");\n\n foreach (var setting in Settings)\n {\n try\n {\n if (setting.RegistrySetting != null)\n {\n _logService.Log(LogLevel.Info, $\"Checking status for setting: {setting.Name}\");\n\n // Get the status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // Get the current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name}: {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Add to LinkedRegistrySettingsWithValues for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Checking linked registry settings status for: {setting.Name} with {setting.LinkedRegistrySettings.Settings.Count} registry entries\");\n\n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(regSetting.Hive);\n string fullPath = $\"{hiveString}\\\\{regSetting.SubKey}\";\n _logService.Log(LogLevel.Info, $\"Registry entry: {fullPath}\\\\{regSetting.Name}, EnabledValue={regSetting.EnabledValue}, DisabledValue={regSetting.DisabledValue}\");\n\n // Check if the key exists\n bool keyExists = _registryService.KeyExists(fullPath);\n _logService.Log(LogLevel.Info, $\"Key exists: {keyExists}\");\n\n if (keyExists)\n {\n // Check if the value exists and get its current value\n var currentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value: {currentValue ?? \"null\"}\");\n }\n }\n\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n _logService.Log(LogLevel.Info, $\"Combined status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name} (first entry): {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value for linked setting {regSetting.Name}: {regCurrentValue ?? \"null\"}\");\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Registry setting is null for {setting.Name}\");\n setting.Status = RegistrySettingStatus.Unknown;\n setting.StatusMessage = \"Registry setting information is missing\";\n }\n\n // If this is a grouped setting, update child settings too\n if (setting.IsGroupedSetting && setting.ChildSettings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Updating {setting.ChildSettings.Count} child settings for {setting.Name}\");\n foreach (var childSetting in setting.ChildSettings)\n {\n if (childSetting.RegistrySetting != null)\n {\n var status = await _registryService.GetSettingStatusAsync(childSetting.RegistrySetting);\n childSetting.Status = status;\n\n var currentValue = await _registryService.GetCurrentValueAsync(childSetting.RegistrySetting);\n childSetting.CurrentValue = currentValue;\n\n childSetting.StatusMessage = GetStatusMessage(childSetting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Child setting {childSetting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n childSetting.IsUpdatingFromCode = true;\n try\n {\n childSetting.IsSelected = shouldBeSelected;\n }\n finally\n {\n childSetting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating status for setting {setting.Name}: {ex.Message}\");\n setting.Status = RegistrySettingStatus.Error;\n setting.StatusMessage = $\"Error: {ex.Message}\";\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking gaming and performance setting statuses: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0)\n return;\n\n var selectedCount = Settings.Count(setting => setting.IsSelected);\n IsSelected = selectedCount == Settings.Count;\n }\n\n /// \n /// Gets a user-friendly status message for a setting.\n /// \n /// The setting to get the status message for.\n /// A user-friendly status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied =>\n \"This setting is enabled (toggle is ON).\",\n\n RegistrySettingStatus.NotApplied =>\n setting.CurrentValue == null\n ? \"This setting is not applied (registry value does not exist).\"\n : \"This setting is disabled (toggle is OFF).\",\n\n RegistrySettingStatus.Modified =>\n \"This setting has a custom value that differs from both enabled and disabled values.\",\n\n RegistrySettingStatus.Error =>\n \"An error occurred while checking this setting's status.\",\n\n _ => \"The status of this setting is unknown.\"\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/CustomizeConfigurationApplier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.Customize.Models;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.Customize.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for applying configuration to the Customize section.\n /// \n public class CustomizeConfigurationApplier : ISectionConfigurationApplier\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n private readonly IViewModelRefresher _viewModelRefresher;\n private readonly IConfigurationPropertyUpdater _propertyUpdater;\n private readonly IThemeService _themeService;\n private readonly IDialogService _dialogService;\n\n /// \n /// Gets the section name that this applier handles.\n /// \n public string SectionName => \"Customize\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n /// The view model refresher.\n /// The property updater.\n /// The theme service.\n /// The dialog service.\n public CustomizeConfigurationApplier(\n IServiceProvider serviceProvider,\n ILogService logService,\n IViewModelRefresher viewModelRefresher,\n IConfigurationPropertyUpdater propertyUpdater,\n IThemeService themeService,\n IDialogService dialogService)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _viewModelRefresher = viewModelRefresher ?? throw new ArgumentNullException(nameof(viewModelRefresher));\n _propertyUpdater = propertyUpdater ?? throw new ArgumentNullException(nameof(propertyUpdater));\n _themeService = themeService ?? throw new ArgumentNullException(nameof(themeService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n }\n\n /// \n /// Applies the configuration to the Customize section.\n /// \n /// The configuration file to apply.\n /// True if any items were updated, false otherwise.\n public async Task ApplyConfigAsync(ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Applying configuration to CustomizeViewModel\");\n \n var viewModel = _serviceProvider.GetService();\n if (viewModel == null)\n {\n _logService.Log(LogLevel.Warning, \"CustomizeViewModel not available\");\n return false;\n }\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, \"CustomizeViewModel not initialized, initializing now\");\n await viewModel.InitializeCommand.ExecuteAsync(null);\n }\n \n int totalUpdatedCount = 0;\n \n // Handle Windows Theme customizations\n totalUpdatedCount += await ApplyWindowsThemeCustomizations(viewModel, configFile);\n \n // Apply the configuration directly to the view model's items\n int itemsUpdatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Items, configFile);\n totalUpdatedCount += itemsUpdatedCount;\n \n _logService.Log(LogLevel.Info, $\"Updated {totalUpdatedCount} items in CustomizeViewModel\");\n \n // Refresh the UI\n await _viewModelRefresher.RefreshViewModelAsync(viewModel);\n \n // After applying all configuration settings, prompt for cleaning taskbar and Start Menu\n await PromptForCleaningTaskbarAndStartMenu(viewModel);\n \n return totalUpdatedCount > 0;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying Customize configuration: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Prompts the user to clean the taskbar and Start Menu after configuration import.\n /// \n /// The customize view model.\n /// A task representing the asynchronous operation.\n private async Task PromptForCleaningTaskbarAndStartMenu(CustomizeViewModel viewModel)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Prompting for cleaning taskbar and Start Menu\");\n \n // Prompt for cleaning taskbar\n if (viewModel.TaskbarSettings != null)\n {\n // Use Application.Current.Dispatcher to ensure we're on the UI thread\n bool? cleanTaskbarResult = await Application.Current.Dispatcher.InvokeAsync(() => {\n return CustomDialog.ShowConfirmation(\n \"Clean Taskbar\",\n \"Do you want to clean the taskbar?\",\n new List { \"Cleaning the taskbar will remove pinned items and reset it to default settings.\" }, // Put message in the middle section\n \"\" // Empty footer\n );\n });\n \n bool cleanTaskbar = cleanTaskbarResult == true;\n \n if (cleanTaskbar)\n {\n _logService.Log(LogLevel.Info, \"User chose to clean the taskbar\");\n \n // Execute the clean taskbar command\n if (viewModel.TaskbarSettings.CleanTaskbarCommand != null && \n viewModel.TaskbarSettings.CleanTaskbarCommand.CanExecute(null))\n {\n await viewModel.TaskbarSettings.CleanTaskbarCommand.ExecuteAsync(null);\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"CleanTaskbarCommand not available\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Info, \"User chose not to clean the taskbar\");\n }\n }\n \n // Prompt for cleaning Start Menu\n if (viewModel.StartMenuSettings != null)\n {\n // Use Application.Current.Dispatcher to ensure we're on the UI thread\n bool? cleanStartMenuResult = await Application.Current.Dispatcher.InvokeAsync(() => {\n return CustomDialog.ShowConfirmation(\n \"Clean Start Menu\",\n \"Do you want to clean the Start Menu?\",\n new List { \"Cleaning the Start Menu will remove pinned items and reset it to default settings.\" }, // Put message in the middle section\n \"\" // Empty footer\n );\n });\n \n bool cleanStartMenu = cleanStartMenuResult == true;\n \n if (cleanStartMenu)\n {\n _logService.Log(LogLevel.Info, \"User chose to clean the Start Menu\");\n \n // Execute the clean Start Menu command\n if (viewModel.StartMenuSettings.CleanStartMenuCommand != null && \n viewModel.StartMenuSettings.CleanStartMenuCommand.CanExecute(null))\n {\n await viewModel.StartMenuSettings.CleanStartMenuCommand.ExecuteAsync(null);\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"CleanStartMenuCommand not available\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Info, \"User chose not to clean the Start Menu\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error prompting for cleaning taskbar and Start Menu: {ex.Message}\");\n }\n }\n\n private async Task ApplyWindowsThemeCustomizations(CustomizeViewModel viewModel, ConfigurationFile configFile)\n {\n int updatedCount = 0;\n \n try\n {\n // Get the WindowsThemeSettings property from the view model\n var windowsThemeViewModel = viewModel.WindowsThemeSettings;\n if (windowsThemeViewModel == null)\n {\n _logService.Log(LogLevel.Warning, \"WindowsThemeSettings not found in CustomizeViewModel\");\n return 0;\n }\n \n _logService.Log(LogLevel.Info, \"Found WindowsThemeSettings, checking for Theme Selector item\");\n \n // Check if there's a Theme Selector item in the config file\n var themeItem = configFile.Items?.FirstOrDefault(item =>\n (item.Name?.Contains(\"Windows Theme\") == true ||\n item.Name?.Contains(\"Theme Selector\") == true ||\n item.Name?.Contains(\"Choose Your Mode\") == true ||\n (item.CustomProperties.TryGetValue(\"Id\", out var id) && id?.ToString() == \"ThemeSelector\")));\n \n if (themeItem != null)\n {\n _logService.Log(LogLevel.Info, $\"Found Theme Selector item: {themeItem.Name}\");\n \n string newSelectedTheme = null;\n \n // Try to get SelectedTheme from CustomProperties first (preferred method)\n if (themeItem.CustomProperties.TryGetValue(\"SelectedTheme\", out var selectedTheme) && selectedTheme != null)\n {\n newSelectedTheme = selectedTheme.ToString();\n _logService.Log(LogLevel.Info, $\"Found SelectedTheme in CustomProperties: {newSelectedTheme}\");\n }\n // If not available, try to use SelectedValue directly\n else if (!string.IsNullOrEmpty(themeItem.SelectedValue))\n {\n newSelectedTheme = themeItem.SelectedValue;\n _logService.Log(LogLevel.Info, $\"Using SelectedValue directly: {newSelectedTheme}\");\n }\n // As a last resort, try to derive it from SliderValue (for backward compatibility)\n else if (themeItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int sliderValueInt = Convert.ToInt32(sliderValue);\n newSelectedTheme = sliderValueInt == 1 ? \"Dark Mode\" : \"Light Mode\";\n _logService.Log(LogLevel.Info, $\"Derived SelectedTheme from SliderValue {sliderValueInt}: {newSelectedTheme}\");\n }\n \n if (!string.IsNullOrEmpty(newSelectedTheme))\n {\n _logService.Log(LogLevel.Info, $\"Updating theme settings in view model to: {newSelectedTheme}\");\n \n // Store the current state of the view model\n bool currentIsDarkMode = windowsThemeViewModel.IsDarkModeEnabled;\n string currentTheme = windowsThemeViewModel.SelectedTheme;\n \n // Update the view model properties to trigger the property change handlers\n // This will show the wallpaper dialog through the normal UI flow\n try\n {\n // Update the IsDarkModeEnabled property first\n bool isDarkMode = newSelectedTheme == \"Dark Mode\";\n \n _logService.Log(LogLevel.Info, $\"Setting IsDarkModeEnabled to {isDarkMode}\");\n windowsThemeViewModel.IsDarkModeEnabled = isDarkMode;\n \n // Then update the SelectedTheme property\n _logService.Log(LogLevel.Info, $\"Setting SelectedTheme to {newSelectedTheme}\");\n windowsThemeViewModel.SelectedTheme = newSelectedTheme;\n \n // The property change handlers in WindowsThemeCustomizationsViewModel will\n // show the wallpaper dialog and apply the theme\n \n _logService.Log(LogLevel.Success, $\"Successfully triggered theme change UI flow for: {newSelectedTheme}\");\n updatedCount++;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating theme settings in view model: {ex.Message}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not determine SelectedTheme from config item\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Theme Selector item not found in config file\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying Windows theme customizations: {ex.Message}\");\n }\n \n return updatedCount;\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/UpdateOptimizationsViewModel.cs", "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Infrastructure.Features.Common.Registry;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Update optimizations.\n /// \n public partial class UpdateOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The view model locator.\n /// The settings registry.\n public UpdateOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n }\n\n /// \n /// Loads the update settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load update optimizations\n var updateOptimizations = Core.Features.Optimize.Models.UpdateOptimizations.GetUpdateOptimizations();\n if (updateOptimizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in updateOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsUpdatingFromCode = true, // Set this to true to allow RefreshStatus to set the correct state\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Add to the settings collection\n Settings.Add(settingItem);\n }\n\n // Register settings with the settings registry if available\n foreach (var setting in Settings)\n {\n if (_settingsRegistry != null && !string.IsNullOrEmpty(setting.Id))\n {\n _settingsRegistry.RegisterSetting(setting);\n _logService.Log(LogLevel.Info, $\"Registered setting {setting.Id} in settings registry during creation\");\n }\n }\n\n // Refresh status for all settings to populate LinkedRegistrySettingsWithValues\n foreach (var setting in Settings)\n {\n await setting.RefreshStatus();\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading update optimizations: {ex.Message}\");\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all Windows Update settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, $\"Checking status for {Settings.Count} Windows Update settings\");\n\n foreach (var setting in Settings)\n {\n try\n {\n if (setting.RegistrySetting != null)\n {\n _logService.Log(LogLevel.Info, $\"Checking status for setting: {setting.Name}\");\n\n // Get the status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // Get the current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name}: {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Add to LinkedRegistrySettingsWithValues for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Checking linked registry settings status for: {setting.Name} with {setting.LinkedRegistrySettings.Settings.Count} registry entries\");\n\n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(regSetting.Hive);\n string fullPath = $\"{hiveString}\\\\{regSetting.SubKey}\";\n _logService.Log(LogLevel.Info, $\"Registry entry: {fullPath}\\\\{regSetting.Name}, EnabledValue={regSetting.EnabledValue}, DisabledValue={regSetting.DisabledValue}\");\n\n // Check if the key exists\n bool keyExists = _registryService.KeyExists(fullPath);\n _logService.Log(LogLevel.Info, $\"Key exists: {keyExists}\");\n\n if (keyExists)\n {\n // Check if the value exists and get its current value\n var currentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value: {currentValue ?? \"null\"}\");\n }\n }\n\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n _logService.Log(LogLevel.Info, $\"Combined status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name} (first entry): {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value for linked setting {regSetting.Name}: {regCurrentValue ?? \"null\"}\");\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Registry setting is null for {setting.Name}\");\n setting.Status = RegistrySettingStatus.Unknown;\n setting.StatusMessage = \"Registry setting information is missing\";\n }\n\n // If this is a grouped setting, update child settings too\n if (setting.IsGroupedSetting && setting.ChildSettings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Updating {setting.ChildSettings.Count} child settings for {setting.Name}\");\n foreach (var childSetting in setting.ChildSettings)\n {\n if (childSetting.RegistrySetting != null)\n {\n var status = await _registryService.GetSettingStatusAsync(childSetting.RegistrySetting);\n childSetting.Status = status;\n\n var currentValue = await _registryService.GetCurrentValueAsync(childSetting.RegistrySetting);\n childSetting.CurrentValue = currentValue;\n\n childSetting.StatusMessage = GetStatusMessage(childSetting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Child setting {childSetting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n childSetting.IsUpdatingFromCode = true;\n try\n {\n childSetting.IsSelected = shouldBeSelected;\n }\n finally\n {\n childSetting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating status for setting {setting.Name}: {ex.Message}\");\n setting.Status = RegistrySettingStatus.Error;\n setting.StatusMessage = $\"Error: {ex.Message}\";\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Windows Update setting statuses: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0)\n return;\n\n var selectedCount = Settings.Count(setting => setting.IsSelected);\n IsSelected = selectedCount == Settings.Count;\n }\n\n /// \n /// Gets a user-friendly status message for a setting.\n /// \n /// The setting to get the status message for.\n /// A user-friendly status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied =>\n \"This setting is enabled (toggle is ON).\",\n\n RegistrySettingStatus.NotApplied =>\n setting.CurrentValue == null\n ? \"This setting is not applied (registry value does not exist).\"\n : \"This setting is disabled (toggle is OFF).\",\n\n RegistrySettingStatus.Modified =>\n \"This setting has a custom value that differs from both enabled and disabled values.\",\n\n RegistrySettingStatus.Error =>\n \"An error occurred while checking this setting's status.\",\n\n _ => \"The status of this setting is unknown.\"\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/ApplicationCloseService.cs", "using System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for handling application close functionality\n /// \n public class ApplicationCloseService : IApplicationCloseService\n {\n private readonly ILogService _logService;\n private readonly string _preferencesFilePath;\n \n /// \n /// Initializes a new instance of the class\n /// \n /// Service for logging\n public ApplicationCloseService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n \n // Set up the preferences file path\n _preferencesFilePath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Config\",\n \"UserPreferences.json\"\n );\n }\n \n /// \n public async Task CloseApplicationWithSupportDialogAsync()\n {\n try\n {\n _logService.LogInformation(\"Closing application with support dialog check\");\n \n // Check if we should show the dialog\n bool showDialog = await ShouldShowSupportDialogAsync();\n \n if (showDialog)\n {\n _logService.LogInformation(\"Showing donation dialog\");\n \n // Show the dialog\n string supportMessage = \"Your support helps keep this project going!\";\n var dialog = await DonationDialog.ShowDonationDialogAsync(\n \"Support Winhance\",\n supportMessage,\n \"Click 'Yes' to show your support!\"\n );\n \n _logService.LogInformation($\"Donation dialog completed with result: {dialog?.DialogResult}, DontShowAgain: {dialog?.DontShowAgain}\");\n \n // Save the \"Don't show again\" preference if checked\n if (dialog != null && dialog.DontShowAgain)\n {\n _logService.LogInformation(\"Saving DontShowSupport preference\");\n await SaveDontShowSupportPreferenceAsync(true);\n }\n \n // Open the donation page if the user clicked Yes\n if (dialog?.DialogResult == true)\n {\n _logService.LogInformation(\"User clicked Yes, opening donation page\");\n try\n {\n var psi = new ProcessStartInfo\n {\n FileName = \"https://ko-fi.com/memstechtips\",\n UseShellExecute = true,\n };\n Process.Start(psi);\n _logService.LogInformation(\"Donation page opened successfully\");\n }\n catch (Exception openEx)\n {\n _logService.LogError($\"Error opening donation page: {openEx.Message}\", openEx);\n }\n }\n }\n else\n {\n _logService.LogInformation(\"Skipping donation dialog due to user preference\");\n }\n \n // Close the application\n _logService.LogInformation(\"Shutting down application\");\n Application.Current.Dispatcher.Invoke(() => Application.Current.Shutdown());\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in CloseApplicationWithSupportDialogAsync: {ex.Message}\", ex);\n \n // Fallback to direct application shutdown\n try\n {\n _logService.LogInformation(\"Falling back to Application.Current.Shutdown()\");\n Application.Current.Dispatcher.Invoke(() => Application.Current.Shutdown());\n }\n catch (Exception shutdownEx)\n {\n _logService.LogError($\"Error shutting down application: {shutdownEx.Message}\", shutdownEx);\n \n // Last resort\n Environment.Exit(0);\n }\n }\n }\n \n /// \n public async Task ShouldShowSupportDialogAsync()\n {\n try\n {\n _logService.LogInformation($\"Checking preferences file: {_preferencesFilePath}\");\n \n // Check if the preference file exists and contains the DontShowSupport setting\n if (File.Exists(_preferencesFilePath))\n {\n string json = await File.ReadAllTextAsync(_preferencesFilePath);\n _logService.LogInformation($\"Preferences file content: {json}\");\n \n // Check if the preference is set to true\n if (\n json.Contains(\"\\\"DontShowSupport\\\": true\")\n || json.Contains(\"\\\"DontShowSupport\\\":true\")\n || json.Contains(\"\\\"DontShowSupport\\\": 1\")\n || json.Contains(\"\\\"DontShowSupport\\\":1\")\n )\n {\n _logService.LogInformation(\"DontShowSupport is set to true, skipping dialog\");\n return false;\n }\n }\n \n // Default to showing the dialog\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking donation dialog preference: {ex.Message}\", ex);\n // Default to showing the dialog if there's an error\n return true;\n }\n }\n \n /// \n public async Task SaveDontShowSupportPreferenceAsync(bool dontShow)\n {\n try\n {\n // Get the preferences directory path\n string preferencesDir = Path.GetDirectoryName(_preferencesFilePath);\n \n // Create the directory if it doesn't exist\n if (!Directory.Exists(preferencesDir))\n {\n Directory.CreateDirectory(preferencesDir);\n }\n \n // Create or update the preferences file\n string json = \"{}\";\n if (File.Exists(_preferencesFilePath))\n {\n json = await File.ReadAllTextAsync(_preferencesFilePath);\n }\n \n // Simple JSON manipulation (not ideal but should work for this case)\n if (json == \"{}\")\n {\n json = \"{ \\\"DontShowSupport\\\": \" + (dontShow ? \"true\" : \"false\") + \" }\";\n }\n else if (json.Contains(\"\\\"DontShowSupport\\\":\") || json.Contains(\"\\\"DontShowSupport\\\": \"))\n {\n json = json.Replace(\"\\\"DontShowSupport\\\": true\", \"\\\"DontShowSupport\\\": \" + (dontShow ? \"true\" : \"false\"));\n json = json.Replace(\"\\\"DontShowSupport\\\": false\", \"\\\"DontShowSupport\\\": \" + (dontShow ? \"true\" : \"false\"));\n json = json.Replace(\"\\\"DontShowSupport\\\":true\", \"\\\"DontShowSupport\\\":\" + (dontShow ? \"true\" : \"false\"));\n json = json.Replace(\"\\\"DontShowSupport\\\":false\", \"\\\"DontShowSupport\\\":\" + (dontShow ? \"true\" : \"false\"));\n }\n else\n {\n // Remove the closing brace\n json = json.TrimEnd('}');\n // Add a comma if there are other properties\n if (json.TrimEnd().EndsWith(\"}\"))\n {\n json += \",\";\n }\n // Add the new property and closing brace\n json += \" \\\"DontShowSupport\\\": \" + (dontShow ? \"true\" : \"false\") + \" }\";\n }\n \n // Write the updated JSON back to the file\n await File.WriteAllTextAsync(_preferencesFilePath, json);\n _logService.LogInformation($\"Successfully saved DontShowSupport preference: {dontShow}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error saving DontShowSupport preference: {ex.Message}\", ex);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppInstallationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Net.Http;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Enums;\nusing Winhance.Core.Features.SoftwareApps.Exceptions;\nusing Winhance.Core.Features.SoftwareApps.Helpers;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that installs standard applications.\n/// \npublic class AppInstallationService\n : BaseInstallationService,\n IAppInstallationService,\n IDisposable\n{\n private readonly string _tempDir = Path.Combine(Path.GetTempPath(), \"WinhanceInstaller\");\n private readonly HttpClient _httpClient;\n private readonly IScriptUpdateService _scriptUpdateService;\n private readonly ISystemServices _systemServices;\n private readonly IWinGetInstallationService _winGetInstallationService;\n private IProgress? _currentProgress;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The PowerShell execution service.\n /// The script update service.\n /// The system services.\n /// The WinGet installation service.\n public AppInstallationService(\n ILogService logService,\n IPowerShellExecutionService powerShellService,\n IScriptUpdateService scriptUpdateService,\n ISystemServices systemServices,\n IWinGetInstallationService winGetInstallationService\n )\n : base(logService, powerShellService)\n {\n _httpClient = new HttpClient();\n _scriptUpdateService = scriptUpdateService;\n _systemServices = systemServices;\n _winGetInstallationService = winGetInstallationService;\n Directory.CreateDirectory(_tempDir);\n }\n\n /// \n public Task> InstallAppAsync(\n AppInfo appInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default\n )\n {\n return InstallItemAsync(appInfo, progress, cancellationToken);\n }\n\n /// \n public Task> CanInstallAppAsync(AppInfo appInfo)\n {\n return CanInstallItemAsync(appInfo);\n }\n\n /// \n protected override async Task> PerformInstallationAsync(\n AppInfo appInfo,\n IProgress? progress,\n CancellationToken cancellationToken\n )\n {\n _currentProgress = progress;\n\n try\n {\n // Check for internet connectivity before starting the installation\n bool isConnected = await _systemServices.IsInternetConnectedAsync(\n true,\n cancellationToken\n );\n if (!isConnected)\n {\n string errorMessage =\n \"No internet connection available. Please check your network connection and try again.\";\n _logService.LogError(errorMessage);\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Installation failed: No internet connection\",\n DetailedMessage = errorMessage,\n LogLevel = LogLevel.Error,\n }\n );\n // Explicitly log failure for the specific app\n _logService.LogError(\n $\"Failed to install app: {appInfo.Name} - No internet connection\"\n );\n return OperationResult.Failed(errorMessage, false);\n }\n\n // Set up a periodic internet connectivity check\n var connectivityCheckTimer = new System.Timers.Timer(5000); // Check every 5 seconds\n bool installationCancelled = false;\n\n connectivityCheckTimer.Elapsed += async (s, e) =>\n {\n try\n {\n bool isStillConnected = await _systemServices.IsInternetConnectedAsync(\n false,\n cancellationToken\n );\n if (!isStillConnected && !installationCancelled)\n {\n installationCancelled = true;\n _logService.LogError(\"Internet connection lost during installation\");\n progress?.Report(\n new TaskProgressDetail\n {\n StatusText = \"Error: Internet connection lost\",\n DetailedMessage =\n \"Internet connection has been lost. Installation has been stopped.\",\n LogLevel = LogLevel.Error,\n }\n );\n\n // Stop the timer\n connectivityCheckTimer.Stop();\n\n // Throw an exception to stop the installation process\n throw new OperationCanceledException(\n \"Installation stopped due to internet connection loss\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in connectivity check: {ex.Message}\");\n connectivityCheckTimer.Stop();\n }\n };\n\n // Start the connectivity check timer\n connectivityCheckTimer.Start();\n bool success = false;\n\n // Verify internet connection again before attempting installation\n isConnected = await _systemServices.IsInternetConnectedAsync(true, cancellationToken);\n if (!isConnected)\n {\n string errorMessage =\n \"No internet connection available. Please check your network connection and try again.\";\n _logService.LogError(errorMessage);\n _logService.LogError(\n $\"Failed to install app: {appInfo.Name} - No internet connection\"\n );\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Installation failed: No internet connection\",\n DetailedMessage = errorMessage,\n LogLevel = LogLevel.Error,\n }\n );\n return OperationResult.Failed(errorMessage, false);\n }\n\n if (appInfo.PackageName.Equals(\"OneDrive\", StringComparison.OrdinalIgnoreCase))\n {\n // Special handling for OneDrive\n success = await InstallOneDriveAsync(progress, cancellationToken);\n }\n else if (appInfo.IsCustomInstall)\n {\n success = await InstallCustomAppAsync(appInfo, progress, cancellationToken);\n }\n else\n {\n // Use WinGet for all standard apps, including appx packages\n // Use PackageID if available, otherwise fall back to PackageName\n string packageIdentifier = !string.IsNullOrEmpty(appInfo.PackageID)\n ? appInfo.PackageID\n : appInfo.PackageName;\n\n // Pass the app's display name to use in progress messages\n try\n {\n // Pass the app's name for display in progress messages\n success = await _winGetInstallationService.InstallWithWingetAsync(\n packageIdentifier,\n progress,\n cancellationToken,\n appInfo.Name\n );\n\n // Double-check success - if WinGet returned success but we have no internet, consider it a failure\n if (success)\n {\n bool stillConnected = await _systemServices.IsInternetConnectedAsync(\n true,\n cancellationToken\n );\n if (!stillConnected)\n {\n _logService.LogError(\n $\"Internet connection lost during installation of {appInfo.Name}\"\n );\n success = false;\n throw new Exception(\"Internet connection lost during installation\");\n }\n }\n }\n catch (Exception ex)\n {\n success = false;\n _logService.LogError($\"Failed to install {appInfo.Name}: {ex.Message}\");\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Installation of {appInfo.Name} failed\",\n DetailedMessage = $\"Error: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n }\n }\n\n // If success is still false, ensure we log the failure\n if (!success)\n {\n _logService.LogError($\"Failed to install app: {appInfo.Name}\");\n }\n\n // Only update BloatRemoval.ps1 if installation was successful AND it's not an external app\n // External apps should never be added to BloatRemoval.ps1\n if (success && !IsExternalApp(appInfo))\n {\n try\n {\n _logService.LogInformation(\n $\"Starting BloatRemoval.ps1 script update for {appInfo.Name}\"\n );\n\n // Update the BloatRemoval.ps1 script to remove the installed app from the removal list\n var appNames = new List { appInfo.PackageName };\n _logService.LogInformation(\n $\"Removing package name from BloatRemoval.ps1: {appInfo.PackageName}\"\n );\n\n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n\n // Add any subpackages if present\n if (appInfo.SubPackages != null && appInfo.SubPackages.Length > 0)\n {\n _logService.LogInformation(\n $\"Adding {appInfo.SubPackages.Length} subpackages for {appInfo.Name}\"\n );\n appSubPackages.Add(appInfo.PackageName, appInfo.SubPackages);\n }\n\n // Add registry settings if present\n if (appInfo.RegistrySettings != null && appInfo.RegistrySettings.Length > 0)\n {\n _logService.LogInformation(\n $\"Adding {appInfo.RegistrySettings.Length} registry settings for {appInfo.Name}\"\n );\n appsWithRegistry.Add(\n appInfo.PackageName,\n new List(appInfo.RegistrySettings)\n );\n }\n\n _logService.LogInformation(\n $\"Updating BloatRemoval.ps1 to remove {appInfo.Name} from removal list\"\n );\n var result = await _scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n true\n ); // true = install operation, so remove from script\n\n _logService.LogInformation(\n $\"Successfully updated BloatRemoval.ps1 script - {appInfo.Name} will no longer be removed\"\n );\n _logService.LogInformation($\"Script update result: {result?.Name ?? \"null\"}\");\n }\n catch (Exception ex)\n {\n _logService.LogError(\n $\"Error updating BloatRemoval.ps1 script for {appInfo.Name}\",\n ex\n );\n _logService.LogError($\"Exception details: {ex.Message}\");\n _logService.LogError($\"Stack trace: {ex.StackTrace}\");\n // Don't fail the installation if script update fails\n }\n }\n else if (success)\n {\n _logService.LogInformation(\n $\"Skipping BloatRemoval.ps1 update because {appInfo.Name} is an external app\"\n );\n }\n else\n {\n _logService.LogInformation(\n $\"Skipping BloatRemoval.ps1 update because installation of {appInfo.Name} was not successful\"\n );\n }\n\n if (success)\n {\n _logService.LogSuccess($\"Successfully installed app: {appInfo.Name}\");\n return OperationResult.Succeeded(success);\n }\n else\n {\n // Double check internet connectivity as a possible cause of failure\n bool internetAvailable = await _systemServices.IsInternetConnectedAsync(\n true,\n cancellationToken\n );\n if (!internetAvailable)\n {\n string errorMessage =\n $\"Installation of {appInfo.Name} failed: No internet connection. Please check your network connection and try again.\";\n _logService.LogError(errorMessage);\n return OperationResult.Failed(errorMessage, false);\n }\n\n // Generic failure\n string failMessage = $\"Installation of {appInfo.Name} failed for unknown reasons.\";\n _logService.LogError(failMessage);\n return OperationResult.Failed(failMessage, false);\n }\n }\n catch (OperationCanceledException)\n {\n _logService.LogWarning($\"Installation of {appInfo.Name} was cancelled by user\");\n return OperationResult.Failed(\"Installation cancelled by user\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error installing {appInfo.Name}\", ex);\n\n // Check if the error might be related to internet connectivity\n bool isConnected = await _systemServices.IsInternetConnectedAsync(\n true,\n cancellationToken\n );\n if (!isConnected)\n {\n string errorMessage =\n $\"Installation failed: No internet connection. Please check your network connection and try again.\";\n _logService.LogError(errorMessage);\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Installation failed: No internet connection\",\n DetailedMessage = errorMessage,\n LogLevel = LogLevel.Error,\n }\n );\n return OperationResult.Failed(errorMessage, false);\n }\n\n return OperationResult.Failed($\"Error installing {appInfo.Name}: {ex.Message}\");\n }\n finally\n {\n // Dispose any timers or resources\n if (progress is IProgress progressReporter)\n {\n // Find and dispose the timer if it exists\n var field = GetType()\n .GetField(\n \"_connectivityCheckTimer\",\n System.Reflection.BindingFlags.NonPublic\n | System.Reflection.BindingFlags.Instance\n );\n if (field != null)\n {\n var timer = field.GetValue(this) as System.Timers.Timer;\n timer?.Stop();\n timer?.Dispose();\n }\n }\n\n _currentProgress = null;\n }\n }\n\n /// \n /// Determines if an app is an external app (third-party) rather than a Windows built-in app.\n /// External apps should not be added to the BloatRemoval script.\n /// \n /// The app to check\n /// True if the app is an external app, false otherwise\n private bool IsExternalApp(AppInfo appInfo)\n {\n // Consider all apps with IsCustomInstall as external apps\n if (appInfo.IsCustomInstall)\n return true;\n\n // Check if the package name starts with Microsoft or matches known Windows app patterns\n bool isMicrosoftApp = appInfo.PackageName.StartsWith(\n \"Microsoft.\",\n StringComparison.OrdinalIgnoreCase\n );\n\n // Check if the app is a number-based Microsoft Store app ID\n bool isStoreAppId =\n !string.IsNullOrEmpty(appInfo.PackageID)\n && (\n appInfo.PackageID.All(c => char.IsLetterOrDigit(c) || c == '.')\n && (appInfo.PackageID.Length == 9 || appInfo.PackageID.Length == 12)\n ); // Microsoft Store app IDs are typically 9 or 12 chars\n\n // Check if it's an optional feature or capability, which are Windows components\n bool isWindowsComponent =\n appInfo.Type == AppType.Capability || appInfo.Type == AppType.OptionalFeature;\n\n // Any third-party app with a period in its name is likely an external app (e.g., VideoLAN.VLC)\n bool isThirdPartyNamedApp =\n !isMicrosoftApp && appInfo.PackageName.Contains('.') && !isWindowsComponent;\n\n // If it's a Microsoft app or Windows component, it's not external\n // Otherwise, it's likely an external app\n return isThirdPartyNamedApp\n || appInfo.IsCustomInstall\n || (!isMicrosoftApp && !isStoreAppId && !isWindowsComponent);\n }\n\n /// \n public Task InstallCustomAppAsync(\n AppInfo appInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default\n )\n {\n // Implementation remains in this class for now\n // In future refactoring phases, this can be moved to a specialized service\n _currentProgress = progress;\n\n try\n {\n // Handle different custom app installations based on package name\n switch (appInfo.PackageName.ToLowerInvariant())\n {\n // Special handling for OneDrive\n case \"onedrive\":\n return InstallOneDriveAsync(progress, cancellationToken);\n\n // Add custom app installation logic here\n // case \"some-app\":\n // return await InstallSomeAppAsync(progress, cancellationToken);\n\n default:\n throw new NotSupportedException(\n $\"Custom installation for '{appInfo.PackageName}' is not supported.\"\n );\n }\n }\n catch (Exception ex)\n {\n var errorType = InstallationErrorHelper.DetermineErrorType(ex.Message);\n var errorMessage = InstallationErrorHelper.GetUserFriendlyErrorMessage(errorType);\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Error in custom installation for {appInfo.Name}: {errorMessage}\",\n DetailedMessage = $\"Exception during custom installation: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"ErrorType\", errorType.ToString() },\n { \"PackageName\", appInfo.PackageName },\n { \"AppName\", appInfo.Name },\n { \"IsCustomInstall\", \"True\" },\n { \"OriginalError\", ex.Message },\n },\n }\n );\n\n return Task.FromResult(false);\n }\n }\n\n /// \n /// Installs an app using WinGet.\n /// \n /// The package name to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// Optional display name for the app.\n /// True if installation was successful; otherwise, false.\n public Task InstallWithWingetAsync(\n string packageName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default,\n string displayName = null\n )\n {\n return _winGetInstallationService.InstallWithWingetAsync(\n packageName,\n progress,\n cancellationToken,\n displayName\n );\n }\n\n /// \n /// Disposes the resources used by the service.\n /// \n public void Dispose()\n {\n _httpClient.Dispose();\n GC.SuppressFinalize(this);\n }\n\n /// \n /// Installs OneDrive from the Microsoft download link.\n /// \n /// Optional progress reporter.\n /// Optional cancellation token.\n /// True if installation was successful; otherwise, false.\n private async Task InstallOneDriveAsync(\n IProgress? progress,\n CancellationToken cancellationToken\n )\n {\n try\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Starting OneDrive installation...\",\n DetailedMessage = \"Downloading OneDrive installer from Microsoft\",\n }\n );\n\n // Download OneDrive from the specific URL\n string downloadUrl = \"https://go.microsoft.com/fwlink/p/?LinkID=2182910\";\n string installerPath = Path.Combine(_tempDir, \"OneDriveSetup.exe\");\n\n using (var client = new HttpClient())\n {\n var response = await client.GetAsync(downloadUrl, cancellationToken);\n if (!response.IsSuccessStatusCode)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Failed to download OneDrive installer\",\n DetailedMessage = $\"HTTP error: {response.StatusCode}\",\n LogLevel = LogLevel.Error,\n }\n );\n return false;\n }\n\n using (\n var fileStream = new FileStream(\n installerPath,\n FileMode.Create,\n FileAccess.Write,\n FileShare.None\n )\n )\n {\n await response.Content.CopyToAsync(fileStream, cancellationToken);\n }\n }\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 50,\n StatusText = \"Installing OneDrive...\",\n DetailedMessage = \"Running OneDrive installer\",\n }\n );\n\n // Run the installer\n using (var process = new System.Diagnostics.Process())\n {\n process.StartInfo.FileName = installerPath;\n process.StartInfo.Arguments = \"/silent\";\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.RedirectStandardError = true;\n process.StartInfo.CreateNoWindow = true;\n\n process.Start();\n await Task.Run(() => process.WaitForExit(), cancellationToken);\n\n bool success = process.ExitCode == 0;\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = success\n ? \"OneDrive installed successfully\"\n : \"OneDrive installation failed\",\n DetailedMessage = $\"Installer exited with code: {process.ExitCode}\",\n LogLevel = success ? LogLevel.Success : LogLevel.Error,\n }\n );\n\n return success;\n }\n }\n catch (Exception ex)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Error installing OneDrive\",\n DetailedMessage = $\"Exception: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/CapabilityRemovalService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service for removing Windows capabilities from the system.\n/// \npublic class CapabilityRemovalService : ICapabilityRemovalService\n{\n private readonly ILogService _logService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IScheduledTaskService _scheduledTaskService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The app discovery service.\n /// The scheduled task service.\n public CapabilityRemovalService(\n ILogService logService,\n IAppDiscoveryService appDiscoveryService,\n IScheduledTaskService scheduledTaskService)\n {\n _logService = logService;\n _appDiscoveryService = appDiscoveryService;\n _scheduledTaskService = scheduledTaskService;\n }\n\n /// \n public async Task RemoveCapabilityAsync(\n CapabilityInfo capabilityInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (capabilityInfo == null)\n {\n throw new ArgumentNullException(nameof(capabilityInfo));\n }\n // Call the other overload and return its result\n return await RemoveCapabilityAsync(capabilityInfo.PackageName, progress, cancellationToken);\n }\n\n /// \n public async Task RemoveCapabilityAsync(\n string capabilityName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n try\n {\n progress?.Report(new TaskProgressDetail { Progress = 0, StatusText = $\"Starting removal of {capabilityName}...\" });\n _logService.LogInformation($\"Removing capability: {capabilityName}\");\n \n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n \n // Step 1: Get a list of all installed capabilities that match the pattern\n List capabilityNames = new List();\n try\n {\n powerShell.Commands.Clear();\n powerShell.AddScript($@\"\n Get-WindowsCapability -Online |\n Where-Object {{ $_.Name -like '{capabilityName}*' }} |\n Select-Object -ExpandProperty Name\n \");\n\n capabilityNames = (await Task.Run(() => powerShell.Invoke())).ToList();\n _logService.LogInformation($\"Found {capabilityNames.Count} capabilities matching '{capabilityName}*'\");\n \n // Log the found capabilities\n foreach (var capName in capabilityNames)\n {\n _logService.LogInformation($\"Found installed capability: {capName}\");\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error retrieving Windows capabilities for '{capabilityName}': {ex.Message}. Will proceed with empty capability list.\");\n // Continue with empty capability list\n }\n\n // If no capabilities found with exact name, try with a more flexible pattern\n if (capabilityNames == null || !capabilityNames.Any())\n {\n try\n {\n // Try with a more flexible pattern that might include tildes\n powerShell.Commands.Clear();\n powerShell.AddScript($@\"\n Get-WindowsCapability -Online |\n Where-Object {{ $_.Name -match '{capabilityName}' }} |\n Select-Object -ExpandProperty Name\n \");\n\n capabilityNames = (await Task.Run(() => powerShell.Invoke())).ToList();\n _logService.LogInformation($\"Found {capabilityNames.Count} capabilities with flexible pattern matching '{capabilityName}'\");\n \n // Log the found capabilities\n foreach (var capName in capabilityNames)\n {\n _logService.LogInformation($\"Found installed capability with flexible pattern: {capName}\");\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error retrieving capabilities with flexible pattern: {ex.Message}\");\n }\n }\n\n bool overallSuccess = true;\n \n if (capabilityNames != null && capabilityNames.Any())\n {\n int totalCapabilities = capabilityNames.Count;\n int currentCapability = 0;\n \n foreach (var capName in capabilityNames)\n {\n currentCapability++;\n progress?.Report(new TaskProgressDetail {\n Progress = (currentCapability * 100) / totalCapabilities,\n StatusText = $\"Removing capability {currentCapability} of {totalCapabilities}: {capName}\"\n });\n \n _logService.LogInformation($\"Removing installed capability: {capName}\");\n\n // Step 2: Remove the capability\n bool success = false;\n try\n {\n powerShell.Commands.Clear();\n powerShell.AddScript($@\"\n Remove-WindowsCapability -Name '{capName}' -Online -ErrorAction SilentlyContinue\n return $?\n \");\n\n var result = await Task.Run(() => powerShell.Invoke());\n success = result.FirstOrDefault();\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing capability '{capName}': {ex.Message}\");\n success = false;\n }\n\n if (success)\n {\n _logService.LogSuccess($\"Successfully removed capability: {capName}\");\n }\n else\n {\n _logService.LogError($\"Failed to remove capability: {capName}\");\n overallSuccess = false;\n }\n }\n \n // Update BloatRemoval.ps1 script and register scheduled task\n if (overallSuccess)\n {\n try\n {\n // Pass the full capability names (with version numbers) to the script update service\n var script = await UpdateBloatRemovalScriptAsync(capabilityNames);\n \n // Register the scheduled task to run the script at startup\n try\n {\n bool taskRegistered = await RegisterBloatRemovalTaskAsync(script);\n if (taskRegistered)\n {\n _logService.LogSuccess($\"Scheduled task registered for BloatRemoval.ps1\");\n }\n else\n {\n _logService.LogWarning($\"Failed to register scheduled task for BloatRemoval.ps1, but continuing operation\");\n }\n }\n catch (Exception taskEx)\n {\n _logService.LogError($\"Error registering scheduled task: {taskEx.Message}\");\n // Don't fail the removal if task registration fails\n }\n }\n catch (Exception scriptEx)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script: {scriptEx.Message}\");\n // Don't fail the removal if script update fails\n }\n }\n \n progress?.Report(new TaskProgressDetail {\n Progress = 100,\n StatusText = overallSuccess ? $\"Successfully removed all capabilities\" : $\"Some capabilities could not be removed\",\n DetailedMessage = $\"Removed {capabilityNames.Count} capabilities matching {capabilityName}\",\n LogLevel = overallSuccess ? LogLevel.Success : LogLevel.Warning\n });\n \n return overallSuccess;\n }\n else\n {\n _logService.LogInformation($\"No installed capabilities found matching: {capabilityName}*\");\n progress?.Report(new TaskProgressDetail {\n Progress = 100,\n StatusText = $\"No installed capabilities found matching: {capabilityName}*\",\n LogLevel = LogLevel.Warning\n });\n \n // Consider it a success if nothing needs to be removed\n return true;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing capability: {capabilityName}\", ex);\n progress?.Report(new TaskProgressDetail {\n Progress = 0,\n StatusText = $\"Error removing {capabilityName}: {ex.Message}\",\n LogLevel = LogLevel.Error\n });\n return false;\n }\n }\n\n // Add missing CanRemoveCapabilityAsync method\n /// \n public Task CanRemoveCapabilityAsync(CapabilityInfo capabilityInfo)\n {\n // Basic implementation: Assume all found capabilities can be removed.\n // TODO: Add actual checks if needed (e.g., dependencies)\n return Task.FromResult(true);\n }\n\n\n /// \n public async Task> RemoveCapabilitiesInBatchAsync(\n List capabilities)\n {\n if (capabilities == null)\n {\n throw new ArgumentNullException(nameof(capabilities));\n }\n\n return await RemoveCapabilitiesInBatchAsync(capabilities.Select(c => c.PackageName).ToList());\n }\n\n /// \n public async Task> RemoveCapabilitiesInBatchAsync(\n List capabilityNames)\n {\n var results = new List<(string Name, bool Success, string? Error)>();\n \n try\n {\n _logService.LogInformation($\"Removing {capabilityNames.Count} Windows capabilities\");\n \n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n \n foreach (var capability in capabilityNames)\n {\n try\n {\n _logService.LogInformation($\"Removing capability: {capability}\");\n \n // Step 1: Get a list of all installed capabilities that match the pattern\n List matchingCapabilities = new List();\n try\n {\n powerShell.Commands.Clear();\n powerShell.AddScript($@\"\n Get-WindowsCapability -Online |\n Where-Object {{ $_.Name -like '{capability}*' -and $_.State -eq 'Installed' }} |\n Select-Object -ExpandProperty Name\n \");\n\n matchingCapabilities = (await Task.Run(() => powerShell.Invoke())).ToList();\n _logService.LogInformation($\"Found {matchingCapabilities.Count} capabilities matching '{capability}*' for batch removal\");\n \n // Log the found capabilities\n foreach (var capName in matchingCapabilities)\n {\n _logService.LogInformation($\"Found installed capability for batch removal: {capName}\");\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error retrieving Windows capabilities for batch removal '{capability}': {ex.Message}. Will proceed with empty capability list.\");\n // Continue with empty capability list\n }\n\n bool success = true;\n string? error = null;\n \n if (matchingCapabilities != null && matchingCapabilities.Any())\n {\n foreach (var capName in matchingCapabilities)\n {\n _logService.LogInformation($\"Removing installed capability in batch: {capName}\");\n\n // Step 2: Remove the capability\n bool capSuccess = false;\n try\n {\n powerShell.Commands.Clear();\n powerShell.AddScript($@\"\n Remove-WindowsCapability -Name '{capName}' -Online -ErrorAction SilentlyContinue\n return $?\n \");\n\n var capResult = await Task.Run(() => powerShell.Invoke());\n capSuccess = capResult.FirstOrDefault();\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing capability in batch '{capName}': {ex.Message}\");\n capSuccess = false;\n }\n\n if (capSuccess)\n {\n _logService.LogSuccess($\"Successfully removed capability in batch: {capName}\");\n }\n else\n {\n _logService.LogError($\"Failed to remove capability in batch: {capName}\");\n success = false;\n error = $\"Failed to remove one or more capabilities\";\n }\n }\n }\n else\n {\n _logService.LogInformation($\"No installed capabilities found matching for batch removal: {capability}*\");\n // Consider it a success if nothing needs to be removed\n success = true;\n }\n \n // If successful, update the BloatRemoval.ps1 script with the full capability names\n if (success && matchingCapabilities.Any())\n {\n try\n {\n await UpdateBloatRemovalScriptAsync(matchingCapabilities);\n _logService.LogInformation($\"Updated BloatRemoval.ps1 script with full capability names for batch removal\");\n }\n catch (Exception scriptEx)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for batch capability removal: {scriptEx.Message}\");\n // Don't fail the removal if script update fails\n }\n }\n \n results.Add((capability, success, error));\n }\n catch (Exception ex)\n {\n results.Add((capability, false, ex.Message));\n _logService.LogError($\"Error removing capability: {capability}\", ex);\n }\n }\n \n return results;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error removing capabilities\", ex);\n return capabilityNames.Select(c => (c, false, $\"Error: {ex.Message}\")).ToList();\n }\n }\n\n // SetExecutionPolicy is now handled by PowerShellFactory\n /// \n /// Updates the BloatRemoval.ps1 script to add the removed capabilities to it.\n /// \n /// The list of capability names with version numbers.\n /// The updated removal script.\n private async Task UpdateBloatRemovalScriptAsync(List capabilityNames)\n {\n try\n {\n // Get the script update service\n var scriptUpdateService = GetScriptUpdateService();\n if (scriptUpdateService == null)\n {\n _logService.LogWarning(\"Script update service not available\");\n throw new InvalidOperationException(\"Script update service not available\");\n }\n \n // Update the script with the full capability names (including version numbers)\n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n \n _logService.LogInformation($\"Updating BloatRemoval.ps1 script for {capabilityNames.Count} capabilities\");\n \n try\n {\n var script = await scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n capabilityNames,\n appsWithRegistry,\n appSubPackages,\n false); // false = removal operation, so add to script\n \n _logService.LogInformation($\"Successfully updated BloatRemoval.ps1 script for capabilities\");\n return script;\n }\n catch (FileNotFoundException)\n {\n _logService.LogInformation($\"BloatRemoval.ps1 script not found. It will be created when needed.\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in script update service for capabilities: {ex.Message}\", ex);\n throw;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for capabilities: {ex.Message}\", ex);\n throw;\n }\n }\n\n /// \n /// Updates the BloatRemoval.ps1 script to add the removed capability to it.\n /// \n /// The capability name.\n /// The updated removal script.\n private async Task UpdateBloatRemovalScriptAsync(string capabilityName)\n {\n try\n {\n // Get the script update service\n var scriptUpdateService = GetScriptUpdateService();\n if (scriptUpdateService == null)\n {\n _logService.LogWarning(\"Script update service not available\");\n throw new InvalidOperationException(\"Script update service not available\");\n }\n \n // Update the script\n var appNames = new List { capabilityName };\n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n \n _logService.LogInformation($\"Updating BloatRemoval.ps1 script for capability: {capabilityName}\");\n \n try\n {\n var script = await scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n false); // false = removal operation, so add to script\n \n _logService.LogInformation($\"Successfully updated BloatRemoval.ps1 script for capability: {capabilityName}\");\n return script;\n }\n catch (FileNotFoundException)\n {\n _logService.LogInformation($\"BloatRemoval.ps1 script not found. It will be created when needed.\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in script update service for capability: {capabilityName}\", ex);\n throw;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for capability: {capabilityName}\", ex);\n throw;\n }\n }\n /// \n /// Registers a scheduled task to run the BloatRemoval script at startup.\n /// \n /// The removal script to register.\n /// True if the task was registered successfully, false otherwise.\n private async Task RegisterBloatRemovalTaskAsync(RemovalScript script)\n {\n try\n {\n if (script == null)\n {\n _logService.LogError(\"Cannot register scheduled task: Script is null\");\n return false;\n }\n \n _logService.LogInformation(\"Registering scheduled task for BloatRemoval.ps1\");\n \n \n // Register the scheduled task\n bool success = await _scheduledTaskService.RegisterScheduledTaskAsync(script);\n \n if (success)\n {\n _logService.LogSuccess(\"Successfully registered scheduled task for BloatRemoval.ps1\");\n }\n else\n {\n _logService.LogError(\"Failed to register scheduled task for BloatRemoval.ps1\");\n }\n \n return success;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error registering scheduled task for BloatRemoval.ps1\", ex);\n return false;\n }\n }\n \n /// \n /// Gets the script update service.\n /// \n /// The script update service or null if not available.\n private IScriptUpdateService? GetScriptUpdateService()\n {\n try\n {\n // This is a simplified implementation. In a real application, you would use dependency injection.\n // For now, we'll create a new instance directly.\n // Use the injected _appDiscoveryService instead of creating a new instance\n var scriptContentModifier = new ScriptContentModifier(_logService);\n return new ScriptUpdateService(_logService, _appDiscoveryService, scriptContentModifier);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to get script update service\", ex);\n return null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/ViewModels/StartMenuCustomizationsViewModel.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Extensions;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Customize.ViewModels\n{\n /// \n /// ViewModel for Start Menu customizations.\n /// \n public partial class StartMenuCustomizationsViewModel : BaseSettingsViewModel\n {\n private readonly ISystemServices _systemServices;\n private bool _isWindows11;\n\n /// \n /// Gets the command to clean the Start Menu.\n /// \n [RelayCommand]\n public async Task CleanStartMenu()\n {\n try\n {\n // Start task with progress\n _progressService.StartTask(\"Cleaning Start Menu...\");\n \n // Update initial progress\n _progressService.UpdateDetailedProgress(new TaskProgressDetail\n {\n StatusText = \"Cleaning Start Menu...\",\n Progress = 0\n });\n\n // Determine Windows version\n _isWindows11 = _systemServices.IsWindows11();\n\n // Clean Start Menu\n await Task.Run(() =>\n {\n StartMenuCustomizations.CleanStartMenu(_isWindows11, _systemServices);\n });\n\n // Log success\n _logService.Log(LogLevel.Info, \"Start Menu cleaned successfully\");\n\n // Update completion progress\n _progressService.UpdateDetailedProgress(new TaskProgressDetail\n {\n StatusText = \"Start Menu cleaned successfully\",\n Progress = 100\n });\n \n // Complete the task\n _progressService.CompleteTask();\n }\n catch (Exception ex)\n {\n // Log error\n _logService.Log(LogLevel.Error, $\"Error cleaning Start Menu: {ex.Message}\");\n\n // Update error progress\n _progressService.UpdateDetailedProgress(new TaskProgressDetail\n {\n StatusText = $\"Error cleaning Start Menu: {ex.Message}\",\n Progress = 100\n });\n \n // Complete the task\n _progressService.CompleteTask();\n }\n }\n\n /// \n /// Gets the command to execute an action.\n /// \n [RelayCommand]\n public async Task ExecuteAction(ApplicationAction? action)\n {\n if (action == null) return;\n\n try\n {\n // Execute the registry action if present\n if (action.RegistrySetting != null)\n {\n string hiveString = action.RegistrySetting.Hive.ToString();\n if (hiveString == \"LocalMachine\") hiveString = \"HKLM\";\n else if (hiveString == \"CurrentUser\") hiveString = \"HKCU\";\n else if (hiveString == \"ClassesRoot\") hiveString = \"HKCR\";\n else if (hiveString == \"Users\") hiveString = \"HKU\";\n else if (hiveString == \"CurrentConfig\") hiveString = \"HKCC\";\n\n string fullPath = $\"{hiveString}\\\\{action.RegistrySetting.SubKey}\";\n _registryService.SetValue(\n fullPath,\n action.RegistrySetting.Name,\n action.RegistrySetting.RecommendedValue,\n action.RegistrySetting.ValueType);\n }\n\n // Execute custom action if present\n if (action.CustomAction != null)\n {\n await action.CustomAction();\n }\n\n _logService.Log(LogLevel.Info, $\"Action '{action.Name}' executed successfully\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error executing action '{action.Name}': {ex.Message}\");\n }\n }\n\n /// \n /// Gets the collection of Start Menu actions.\n /// \n public ObservableCollection Actions { get; } = new();\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The system services.\n public StartMenuCustomizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n ISystemServices systemServices)\n : base(progressService, registryService, logService)\n {\n _systemServices = systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n _isWindows11 = _systemServices.IsWindows11();\n }\n\n /// \n /// Loads the Start Menu customizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Start Menu customizations\n var startMenuCustomizations = Core.Features.Customize.Models.StartMenuCustomizations.GetStartMenuCustomizations();\n if (startMenuCustomizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in startMenuCustomizations.Settings.OrderBy(s => s.Name))\n {\n // Skip Windows 11 specific settings on Windows 10\n if (!_isWindows11 && setting.IsWindows11Only)\n {\n continue;\n }\n\n // Skip Windows 10 specific settings on Windows 11\n if (_isWindows11 && setting.IsWindows10Only)\n {\n continue;\n }\n\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n ControlType = setting.ControlType,\n IsWindows11Only = setting.IsWindows11Only,\n IsWindows10Only = setting.IsWindows10Only\n };\n\n // Add any actions\n var actionsProperty = setting.GetType().GetProperty(\"Actions\");\n if (actionsProperty != null && \n actionsProperty.GetValue(setting) is IEnumerable actions && \n actions.Any())\n {\n // We need to handle this differently since the Actions property doesn't exist in ApplicationSetting\n // This is a temporary workaround until we refactor the code properly\n }\n\n // Set up the registry settings\n if (setting.RegistrySettings != null && setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings != null && setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n var linkedSettings = new LinkedRegistrySettings();\n foreach (var regSetting in setting.RegistrySettings)\n {\n linkedSettings.Settings.Add(regSetting);\n _logService.Log(LogLevel.Info, $\"Adding linked registry setting for {setting.Name}: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}\");\n }\n settingItem.LinkedRegistrySettings = linkedSettings;\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for settings\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Initializes the Start Menu actions.\n /// \n private void InitializeActions()\n {\n Actions.Clear();\n\n // Add Clean Start Menu action\n Actions.Add(new ApplicationAction\n {\n Id = \"clean-start-menu\",\n Name = \"Clean Start Menu\",\n Description = \"Cleans the Start Menu by removing pinned apps and restoring the default layout\",\n CustomAction = async () =>\n {\n await CleanStartMenu();\n return true;\n }\n });\n }\n\n /// \n /// Checks the status of all Start Menu settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n foreach (var setting in Settings)\n {\n // Get status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n setting.Status = status;\n\n // Get current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n setting.CurrentValue = currentValue;\n\n // Set IsRegistryValueNull property based on current value\n setting.IsRegistryValueNull = currentValue == null;\n\n // Update LinkedRegistrySettingsWithValues for tooltip display\n var linkedRegistrySettingsWithValues = new ObservableCollection();\n \n // Get the LinkedRegistrySettings property\n var linkedRegistrySettings = setting.LinkedRegistrySettings;\n \n if (linkedRegistrySettings != null && linkedRegistrySettings.Settings.Count > 0)\n {\n // For linked settings, get fresh values from registry\n bool anyNull = false;\n foreach (var regSetting in linkedRegistrySettings.Settings)\n {\n string hiveString = regSetting.Hive.ToString();\n if (hiveString == \"LocalMachine\") hiveString = \"HKLM\";\n else if (hiveString == \"CurrentUser\") hiveString = \"HKCU\";\n else if (hiveString == \"ClassesRoot\") hiveString = \"HKCR\";\n else if (hiveString == \"Users\") hiveString = \"HKU\";\n else if (hiveString == \"CurrentConfig\") hiveString = \"HKCC\";\n \n var regCurrentValue = _registryService.GetValue(\n $\"{hiveString}\\\\{regSetting.SubKey}\",\n regSetting.Name);\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n linkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // For linked settings, set IsRegistryValueNull if any value is null\n setting.IsRegistryValueNull = anyNull;\n }\n else if (setting.RegistrySetting != null)\n {\n // For single setting\n linkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n // IsRegistryValueNull is already set above\n }\n \n setting.LinkedRegistrySettingsWithValues = linkedRegistrySettingsWithValues;\n\n // Set status message\n string statusMessage = GetStatusMessage(setting);\n setting.StatusMessage = statusMessage;\n\n // Set the IsUpdatingFromCode flag to prevent automatic application\n setting.IsUpdatingFromCode = true;\n\n try\n {\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n // Reset the flag\n setting.IsUpdatingFromCode = false;\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Start Menu setting statuses: {ex.Message}\");\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n // Get status\n var status = setting.Status;\n string message = status switch\n {\n RegistrySettingStatus.Applied => \"Setting is enabled (toggle is ON)\",\n RegistrySettingStatus.NotApplied => \"Setting is disabled (toggle is OFF)\",\n RegistrySettingStatus.Modified => \"Setting has a custom value different from both enabled and disabled values\",\n RegistrySettingStatus.Error => \"Error checking setting status\",\n _ => \"Unknown status\"\n };\n\n // Add current value if available\n var currentValue = setting.CurrentValue;\n if (currentValue != null)\n {\n message += $\"\\nCurrent value: {currentValue}\";\n }\n\n // Add enabled value if available\n var registrySetting = setting.RegistrySetting;\n object? enabledValue = registrySetting?.EnabledValue ?? registrySetting?.RecommendedValue;\n if (enabledValue != null)\n {\n message += $\"\\nEnabled value (ON): {enabledValue}\";\n }\n\n // Add disabled value if available\n object? disabledValue = registrySetting?.DisabledValue ?? registrySetting?.DefaultValue;\n if (disabledValue != null)\n {\n message += $\"\\nDisabled value (OFF): {disabledValue}\";\n }\n\n return message;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/UpdateNotificationDialog.xaml.cs", "using System;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Update notification dialog that shows when a new version is available\n /// \n public partial class UpdateNotificationDialog : Window\n {\n // Default text content for the update dialog\n private static readonly string DefaultTitle = \"Update Available\";\n private static readonly string DefaultUpdateMessage = \"A new version of Winhance is available.\";\n \n public UpdateNotificationDialog(UpdateNotificationViewModel viewModel)\n {\n InitializeComponent();\n DataContext = viewModel;\n }\n \n private void PrimaryButton_Click(object sender, RoutedEventArgs e)\n {\n // Download and install\n if (DataContext is UpdateNotificationViewModel viewModel)\n {\n viewModel.DownloadAndInstallUpdateCommand.Execute(null);\n }\n }\n\n private void SecondaryButton_Click(object sender, RoutedEventArgs e)\n {\n // Remind later\n if (DataContext is UpdateNotificationViewModel viewModel)\n {\n viewModel.RemindLaterCommand.Execute(null);\n }\n DialogResult = false;\n Close();\n }\n \n private void CloseButton_Click(object sender, RoutedEventArgs e)\n {\n // Close without action\n DialogResult = false;\n Close();\n }\n \n /// \n /// Creates and shows an update notification dialog with the specified parameters.\n /// This method ensures the dialog is properly modal and blocks the main window.\n /// \n /// The view model containing update information\n /// The dialog title (optional - uses default if empty)\n /// The update message (optional - uses default if empty)\n /// The dialog instance with DialogResult set\n public static async Task ShowUpdateDialogAsync(\n UpdateNotificationViewModel viewModel,\n string title = \"\",\n string updateMessage = \"\")\n {\n try\n {\n var dialog = new UpdateNotificationDialog(viewModel)\n {\n Title = string.IsNullOrEmpty(title) ? DefaultTitle : title,\n WindowStartupLocation = WindowStartupLocation.CenterOwner,\n ShowInTaskbar = false,\n ResizeMode = ResizeMode.NoResize,\n WindowStyle = WindowStyle.None,\n AllowsTransparency = true\n };\n\n // Set the update message\n dialog.UpdateMessageText.Text = string.IsNullOrEmpty(updateMessage) ? DefaultUpdateMessage : updateMessage;\n \n // Set button content\n dialog.PrimaryButton.Content = \"Download and Install\";\n dialog.SecondaryButton.Content = \"Remind Later\";\n\n // Set the owner to the main window to ensure it appears on top\n if (Application.Current.MainWindow != null && Application.Current.MainWindow != dialog)\n {\n dialog.Owner = Application.Current.MainWindow;\n dialog.Topmost = true; // Ensure it stays on top\n }\n else\n {\n // Try to find the main window another way\n foreach (Window window in Application.Current.Windows)\n {\n if (window != dialog && window.IsVisible)\n {\n dialog.Owner = window;\n dialog.Topmost = true;\n break;\n }\n }\n }\n\n // Make the dialog visible and focused\n dialog.Visibility = Visibility.Visible;\n dialog.Activate();\n dialog.Focus();\n \n // Show the dialog and wait for it to complete\n dialog.ShowDialog();\n \n // Return the dialog\n return dialog;\n }\n catch (Exception ex)\n {\n // Show error message\n MessageBox.Show($\"Error showing update dialog: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n \n // Create a dummy dialog with error result\n var errorDialog = new UpdateNotificationDialog(viewModel);\n errorDialog.DialogResult = false;\n return errorDialog;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppDiscoveryService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service for discovering and querying applications on the system.\n/// \npublic class AppDiscoveryService\n : Winhance.Core.Features.SoftwareApps.Interfaces.IAppDiscoveryService\n{\n private readonly ILogService _logService;\n private readonly ExternalAppCatalog _externalAppCatalog;\n private readonly WindowsAppCatalog _windowsAppCatalog;\n private readonly CapabilityCatalog _capabilityCatalog;\n private readonly FeatureCatalog _featureCatalog;\n private readonly TimeSpan _powershellTimeout = TimeSpan.FromSeconds(10); // Add a timeout for PowerShell commands\n private Dictionary _installationStatusCache = new Dictionary(\n StringComparer.OrdinalIgnoreCase\n );\n private DateTime _lastCacheRefresh = DateTime.MinValue;\n private readonly TimeSpan _cacheLifetime = TimeSpan.FromMinutes(5);\n private readonly object _cacheLock = new object();\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public AppDiscoveryService(ILogService logService)\n {\n _logService = logService;\n _externalAppCatalog = ExternalAppCatalog.CreateDefault();\n _windowsAppCatalog = WindowsAppCatalog.CreateDefault();\n _capabilityCatalog = CapabilityCatalog.CreateDefault();\n _featureCatalog = FeatureCatalog.CreateDefault();\n }\n\n /// \n public async Task> GetInstallableAppsAsync()\n {\n try\n {\n _logService.LogInformation(\"Getting installable external apps list\");\n var installableApps = _externalAppCatalog.ExternalApps.ToList();\n\n // Return the apps without checking installation status initially\n // This will allow the UI to load faster\n _logService.LogInformation($\"Found {installableApps.Count} installable external apps\");\n return installableApps;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error retrieving installable external apps\", ex);\n return new List();\n }\n }\n\n /// \n public async Task> GetStandardAppsAsync()\n {\n try\n {\n _logService.LogInformation(\"Getting standard Windows apps list\");\n var standardApps = _windowsAppCatalog.WindowsApps.ToList();\n\n // Return the apps without checking installation status initially\n // This will allow the UI to load faster\n _logService.LogInformation($\"Found {standardApps.Count} standard Windows apps\");\n return standardApps;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error retrieving standard Windows apps\", ex);\n return new List();\n }\n }\n\n /// \n public async Task> GetCapabilitiesAsync()\n {\n try\n {\n _logService.LogInformation(\"Getting Windows capabilities list\");\n var capabilities = _capabilityCatalog.Capabilities.ToList();\n\n // Return the capabilities without checking installation status initially\n // This will allow the UI to load faster\n _logService.LogInformation($\"Found {capabilities.Count} capabilities\");\n return capabilities;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error retrieving capabilities\", ex);\n return new List();\n }\n }\n\n /// \n public async Task> GetOptionalFeaturesAsync()\n {\n try\n {\n _logService.LogInformation(\"Getting Windows optional features list\");\n var features = _featureCatalog.Features.ToList();\n\n // Return the features without checking installation status initially\n // This will allow the UI to load faster\n _logService.LogInformation($\"Found {features.Count} optional features\");\n return features;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error retrieving optional features\", ex);\n return new List();\n }\n }\n\n /// \n public async Task IsAppInstalledAsync(string packageName)\n {\n return await IsAppInstalledAsync(packageName, CancellationToken.None);\n }\n\n /// \n public async Task IsAppInstalledAsync(\n string packageName,\n CancellationToken cancellationToken = default\n )\n {\n try\n {\n // Check cache first\n lock (_cacheLock)\n {\n if (_installationStatusCache.TryGetValue(packageName, out bool cachedStatus))\n {\n // Only use cache if it's fresh\n if (DateTime.Now - _lastCacheRefresh < _cacheLifetime)\n {\n return cachedStatus;\n }\n }\n }\n\n // Determine item type more efficiently by using a type flag in the item itself\n // This avoids searching through collections each time\n bool isCapability = _capabilityCatalog.Capabilities.Any(c =>\n c.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase)\n );\n bool isFeature =\n !isCapability\n && _featureCatalog.Features.Any(f =>\n f.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase)\n );\n\n bool isInstalled = false;\n\n // Check if this app has subpackages\n string[]? subPackages = null;\n if (!isCapability && !isFeature)\n {\n // Find the app definition to check for subpackages\n var appDefinition = _windowsAppCatalog.WindowsApps.FirstOrDefault(a =>\n a.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (appDefinition?.SubPackages != null && appDefinition.SubPackages.Length > 0)\n {\n subPackages = appDefinition.SubPackages;\n _logService.LogInformation(\n $\"App {packageName} has {subPackages.Length} subpackages\"\n );\n }\n }\n\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n\n if (isCapability)\n {\n // Check capability status\n powerShell.AddScript(\n @\"\n param($capabilityName)\n try {\n $capability = Get-WindowsCapability -Online |\n Where-Object { $_.Name -like \"\"$capabilityName*\"\" } |\n Select-Object -First 1\n return $capability -ne $null -and $capability.State -eq 'Installed'\n }\n catch {\n return $false\n }\n \"\n );\n powerShell.AddParameter(\"capabilityName\", packageName);\n }\n else if (isFeature)\n {\n // Check feature status\n powerShell.AddScript(\n @\"\n param($featureName)\n try {\n $feature = Get-WindowsOptionalFeature -Online |\n Where-Object { $_.FeatureName -eq $featureName }\n return $feature -ne $null -and $feature.State -eq 'Enabled'\n }\n catch {\n return $false\n }\n \"\n );\n powerShell.AddParameter(\"featureName\", packageName);\n }\n else\n {\n // Check standard app status using the same approach as the original PowerShell script\n // But also check subpackages if the main package is not installed\n using var powerShellForAppx = PowerShellFactory.CreateForAppxCommands(_logService);\n powerShellForAppx.AddScript(\n @\"\n param($packageName, $subPackages)\n try {\n # Check main package\n $appx = Get-AppxPackage -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $packageName }\n $isInstalled = ($appx -ne $null)\n Write-Output \"\"Checking if $packageName is installed: $isInstalled\"\"\n \n # If not installed and we have subpackages, check those too\n if (-not $isInstalled -and $subPackages -ne $null) {\n foreach ($subPackage in $subPackages) {\n Write-Output \"\"Checking subpackage: $subPackage\"\"\n $subAppx = Get-AppxPackage -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $subPackage }\n if ($subAppx -ne $null) {\n $isInstalled = $true\n Write-Output \"\"Subpackage $subPackage is installed\"\"\n break\n }\n }\n }\n \n return $isInstalled\n }\n catch {\n Write-Output \"\"Error checking if $packageName is installed: $_\"\"\n return $false\n }\n \"\n );\n powerShellForAppx.AddParameter(\"packageName\", packageName);\n powerShellForAppx.AddParameter(\"subPackages\", subPackages);\n\n // Execute with timeout\n var task = Task.Run(() => powerShellForAppx.Invoke());\n if (await Task.WhenAny(task, Task.Delay(_powershellTimeout)) == task)\n {\n var result = await task;\n isInstalled = result.FirstOrDefault();\n }\n else\n {\n _logService.LogWarning(\n $\"Timeout checking installation status for {packageName}\"\n );\n isInstalled = false;\n }\n }\n\n // Cache the result\n lock (_cacheLock)\n {\n _installationStatusCache[packageName] = isInstalled;\n _lastCacheRefresh = DateTime.Now;\n }\n\n return isInstalled;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking if item is installed: {packageName}\", ex);\n return false;\n }\n }\n\n /// \n /// Efficiently checks installation status for multiple items at once.\n /// \n /// The package names to check.\n /// A dictionary mapping package names to their installation status.\n public async Task> GetInstallationStatusBatchAsync(\n IEnumerable packageNames\n )\n {\n var result = new Dictionary(StringComparer.OrdinalIgnoreCase);\n var packageList = packageNames.ToList();\n\n if (!packageList.Any())\n return result;\n\n try\n {\n // Check for special apps that need custom detection logic\n var oneNotePackage = \"Microsoft.Office.OneNote\";\n bool hasOneNote = packageList.Any(p =>\n p.Equals(oneNotePackage, StringComparison.OrdinalIgnoreCase)\n );\n bool oneNoteInstalled = false;\n\n // If OneNote is in the list, check it separately using our special detection\n if (hasOneNote)\n {\n oneNoteInstalled = await IsOneNoteInstalledAsync();\n _logService.LogInformation(\n $\"OneNote special registry check result: {oneNoteInstalled}\"\n );\n // Remove OneNote from the list as we'll handle it separately\n packageList = packageList\n .Where(p => !p.Equals(oneNotePackage, StringComparison.OrdinalIgnoreCase))\n .ToList();\n }\n\n // Group items by type for batch processing\n var capabilities = packageList\n .Where(p =>\n _capabilityCatalog.Capabilities.Any(c =>\n c.PackageName.Equals(p, StringComparison.OrdinalIgnoreCase)\n )\n )\n .ToList();\n\n var features = packageList\n .Where(p =>\n _featureCatalog.Features.Any(f =>\n f.PackageName.Equals(p, StringComparison.OrdinalIgnoreCase)\n )\n )\n .ToList();\n\n var standardApps = packageList.Except(capabilities).Except(features).ToList();\n\n // Process capabilities in batch\n if (capabilities.Any())\n {\n var capabilityStatuses = await GetCapabilitiesStatusBatchAsync(capabilities);\n foreach (var pair in capabilityStatuses)\n {\n result[pair.Key] = pair.Value;\n }\n }\n\n // Process features in batch\n if (features.Any())\n {\n var featureStatuses = await GetFeaturesStatusBatchAsync(features);\n foreach (var pair in featureStatuses)\n {\n result[pair.Key] = pair.Value;\n }\n }\n\n // Process standard apps in batch\n if (standardApps.Any())\n {\n var appStatuses = await GetStandardAppsStatusBatchAsync(standardApps);\n foreach (var pair in appStatuses)\n {\n result[pair.Key] = pair.Value;\n }\n }\n\n // Add OneNote result if it was in the original list\n if (hasOneNote)\n {\n // Check if OneNote is also detected via AppX package\n bool appxOneNoteInstalled = false;\n if (result.TryGetValue(oneNotePackage, out bool appxInstalled))\n {\n appxOneNoteInstalled = appxInstalled;\n }\n\n // Use either the registry check or AppX check - if either is true, OneNote is installed\n result[oneNotePackage] = oneNoteInstalled || appxOneNoteInstalled;\n _logService.LogInformation(\n $\"Final OneNote installation status: {result[oneNotePackage]} (Registry: {oneNoteInstalled}, AppX: {appxOneNoteInstalled})\"\n );\n }\n\n // Cache all results\n lock (_cacheLock)\n {\n foreach (var pair in result)\n {\n _installationStatusCache[pair.Key] = pair.Value;\n }\n _lastCacheRefresh = DateTime.Now;\n }\n\n return result;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking batch installation status\", ex);\n return packageList.ToDictionary(p => p, p => false, StringComparer.OrdinalIgnoreCase);\n }\n }\n\n private async Task> GetCapabilitiesStatusBatchAsync(\n List capabilities\n )\n {\n var result = new Dictionary(StringComparer.OrdinalIgnoreCase);\n\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n\n // Get all installed capabilities in one query\n powerShell.AddScript(\n @\"\n try {\n $installedCapabilities = Get-WindowsCapability -Online | Where-Object { $_.State -eq 'Installed' }\n return $installedCapabilities | Select-Object -ExpandProperty Name\n }\n catch {\n return @()\n }\n \"\n );\n\n var task = Task.Run(() => powerShell.Invoke());\n if (await Task.WhenAny(task, Task.Delay(_powershellTimeout)) == task)\n {\n var installedCapabilities = (await task).ToList();\n\n // Check each capability against the installed list\n foreach (var capability in capabilities)\n {\n result[capability] = installedCapabilities.Any(c =>\n c.StartsWith(capability, StringComparison.OrdinalIgnoreCase)\n );\n }\n }\n else\n {\n _logService.LogWarning(\"Timeout getting installed capabilities\");\n foreach (var capability in capabilities)\n {\n result[capability] = false;\n }\n }\n\n return result;\n }\n\n private async Task> GetFeaturesStatusBatchAsync(List features)\n {\n var result = new Dictionary(StringComparer.OrdinalIgnoreCase);\n\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n\n // Get all enabled features in one query\n powerShell.AddScript(\n @\"\n try {\n $enabledFeatures = Get-WindowsOptionalFeature -Online | Where-Object { $_.State -eq 'Enabled' }\n return $enabledFeatures | Select-Object -ExpandProperty FeatureName\n }\n catch {\n return @()\n }\n \"\n );\n\n var task = Task.Run(() => powerShell.Invoke());\n if (await Task.WhenAny(task, Task.Delay(_powershellTimeout)) == task)\n {\n var enabledFeatures = (await task).ToList();\n\n // Check each feature against the enabled list\n foreach (var feature in features)\n {\n result[feature] = enabledFeatures.Any(f =>\n f.Equals(feature, StringComparison.OrdinalIgnoreCase)\n );\n }\n }\n else\n {\n _logService.LogWarning(\"Timeout getting enabled features\");\n foreach (var feature in features)\n {\n result[feature] = false;\n }\n }\n\n return result;\n }\n\n private async Task> GetStandardAppsStatusBatchAsync(List apps)\n {\n var result = new Dictionary(StringComparer.OrdinalIgnoreCase);\n\n using var powerShell = PowerShellFactory.CreateForAppxCommands(_logService);\n // No need to set execution policy as it's already done in the factory\n\n // Get all installed apps in one query using the same approach as the original PowerShell script\n powerShell.AddScript(\n @\"\n try {\n $installedApps = @(Get-AppxPackage | Select-Object -ExpandProperty Name)\n \n # Log the count for diagnostic purposes\n Write-Output \"\"Found $($installedApps.Count) installed apps\"\"\n \n # Return the array of names\n return $installedApps\n }\n catch {\n Write-Output \"\"Error getting installed apps: $_\"\"\n return @()\n }\n \"\n );\n\n var task = Task.Run(() => powerShell.Invoke());\n if (await Task.WhenAny(task, Task.Delay(_powershellTimeout)) == task)\n {\n var installedApps = (await task).ToList();\n\n // Check each app against the installed list\n foreach (var app in apps)\n {\n // First check if the main package is installed\n bool isInstalled = installedApps.Any(a =>\n a.Equals(app, StringComparison.OrdinalIgnoreCase)\n );\n\n // If not installed, check if it has subpackages and if any of them are installed\n if (!isInstalled)\n {\n var appDefinition = _windowsAppCatalog.WindowsApps.FirstOrDefault(a =>\n a.PackageName.Equals(app, StringComparison.OrdinalIgnoreCase)\n );\n\n if (appDefinition?.SubPackages != null && appDefinition.SubPackages.Length > 0)\n {\n foreach (var subPackage in appDefinition.SubPackages)\n {\n if (\n installedApps.Any(a =>\n a.Equals(subPackage, StringComparison.OrdinalIgnoreCase)\n )\n )\n {\n isInstalled = true;\n _logService.LogInformation(\n $\"App {app} is installed via subpackage {subPackage}\"\n );\n break;\n }\n }\n }\n }\n\n result[app] = isInstalled;\n }\n }\n else\n {\n _logService.LogWarning(\"Timeout getting installed apps\");\n foreach (var app in apps)\n {\n result[app] = false;\n }\n }\n\n return result;\n }\n\n /// \n public async Task IsEdgeInstalledAsync()\n {\n try\n {\n _logService.LogInformation(\"Checking if Microsoft Edge is installed\");\n\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n\n // Only check the specific registry key as requested\n powerShell.AddScript(\n @\"\n try {\n $result = Get-ItemProperty \"\"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\msedge.exe\"\" -ErrorAction SilentlyContinue\n return $result -ne $null\n }\n catch {\n Write-Output \"\"Error checking Edge registry key: $($_.Exception.Message)\"\"\n return $false\n }\n \"\n );\n\n var result = await ExecuteWithTimeoutAsync(powerShell, 15);\n bool isInstalled = result.FirstOrDefault();\n\n _logService.LogInformation($\"Edge registry check result: {isInstalled}\");\n return isInstalled;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking Edge installation\", ex);\n return false;\n }\n }\n\n /// \n public async Task IsOneDriveInstalledAsync()\n {\n try\n {\n _logService.LogInformation(\"Checking if OneDrive is installed\");\n\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n\n // Check the specific registry keys\n powerShell.AddScript(\n @\"\n try {\n # Check the two specific registry keys\n $hklmKey = Get-ItemProperty \"\"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneDriveSetup.exe\"\" -ErrorAction SilentlyContinue\n $hkcuKey = Get-ItemProperty \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneDriveSetup.exe\"\" -ErrorAction SilentlyContinue\n \n # Return true if either key exists\n return ($hklmKey -ne $null) -or ($hkcuKey -ne $null)\n }\n catch {\n Write-Output \"\"Error checking OneDrive registry: $($_.Exception.Message)\"\"\n return $false\n }\n \"\n );\n\n var result = await ExecuteWithTimeoutAsync(powerShell, 15);\n bool isInstalled = result.FirstOrDefault();\n\n _logService.LogInformation($\"OneDrive registry check result: {isInstalled}\");\n return isInstalled;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking OneDrive installation\", ex);\n return false;\n }\n }\n\n /// \n public async Task IsOneNoteInstalledAsync()\n {\n try\n {\n _logService.LogInformation(\"Checking if OneNote is installed\");\n\n // First, try a simpler, more direct approach without recursive searches\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n\n // Use a more targeted, non-recursive approach for better performance and reliability\n powerShell.AddScript(\n @\"\n try {\n # Check for OneNote in common registry locations using direct paths instead of recursive searches\n \n # Check standard uninstall keys\n $installed = $false\n \n # Check for OneNote in standard uninstall locations\n $hklmKeys = Get-ChildItem \"\"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\"\" -ErrorAction SilentlyContinue | \n Get-ItemProperty -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like \"\"*OneNote*\"\" }\n if ($hklmKeys) { $installed = $true }\n \n $hkcuKeys = Get-ChildItem \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\"\" -ErrorAction SilentlyContinue | \n Get-ItemProperty -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like \"\"*OneNote*\"\" }\n if ($hkcuKeys) { $installed = $true }\n \n # Check for Wow6432Node registry keys (for 32-bit apps on 64-bit Windows)\n $hklmWowKeys = Get-ChildItem \"\"HKLM:\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\"\" -ErrorAction SilentlyContinue | \n Get-ItemProperty -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like \"\"*OneNote*\"\" }\n if ($hklmWowKeys) { $installed = $true }\n \n # Check for UWP/Store app version\n try {\n $appxPackage = Get-AppxPackage -Name Microsoft.Office.OneNote -ErrorAction SilentlyContinue\n if ($appxPackage) { $installed = $true }\n } catch {\n # Ignore errors with AppX commands\n }\n \n return $installed\n }\n catch {\n Write-Output \"\"Error checking OneNote registry: $($_.Exception.Message)\"\"\n return $false\n }\n \"\n );\n\n // Use a shorter timeout to prevent hanging\n var result = await ExecuteWithTimeoutAsync(powerShell, 10);\n bool isInstalled = result.FirstOrDefault();\n\n _logService.LogInformation($\"OneNote registry check result: {isInstalled}\");\n return isInstalled;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking OneNote installation\", ex);\n // Don't crash the application if OneNote check fails\n return false;\n }\n }\n\n // SetExecutionPolicy is now handled by PowerShellFactory\n\n /// \n /// Clears the installation status cache, forcing fresh checks on next query.\n /// Call this after installing or removing items.\n /// \n public void ClearInstallationStatusCache()\n {\n lock (_cacheLock)\n {\n _installationStatusCache.Clear();\n }\n }\n\n /// \n /// Executes a PowerShell command with a timeout.\n /// \n /// The type of result to return.\n /// The PowerShell instance.\n /// The timeout in seconds.\n /// The result of the PowerShell command.\n private async Task> ExecuteWithTimeoutAsync(\n PowerShell powerShell,\n int timeoutSeconds\n )\n {\n // Create a cancellation token source for the timeout\n using var cancellationTokenSource = new CancellationTokenSource();\n\n try\n {\n // Set up the timeout\n cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(timeoutSeconds));\n\n // Run the PowerShell command with cancellation support\n var task = Task.Run(\n () =>\n {\n try\n {\n // Check if cancellation was requested before starting\n if (cancellationTokenSource.Token.IsCancellationRequested)\n {\n _logService.LogWarning(\n \"PowerShell execution cancelled before starting\"\n );\n return new System.Collections.ObjectModel.Collection();\n }\n\n // Execute the PowerShell command\n return powerShell.Invoke();\n }\n catch (Exception innerEx)\n {\n _logService.LogError(\n $\"Error in PowerShell execution thread: {innerEx.Message}\",\n innerEx\n );\n return new System.Collections.ObjectModel.Collection();\n }\n },\n cancellationTokenSource.Token\n );\n\n // Wait for completion or timeout\n if (\n await Task.WhenAny(\n task,\n Task.Delay(TimeSpan.FromSeconds(timeoutSeconds), cancellationTokenSource.Token)\n ) == task\n )\n {\n // Task completed within timeout\n if (task.IsCompletedSuccessfully)\n {\n return await task;\n }\n else if (task.IsFaulted)\n {\n _logService.LogError(\n $\"PowerShell task faulted: {task.Exception?.Message}\",\n task.Exception\n );\n }\n else if (task.IsCanceled)\n {\n _logService.LogWarning(\"PowerShell task was cancelled\");\n }\n }\n else\n {\n // Task timed out, attempt to cancel it\n _logService.LogWarning(\n $\"PowerShell execution timed out after {timeoutSeconds} seconds\"\n );\n cancellationTokenSource.Cancel();\n\n // Try to stop the PowerShell pipeline if it's still running\n try\n {\n powerShell.Stop();\n }\n catch (Exception stopEx)\n {\n _logService.LogWarning($\"Error stopping PowerShell pipeline: {stopEx.Message}\");\n }\n }\n\n // Return empty collection if we reached here (timeout or error)\n return new System.Collections.ObjectModel.Collection();\n }\n catch (OperationCanceledException)\n {\n _logService.LogWarning(\n $\"PowerShell execution cancelled after {timeoutSeconds} seconds\"\n );\n return new System.Collections.ObjectModel.Collection();\n }\n catch (Exception ex)\n {\n _logService.LogError(\n $\"Error executing PowerShell command with timeout: {ex.Message}\",\n ex\n );\n return new System.Collections.ObjectModel.Collection();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScriptUpdateService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\n/// \n/// Implementation of IScriptUpdateService that provides methods for updating script content.\n/// \npublic class ScriptUpdateService : IScriptUpdateService\n{\n private readonly ILogService _logService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IScriptContentModifier _scriptContentModifier;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The app discovery service.\n /// The script content modifier.\n public ScriptUpdateService(\n ILogService logService,\n IAppDiscoveryService appDiscoveryService,\n IScriptContentModifier scriptContentModifier)\n {\n _logService = logService;\n _appDiscoveryService = appDiscoveryService;\n _scriptContentModifier = scriptContentModifier;\n }\n\n /// \n public async Task UpdateExistingBloatRemovalScriptAsync(\n List appNames,\n Dictionary> appsWithRegistry,\n Dictionary appSubPackages,\n bool isInstallOperation = false)\n {\n try\n {\n string bloatRemovalScriptPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n \"Winhance\",\n \"Scripts\",\n \"BloatRemoval.ps1\"\n );\n \n _logService.LogInformation($\"Checking for BloatRemoval.ps1 at path: {bloatRemovalScriptPath}\");\n \n string scriptContent;\n \n if (!File.Exists(bloatRemovalScriptPath))\n {\n _logService.LogWarning($\"BloatRemoval.ps1 file not found at: {bloatRemovalScriptPath}\");\n \n // Create the directory if it doesn't exist\n string scriptDirectory = Path.GetDirectoryName(bloatRemovalScriptPath);\n if (!Directory.Exists(scriptDirectory))\n {\n _logService.LogInformation($\"Creating directory: {scriptDirectory}\");\n Directory.CreateDirectory(scriptDirectory);\n }\n \n // Create a basic BloatRemoval.ps1 file if it doesn't exist\n _logService.LogInformation(\"Creating a new BloatRemoval.ps1 file\");\n string basicScriptContent = @\"\n# BloatRemoval.ps1\n# This script removes Windows bloatware apps and prevents them from reinstalling\n# Source: Winhance (https://github.com/memstechtips/Winhance)\n# Generated by Winhance on \" + DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\") + @\"\n\n#region Definitions\n# Capabilities to remove\n$capabilities = @(\n)\n\n# Packages to remove\n$packages = @(\n)\n\n# Optional Features to disable\n$optionalFeatures = @(\n)\n#endregion\n\n#region Process Capabilities\nWrite-Host \"\"=== Removing Windows Capabilities ===\"\" -ForegroundColor Cyan\nforeach ($capability in $capabilities) {\n Write-Host \"\"Removing capability: $capability\"\" -ForegroundColor Yellow\n Remove-WindowsCapability -Online -Name $capability | Out-Null\n}\n#endregion\n\n#region Process Packages\nWrite-Host \"\"=== Removing Windows Apps ===\"\" -ForegroundColor Cyan\nforeach ($package in $packages) {\n Write-Host \"\"Removing package: $package\"\" -ForegroundColor Yellow\n Get-AppxPackage -Name $package -AllUsers | ForEach-Object {\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }\n}\n#endregion\n\n#region Process Optional Features\nWrite-Host \"\"=== Disabling Optional Features ===\"\" -ForegroundColor Cyan\nforeach ($feature in $optionalFeatures) {\n Write-Host \"\"Disabling optional feature: $feature\"\" -ForegroundColor Yellow\n Disable-WindowsOptionalFeature -Online -FeatureName $feature -NoRestart | Out-Null\n}\n#endregion\n\n#region Registry Settings\n# Registry settings\n#endregion\n\n# Prevent apps from reinstalling\nreg add \"\"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\CloudContent\"\" /v \"\"DisableWindowsConsumerFeatures\"\" /t REG_DWORD /d 1 /f | Out-Null\n\n\";\n await File.WriteAllTextAsync(bloatRemovalScriptPath, basicScriptContent);\n scriptContent = basicScriptContent;\n _logService.LogInformation(\"Created new BloatRemoval.ps1 file\");\n }\n else\n {\n _logService.LogInformation(\"BloatRemoval.ps1 file found, reading content\");\n scriptContent = await File.ReadAllTextAsync(bloatRemovalScriptPath);\n }\n\n // Separate capabilities, packages, and optional features\n var capabilities = new List();\n var packages = new List();\n var optionalFeatures = new List();\n\n foreach (var appName in appNames)\n {\n if (\n !appName.Equals(\"Edge\", StringComparison.OrdinalIgnoreCase)\n && !appName.Equals(\"OneDrive\", StringComparison.OrdinalIgnoreCase)\n )\n {\n // Check if this is an OptionalFeature\n bool isOptionalFeature = false;\n bool isCapability = false;\n\n // Get app info from the catalog\n var allRemovableApps = (\n await _appDiscoveryService.GetStandardAppsAsync()\n ).ToList();\n var appInfo = allRemovableApps.FirstOrDefault(a =>\n a.PackageName.Equals(appName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (appInfo != null)\n {\n isOptionalFeature = appInfo.Type == AppType.OptionalFeature;\n isCapability = appInfo.Type == AppType.Capability;\n }\n\n // Check if this app has registry settings\n if (appsWithRegistry.TryGetValue(appName, out var registrySettings))\n {\n // Look for a special metadata registry setting that indicates if this is a capability\n var capabilitySetting = registrySettings.FirstOrDefault(s =>\n s.Name.Equals(\"IsCapability\", StringComparison.OrdinalIgnoreCase)\n );\n\n if (\n capabilitySetting != null\n && capabilitySetting.Value is bool capabilityValue\n )\n {\n isCapability = capabilityValue;\n }\n }\n\n // Extract the base name without version for capability detection\n string baseAppName = appName;\n if (appName.Contains(\"~~~~\"))\n {\n // Extract the base name before the version (~~~~)\n baseAppName = appName.Split('~')[0];\n _logService.LogInformation($\"Extracted base capability name '{baseAppName}' from '{appName}'\");\n }\n \n // Check if this is a known Windows optional feature\n if (\n appName.Equals(\"Recall\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"NetFx3\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"Microsoft-Hyper-V-All\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"Microsoft-Hyper-V-Tools-All\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"Microsoft-Hyper-V-Hypervisor\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"Microsoft-Windows-Subsystem-Linux\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"MicrosoftCorporationII.WindowsSubsystemForAndroid\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"Containers-DisposableClientVM\", StringComparison.OrdinalIgnoreCase) ||\n isOptionalFeature\n )\n {\n _logService.LogInformation($\"Adding {appName} to optional features array\");\n optionalFeatures.Add(appName);\n continue;\n }\n \n // Known capabilities have specific formats\n if (\n isCapability\n || baseAppName.Equals(\n \"Browser.InternetExplorer\",\n StringComparison.OrdinalIgnoreCase\n )\n || baseAppName.Equals(\"MathRecognizer\", StringComparison.OrdinalIgnoreCase)\n || baseAppName.Equals(\"OpenSSH.Client\", StringComparison.OrdinalIgnoreCase)\n || baseAppName.Equals(\"OpenSSH.Server\", StringComparison.OrdinalIgnoreCase)\n || baseAppName.Equals(\n \"Microsoft.Windows.PowerShell.ISE\",\n StringComparison.OrdinalIgnoreCase\n )\n || baseAppName.Equals(\"App.StepsRecorder\", StringComparison.OrdinalIgnoreCase)\n || baseAppName.Equals(\n \"Media.WindowsMediaPlayer\",\n StringComparison.OrdinalIgnoreCase\n )\n || baseAppName.Equals(\n \"App.Support.QuickAssist\",\n StringComparison.OrdinalIgnoreCase\n )\n || baseAppName.Equals(\n \"Microsoft.Windows.WordPad\",\n StringComparison.OrdinalIgnoreCase\n )\n || baseAppName.Equals(\n \"Microsoft.Windows.MSPaint\",\n StringComparison.OrdinalIgnoreCase\n )\n // Check if the app name contains version numbers in the format ~~~~0.0.1.0\n || appName.Contains(\"~~~~\")\n )\n {\n _logService.LogInformation($\"Adding {appName} to capabilities array\");\n capabilities.Add(appName);\n }\n else\n {\n // Explicitly handle Copilot and Xbox packages\n bool isCopilotOrXbox =\n appName.Contains(\"Copilot\", StringComparison.OrdinalIgnoreCase)\n || appName.Contains(\"Xbox\", StringComparison.OrdinalIgnoreCase);\n \n _logService.LogInformation($\"Adding {appName} to packages array\");\n packages.Add(appName);\n }\n }\n }\n\n // Process subpackages and add them to the packages list\n if (appSubPackages != null && appSubPackages.Count > 0)\n {\n _logService.LogInformation(\n $\"Processing {appSubPackages.Count} app entries with subpackages\"\n );\n\n foreach (var packageEntry in appSubPackages)\n {\n string parentPackage = packageEntry.Key;\n string[] subPackages = packageEntry.Value;\n\n // Only process subpackages if the parent package is in the packages list\n // or if it's a special case like Copilot or Xbox\n bool isSpecialApp =\n parentPackage.Contains(\"Copilot\", StringComparison.OrdinalIgnoreCase)\n || parentPackage.Contains(\"Xbox\", StringComparison.OrdinalIgnoreCase)\n || parentPackage.Equals(\n \"Microsoft.GamingApp\",\n StringComparison.OrdinalIgnoreCase\n );\n\n if (packages.Contains(parentPackage) || isSpecialApp)\n {\n if (subPackages != null && subPackages.Length > 0)\n {\n _logService.LogInformation(\n $\"Adding {subPackages.Length} subpackages for {parentPackage}\"\n );\n\n foreach (var subPackage in subPackages)\n {\n if (\n !packages.Contains(subPackage, StringComparer.OrdinalIgnoreCase)\n )\n {\n _logService.LogInformation(\n $\"Adding subpackage: {subPackage} for {parentPackage}\"\n );\n packages.Add(subPackage);\n }\n }\n }\n }\n }\n }\n\n // Update the script content with new entries\n if (capabilities.Count > 0)\n {\n scriptContent = UpdateCapabilitiesArrayInScript(scriptContent, capabilities, isInstallOperation);\n }\n\n if (optionalFeatures.Count > 0)\n {\n scriptContent = UpdateOptionalFeaturesInScript(scriptContent, optionalFeatures, isInstallOperation);\n }\n\n if (packages.Count > 0)\n {\n scriptContent = UpdatePackagesArrayInScript(scriptContent, packages, isInstallOperation);\n }\n\n if (appsWithRegistry.Count > 0)\n {\n scriptContent = UpdateRegistrySettingsInScript(scriptContent, appsWithRegistry);\n }\n\n // Save the updated script\n await File.WriteAllTextAsync(bloatRemovalScriptPath, scriptContent);\n\n // Return the updated script\n return new RemovalScript\n {\n Name = \"BloatRemoval\",\n Content = scriptContent,\n TargetScheduledTaskName = \"Winhance\\\\BloatRemoval\",\n RunOnStartup = true,\n };\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating existing BloatRemoval script: {ex.Message}\", ex);\n _logService.LogError($\"Stack trace: {ex.StackTrace}\");\n \n // Create a basic error report\n try\n {\n string errorReportPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.Desktop),\n \"WinhanceScriptUpdateError.txt\"\n );\n \n string errorReport = $@\"\nScript Update Error Report\nTime: {DateTime.Now}\nError: {ex.Message}\nStack Trace: {ex.StackTrace}\nInner Exception: {ex.InnerException?.Message}\n\nApp Names: {string.Join(\", \", appNames)}\nApps with Registry: {appsWithRegistry.Count}\nApp SubPackages: {appSubPackages.Count}\n\";\n \n await File.WriteAllTextAsync(errorReportPath, errorReport);\n _logService.LogInformation($\"Error report written to: {errorReportPath}\");\n }\n catch (Exception reportEx)\n {\n _logService.LogError($\"Failed to write error report: {reportEx.Message}\");\n }\n \n throw;\n }\n }\n\n /// \n public string UpdateCapabilitiesArrayInScript(string scriptContent, List capabilities, bool isInstallOperation = false)\n {\n try\n {\n _logService.LogInformation($\"Updating capabilities array with {capabilities.Count} capabilities\");\n\n // Find the capabilities array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$capabilities = @(\");\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $capabilities array in BloatRemoval.ps1\");\n \n // If this is an install operation, we don't need to add anything\n if (isInstallOperation)\n {\n _logService.LogInformation(\"Install operation with no capabilities array found - nothing to remove\");\n return scriptContent;\n }\n \n // For removal operations, we need to add the capabilities array and processing code\n _logService.LogInformation(\"Creating capabilities array in BloatRemoval.ps1\");\n \n // Find a good place to insert the section (at the beginning of the script or before packages)\n int insertIndex = scriptContent.IndexOf(\"$packages = @(\");\n if (insertIndex == -1)\n {\n // If no packages array, find the first non-comment line\n var scriptLines = scriptContent.Split('\\n');\n for (int i = 0; i < scriptLines.Length; i++)\n {\n if (!scriptLines[i].TrimStart().StartsWith(\"#\") && !string.IsNullOrWhiteSpace(scriptLines[i]))\n {\n insertIndex = scriptContent.IndexOf(scriptLines[i]);\n break;\n }\n }\n \n // If still not found, insert at the beginning\n if (insertIndex == -1)\n {\n insertIndex = 0;\n }\n }\n \n // Create the capabilities section\n var capabilitiesSection = new StringBuilder();\n capabilitiesSection.AppendLine(\"# Capabilities to remove\");\n capabilitiesSection.AppendLine(\"$capabilities = @(\");\n \n // Add capabilities without trailing comma on the last item\n for (int i = 0; i < capabilities.Count; i++)\n {\n string capability = capabilities[i];\n if (i < capabilities.Count - 1)\n {\n capabilitiesSection.AppendLine($\" '{capability}',\");\n }\n else\n {\n capabilitiesSection.AppendLine($\" '{capability}'\");\n }\n }\n \n capabilitiesSection.AppendLine(\")\");\n capabilitiesSection.AppendLine();\n capabilitiesSection.AppendLine(\"# Process capabilities\");\n capabilitiesSection.AppendLine(\"foreach ($capability in $capabilities) {\");\n capabilitiesSection.AppendLine(\" Write-Host \\\"Removing capability: $capability\\\" -ForegroundColor Yellow\");\n capabilitiesSection.AppendLine(\" Remove-WindowsCapability -Online -Name $capability | Out-Null\");\n capabilitiesSection.AppendLine(\"}\");\n capabilitiesSection.AppendLine();\n \n // Insert the section\n return scriptContent.Substring(0, insertIndex) \n + capabilitiesSection.ToString() \n + scriptContent.Substring(insertIndex);\n }\n\n // Find the end of the capabilities array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find end of $capabilities array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the capabilities in the array\n var existingCapabilities = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var capability = trimmedLine.Trim('\\'', '\"', ' ', ',');\n existingCapabilities.Add(capability);\n }\n }\n\n bool modified = false;\n \n if (isInstallOperation)\n {\n // For install operations, REMOVE the capability from the list\n foreach (var capability in capabilities)\n {\n // Extract the base name without version for capability matching\n string baseCapabilityName = capability;\n if (capability.Contains(\"~~~~\"))\n {\n // Extract the base name before the version (~~~~)\n baseCapabilityName = capability.Split('~')[0];\n _logService.LogInformation($\"Extracted base capability name '{baseCapabilityName}' from '{capability}' for removal\");\n }\n \n // Find any capability in the list that matches the base name (regardless of version)\n var matchingCapabilities = existingCapabilities\n .Where(c => c.StartsWith(baseCapabilityName, StringComparison.OrdinalIgnoreCase) || \n (c.Contains(\"~~~~\") && c.Split('~')[0].Equals(baseCapabilityName, StringComparison.OrdinalIgnoreCase)))\n .ToList();\n \n foreach (var matchingCapability in matchingCapabilities)\n {\n existingCapabilities.Remove(matchingCapability);\n _logService.LogInformation($\"Removed capability: {matchingCapability} from BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n // Even if no capabilities were found to remove, we should still return the updated script\n // This ensures the method doesn't exit early when no matches are found\n if (!modified)\n {\n _logService.LogInformation(\"No capabilities to remove from BloatRemoval.ps1\");\n }\n }\n else\n {\n // For removal operations, ADD the capability to the list\n foreach (var capability in capabilities)\n {\n if (!existingCapabilities.Contains(capability, StringComparer.OrdinalIgnoreCase))\n {\n existingCapabilities.Add(capability);\n _logService.LogInformation($\"Added capability: {capability} to BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n if (!modified)\n {\n _logService.LogInformation(\"No new capabilities to add to BloatRemoval.ps1\");\n return scriptContent;\n }\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$capabilities = @(\");\n\n // Add capabilities without trailing comma on the last item\n for (int i = 0; i < existingCapabilities.Count; i++)\n {\n string capability = existingCapabilities[i];\n if (i < existingCapabilities.Count - 1)\n {\n newArrayContent.AppendLine($\" '{capability}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{capability}'\");\n }\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error updating capabilities array in script\", ex);\n return scriptContent;\n }\n }\n\n /// \n public string UpdatePackagesArrayInScript(string scriptContent, List packages, bool isInstallOperation = false)\n {\n try\n {\n _logService.LogInformation($\"Updating packages array with {packages.Count} packages\");\n\n // Find the packages array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$packages = @(\");\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the packages array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find end of $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the packages in the array\n var existingPackages = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var package = trimmedLine.Trim('\\'', '\"', ' ', ',');\n existingPackages.Add(package);\n }\n }\n\n bool modified = false;\n \n if (isInstallOperation)\n {\n // For install operations, REMOVE the package from the list\n foreach (var package in packages)\n {\n // Extract the base name without version for package matching\n string basePackageName = package;\n if (package.Contains(\"~~~~\"))\n {\n // Extract the base name before the version (~~~~)\n basePackageName = package.Split('~')[0];\n _logService.LogInformation($\"Extracted base package name '{basePackageName}' from '{package}' for removal\");\n }\n \n // Find any package in the list that matches the base name (regardless of version)\n var matchingPackages = existingPackages\n .Where(p => p.StartsWith(basePackageName, StringComparison.OrdinalIgnoreCase) || \n (p.Contains(\"~~~~\") && p.Split('~')[0].Equals(basePackageName, StringComparison.OrdinalIgnoreCase)))\n .ToList();\n \n foreach (var matchingPackage in matchingPackages)\n {\n existingPackages.Remove(matchingPackage);\n _logService.LogInformation($\"Removed package: {matchingPackage} from BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n if (!modified)\n {\n _logService.LogInformation(\"No packages to remove from BloatRemoval.ps1\");\n }\n }\n else\n {\n // For removal operations, ADD the package to the list\n foreach (var package in packages)\n {\n if (!existingPackages.Contains(package, StringComparer.OrdinalIgnoreCase))\n {\n existingPackages.Add(package);\n _logService.LogInformation($\"Added package: {package} to BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n if (!modified)\n {\n _logService.LogInformation(\"No new packages to add to BloatRemoval.ps1\");\n return scriptContent;\n }\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$packages = @(\");\n\n // Add packages without trailing comma on the last item\n for (int i = 0; i < existingPackages.Count; i++)\n {\n string package = existingPackages[i];\n if (i < existingPackages.Count - 1)\n {\n newArrayContent.AppendLine($\" '{package}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{package}'\");\n }\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error updating packages array in script\", ex);\n return scriptContent;\n }\n }\n\n /// \n public string UpdateOptionalFeaturesInScript(string scriptContent, List features, bool isInstallOperation = false)\n {\n try\n {\n _logService.LogInformation($\"Updating optional features with {features.Count} features\");\n\n // Check if the optional features section exists\n int sectionStartIndex = scriptContent.IndexOf(\"# Disable Optional Features\");\n \n // If the section doesn't exist, create it\n if (sectionStartIndex == -1)\n {\n _logService.LogInformation(\"Creating Optional Features section in BloatRemoval.ps1\");\n \n // Find a good place to insert the section (after the packages section)\n int packagesEndIndex = -1;\n \n // First, try to find the #endregion marker after the packages section\n int processPackagesIndex = scriptContent.IndexOf(\"# Process Packages\");\n if (processPackagesIndex != -1)\n {\n int endRegionIndex = scriptContent.IndexOf(\"#endregion\", processPackagesIndex);\n if (endRegionIndex != -1)\n {\n // Find the end of the line after the #endregion\n int newlineIndex = scriptContent.IndexOf('\\n', endRegionIndex);\n if (newlineIndex != -1)\n {\n packagesEndIndex = newlineIndex + 1; // Include the newline\n }\n else\n {\n packagesEndIndex = scriptContent.Length;\n }\n }\n }\n \n // If we couldn't find the #endregion marker, look for the Registry settings section\n if (packagesEndIndex == -1)\n {\n int registryIndex = scriptContent.IndexOf(\"# Registry settings\");\n if (registryIndex != -1)\n {\n packagesEndIndex = registryIndex;\n }\n }\n \n // If we still can't find a good insertion point, look for the end of the packages foreach loop\n if (packagesEndIndex == -1)\n {\n int packagesForEachIndex = scriptContent.IndexOf(\"foreach ($package in $packages)\");\n if (packagesForEachIndex != -1)\n {\n // Find the matching closing brace for the foreach loop\n int openBraces = 0;\n int closeBraces = 0;\n int currentIndex = packagesForEachIndex;\n \n while (currentIndex < scriptContent.Length)\n {\n if (scriptContent[currentIndex] == '{')\n {\n openBraces++;\n }\n else if (scriptContent[currentIndex] == '}')\n {\n closeBraces++;\n if (closeBraces == openBraces && openBraces > 0)\n {\n // Found the matching closing brace\n int braceIndex = currentIndex;\n \n // Find the end of the line after the closing brace\n int newlineIndex = scriptContent.IndexOf('\\n', braceIndex);\n if (newlineIndex != -1)\n {\n packagesEndIndex = newlineIndex + 1; // Include the newline\n }\n else\n {\n packagesEndIndex = scriptContent.Length;\n }\n break;\n }\n }\n currentIndex++;\n }\n }\n }\n \n // If we still couldn't find a good insertion point, just append to the end of the script\n if (packagesEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find a good insertion point for optional features section, appending to the end\");\n packagesEndIndex = scriptContent.Length;\n }\n \n // Create the optional features section\n var optionalFeaturesSection = new StringBuilder();\n optionalFeaturesSection.AppendLine();\n optionalFeaturesSection.AppendLine(\"# Disable Optional Features\");\n optionalFeaturesSection.AppendLine(\"$optionalFeatures = @(\");\n \n // Add features without trailing comma on the last item\n for (int i = 0; i < features.Count; i++)\n {\n string feature = features[i];\n if (i < features.Count - 1)\n {\n optionalFeaturesSection.AppendLine($\" '{feature}',\");\n }\n else\n {\n optionalFeaturesSection.AppendLine($\" '{feature}'\");\n }\n }\n \n optionalFeaturesSection.AppendLine(\")\");\n optionalFeaturesSection.AppendLine();\n optionalFeaturesSection.AppendLine(\"foreach ($feature in $optionalFeatures) {\");\n optionalFeaturesSection.AppendLine(\" Write-Host \\\"Disabling optional feature: $feature\\\" -ForegroundColor Yellow\");\n optionalFeaturesSection.AppendLine(\" Disable-WindowsOptionalFeature -Online -FeatureName $feature -NoRestart | Out-Null\");\n optionalFeaturesSection.AppendLine(\"}\");\n \n // Insert the section\n return scriptContent.Substring(0, packagesEndIndex) \n + optionalFeaturesSection.ToString() \n + scriptContent.Substring(packagesEndIndex);\n }\n \n // If the section exists, update it\n int arrayStartIndex = scriptContent.IndexOf(\"$optionalFeatures = @(\", sectionStartIndex);\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $optionalFeatures array in BloatRemoval.ps1\");\n return scriptContent;\n }\n \n // Find the end of the optional features array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find end of $optionalFeatures array in BloatRemoval.ps1\");\n return scriptContent;\n }\n \n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n \n // Parse the optional features in the array\n var optionalFeatures = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var feature = trimmedLine.Trim('\\'', '\"', ' ', ',');\n optionalFeatures.Add(feature);\n }\n }\n \n bool modified = false;\n \n if (isInstallOperation)\n {\n // For install operations, REMOVE the optional feature from the list\n foreach (var feature in features)\n {\n // Extract the base name without version for feature matching\n string baseFeatureName = feature;\n if (feature.Contains(\"~~~~\"))\n {\n // Extract the base name before the version (~~~~)\n baseFeatureName = feature.Split('~')[0];\n _logService.LogInformation($\"Extracted base feature name '{baseFeatureName}' from '{feature}' for removal\");\n }\n \n // Find any feature in the list that matches the base name (regardless of version)\n var matchingFeatures = optionalFeatures\n .Where(f => f.StartsWith(baseFeatureName, StringComparison.OrdinalIgnoreCase) || \n (f.Contains(\"~~~~\") && f.Split('~')[0].Equals(baseFeatureName, StringComparison.OrdinalIgnoreCase)))\n .ToList();\n \n foreach (var matchingFeature in matchingFeatures)\n {\n optionalFeatures.Remove(matchingFeature);\n _logService.LogInformation($\"Removed optional feature: {matchingFeature} from BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n if (!modified)\n {\n _logService.LogInformation(\"No optional features to remove from BloatRemoval.ps1\");\n }\n }\n else\n {\n // For removal operations, ADD the optional feature to the list\n foreach (var feature in features)\n {\n if (!optionalFeatures.Contains(feature, StringComparer.OrdinalIgnoreCase))\n {\n optionalFeatures.Add(feature);\n _logService.LogInformation($\"Added optional feature: {feature} to BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n if (!modified)\n {\n _logService.LogInformation(\"No new optional features to add to BloatRemoval.ps1\");\n }\n }\n \n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$optionalFeatures = @(\");\n \n // Add features without trailing comma on the last item\n for (int i = 0; i < optionalFeatures.Count; i++)\n {\n string feature = optionalFeatures[i];\n if (i < optionalFeatures.Count - 1)\n {\n newArrayContent.AppendLine($\" '{feature}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{feature}'\");\n }\n }\n \n newArrayContent.Append(\")\");\n \n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error updating optional features in script\", ex);\n return scriptContent;\n }\n }\n\n /// \n public string UpdateRegistrySettingsInScript(string scriptContent, Dictionary> appsWithRegistry)\n {\n try\n {\n _logService.LogInformation($\"Updating registry settings for {appsWithRegistry.Count} apps\");\n\n // Find the registry settings section\n int registrySectionIndex = scriptContent.IndexOf(\"# Registry settings\");\n if (registrySectionIndex == -1)\n {\n // If the registry settings section doesn't exist, create it\n _logService.LogInformation(\"Creating Registry settings section in BloatRemoval.ps1\");\n \n // Find a good place to insert the section (at the end of the script)\n int insertIndex = scriptContent.Length;\n \n // Create the registry settings section\n var registrySection = new StringBuilder();\n registrySection.AppendLine();\n registrySection.AppendLine(\"# Registry settings\");\n \n // Add registry settings for each app\n foreach (var appEntry in appsWithRegistry)\n {\n string appName = appEntry.Key;\n List settings = appEntry.Value;\n \n if (settings == null || settings.Count == 0)\n {\n continue;\n }\n \n registrySection.AppendLine();\n registrySection.AppendLine($\"# Registry settings for {appName}\");\n \n foreach (var setting in settings)\n {\n if (setting.Path == null || setting.Name == null)\n {\n continue;\n }\n \n string regType = RegistryScriptHelper.GetRegTypeString(setting.ValueKind);\n string regValue = FormatRegistryValue(setting.Value, setting.ValueKind);\n \n registrySection.AppendLine($\"reg add \\\"{setting.Path}\\\" /v \\\"{setting.Name}\\\" /t {regType} /d {regValue} /f\");\n }\n }\n \n // Insert the section\n return scriptContent + registrySection.ToString();\n }\n \n // If the registry settings section exists, update it\n StringBuilder updatedContent = new StringBuilder(scriptContent);\n \n // Add registry settings for each app\n foreach (var appEntry in appsWithRegistry)\n {\n string appName = appEntry.Key;\n List settings = appEntry.Value;\n \n if (settings == null || settings.Count == 0)\n {\n continue;\n }\n \n // Check if this app already has registry settings in the script\n string appSectionHeader = $\"# Registry settings for {appName}\";\n int appSectionIndex = updatedContent.ToString().IndexOf(appSectionHeader, registrySectionIndex);\n \n if (appSectionIndex == -1)\n {\n // App doesn't have registry settings yet, add them\n _logService.LogInformation($\"Adding registry settings for {appName} to BloatRemoval.ps1\");\n \n // Find the end of the registry settings section or the start of the next major section\n int endOfRegistrySection = updatedContent.ToString().IndexOf(\"# Prevent apps from reinstalling\", registrySectionIndex);\n if (endOfRegistrySection == -1)\n {\n endOfRegistrySection = updatedContent.Length;\n }\n \n // Create the app registry settings section\n var appRegistrySection = new StringBuilder();\n appRegistrySection.AppendLine();\n appRegistrySection.AppendLine(appSectionHeader);\n \n foreach (var setting in settings)\n {\n if (setting.Path == null || setting.Name == null)\n {\n continue;\n }\n \n string regType = RegistryScriptHelper.GetRegTypeString(setting.ValueKind);\n string regValue = FormatRegistryValue(setting.Value, setting.ValueKind);\n \n appRegistrySection.AppendLine($\"reg add \\\"{setting.Path}\\\" /v \\\"{setting.Name}\\\" /t {regType} /d {regValue} /f\");\n }\n \n // Insert the app registry settings section\n updatedContent.Insert(endOfRegistrySection, appRegistrySection.ToString());\n }\n else\n {\n // App already has registry settings, update them\n _logService.LogInformation($\"Updating registry settings for {appName} in BloatRemoval.ps1\");\n \n // Find the end of the app section (next app section or end of registry section)\n int nextAppSectionIndex = updatedContent.ToString().IndexOf(\"# Registry settings for\", appSectionIndex + appSectionHeader.Length);\n if (nextAppSectionIndex == -1)\n {\n nextAppSectionIndex = updatedContent.ToString().IndexOf(\"# Prevent apps from reinstalling\", appSectionIndex);\n if (nextAppSectionIndex == -1)\n {\n nextAppSectionIndex = updatedContent.Length;\n }\n }\n \n // Create the updated app registry settings section\n var updatedAppRegistrySection = new StringBuilder();\n updatedAppRegistrySection.AppendLine(appSectionHeader);\n \n foreach (var setting in settings)\n {\n if (setting.Path == null || setting.Name == null)\n {\n continue;\n }\n \n string regType = RegistryScriptHelper.GetRegTypeString(setting.ValueKind);\n string regValue = FormatRegistryValue(setting.Value, setting.ValueKind);\n \n updatedAppRegistrySection.AppendLine($\"reg add \\\"{setting.Path}\\\" /v \\\"{setting.Name}\\\" /t {regType} /d {regValue} /f\");\n }\n \n // Replace the old app registry settings section with the new one\n updatedContent.Remove(appSectionIndex, nextAppSectionIndex - appSectionIndex);\n updatedContent.Insert(appSectionIndex, updatedAppRegistrySection.ToString());\n }\n }\n \n return updatedContent.ToString();\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error updating registry settings in script\", ex);\n return scriptContent;\n }\n }\n\n /// \n /// Formats a registry value for use in a reg.exe command.\n /// \n /// The value to format.\n /// The registry value kind.\n /// The formatted value.\n private string FormatRegistryValue(object value, RegistryValueKind valueKind)\n {\n if (value == null)\n {\n return \"\\\"\\\"\";\n }\n\n switch (valueKind)\n {\n case RegistryValueKind.String:\n case RegistryValueKind.ExpandString:\n return $\"\\\"{value}\\\"\";\n case RegistryValueKind.DWord:\n case RegistryValueKind.QWord:\n return value.ToString();\n case RegistryValueKind.Binary:\n if (value is byte[] bytes)\n {\n return BitConverter.ToString(bytes).Replace(\"-\", \",\");\n }\n return \"\\\"\\\"\";\n case RegistryValueKind.MultiString:\n if (value is string[] strings)\n {\n return $\"\\\"{string.Join(\"\\\\0\", strings)}\\\\0\\\"\";\n }\n return \"\\\"\\\"\";\n default:\n return $\"\\\"{value}\\\"\";\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/NotificationOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\n\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Notifications optimizations.\n /// \n public class NotificationOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDialogService _dialogService;\n private readonly IDependencyManager _dependencyManager;\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dialog service.\n /// The dependency manager.\n /// The view model locator.\n /// The settings registry.\n public NotificationOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDialogService dialogService,\n IDependencyManager dependencyManager,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _dependencyManager = dependencyManager ?? throw new ArgumentNullException(nameof(dependencyManager));\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n _logService.Log(LogLevel.Info, \"NotificationOptimizationsViewModel instance created\");\n }\n\n /// \n /// Loads the Notifications settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, \"NotificationOptimizationsViewModel.LoadSettingsAsync: Starting to load notification optimizations\");\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Notification optimizations from NotificationOptimizations\n var notificationOptimizations = Core.Features.Optimize.Models.NotificationOptimizations.GetNotificationOptimizations();\n _logService.Log(LogLevel.Info, $\"NotificationOptimizationsViewModel.LoadSettingsAsync: Got {notificationOptimizations?.Settings?.Count ?? 0} notification optimizations\");\n if (notificationOptimizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in notificationOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = false, // Always initialize as unchecked\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Register the setting in the settings registry if available\n if (_settingsRegistry != null && !string.IsNullOrEmpty(settingItem.Id))\n {\n _settingsRegistry.RegisterSetting(settingItem);\n _logService.Log(LogLevel.Info, $\"Registered setting {settingItem.Id} in settings registry during creation\");\n }\n\n Settings.Add(settingItem);\n _logService.Log(LogLevel.Info, $\"NotificationOptimizationsViewModel.LoadSettingsAsync: Added setting {setting.Name} to collection\");\n }\n\n // Set up property change handlers for checkboxes\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n\n _logService.Log(LogLevel.Info, $\"NotificationOptimizationsViewModel.LoadSettingsAsync: Added {Settings.Count} settings to collection\");\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n\n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading notification settings: {ex.Message}\");\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all Notifications settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"NotificationOptimizationsViewModel.CheckSettingStatusesAsync: Checking status for {Settings.Count} settings\");\n\n foreach (var setting in Settings)\n {\n if (setting.RegistrySetting != null)\n {\n // Get status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n setting.Status = status;\n\n // Get current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n setting.CurrentValue = currentValue;\n \n // Set IsRegistryValueNull property based on current value\n setting.IsRegistryValueNull = currentValue == null;\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking notification setting statuses: {ex.Message}\");\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied => \"Applied\",\n RegistrySettingStatus.NotApplied => \"Not Applied\",\n RegistrySettingStatus.Error => \"Error\",\n RegistrySettingStatus.Unknown => \"Unknown\",\n _ => \"Unknown\"\n };\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0) return;\n\n bool allSelected = Settings.All(s => s.IsSelected);\n bool anySelected = Settings.Any(s => s.IsSelected);\n\n IsSelected = allSelected;\n }\n\n /// \n /// Converts a RegistryHive enum to its string representation (HKCU, HKLM, etc.)\n /// \n /// The registry hive.\n /// The string representation of the registry hive.\n private string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => hive.ToString()\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/BaseViewModel.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Runtime.CompilerServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// Base view model class that implements INotifyPropertyChanged and provides common functionality.\n /// \n public abstract class BaseViewModel : ObservableObject, IDisposable, IViewModel\n {\n private readonly ITaskProgressService _progressService;\n private readonly ILogService _logService;\n private readonly IMessengerService _messengerService;\n private bool _isDisposed;\n private bool _isLoading;\n private string _statusText = string.Empty;\n private double _currentProgress;\n private bool _isIndeterminate;\n private ObservableCollection _logMessages =\n new ObservableCollection();\n private bool _areDetailsExpanded;\n private bool _canCancelTask;\n private bool _isTaskRunning;\n private ICommand _cancelCommand;\n\n /// \n /// Gets or sets whether the view model is loading.\n /// \n public bool IsLoading\n {\n get => _isLoading;\n protected set => SetProperty(ref _isLoading, value);\n }\n\n /// \n /// Gets the command to cancel the current task.\n /// \n public ICommand CancelCommand =>\n _cancelCommand ??= new RelayCommand(CancelCurrentTask, () => CanCancelTask);\n\n /// \n /// Gets or sets the status text.\n /// \n public string StatusText\n {\n get => _statusText;\n protected set => SetProperty(ref _statusText, value);\n }\n\n /// \n /// Gets or sets the current progress value (0-100).\n /// \n public double CurrentProgress\n {\n get => _currentProgress;\n protected set => SetProperty(ref _currentProgress, value);\n }\n\n /// \n /// Gets or sets whether the progress is indeterminate.\n /// \n public bool IsIndeterminate\n {\n get => _isIndeterminate;\n protected set => SetProperty(ref _isIndeterminate, value);\n }\n\n /// \n /// Gets the collection of log messages.\n /// \n public ObservableCollection LogMessages => _logMessages;\n\n /// \n /// Gets or sets whether the details are expanded.\n /// \n public bool AreDetailsExpanded\n {\n get => _areDetailsExpanded;\n set => SetProperty(ref _areDetailsExpanded, value);\n }\n\n /// \n /// Gets or sets whether the task can be cancelled.\n /// \n public bool CanCancelTask\n {\n get => _canCancelTask;\n protected set => SetProperty(ref _canCancelTask, value);\n }\n\n /// \n /// Gets or sets whether a task is running.\n /// \n public bool IsTaskRunning\n {\n get => _isTaskRunning;\n protected set => SetProperty(ref _isTaskRunning, value);\n }\n\n /// \n /// Gets the command to cancel the current task.\n /// \n public ICommand CancelTaskCommand { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The log service.\n /// The messenger service.\n protected BaseViewModel(\n ITaskProgressService progressService,\n ILogService logService,\n IMessengerService messengerService\n )\n {\n _progressService =\n progressService ?? throw new ArgumentNullException(nameof(progressService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _messengerService =\n messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n\n // Subscribe to progress service events\n if (_progressService != null)\n {\n _progressService.ProgressUpdated -= ProgressService_ProgressUpdated;\n _progressService.ProgressUpdated += ProgressService_ProgressUpdated;\n _progressService.LogMessageAdded -= ProgressService_LogMessageAdded;\n _progressService.LogMessageAdded += ProgressService_LogMessageAdded;\n }\n\n CancelTaskCommand = new RelayCommand(\n CancelCurrentTask,\n () => CanCancelTask && IsTaskRunning\n );\n _cancelCommand = CancelTaskCommand; // Ensure both commands point to the same implementation\n }\n\n /// \n /// Initializes a new instance of the class.\n /// This constructor is for backward compatibility.\n /// \n /// The task progress service.\n /// The messenger service.\n protected BaseViewModel(\n ITaskProgressService progressService,\n IMessengerService messengerService\n )\n : this(\n progressService,\n new Core.Features.Common.Services.LogService(),\n messengerService\n ) { }\n\n /// \n /// Initializes a new instance of the class.\n /// This constructor is for backward compatibility.\n /// \n /// The task progress service.\n protected BaseViewModel(ITaskProgressService progressService)\n : this(\n progressService,\n new Core.Features.Common.Services.LogService(),\n new Features.Common.Services.MessengerService()\n ) { }\n\n /// \n /// Disposes of the resources used by the ViewModel\n /// \n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n /// \n /// Disposes of the resources used by the ViewModel\n /// \n /// Whether to dispose of managed resources\n protected virtual void Dispose(bool disposing)\n {\n if (!_isDisposed)\n {\n if (disposing)\n {\n // Unsubscribe from events\n _progressService.ProgressUpdated -= ProgressService_ProgressUpdated;\n _progressService.LogMessageAdded -= ProgressService_LogMessageAdded;\n\n // Unregister from messenger\n if (_messengerService != null)\n {\n _messengerService.Unregister(this);\n }\n }\n\n _isDisposed = true;\n }\n }\n\n /// \n /// Finalizer to ensure resources are released\n /// \n ~BaseViewModel()\n {\n Dispose(false);\n }\n\n /// \n /// Called when the view model is navigated to\n /// \n /// Navigation parameter\n public virtual void OnNavigatedTo(object? parameter = null)\n {\n // Base implementation does nothing\n // Derived classes should override if they need to handle parameters\n }\n\n /// \n /// Handles the ProgressUpdated event of the progress service.\n /// \n /// The source of the event.\n /// The progress detail.\n private void ProgressService_ProgressUpdated(\n object? sender,\n Winhance.Core.Features.Common.Models.TaskProgressDetail detail\n )\n {\n // Update local properties\n IsLoading = _progressService.IsTaskRunning;\n StatusText = detail.StatusText ?? string.Empty;\n CurrentProgress = detail.Progress ?? 0;\n IsIndeterminate = detail.IsIndeterminate;\n IsTaskRunning = _progressService.IsTaskRunning;\n CanCancelTask =\n _progressService.IsTaskRunning\n && _progressService.CurrentTaskCancellationSource != null;\n\n // Send a message for UI updates that may occur in other threads\n _messengerService.Send(\n new TaskProgressMessage\n {\n Progress = detail.Progress ?? 0,\n StatusText = detail.StatusText ?? string.Empty,\n IsIndeterminate = detail.IsIndeterminate,\n IsTaskRunning = _progressService.IsTaskRunning,\n CanCancel =\n _progressService.IsTaskRunning\n && _progressService.CurrentTaskCancellationSource != null,\n }\n );\n }\n\n /// \n /// Handles the LogMessageAdded event of the progress service.\n /// \n /// The source of the event.\n /// The log message.\n private void ProgressService_LogMessageAdded(object? sender, string message)\n {\n if (string.IsNullOrEmpty(message))\n return;\n\n // Add to local collection\n var logMessageViewModel = new LogMessageViewModel\n {\n Message = message,\n Level = LogLevel.Info, // Default to Info since we don't have level information\n Timestamp = DateTime.Now,\n };\n\n LogMessages.Add(logMessageViewModel);\n\n // Auto-expand details on error or warning (we can't determine this from the string message)\n\n // Send a message for UI updates that may occur in other threads\n _messengerService.Send(\n new LogMessage\n {\n Message = message,\n Level = LogLevel.Info, // Default to Info since we don't have level information\n Exception = null,\n }\n );\n }\n\n /// \n /// Cancels the current task.\n /// \n protected void CancelCurrentTask()\n {\n if (_progressService.CurrentTaskCancellationSource != null && CanCancelTask)\n {\n _logService.LogInformation(\"User requested task cancellation\");\n _progressService.CancelCurrentTask();\n }\n }\n\n /// \n /// Executes an operation with progress reporting.\n /// \n /// The operation to execute.\n /// The name of the task.\n /// Whether the progress is indeterminate.\n /// A task representing the asynchronous operation.\n protected async Task ExecuteWithProgressAsync(\n Func operation,\n string taskName,\n bool isIndeterminate = false\n )\n {\n try\n {\n _progressService.StartTask(taskName, isIndeterminate);\n await operation(_progressService);\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in {taskName}: {ex.Message}\", ex);\n _progressService.AddLogMessage($\"Error: {ex.Message}\");\n throw;\n }\n finally\n {\n if (_progressService.IsTaskRunning)\n {\n _progressService.CompleteTask();\n }\n }\n }\n\n /// \n /// Executes an operation with progress reporting and returns a result.\n /// \n /// The type of the result.\n /// The operation to execute.\n /// The name of the task.\n /// Whether the progress is indeterminate.\n /// A task representing the asynchronous operation.\n protected async Task ExecuteWithProgressAsync(\n Func> operation,\n string taskName,\n bool isIndeterminate = false\n )\n {\n try\n {\n _progressService.StartTask(taskName, isIndeterminate);\n return await operation(_progressService);\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in {taskName}: {ex.Message}\", ex);\n _progressService.AddLogMessage($\"Error: {ex.Message}\");\n throw;\n }\n finally\n {\n if (_progressService.IsTaskRunning)\n {\n _progressService.CompleteTask();\n }\n }\n }\n\n /// \n /// Executes an operation with detailed progress reporting.\n /// \n /// The operation to execute.\n /// The name of the task.\n /// Whether the progress is indeterminate.\n /// A task representing the asynchronous operation.\n protected async Task ExecuteWithProgressAsync(\n Func<\n IProgress,\n CancellationToken,\n Task\n > operation,\n string taskName,\n bool isIndeterminate = false\n )\n {\n try\n {\n // Clear previous log messages\n LogMessages.Clear();\n\n _progressService.StartTask(taskName, isIndeterminate);\n var progress = _progressService.CreateDetailedProgress();\n var cancellationToken = _progressService.CurrentTaskCancellationSource.Token;\n\n await operation(progress, cancellationToken);\n }\n catch (OperationCanceledException)\n {\n _progressService.AddLogMessage(\"Operation cancelled by user\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in {taskName}: {ex.Message}\", ex);\n _progressService.AddLogMessage($\"Error: {ex.Message}\");\n throw;\n }\n finally\n {\n if (_progressService.IsTaskRunning)\n {\n _progressService.CompleteTask();\n }\n }\n }\n\n /// \n /// Executes an operation with detailed progress reporting and returns a result.\n /// \n /// The type of the result.\n /// The operation to execute.\n /// The name of the task.\n /// Whether the progress is indeterminate.\n /// A task representing the asynchronous operation.\n protected async Task ExecuteWithProgressAsync(\n Func<\n IProgress,\n CancellationToken,\n Task\n > operation,\n string taskName,\n bool isIndeterminate = false\n )\n {\n try\n {\n // Clear previous log messages\n LogMessages.Clear();\n\n _progressService.StartTask(taskName, isIndeterminate);\n var progress = _progressService.CreateDetailedProgress();\n var cancellationToken = _progressService.CurrentTaskCancellationSource.Token;\n\n return await operation(progress, cancellationToken);\n }\n catch (OperationCanceledException)\n {\n _progressService.AddLogMessage(\"Operation cancelled by user\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in {taskName}: {ex.Message}\", ex);\n _progressService.AddLogMessage($\"Error: {ex.Message}\");\n throw;\n }\n finally\n {\n if (_progressService.IsTaskRunning)\n {\n _progressService.CompleteTask();\n }\n }\n }\n\n /// \n /// Gets the progress service.\n /// \n protected ITaskProgressService ProgressService => _progressService;\n\n /// \n /// Logs an informational message.\n /// \n /// The message to log.\n protected void LogInfo(string message)\n {\n _logService.LogInformation(message);\n }\n\n /// \n /// Logs an error message.\n /// \n /// The message to log.\n /// The exception associated with the error, if any.\n protected void LogError(string message, Exception? exception = null)\n {\n _logService.LogError(message, exception);\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ViewModelRefresher.cs", "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Threading;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for refreshing view models after configuration changes.\n /// \n public class ViewModelRefresher : IViewModelRefresher\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public ViewModelRefresher(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Refreshes a view model after configuration changes.\n /// \n /// The view model to refresh.\n /// A task representing the asynchronous operation.\n public async Task RefreshViewModelAsync(object viewModel)\n {\n try\n {\n // Special handling for OptimizeViewModel\n if (viewModel is Winhance.WPF.Features.Optimize.ViewModels.OptimizeViewModel optimizeViewModel)\n {\n _logService.Log(LogLevel.Debug, \"Refreshing OptimizeViewModel and its child view models\");\n \n // Refresh child view models first\n var childViewModels = new object[]\n {\n optimizeViewModel.GamingandPerformanceOptimizationsViewModel,\n optimizeViewModel.PrivacyOptimizationsViewModel,\n optimizeViewModel.UpdateOptimizationsViewModel,\n optimizeViewModel.PowerSettingsViewModel,\n optimizeViewModel.WindowsSecuritySettingsViewModel,\n optimizeViewModel.ExplorerOptimizationsViewModel,\n optimizeViewModel.NotificationOptimizationsViewModel,\n optimizeViewModel.SoundOptimizationsViewModel\n };\n \n foreach (var childViewModel in childViewModels)\n {\n if (childViewModel != null)\n {\n // Try to refresh each child view model\n await RefreshChildViewModelAsync(childViewModel);\n }\n }\n \n // Then reload the main view model's items to reflect changes in child view models\n await optimizeViewModel.LoadItemsAsync();\n \n // Notify UI of changes using a safer approach\n try\n {\n // Try to find a method that takes a string parameter\n var methods = optimizeViewModel.GetType().GetMethods(\n System.Reflection.BindingFlags.Public |\n System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance)\n .Where(m => (m.Name == \"RaisePropertyChanged\" || m.Name == \"OnPropertyChanged\") &&\n m.GetParameters().Length == 1 &&\n m.GetParameters()[0].ParameterType == typeof(string))\n .ToList();\n \n if (methods.Any())\n {\n var method = methods.First();\n // Refresh key properties\n // Execute property change notifications on the UI thread\n ExecuteOnUIThread(() => {\n method.Invoke(optimizeViewModel, new object[] { \"Items\" });\n method.Invoke(optimizeViewModel, new object[] { \"IsInitialized\" });\n method.Invoke(optimizeViewModel, new object[] { \"IsLoading\" });\n _logService.Log(LogLevel.Debug, $\"Refreshed OptimizeViewModel properties using {method.Name} on UI thread\");\n });\n }\n else\n {\n // If no suitable method is found, try using RefreshCommand\n var refreshCommand = optimizeViewModel.GetType().GetProperty(\"RefreshCommand\")?.GetValue(optimizeViewModel) as System.Windows.Input.ICommand;\n if (refreshCommand != null && refreshCommand.CanExecute(null))\n {\n ExecuteOnUIThread(() => {\n refreshCommand.Execute(null);\n _logService.Log(LogLevel.Debug, \"Refreshed OptimizeViewModel using RefreshCommand on UI thread\");\n });\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error refreshing OptimizeViewModel: {ex.Message}\");\n }\n \n return;\n }\n \n // Standard refresh logic for other view models\n // Try multiple refresh methods in order of preference\n \n // 1. First try RefreshCommand if available\n var refreshCommandProperty = viewModel.GetType().GetProperty(\"RefreshCommand\");\n if (refreshCommandProperty != null)\n {\n var refreshCommand = refreshCommandProperty.GetValue(viewModel) as System.Windows.Input.ICommand;\n if (refreshCommand != null && refreshCommand.CanExecute(null))\n {\n ExecuteOnUIThread(() => {\n refreshCommand.Execute(null);\n _logService.Log(LogLevel.Debug, $\"Refreshed {viewModel.GetType().Name} using RefreshCommand on UI thread\");\n });\n return;\n }\n }\n \n // 2. Try RaisePropertyChanged for the Items property if the view model implements INotifyPropertyChanged\n if (viewModel is System.ComponentModel.INotifyPropertyChanged)\n {\n try\n {\n // Use a safer approach to find property changed methods\n var methods = viewModel.GetType().GetMethods(\n System.Reflection.BindingFlags.Public |\n System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance)\n .Where(m => (m.Name == \"RaisePropertyChanged\" || m.Name == \"OnPropertyChanged\") &&\n m.GetParameters().Length == 1 &&\n m.GetParameters()[0].ParameterType == typeof(string))\n .ToList();\n \n if (methods.Any())\n {\n var method = methods.First();\n ExecuteOnUIThread(() => {\n method.Invoke(viewModel, new object[] { \"Items\" });\n _logService.Log(LogLevel.Debug, $\"Refreshed {viewModel.GetType().Name} using {method.Name} on UI thread\");\n });\n return;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error finding property changed method: {ex.Message}\");\n // Continue with other refresh methods\n }\n }\n \n // 3. Try LoadItemsAsync method\n var loadItemsMethod = viewModel.GetType().GetMethod(\"LoadItemsAsync\");\n if (loadItemsMethod != null)\n {\n await (Task)loadItemsMethod.Invoke(viewModel, null);\n return;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error refreshing UI: {ex.Message}\");\n }\n }\n\n /// \n /// Refreshes a child view model after configuration changes.\n /// \n /// The child view model to refresh.\n /// A task representing the asynchronous operation.\n public async Task RefreshChildViewModelAsync(object childViewModel)\n {\n try\n {\n // Try to find and call CheckSettingStatusesAsync method\n var checkStatusMethod = childViewModel.GetType().GetMethod(\"CheckSettingStatusesAsync\");\n if (checkStatusMethod != null)\n {\n await (Task)checkStatusMethod.Invoke(childViewModel, null);\n _logService.Log(LogLevel.Debug, $\"Called CheckSettingStatusesAsync on {childViewModel.GetType().Name}\");\n }\n \n // Try to notify property changes using a safer approach\n if (childViewModel is System.ComponentModel.INotifyPropertyChanged)\n {\n try\n {\n // Use a safer approach to find the right PropertyChanged event\n var propertyChangedEvent = childViewModel.GetType().GetEvent(\"PropertyChanged\");\n if (propertyChangedEvent != null)\n {\n // Try to find a method that raises the PropertyChanged event\n // Look for a method that takes a string parameter first\n var methods = childViewModel.GetType().GetMethods(\n System.Reflection.BindingFlags.Public |\n System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance)\n .Where(m => (m.Name == \"RaisePropertyChanged\" || m.Name == \"OnPropertyChanged\") &&\n m.GetParameters().Length == 1 &&\n m.GetParameters()[0].ParameterType == typeof(string))\n .ToList();\n \n if (methods.Any())\n {\n var method = methods.First();\n // Refresh Settings property and IsSelected property on UI thread\n ExecuteOnUIThread(() => {\n method.Invoke(childViewModel, new object[] { \"Settings\" });\n method.Invoke(childViewModel, new object[] { \"IsSelected\" });\n _logService.Log(LogLevel.Debug, $\"Refreshed properties on {childViewModel.GetType().Name} using {method.Name} on UI thread\");\n });\n }\n else\n {\n // If no method with string parameter is found, try to find a method that takes PropertyChangedEventArgs\n var refreshCommand = childViewModel.GetType().GetProperty(\"RefreshCommand\")?.GetValue(childViewModel) as System.Windows.Input.ICommand;\n if (refreshCommand != null && refreshCommand.CanExecute(null))\n {\n ExecuteOnUIThread(() => {\n refreshCommand.Execute(null);\n _logService.Log(LogLevel.Debug, $\"Refreshed {childViewModel.GetType().Name} using RefreshCommand on UI thread\");\n });\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error refreshing child view model properties: {ex.Message}\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error refreshing child view model: {ex.Message}\");\n }\n }\n \n /// \n /// Executes an action on the UI thread.\n /// \n /// The action to execute.\n private void ExecuteOnUIThread(Action action)\n {\n try\n {\n // Check if we have access to a dispatcher\n if (Application.Current != null && Application.Current.Dispatcher != null)\n {\n // Check if we're already on the UI thread\n if (Application.Current.Dispatcher.CheckAccess())\n {\n // We're on the UI thread, execute directly\n action();\n }\n else\n {\n // We're not on the UI thread, invoke on the UI thread\n Application.Current.Dispatcher.Invoke(action, DispatcherPriority.Background);\n }\n }\n else\n {\n // No dispatcher available, execute directly\n action();\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error executing action on UI thread: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n \n // Try to execute the action directly as a fallback\n try\n {\n action();\n }\n catch (Exception innerEx)\n {\n _logService.Log(LogLevel.Error, $\"Error executing action directly: {innerEx.Message}\");\n }\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Utilities/PowerShellFactory.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Management.Automation;\nusing System.Management.Automation.Runspaces;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.Utilities\n{\n /// \n /// Factory for creating PowerShell instances with specific runtime configurations.\n /// \n public static class PowerShellFactory\n {\n private static readonly string WindowsPowerShellPath =\n @\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\";\n private static readonly string PowerShellCorePath =\n @\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\";\n\n // Reference to the system service - will be set by the first call to CreateWindowsPowerShell\n private static ISystemServices _systemServices;\n\n /// \n /// Determines if the current OS is Windows 10 (which has issues with Appx module in PowerShell Core)\n /// \n /// True if running on Windows 10, false otherwise\n private static bool IsWindows10()\n {\n // Use the system services if available\n if (_systemServices != null)\n {\n // Use the centralized Windows version detection\n return !_systemServices.IsWindows11();\n }\n\n // Fallback to direct OS version check if system services are not available\n try\n {\n // Get OS version information\n var osVersion = Environment.OSVersion;\n\n // Windows 10 has major version 10 and build number less than 22000\n // Windows 11 has build number 22000 or higher\n bool isWin10ByVersion =\n osVersion.Platform == PlatformID.Win32NT\n && osVersion.Version.Major == 10\n && osVersion.Version.Build < 22000;\n\n // Additional check using ProductName which is more reliable\n bool isWin10ByProductName = false;\n try\n {\n // Check the product name from registry\n using (\n var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(\n @\"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\"\n )\n )\n {\n if (key != null)\n {\n var productName = key.GetValue(\"ProductName\") as string;\n isWin10ByProductName =\n productName != null && productName.Contains(\"Windows 10\");\n\n // If product name explicitly contains Windows 11, it's definitely not Windows 10\n if (productName != null && productName.Contains(\"Windows 11\"))\n {\n return false;\n }\n }\n }\n }\n catch\n {\n // If registry check fails, rely on version check only\n }\n\n // Return true if either method indicates Windows 10\n return isWin10ByVersion || isWin10ByProductName;\n }\n catch\n {\n // If there's any error, assume it's Windows 10 to ensure compatibility\n // This is safer than assuming it's not Windows 10\n return true;\n }\n }\n\n /// \n /// Creates a PowerShell instance configured to use Windows PowerShell 5.1.\n /// On Windows 10, it ensures compatibility with the Appx module by using Windows PowerShell.\n /// \n /// Optional log service for diagnostic information.\n /// A PowerShell instance configured to use Windows PowerShell 5.1.\n public static PowerShell CreateWindowsPowerShell(\n ILogService logService = null,\n ISystemServices systemServices = null\n )\n {\n try\n {\n // Store the system services reference if provided\n if (systemServices != null)\n {\n _systemServices = systemServices;\n }\n\n PowerShell powerShell;\n\n // Create a default PowerShell instance\n powerShell = PowerShell.Create();\n\n // Check if we're running on Windows 10\n bool isWin10 = IsWindows10();\n\n // Additional check for build number to ensure Windows 11 is properly detected\n var osVersion = Environment.OSVersion;\n if (osVersion.Version.Build >= 22000)\n {\n // If build number indicates Windows 11, override the IsWindows10 result\n isWin10 = false;\n logService?.LogInformation(\n $\"Detected Windows 11 (Build: {osVersion.Version.Build}) - Using standard PowerShell Core for Appx commands\"\n );\n }\n else if (isWin10)\n {\n logService?.LogInformation(\n \"Detected Windows 10 - Using direct Windows PowerShell execution for Appx commands\"\n );\n\n // On Windows 10, immediately set up direct execution for Appx commands\n // This avoids WinRM connection issues and ensures compatibility\n powerShell.AddScript(\n $@\"\n function Invoke-WindowsPowerShell {{\n param(\n [Parameter(Mandatory=$true)]\n [string]$Command\n )\n \n try {{\n $psi = New-Object System.Diagnostics.ProcessStartInfo\n $psi.FileName = '{WindowsPowerShellPath}'\n $psi.Arguments = \"\"-NoProfile -ExecutionPolicy Bypass -Command `\"\"$Command`\"\"\"\"\n $psi.RedirectStandardOutput = $true\n $psi.RedirectStandardError = $true\n $psi.UseShellExecute = $false\n $psi.CreateNoWindow = $true\n \n $process = New-Object System.Diagnostics.Process\n $process.StartInfo = $psi\n $process.Start() | Out-Null\n \n $output = $process.StandardOutput.ReadToEnd()\n $error = $process.StandardError.ReadToEnd()\n $process.WaitForExit()\n \n if ($error) {{\n Write-Warning \"\"Windows PowerShell error: $error\"\"\n }}\n \n return $output\n }} catch {{\n Write-Warning \"\"Error invoking Windows PowerShell: $_\"\"\n return $null\n }}\n }}\n \n # Override Get-AppxPackage to use Windows PowerShell directly\n function Get-AppxPackage {{\n param(\n [Parameter(Position=0)]\n [string]$Name = '*'\n )\n \n Write-Output \"\"Using direct Windows PowerShell execution for Get-AppxPackage\"\"\n $result = Invoke-WindowsPowerShell \"\"Get-AppxPackage -Name '$Name' | ConvertTo-Json -Depth 5 -Compress\"\"\n if ($result) {{\n try {{\n $packages = $result | ConvertFrom-Json -ErrorAction SilentlyContinue\n return $packages\n }} catch {{\n Write-Warning \"\"Error parsing AppX package results: $_\"\"\n return $null\n }}\n }}\n return $null\n }}\n \n # Override Remove-AppxPackage to use Windows PowerShell directly\n function Remove-AppxPackage {{\n param(\n [Parameter(Mandatory=$true)]\n [string]$Package\n )\n \n Write-Output \"\"Using direct Windows PowerShell execution for Remove-AppxPackage\"\"\n $result = Invoke-WindowsPowerShell \"\"Remove-AppxPackage -Package '$Package'\"\"\n return $result\n }}\n \n # Override Add-AppxPackage to use Windows PowerShell directly\n function Add-AppxPackage {{\n param(\n [Parameter(Mandatory=$true)]\n [string]$Path\n )\n \n Write-Output \"\"Using direct Windows PowerShell execution for Add-AppxPackage\"\"\n $result = Invoke-WindowsPowerShell \"\"Add-AppxPackage -Path '$Path'\"\"\n return $result\n }}\n \n # Override Get-AppxProvisionedPackage to use Windows PowerShell directly\n function Get-AppxProvisionedPackage {{\n param(\n [Parameter(Mandatory=$true)]\n [switch]$Online\n )\n \n Write-Output \"\"Using direct Windows PowerShell execution for Get-AppxProvisionedPackage\"\"\n $result = Invoke-WindowsPowerShell \"\"Get-AppxProvisionedPackage -Online | ConvertTo-Json -Depth 5 -Compress\"\"\n if ($result) {{\n try {{\n $packages = $result | ConvertFrom-Json -ErrorAction SilentlyContinue\n return $packages\n }} catch {{\n Write-Warning \"\"Error parsing provisioned package results: $_\"\"\n return $null\n }}\n }}\n return $null\n }}\n \n # Override Remove-AppxProvisionedPackage to use Windows PowerShell directly\n function Remove-AppxProvisionedPackage {{\n param(\n [Parameter(Mandatory=$true)]\n [switch]$Online,\n \n [Parameter(Mandatory=$true)]\n [string]$PackageName\n )\n \n Write-Output \"\"Using direct Windows PowerShell execution for Remove-AppxProvisionedPackage\"\"\n $result = Invoke-WindowsPowerShell \"\"Remove-AppxProvisionedPackage -Online -PackageName '$PackageName'\"\"\n return $result\n }}\n \n Write-Output \"\"Configured Windows PowerShell direct execution for Appx commands\"\"\n \"\n );\n\n var directExecutionResults = powerShell.Invoke();\n foreach (var result in directExecutionResults)\n {\n logService?.LogInformation($\"Direct execution setup: {result}\");\n }\n }\n else\n {\n logService?.LogInformation(\n \"Not running on Windows 10 - Using standard PowerShell Core for Appx commands\"\n );\n }\n\n // Configure PowerShell to use Windows PowerShell modules and set execution policy\n powerShell.Commands.Clear();\n\n // Different script for Windows 10 vs Windows 11\n if (isWin10)\n {\n // For Windows 10, report that we're using Windows PowerShell 5.1 for Appx commands\n powerShell.AddScript(\n @\"\n # Set execution policy\n try {\n Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force -ErrorAction SilentlyContinue\n } catch {\n # Ignore errors\n }\n \n # Ensure Windows PowerShell modules are available\n $WindowsPowerShellModulePath = \"\"$env:SystemRoot\\System32\\WindowsPowerShell\\v1.0\\Modules\"\"\n if ($env:PSModulePath -notlike \"\"*$WindowsPowerShellModulePath*\"\") {\n $env:PSModulePath = $env:PSModulePath + \"\";\"\" + $WindowsPowerShellModulePath\n }\n \n # Log PowerShell version information\n # Since we're using direct Windows PowerShell execution on Windows 10, report that version\n Write-Output \"\"Using PowerShell version: 5.1 (WindowsPowerShell)\"\"\n Write-Output \"\"OS Version: $([System.Environment]::OSVersion.Version)\"\"\n \"\n );\n }\n else\n {\n // For Windows 11, use standard PowerShell Core and report its version\n powerShell.AddScript(\n @\"\n # Set execution policy\n try {\n Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force -ErrorAction SilentlyContinue\n } catch {\n # Ignore errors\n }\n \n # Ensure Windows PowerShell modules are available\n $WindowsPowerShellModulePath = \"\"$env:SystemRoot\\System32\\WindowsPowerShell\\v1.0\\Modules\"\"\n if ($env:PSModulePath -notlike \"\"*$WindowsPowerShellModulePath*\"\") {\n $env:PSModulePath = $env:PSModulePath + \"\";\"\" + $WindowsPowerShellModulePath\n }\n \n # Import Appx module for Windows 11\n try {\n Import-Module Appx -ErrorAction SilentlyContinue\n } catch {\n # Module might not be available, continue anyway\n }\n \n # Log PowerShell version for diagnostics\n $PSVersionInfo = $PSVersionTable.PSVersion\n Write-Output \"\"Using PowerShell version: $($PSVersionInfo.Major).$($PSVersionInfo.Minor) ($($PSVersionTable.PSEdition))\"\"\n Write-Output \"\"OS Version: $([System.Environment]::OSVersion.Version)\"\"\n \"\n );\n }\n\n var results = powerShell.Invoke();\n foreach (var result in results)\n {\n logService?.LogInformation($\"PowerShell initialization: {result}\");\n }\n\n powerShell.Commands.Clear();\n\n return powerShell;\n }\n catch (Exception ex)\n {\n logService?.LogError(\n $\"Error creating Windows PowerShell instance: {ex.Message}\",\n ex\n );\n\n // Fall back to default PowerShell instance if creation fails\n return PowerShell.Create();\n }\n }\n\n /// \n /// Creates a PowerShell instance with the default configuration.\n /// On Windows 10, it will use the same compatibility approach as CreateWindowsPowerShell.\n /// \n /// A default PowerShell instance.\n public static PowerShell CreateDefault()\n {\n // Use the same Windows 10 compatibility approach as CreateWindowsPowerShell\n return CreateWindowsPowerShell();\n }\n\n /// \n /// Creates a PowerShell instance for executing Appx-related commands.\n /// This method always uses Windows PowerShell 5.1 on Windows 10 for compatibility.\n /// \n /// Optional log service for diagnostic information.\n /// Optional system services for OS detection.\n /// A PowerShell instance configured for Appx commands.\n public static PowerShell CreateForAppxCommands(\n ILogService logService = null,\n ISystemServices systemServices = null\n )\n {\n // Always use Windows PowerShell for Appx commands on Windows 10\n return CreateWindowsPowerShell(logService, systemServices);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Utilities/WinGetInstallationScript.cs", "using System;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Management.Automation;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Utilities\n{\n /// \n /// Provides functionality to install WinGet when it is not found on the system.\n /// \n public static class WinGetInstallationScript\n {\n /// \n /// The PowerShell script used to install WinGet by downloading it directly from GitHub.\n /// \n public static readonly string InstallScript =\n @\"\n# PowerShell script to install WinGet from GitHub\nWrite-Output \"\"Starting WinGet installation process... [PROGRESS:25]\"\"\n\n# Create a temporary directory for downloads\n$tempDir = Join-Path $env:TEMP \"\"WinGetInstall\"\"\nif (Test-Path $tempDir) {\n Remove-Item -Path $tempDir -Recurse -Force\n}\nNew-Item -Path $tempDir -ItemType Directory -Force | Out-Null\n\ntry {\n # Download URLs\n $dependenciesUrl = \"\"https://github.com/microsoft/winget-cli/releases/latest/download/DesktopAppInstaller_Dependencies.zip\"\"\n $installerUrl = \"\"https://github.com/microsoft/winget-cli/releases/latest/download/Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle\"\"\n $licenseUrl = \"\"https://github.com/microsoft/winget-cli/releases/latest/download/e53e159d00e04f729cc2180cffd1c02e_License1.xml\"\"\n \n # Download paths\n $dependenciesPath = Join-Path $tempDir \"\"DesktopAppInstaller_Dependencies.zip\"\"\n $installerPath = Join-Path $tempDir \"\"Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle\"\"\n $licensePath = Join-Path $tempDir \"\"e53e159d00e04f729cc2180cffd1c02e_License1.xml\"\"\n \n # Download the dependencies\n Write-Output \"\"Downloading WinGet dependencies... [PROGRESS:30]\"\"\n Invoke-WebRequest -Uri $dependenciesUrl -OutFile $dependenciesPath -UseBasicParsing\n \n # Download the installer\n Write-Output \"\"Downloading WinGet installer... [PROGRESS:40]\"\"\n Invoke-WebRequest -Uri $installerUrl -OutFile $installerPath -UseBasicParsing\n \n # Download the license file (needed for LTSC editions)\n Write-Output \"\"Downloading WinGet license file... [PROGRESS:45]\"\"\n Invoke-WebRequest -Uri $licenseUrl -OutFile $licensePath -UseBasicParsing\n \n # Extract the dependencies\n Write-Output \"\"Extracting dependencies... [PROGRESS:50]\"\"\n $extractPath = Join-Path $tempDir \"\"Dependencies\"\"\n Expand-Archive -Path $dependenciesPath -DestinationPath $extractPath -Force\n \n # Install all dependencies\n Write-Output \"\"Installing dependencies... [PROGRESS:60]\"\"\n $dependencyFiles = Get-ChildItem -Path $extractPath -Filter *.appx -Recurse\n foreach ($file in $dependencyFiles) {\n Write-Output \"\"Installing dependency: $($file.Name)\"\"\n try {\n Add-AppxPackage -Path $file.FullName\n }\n catch {\n Write-Output \"\"[ERROR] Failed to install WinGet: $($_.Exception.Message)\"\"\n throw $_\n }\n }\n \n # Install the WinGet installer\n Write-Output \"\"Installing WinGet... [PROGRESS:80]\"\"\n try {\n # Always use Add-AppxProvisionedPackage with license for all Windows editions\n Write-Output \"\"Installing WinGet with license file\"\"\n Add-AppxProvisionedPackage -Online -PackagePath $installerPath -LicensePath $licensePath\n Write-Output \"\"WinGet installation completed successfully [PROGRESS:90]\"\"\n \n # Refresh PATH environment variable to include WindowsApps directory where WinGet is installed\n Write-Output \"\"Refreshing PATH environment to include WinGet...\"\"\n $env:Path = [System.Environment]::GetEnvironmentVariable(\"\"Path\"\", \"\"Machine\"\") + \"\";\"\" + [System.Environment]::GetEnvironmentVariable(\"\"Path\"\", \"\"User\"\")\n \n # Verify WinGet installation by running a command\n Write-Output \"\"Verifying WinGet installation...\"\"\n \n # Try to find WinGet in common locations\n $wingetPaths = @(\n \"\"winget.exe\"\", # Check if it's in PATH\n \"\"$env:LOCALAPPDATA\\Microsoft\\WindowsApps\\winget.exe\"\",\n \"\"$env:ProgramFiles\\WindowsApps\\Microsoft.DesktopAppInstaller_*\\winget.exe\"\"\n )\n \n $wingetFound = $false\n foreach ($path in $wingetPaths) {\n if ($path -like \"\"*`**\"\") {\n # Handle wildcard paths\n $resolvedPaths = Resolve-Path $path -ErrorAction SilentlyContinue\n if ($resolvedPaths) {\n foreach ($resolvedPath in $resolvedPaths) {\n if (Test-Path $resolvedPath) {\n Write-Output \"\"Found WinGet at: $resolvedPath\"\"\n $wingetFound = $true\n # Add the directory to PATH if not already there\n $wingetDir = Split-Path $resolvedPath\n if ($env:Path -notlike \"\"*$wingetDir*\"\") {\n $env:Path += \"\";$wingetDir\"\"\n }\n break\n }\n }\n }\n } else {\n # Handle direct paths\n if (Test-Path $path) {\n Write-Output \"\"Found WinGet at: $path\"\"\n $wingetFound = $true\n # Add the directory to PATH if not already there\n $wingetDir = Split-Path $path\n if ($env:Path -notlike \"\"*$wingetDir*\"\") {\n $env:Path += \"\";$wingetDir\"\"\n }\n break\n }\n }\n }\n \n if (-not $wingetFound) {\n # Try running winget command directly to see if it works\n try {\n $wingetVersion = & winget.exe --version 2>&1\n if ($LASTEXITCODE -eq 0) {\n Write-Output \"\"WinGet is available in PATH: $wingetVersion\"\"\n $wingetFound = $true\n }\n } catch {\n Write-Output \"\"WinGet command not found in PATH\"\"\n }\n }\n \n if (-not $wingetFound) {\n Write-Output \"\"[WARNING] WinGet was installed but could not be found in PATH. You may need to restart your system.\"\"\n }\n }\n catch {\n Write-Output \"\"[ERROR] Failed to install WinGet: $($_.Exception.Message)\"\"\n throw $_\n }\n}\ncatch {\n Write-Output \"\"[ERROR] An error occurred during WinGet installation: $($_.Exception.Message)\"\"\n throw $_\n}\nfinally {\n # Clean up\n Write-Output \"\"Cleaning up temporary files... [PROGRESS:95]\"\"\n if (Test-Path $tempDir) {\n Remove-Item -Path $tempDir -Recurse -Force\n }\n Write-Output \"\"WinGet installation process completed [PROGRESS:100]\"\"\n}\n\";\n\n /// \n /// Installs WinGet by downloading it directly from GitHub and installing it.\n /// \n /// Optional progress reporting.\n /// Optional logger for logging the installation process.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with a result indicating success or failure.\n public static async Task<(bool Success, string Message)> InstallWinGetAsync(\n IProgress progress = null,\n ILogService logger = null,\n CancellationToken cancellationToken = default\n )\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 10,\n StatusText = \"Preparing to download WinGet from GitHub...\",\n DetailedMessage =\n \"This may take a few minutes depending on your internet connection.\",\n }\n );\n\n logger?.LogInformation(\"Starting WinGet installation by downloading from GitHub\");\n\n // Create a temporary directory if it doesn't exist\n string tempDir = Path.Combine(Path.GetTempPath(), \"WinhanceTemp\");\n Directory.CreateDirectory(tempDir);\n\n // Create a temporary script file\n string scriptPath = Path.Combine(tempDir, $\"WinGetInstall_{Guid.NewGuid()}.ps1\");\n\n // Write the installation script to the file\n File.WriteAllText(scriptPath, InstallScript);\n\n try\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 20,\n StatusText = \"Downloading and installing WinGet components...\",\n DetailedMessage =\n \"This may take a few minutes depending on your internet connection.\",\n }\n );\n\n // Execute the PowerShell script with elevated privileges\n // Use PowerShellFactory to ensure we get the right PowerShell version based on OS\n // This is especially important for Windows 10 where Add-AppxPackage needs Windows PowerShell 5.1\n // We need to use Windows PowerShell 5.1 on Windows 10 for Add-AppxPackage command\n using (var powerShell = PowerShellFactory.CreateForAppxCommands(logger))\n {\n // Add the script to execute\n powerShell.AddScript($\". '{scriptPath}'\");\n\n // Set up real-time output processing using PowerShell events\n var outputBuilder = new StringBuilder();\n\n // Subscribe to the DataAdded event for Information stream\n powerShell.Streams.Information.DataAdded += (sender, e) =>\n {\n var streamObjectsReceived = sender as PSDataCollection;\n if (streamObjectsReceived != null)\n {\n var informationRecord = streamObjectsReceived[e.Index];\n string output = informationRecord.MessageData.ToString();\n outputBuilder.AppendLine(output);\n logger?.LogInformation($\"WinGet installation: {output}\");\n\n ProcessOutputLine(output, progress, logger);\n }\n };\n\n // Subscribe to the DataAdded event for Output stream\n var outputCollection = new PSDataCollection();\n outputCollection.DataAdded += (sender, e) =>\n {\n var streamObjectsReceived = sender as PSDataCollection;\n if (streamObjectsReceived != null)\n {\n var outputObject = streamObjectsReceived[e.Index];\n string output = outputObject.ToString();\n outputBuilder.AppendLine(output);\n logger?.LogInformation($\"WinGet installation: {output}\");\n\n ProcessOutputLine(output, progress, logger);\n }\n };\n\n // Execute the script asynchronously to capture real-time output\n await Task.Run(\n () => powerShell.Invoke(null, outputCollection),\n cancellationToken\n );\n\n // Helper method to process output lines for progress and error markers\n void ProcessOutputLine(\n string output,\n IProgress progress,\n ILogService logger\n )\n {\n // Check for progress markers in the output\n if (output.Contains(\"[PROGRESS:\"))\n {\n var progressMatch = System.Text.RegularExpressions.Regex.Match(\n output,\n @\"\\[PROGRESS:(\\d+)\\]\"\n );\n if (\n progressMatch.Success\n && int.TryParse(\n progressMatch.Groups[1].Value,\n out int progressValue\n )\n )\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = progressValue,\n StatusText = output.Replace(progressMatch.Value, \"\").Trim(),\n }\n );\n }\n }\n // Check for error markers in the output\n else if (output.Contains(\"[ERROR]\"))\n {\n var errorMessage = output.Replace(\"[ERROR]\", \"\").Trim();\n logger?.LogError($\"WinGet installation error: {errorMessage}\");\n }\n }\n\n // Check for errors\n if (powerShell.HadErrors)\n {\n var errorBuilder = new StringBuilder(\"Errors during WinGet installation:\");\n foreach (var error in powerShell.Streams.Error)\n {\n errorBuilder.AppendLine(error.Exception.Message);\n logger?.LogError(\n $\"WinGet installation error: {error.Exception.Message}\"\n );\n }\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = \"WinGet installation failed\",\n DetailedMessage = errorBuilder.ToString(),\n LogLevel = Winhance.Core.Features.Common.Enums.LogLevel.Error,\n }\n );\n\n return (false, errorBuilder.ToString());\n }\n\n // Report success\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = \"WinGet installation completed successfully\",\n DetailedMessage = \"WinGet has been installed and is ready to use.\",\n }\n );\n\n logger?.LogInformation(\"WinGet installation completed successfully\");\n return (true, \"WinGet has been successfully installed.\");\n }\n }\n catch (Exception ex)\n {\n string errorMessage = $\"Error installing WinGet: {ex.Message}\";\n logger?.LogError(errorMessage, ex);\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = \"WinGet installation failed\",\n DetailedMessage = errorMessage,\n LogLevel = Winhance.Core.Features.Common.Enums.LogLevel.Error,\n }\n );\n\n return (false, errorMessage);\n }\n finally\n {\n // Clean up the temporary script file\n try\n {\n if (File.Exists(scriptPath))\n {\n File.Delete(scriptPath);\n }\n }\n catch (Exception ex)\n {\n logger?.LogWarning($\"Failed to delete temporary script file: {ex.Message}\");\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Optimize/Services/PowerPlanService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Optimize.Interfaces;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Infrastructure.Features.Optimize.Services\n{\n /// \n /// Service for managing Windows power plans.\n /// \n public class PowerPlanService : IPowerPlanService\n {\n private readonly IPowerShellExecutionService _powerShellService;\n private readonly ILogService _logService;\n \n // Dictionary to cache applied settings state\n private Dictionary AppliedSettings { get; } = new Dictionary();\n\n /// \n /// GUID for the Balanced power plan.\n /// \n public static readonly string BALANCED_PLAN_GUID = \"381b4222-f694-41f0-9685-ff5bb260df2e\";\n\n /// \n /// GUID for the High Performance power plan.\n /// \n public static readonly string HIGH_PERFORMANCE_PLAN_GUID = \"8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c\";\n\n /// \n /// GUID for the Ultimate Performance power plan.\n /// This is not readonly because it may be updated at runtime when the plan is created.\n /// \n public static string ULTIMATE_PERFORMANCE_PLAN_GUID = \"e9a42b02-d5df-448d-aa00-03f14749eb61\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The PowerShell execution service.\n /// The log service.\n public PowerPlanService(IPowerShellExecutionService powerShellService, ILogService logService)\n {\n _powerShellService = powerShellService ?? throw new ArgumentNullException(nameof(powerShellService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public async Task GetActivePowerPlanGuidAsync()\n {\n try\n {\n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5));\n var cancellationToken = cancellationTokenSource.Token;\n \n // Execute powercfg /getactivescheme to get the active power plan\n var executeTask = _powerShellService.ExecuteScriptAsync(\"powercfg /getactivescheme\");\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(executeTask, Task.Delay(5000, cancellationToken));\n \n if (!executeTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Getting active power plan timed out, defaulting to Balanced\");\n return BALANCED_PLAN_GUID;\n }\n \n var result = await executeTask;\n \n // Parse the output to extract the GUID\n // Example output: \"Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)\"\n if (result.Contains(\"GUID:\"))\n {\n int guidStart = result.IndexOf(\"GUID:\") + 5;\n int guidEnd = result.IndexOf(\" (\", guidStart);\n if (guidEnd > guidStart)\n {\n string guid = result.Substring(guidStart, guidEnd - guidStart).Trim();\n return guid;\n }\n }\n \n _logService.Log(LogLevel.Warning, \"Failed to parse active power plan GUID, defaulting to Balanced\");\n return BALANCED_PLAN_GUID; // Default to Balanced if parsing fails\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"Operation timed out while getting active power plan, defaulting to Balanced\");\n return BALANCED_PLAN_GUID;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting active power plan: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return BALANCED_PLAN_GUID; // Default to Balanced on error\n }\n }\n\n /// \n public async Task SetPowerPlanAsync(string planGuid)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Setting power plan to GUID: {planGuid}\");\n \n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(10));\n var cancellationToken = cancellationTokenSource.Token;\n \n // Special handling for Ultimate Performance plan\n if (planGuid == ULTIMATE_PERFORMANCE_PLAN_GUID)\n {\n _logService.Log(LogLevel.Info, \"Ultimate Performance plan selected, applying with custom GUID and settings\");\n \n // Use the custom GUID for Ultimate Performance plan\n const string customUltimateGuid = \"99999999-9999-9999-9999-999999999999\";\n \n try\n {\n // Create the plan with the custom GUID\n var createTask = _powerShellService.ExecuteScriptAsync(\n $\"powercfg {PowerOptimizations.UltimatePerformancePowerPlan.PowerCfgCommands[\"CreateUltimatePlan\"]}\");\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(createTask, Task.Delay(5000, cancellationToken));\n \n if (!createTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Creating Ultimate Performance plan timed out\");\n return false;\n }\n \n var createResult = await createTask;\n if (createResult.Contains(\"Error\") || createResult.Contains(\"error\"))\n {\n _logService.Log(LogLevel.Error, $\"Error creating Ultimate Performance plan: {createResult}\");\n return false;\n }\n \n // Set it as the active plan\n var setActiveTask = _powerShellService.ExecuteScriptAsync(\n $\"powercfg {PowerOptimizations.UltimatePerformancePowerPlan.PowerCfgCommands[\"SetActivePlan\"]}\");\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(setActiveTask, Task.Delay(5000, cancellationToken));\n \n if (!setActiveTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Setting Ultimate Performance plan as active timed out\");\n return false;\n }\n \n var setActiveResult = await setActiveTask;\n if (setActiveResult.Contains(\"Error\") || setActiveResult.Contains(\"error\"))\n {\n _logService.Log(LogLevel.Error, $\"Error setting Ultimate Performance plan as active: {setActiveResult}\");\n return false;\n }\n \n // Apply all the powercfg commands\n _logService.Log(LogLevel.Info, $\"Applying {PowerOptimizations.UltimatePerformancePowerPlan.PowerCfgCommands.Count} Ultimate Performance settings\");\n \n bool allCommandsSucceeded = true;\n foreach (var command in PowerOptimizations.UltimatePerformancePowerPlan.PowerCfgCommands)\n {\n // Check for cancellation\n if (cancellationToken.IsCancellationRequested)\n {\n _logService.Log(LogLevel.Warning, \"Operation timed out while applying Ultimate Performance settings\");\n return false;\n }\n \n // Skip the CreateUltimatePlan and SetActivePlan commands as we've already executed them\n if (command.Key == \"CreateUltimatePlan\" || command.Key == \"SetActivePlan\")\n continue;\n \n var cmdTask = _powerShellService.ExecuteScriptAsync($\"powercfg {command.Value}\");\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(cmdTask, Task.Delay(2000, cancellationToken));\n \n if (!cmdTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, $\"Command {command.Key} timed out\");\n allCommandsSucceeded = false;\n continue;\n }\n \n var cmdResult = await cmdTask;\n if (cmdResult.Contains(\"Error\") || cmdResult.Contains(\"error\"))\n {\n _logService.Log(LogLevel.Warning, $\"Error applying Ultimate Performance setting {command.Key}: {cmdResult}\");\n allCommandsSucceeded = false;\n }\n }\n \n if (!allCommandsSucceeded)\n {\n _logService.Log(LogLevel.Warning, \"Some Ultimate Performance settings could not be applied\");\n }\n \n // Update the static GUID to use our custom one\n ULTIMATE_PERFORMANCE_PLAN_GUID = customUltimateGuid;\n \n // Also update the PowerOptimizations class to use this new GUID\n var field = typeof(PowerOptimizations.PowerPlans).GetField(\"UltimatePerformance\");\n if (field != null)\n {\n var ultimatePerformancePlan = field.GetValue(null) as PowerPlan;\n if (ultimatePerformancePlan != null)\n {\n // Use reflection to update the Guid property\n var guidProperty = typeof(PowerPlan).GetProperty(\"Guid\");\n if (guidProperty != null)\n {\n guidProperty.SetValue(ultimatePerformancePlan, customUltimateGuid);\n _logService.Log(LogLevel.Info, \"Updated PowerOptimizations.PowerPlans.UltimatePerformance.Guid\");\n }\n }\n }\n \n // Verify the plan was set correctly\n var verifyTask = GetActivePowerPlanGuidAsync();\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(verifyTask, Task.Delay(3000, cancellationToken));\n \n if (!verifyTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Verifying active power plan timed out\");\n return false;\n }\n \n var currentPlan = await verifyTask;\n if (currentPlan != customUltimateGuid)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to set Ultimate Performance plan. Expected: {customUltimateGuid}, Actual: {currentPlan}\");\n return false;\n }\n \n _logService.Log(LogLevel.Info, $\"Successfully set Ultimate Performance plan with GUID: {customUltimateGuid}\");\n return true;\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"Operation timed out while setting Ultimate Performance plan\");\n return false;\n }\n }\n else\n {\n try\n {\n // For other plans, ensure they exist before trying to set them\n var ensureTask = EnsurePowerPlanExistsAsync(planGuid);\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(ensureTask, Task.Delay(5000, cancellationToken));\n \n if (!ensureTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Ensuring power plan exists timed out\");\n return false;\n }\n \n bool planExists = await ensureTask;\n if (!planExists)\n {\n _logService.Log(LogLevel.Error, $\"Failed to ensure power plan exists: {planGuid}\");\n return false;\n }\n \n // Set the active power plan\n var setTask = _powerShellService.ExecuteScriptAsync($\"powercfg /setactive {planGuid}\");\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(setTask, Task.Delay(5000, cancellationToken));\n \n if (!setTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Setting power plan timed out\");\n return false;\n }\n \n var result = await setTask;\n \n // Check for errors in the result\n if (result.Contains(\"Error\") || result.Contains(\"error\"))\n {\n _logService.Log(LogLevel.Error, $\"Error setting power plan: {result}\");\n return false;\n }\n \n // Verify the plan was set correctly\n var verifyTask = GetActivePowerPlanGuidAsync();\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(verifyTask, Task.Delay(3000, cancellationToken));\n \n if (!verifyTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Verifying active power plan timed out\");\n return false;\n }\n \n var currentPlan = await verifyTask;\n if (currentPlan != planGuid)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to set power plan. Expected: {planGuid}, Actual: {currentPlan}\");\n return false;\n }\n \n _logService.Log(LogLevel.Info, $\"Successfully set power plan to GUID: {planGuid}\");\n return true;\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"Operation timed out while setting power plan\");\n return false;\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting power plan: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n\n /// \n public async Task EnsurePowerPlanExistsAsync(string planGuid, string sourcePlanGuid = null)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Ensuring power plan exists: {planGuid}\");\n\n // Check if the plan exists\n var plansResult = await _powerShellService.ExecuteScriptAsync(\"powercfg /list\");\n \n if (!plansResult.Contains(planGuid))\n {\n _logService.Log(LogLevel.Info, $\"Power plan {planGuid} does not exist, creating it\");\n\n // Plan doesn't exist, create it based on the plan type\n if (planGuid == BALANCED_PLAN_GUID)\n {\n // Restore default schemes to ensure Balanced plan exists\n await _powerShellService.ExecuteScriptAsync(\"powercfg -restoredefaultschemes\");\n _logService.Log(LogLevel.Info, \"Restored default power schemes to ensure Balanced plan exists\");\n }\n else if (planGuid == HIGH_PERFORMANCE_PLAN_GUID)\n {\n // Restore default schemes to ensure High Performance plan exists\n await _powerShellService.ExecuteScriptAsync(\"powercfg -restoredefaultschemes\");\n _logService.Log(LogLevel.Info, \"Restored default power schemes to ensure High Performance plan exists\");\n }\n else if (planGuid == ULTIMATE_PERFORMANCE_PLAN_GUID)\n {\n // Ultimate Performance is a hidden power plan that needs to be created with a special command\n // First restore default schemes to ensure we have a clean state\n await _powerShellService.ExecuteScriptAsync(\"powercfg -restoredefaultschemes\");\n \n // Create the Ultimate Performance plan using the Windows built-in command\n // This is the official way to create this plan\n var result = await _powerShellService.ExecuteScriptAsync(\"powercfg -duplicatescheme 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c\");\n \n // Extract the GUID of the newly created plan from the result\n // Example output: \"Power Scheme GUID: 11111111-2222-3333-4444-555555555555 (Copy of High Performance)\"\n string newGuid = string.Empty;\n if (result.Contains(\"Power Scheme GUID:\"))\n {\n int guidStart = result.IndexOf(\"Power Scheme GUID:\") + 18;\n int guidEnd = result.IndexOf(\" (\", guidStart);\n if (guidEnd > guidStart)\n {\n newGuid = result.Substring(guidStart, guidEnd - guidStart).Trim();\n _logService.Log(LogLevel.Info, $\"Created new power plan with GUID: {newGuid}\");\n }\n }\n \n if (!string.IsNullOrEmpty(newGuid))\n {\n // Rename it to \"Ultimate Performance\"\n await _powerShellService.ExecuteScriptAsync($\"powercfg -changename {newGuid} \\\"Ultimate Performance\\\" \\\"Provides ultimate performance on Windows.\\\"\");\n \n // Update our constant to use this new GUID for future operations\n // Note: This is a static field, so it will be updated for the lifetime of the application\n ULTIMATE_PERFORMANCE_PLAN_GUID = newGuid;\n \n // Also update the PowerOptimizations class to use this new GUID\n // This is needed because the PowerOptimizationsViewModel uses PowerOptimizations.PowerPlans\n var field = typeof(PowerOptimizations.PowerPlans).GetField(\"UltimatePerformance\");\n if (field != null)\n {\n var ultimatePerformancePlan = field.GetValue(null) as PowerPlan;\n if (ultimatePerformancePlan != null)\n {\n // Use reflection to update the Guid property\n var guidProperty = typeof(PowerPlan).GetProperty(\"Guid\");\n if (guidProperty != null)\n {\n guidProperty.SetValue(ultimatePerformancePlan, newGuid);\n _logService.Log(LogLevel.Info, \"Updated PowerOptimizations.PowerPlans.UltimatePerformance.Guid\");\n }\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Created and renamed Ultimate Performance power plan with GUID: {newGuid}\");\n \n // Return true since we've created the plan, but with a different GUID\n return true;\n }\n \n _logService.Log(LogLevel.Warning, \"Failed to create Ultimate Performance power plan\");\n }\n else if (sourcePlanGuid != null)\n {\n // Create a custom plan from the source plan\n await _powerShellService.ExecuteScriptAsync($\"powercfg /duplicatescheme {sourcePlanGuid} {planGuid}\");\n _logService.Log(LogLevel.Info, $\"Created custom power plan with GUID {planGuid} from source {sourcePlanGuid}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Cannot create power plan with GUID {planGuid} - no source plan specified\");\n return false;\n }\n \n // Verify the plan was created\n plansResult = await _powerShellService.ExecuteScriptAsync(\"powercfg /list\");\n if (!plansResult.Contains(planGuid))\n {\n _logService.Log(LogLevel.Warning, $\"Failed to create power plan with GUID {planGuid}\");\n return false;\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Power plan {planGuid} exists\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error ensuring power plan exists: {ex.Message}\");\n return false;\n }\n }\n\n /// \n public async Task> GetAvailablePowerPlansAsync()\n {\n var powerPlans = new List();\n \n try\n {\n _logService.Log(LogLevel.Info, \"Getting available power plans\");\n var result = await _powerShellService.ExecuteScriptAsync(\"powercfg /list\");\n \n // Parse the output to extract power plans\n // Example output:\n // Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)\n // Power Scheme GUID: 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c (High Performance)\n \n string[] lines = result.Split(new[] { '\\r', '\\n' }, StringSplitOptions.RemoveEmptyEntries);\n foreach (var line in lines)\n {\n if (line.Contains(\"Power Scheme GUID:\"))\n {\n int guidStart = line.IndexOf(\"GUID:\") + 5;\n int guidEnd = line.IndexOf(\" (\", guidStart);\n if (guidEnd > guidStart)\n {\n string guid = line.Substring(guidStart, guidEnd - guidStart).Trim();\n \n int nameStart = line.IndexOf(\"(\", guidEnd) + 1;\n int nameEnd = line.IndexOf(\")\", nameStart);\n if (nameEnd > nameStart)\n {\n string name = line.Substring(nameStart, nameEnd - nameStart).Trim();\n \n powerPlans.Add(new PowerPlan { Guid = guid, Name = name });\n _logService.Log(LogLevel.Info, $\"Found power plan: {name} ({guid})\");\n }\n }\n }\n }\n \n return powerPlans;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting available power plans: {ex.Message}\");\n return powerPlans;\n }\n }\n \n /// \n public async Task ExecutePowerCfgCommandAsync(string command)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Executing PowerCfg command: {command}\");\n \n // Execute the PowerCfg command\n var result = await _powerShellService.ExecuteScriptAsync($\"powercfg {command}\");\n \n // Check for errors in the result\n if (result.Contains(\"Error\") || result.Contains(\"error\"))\n {\n // Check if this is a hardware-dependent setting that doesn't exist\n if (result.Contains(\"specified does not exist\"))\n {\n _logService.Log(LogLevel.Warning, $\"Hardware-dependent setting not available on this system: {result}\");\n // Return true because this is an expected condition, not a failure\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Error executing PowerCfg command: {result}\");\n return false;\n }\n }\n \n _logService.Log(LogLevel.Info, $\"PowerCfg command executed successfully: {command}\");\n return true;\n }\n catch (Exception ex)\n {\n // Check if this is a hardware-dependent setting that doesn't exist\n if (ex.Message.Contains(\"specified does not exist\"))\n {\n _logService.Log(LogLevel.Warning, $\"Hardware-dependent setting not available on this system: {ex.Message}\");\n // Return true because this is an expected condition, not a failure\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Error executing PowerCfg command: {ex.Message}\");\n return false;\n }\n }\n }\n \n /// \n public async Task ApplyPowerSettingAsync(string subgroupGuid, string settingGuid, string value, bool isAcSetting)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Applying power setting: subgroup={subgroupGuid}, setting={settingGuid}, value={value}, isAC={isAcSetting}\");\n \n // Determine the command prefix based on whether this is an AC or DC setting\n string prefix = isAcSetting ? \"/setacvalueindex\" : \"/setdcvalueindex\";\n \n // Get the active power plan GUID\n string planGuid = await GetActivePowerPlanGuidAsync();\n \n // Execute the PowerCfg command to set the value\n var result = await _powerShellService.ExecuteScriptAsync($\"powercfg {prefix} {planGuid} {subgroupGuid} {settingGuid} {value}\");\n \n // Check for errors in the result\n if (result.Contains(\"Error\") || result.Contains(\"error\"))\n {\n // Check if this is a hardware-dependent setting that doesn't exist\n if (result.Contains(\"specified does not exist\"))\n {\n _logService.Log(LogLevel.Warning, $\"Hardware-dependent setting not available on this system: subgroup={subgroupGuid}, setting={settingGuid}\");\n // Return true because this is an expected condition, not a failure\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Error applying power setting: {result}\");\n return false;\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Power setting applied successfully\");\n return true;\n }\n catch (Exception ex)\n {\n // Check if this is a hardware-dependent setting that doesn't exist\n if (ex.Message.Contains(\"specified does not exist\"))\n {\n _logService.Log(LogLevel.Warning, $\"Hardware-dependent setting not available on this system: {ex.Message}\");\n // Return true because this is an expected condition, not a failure\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Error applying power setting: {ex.Message}\");\n return false;\n }\n }\n }\n \n /// \n public async Task IsPowerCfgSettingAppliedAsync(PowerCfgSetting setting)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Checking if PowerCfg setting is applied: {setting.Description}\");\n \n // Extract the command type from the setting\n string command = setting.Command;\n \n // Get the active power plan GUID\n string activePlanGuid = await GetActivePowerPlanGuidAsync();\n \n // Replace placeholder GUID with active power plan GUID\n command = command.Replace(\"{active_guid}\", activePlanGuid);\n \n // Create a unique key for this setting\n string settingKey = $\"{setting.Description}:{setting.EnabledValue}\";\n \n // Special handling for Desktop Slideshow setting\n if (setting.Description.Contains(\"desktop slideshow\"))\n {\n // Extract subgroup and setting GUIDs\n var parts = command.Split(' ');\n if (parts.Length >= 5)\n {\n string subgroupGuid = parts[2];\n string settingGuid = parts[3];\n string expectedValue = parts[4];\n \n // Query the current value\n var result = await _powerShellService.ExecuteScriptAsync($\"powercfg /query {activePlanGuid} {subgroupGuid} {settingGuid}\");\n \n // For Desktop Slideshow, value 0 means \"Available\" (slideshow enabled)\n // and value 1 means \"Paused\" (slideshow disabled)\n // This is counter-intuitive, so we need special handling\n \n // Extract the current value\n string currentValue = ExtractPowerSettingValue(result, command.Contains(\"setacvalueindex\"));\n \n if (!string.IsNullOrEmpty(currentValue))\n {\n // Normalize the values for comparison\n string normalizedCurrentValue = NormalizeHexValue(currentValue);\n string normalizedExpectedValue = NormalizeHexValue(expectedValue);\n \n // For Desktop Slideshow, we need to check if the current value matches the expected value\n // Value 0 means \"Available\" (slideshow enabled)\n // Value 1 means \"Paused\" (slideshow disabled)\n bool settingApplied = string.Equals(normalizedCurrentValue, normalizedExpectedValue, StringComparison.OrdinalIgnoreCase);\n \n _logService.Log(LogLevel.Info, $\"Desktop Slideshow setting check: current={normalizedCurrentValue}, expected={normalizedExpectedValue}, isApplied={settingApplied}\");\n \n // Cache the result\n AppliedSettings[settingKey] = settingApplied;\n return settingApplied;\n }\n }\n }\n \n if (command.Contains(\"hibernate\"))\n {\n // Check hibernate state\n var result = await _powerShellService.ExecuteScriptAsync(\"powercfg /a\");\n \n if (command.Contains(\"off\"))\n {\n // If command is to disable hibernate, check if hibernate is not available\n bool isHibernateDisabled = result.Contains(\"Hibernation has been disabled\");\n _logService.Log(LogLevel.Info, $\"Hibernate state check: disabled={isHibernateDisabled}\");\n \n // Cache the result\n AppliedSettings[settingKey] = isHibernateDisabled;\n return isHibernateDisabled;\n }\n else\n {\n // If command is to enable hibernate, check if hibernate is available\n bool isHibernateEnabled = result.Contains(\"Hibernation\") && !result.Contains(\"Hibernation has been disabled\");\n _logService.Log(LogLevel.Info, $\"Hibernate state check: enabled={isHibernateEnabled}\");\n \n // Cache the result\n AppliedSettings[settingKey] = isHibernateEnabled;\n return isHibernateEnabled;\n }\n }\n else if (command.Contains(\"setacvalueindex\") || command.Contains(\"setdcvalueindex\"))\n {\n // Extract subgroup, setting, and value GUIDs\n var parts = command.Split(' ');\n if (parts.Length >= 5)\n {\n string subgroupGuid = parts[2];\n string settingGuid = parts[3];\n string expectedValue = parts[4];\n \n // Query the current value\n var result = await _powerShellService.ExecuteScriptAsync($\"powercfg /query {activePlanGuid} {subgroupGuid} {settingGuid}\");\n _logService.Log(LogLevel.Debug, $\"Query result for {subgroupGuid} {settingGuid}: {result}\");\n \n // Extract the current value\n bool isAcSetting = command.Contains(\"setacvalueindex\");\n string currentValue = ExtractPowerSettingValue(result, isAcSetting);\n \n if (!string.IsNullOrEmpty(currentValue))\n {\n // Normalize the values for comparison\n string normalizedCurrentValue = NormalizeHexValue(currentValue);\n string normalizedExpectedValue = NormalizeHexValue(expectedValue);\n \n // Compare case-insensitive\n bool settingApplied = string.Equals(normalizedCurrentValue, normalizedExpectedValue, StringComparison.OrdinalIgnoreCase);\n _logService.Log(LogLevel.Info, $\"PowerCfg setting check: current={normalizedCurrentValue}, expected={normalizedExpectedValue}, isApplied={settingApplied}\");\n \n // Cache the result\n AppliedSettings[settingKey] = settingApplied;\n return settingApplied;\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Could not find current value in query result for {subgroupGuid} {settingGuid}\");\n \n // For settings we can't determine, check if the setting exists in the power plan\n var queryResult = await _powerShellService.ExecuteScriptAsync($\"powercfg /query {activePlanGuid} {subgroupGuid} {settingGuid}\");\n \n // If the query returns information about the setting, it exists\n bool settingExists = !queryResult.Contains(\"does not exist\") && queryResult.Contains(settingGuid);\n \n _logService.Log(LogLevel.Info, $\"PowerCfg setting existence check: {settingExists}\");\n \n if (settingExists)\n {\n // If the setting exists but we couldn't extract the value,\n // assume it's not applied so the user can apply it\n AppliedSettings[settingKey] = false;\n return false;\n }\n else\n {\n // If the setting doesn't exist, it might be hardware-dependent\n // In this case, we should return false so the user can apply it if needed\n AppliedSettings[settingKey] = false;\n return false;\n }\n }\n }\n }\n else if (command.Contains(\"CHANGEPOWERPLAN\"))\n {\n // For CHANGEPOWERPLAN commands, we can't easily check the state\n // Assume they're applied if we've tried to apply them before\n _logService.Log(LogLevel.Info, $\"CHANGEPOWERPLAN command detected, assuming applied: {setting.Description}\");\n \n // Cache the result\n AppliedSettings[settingKey] = true;\n return true;\n }\n \n // For any other commands we can't determine, make a best effort check\n _logService.Log(LogLevel.Warning, $\"Could not determine state for PowerCfg setting: {setting.Description}, checking via command output\");\n \n // Execute a query command to get all power settings\n var allPowerSettings = await _powerShellService.ExecuteScriptAsync(\"powercfg /q\");\n \n // Try to extract the command parameters to check if they're in the query result\n string[] cmdParts = command.Split(' ');\n bool isApplied = false;\n \n // If the command has parameters, check if they appear in the query result\n if (cmdParts.Length > 1)\n {\n // Check if any of the command parameters appear in the query result\n // This is a heuristic approach but better than assuming always applied\n for (int i = 1; i < cmdParts.Length; i++)\n {\n if (cmdParts[i].Length > 8 && allPowerSettings.Contains(cmdParts[i]))\n {\n isApplied = true;\n break;\n }\n }\n }\n \n // Cache the result\n AppliedSettings[settingKey] = isApplied;\n return isApplied;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking PowerCfg setting state: {ex.Message}\");\n \n // On error, assume not applied so user can reapply\n return false;\n }\n }\n \n /// \n /// Extracts the power setting value from the query result.\n /// \n /// The result of the powercfg /query command.\n /// Whether this is an AC setting (true) or DC setting (false).\n /// The extracted value, or empty string if not found.\n private string ExtractPowerSettingValue(string queryResult, bool isAcSetting)\n {\n try\n {\n _logService.Log(LogLevel.Debug, $\"Extracting power setting value from query result (isAC={isAcSetting})\");\n \n // Try multiple patterns to extract the current value\n \n // Pattern 1: Standard format \"Current AC/DC Power Setting Index: 0x00000000\"\n string acPattern = \"Current AC Power Setting Index: (.+)\";\n string dcPattern = \"Current DC Power Setting Index: (.+)\";\n \n string pattern = isAcSetting ? acPattern : dcPattern;\n var match = System.Text.RegularExpressions.Regex.Match(queryResult, pattern);\n \n if (match.Success)\n {\n string value = match.Groups[1].Value.Trim();\n _logService.Log(LogLevel.Debug, $\"Found value using pattern 1: {value}\");\n return value;\n }\n \n // Pattern 2: Alternative format \"Power Setting Index: 0x00000000\"\n pattern = \"Power Setting Index: (.+)\";\n match = System.Text.RegularExpressions.Regex.Match(queryResult, pattern);\n \n if (match.Success)\n {\n string value = match.Groups[1].Value.Trim();\n _logService.Log(LogLevel.Debug, $\"Found value using pattern 2: {value}\");\n return value;\n }\n \n // Pattern 3: Look for AC/DC value specifically\n if (isAcSetting)\n {\n pattern = \"AC:\\\\s*0x[0-9A-Fa-f]+\";\n match = System.Text.RegularExpressions.Regex.Match(queryResult, pattern);\n \n if (match.Success)\n {\n string fullMatch = match.Value.Trim();\n string value = fullMatch.Substring(fullMatch.IndexOf(\"0x\"));\n _logService.Log(LogLevel.Debug, $\"Found value using AC pattern: {value}\");\n return value;\n }\n }\n else\n {\n pattern = \"DC:\\\\s*0x[0-9A-Fa-f]+\";\n match = System.Text.RegularExpressions.Regex.Match(queryResult, pattern);\n \n if (match.Success)\n {\n string fullMatch = match.Value.Trim();\n string value = fullMatch.Substring(fullMatch.IndexOf(\"0x\"));\n _logService.Log(LogLevel.Debug, $\"Found value using DC pattern: {value}\");\n return value;\n }\n }\n \n // Pattern 4: Look for any line with a hex value\n pattern = \"0x[0-9A-Fa-f]+\";\n match = System.Text.RegularExpressions.Regex.Match(queryResult, pattern);\n \n if (match.Success)\n {\n string value = match.Value.Trim();\n _logService.Log(LogLevel.Debug, $\"Found value using hex pattern: {value}\");\n return value;\n }\n \n // If no pattern matches, return empty string\n _logService.Log(LogLevel.Warning, \"Could not extract power setting value from query result\");\n return string.Empty;\n }\n catch (Exception ex)\n {\n // If an error occurs, log it and return empty string\n _logService.Log(LogLevel.Error, $\"Error extracting power setting value: {ex.Message}\");\n return string.Empty;\n }\n }\n \n /// \n /// Normalizes a hex value for comparison.\n /// \n /// The hex value to normalize.\n /// The normalized value.\n private string NormalizeHexValue(string value)\n {\n if (string.IsNullOrEmpty(value))\n {\n return \"0\";\n }\n \n // Remove 0x prefix if present\n if (value.StartsWith(\"0x\", StringComparison.OrdinalIgnoreCase))\n {\n value = value.Substring(2);\n }\n \n // Remove leading zeros\n value = value.TrimStart('0');\n \n // If the value is empty after trimming zeros, it's zero\n if (string.IsNullOrEmpty(value))\n {\n return \"0\";\n }\n \n return value;\n }\n \n /// \n public async Task AreAllPowerCfgSettingsAppliedAsync(List settings)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Checking if all PowerCfg settings are applied: {settings.Count} settings\");\n \n // Get the active power plan GUID once for all settings\n string activePlanGuid = await GetActivePowerPlanGuidAsync();\n _logService.Log(LogLevel.Info, $\"Active power plan GUID: {activePlanGuid}\");\n \n // Track which settings are not applied\n List notAppliedSettings = new List();\n \n foreach (var setting in settings)\n {\n bool isApplied = await IsPowerCfgSettingAppliedAsync(setting);\n \n if (!isApplied)\n {\n _logService.Log(LogLevel.Info, $\"PowerCfg setting not applied: {setting.Description}\");\n notAppliedSettings.Add(setting.Description);\n }\n }\n \n if (notAppliedSettings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"{notAppliedSettings.Count} PowerCfg settings not applied: {string.Join(\", \", notAppliedSettings)}\");\n return false;\n }\n \n _logService.Log(LogLevel.Info, $\"All PowerCfg settings are applied\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking PowerCfg settings: {ex.Message}\");\n return false;\n }\n }\n \n /// \n public async Task ApplyPowerCfgSettingsAsync(List settings)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Applying {settings.Count} PowerCfg settings\");\n \n bool allSucceeded = true;\n \n // Get the active power plan GUID\n string activePlanGuid = await GetActivePowerPlanGuidAsync();\n _logService.Log(LogLevel.Info, $\"Using active power plan GUID: {activePlanGuid}\");\n \n foreach (var setting in settings)\n {\n _logService.Log(LogLevel.Info, $\"Applying PowerCfg setting: {setting.Description}\");\n \n // Extract the command without the \"powercfg \" prefix\n string command = setting.Command;\n if (command.StartsWith(\"powercfg \"))\n {\n command = command.Substring(9);\n }\n \n // Replace placeholder GUID with active power plan GUID\n command = command.Replace(\"{active_guid}\", activePlanGuid);\n \n // Execute the command\n bool success = await ExecutePowerCfgCommandAsync(command);\n \n if (!success)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to apply PowerCfg setting: {setting.Description}\");\n allSucceeded = false;\n }\n }\n \n return allSucceeded;\n }\n catch (Exception ex)\n {\n // Check if this is a hardware-dependent setting that doesn't exist\n if (ex.Message.Contains(\"specified does not exist\"))\n {\n _logService.Log(LogLevel.Warning, $\"Hardware-dependent setting not available on this system: {ex.Message}\");\n // Return true because this is an expected condition, not a failure\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Error applying PowerCfg settings: {ex.Message}\");\n return false;\n }\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceEnsureKey.cs", "using Microsoft.Win32;\nusing System;\nusing System.Runtime.InteropServices;\nusing System.Security.AccessControl;\nusing System.Security.Principal;\nusing System.Threading.Tasks;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n public partial class RegistryService\n {\n // Windows API imports for registry operations\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int RegOpenKeyEx(IntPtr hKey, string subKey, int ulOptions, int samDesired, out IntPtr hkResult);\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int RegCloseKey(IntPtr hKey);\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int RegGetKeySecurity(IntPtr hKey, int securityInformation, byte[] pSecurityDescriptor, ref int lpcbSecurityDescriptor);\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int RegSetKeySecurity(IntPtr hKey, int securityInformation, byte[] pSecurityDescriptor);\n\n // Constants for Windows API\n private const int KEY_ALL_ACCESS = 0xF003F;\n private const int OWNER_SECURITY_INFORMATION = 0x00000001;\n private const int DACL_SECURITY_INFORMATION = 0x00000004;\n private const int ERROR_SUCCESS = 0;\n\n // Root key handles\n private static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(-2147483647);\n private static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(-2147483646);\n private static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(-2147483648);\n private static readonly IntPtr HKEY_USERS = new IntPtr(-2147483645);\n private static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(-2147483643);\n\n /// \n /// Takes ownership of a registry key and grants full control to the current user.\n /// \n /// The root registry key.\n /// The path to the subkey.\n /// True if ownership was successfully taken, false otherwise.\n private bool TakeOwnershipOfKey(RegistryKey rootKey, string subKeyPath)\n {\n try\n {\n _logService.LogInformation($\"Attempting to take ownership of registry key: {rootKey.Name}\\\\{subKeyPath}\");\n\n // Get the root key handle\n IntPtr hRootKey = GetRootKeyHandle(rootKey);\n if (hRootKey == IntPtr.Zero)\n {\n _logService.LogError(\"Invalid root key handle\");\n return false;\n }\n\n // Open the key with special permissions\n IntPtr hKey;\n int result = RegOpenKeyEx(hRootKey, subKeyPath, 0, KEY_ALL_ACCESS, out hKey);\n if (result != ERROR_SUCCESS)\n {\n _logService.LogError($\"Failed to open registry key for ownership change: {result}\");\n return false;\n }\n\n try\n {\n // Get the current security descriptor\n int securityDescriptorSize = 0;\n RegGetKeySecurity(hKey, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, null, ref securityDescriptorSize);\n byte[] securityDescriptor = new byte[securityDescriptorSize];\n result = RegGetKeySecurity(hKey, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, securityDescriptor, ref securityDescriptorSize);\n if (result != ERROR_SUCCESS)\n {\n _logService.LogError($\"Failed to get registry key security: {result}\");\n return false;\n }\n\n // Create a new security descriptor\n RawSecurityDescriptor rawSD = new RawSecurityDescriptor(securityDescriptor, 0);\n \n // Set the owner to the current user\n WindowsIdentity currentUser = WindowsIdentity.GetCurrent();\n rawSD.Owner = currentUser.User;\n\n // Create a new DACL\n RawAcl rawAcl = rawSD.DiscretionaryAcl != null ?\n rawSD.DiscretionaryAcl :\n new RawAcl(8, 1);\n\n // Add access rules\n // Current user\n if (currentUser.User != null)\n {\n rawAcl.InsertAce(0, new CommonAce(\n AceFlags.None,\n AceQualifier.AccessAllowed,\n (int)RegistryRights.FullControl,\n currentUser.User,\n false,\n null));\n }\n\n // Administrators\n rawAcl.InsertAce(0, new CommonAce(\n AceFlags.None,\n AceQualifier.AccessAllowed,\n (int)RegistryRights.FullControl,\n new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),\n false,\n null));\n\n // SYSTEM\n rawAcl.InsertAce(0, new CommonAce(\n AceFlags.None,\n AceQualifier.AccessAllowed,\n (int)RegistryRights.FullControl,\n new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),\n false,\n null));\n\n // Set the DACL\n rawSD.DiscretionaryAcl = rawAcl;\n\n // Convert back to byte array\n byte[] newSD = new byte[rawSD.BinaryLength];\n rawSD.GetBinaryForm(newSD, 0);\n\n // Set the new security descriptor\n result = RegSetKeySecurity(hKey, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, newSD);\n if (result != ERROR_SUCCESS)\n {\n _logService.LogError($\"Failed to set registry key security: {result}\");\n return false;\n }\n\n _logService.LogSuccess($\"Successfully took ownership of registry key: {rootKey.Name}\\\\{subKeyPath}\");\n return true;\n }\n finally\n {\n // Close the key\n RegCloseKey(hKey);\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error taking ownership of registry key: {ex.Message}\", ex);\n return false;\n }\n }\n\n /// \n /// Gets the native handle for a root registry key.\n /// \n private IntPtr GetRootKeyHandle(RegistryKey rootKey)\n {\n if (rootKey == Microsoft.Win32.Registry.CurrentUser)\n return HKEY_CURRENT_USER;\n else if (rootKey == Microsoft.Win32.Registry.LocalMachine)\n return HKEY_LOCAL_MACHINE;\n else if (rootKey == Microsoft.Win32.Registry.ClassesRoot)\n return HKEY_CLASSES_ROOT;\n else if (rootKey == Microsoft.Win32.Registry.Users)\n return HKEY_USERS;\n else if (rootKey == Microsoft.Win32.Registry.CurrentConfig)\n return HKEY_CURRENT_CONFIG;\n else\n return IntPtr.Zero;\n }\n\n private RegistryKey? EnsureKeyWithFullAccess(RegistryKey rootKey, string subKeyPath)\n {\n try\n {\n // Try to open existing key first\n RegistryKey? key = rootKey.OpenSubKey(subKeyPath, true);\n \n if (key != null)\n {\n return key; // Key exists and we got write access\n }\n \n // Check if the key exists but we don't have access\n RegistryKey? readOnlyKey = rootKey.OpenSubKey(subKeyPath, false);\n if (readOnlyKey != null)\n {\n // Key exists but we don't have write access, try to take ownership\n readOnlyKey.Close();\n _logService.LogInformation($\"Registry key exists but we don't have write access: {rootKey.Name}\\\\{subKeyPath}\");\n \n // Try to take ownership of the key\n bool ownershipTaken = TakeOwnershipOfKey(rootKey, subKeyPath);\n if (ownershipTaken)\n {\n // Try to open the key again with write access\n key = rootKey.OpenSubKey(subKeyPath, true);\n if (key != null)\n {\n _logService.LogSuccess($\"Successfully opened registry key after taking ownership: {rootKey.Name}\\\\{subKeyPath}\");\n return key;\n }\n }\n \n _logService.LogWarning($\"Failed to get write access to registry key even after taking ownership: {rootKey.Name}\\\\{subKeyPath}\");\n }\n \n // Key doesn't exist or we couldn't get access - we need to create the entire path\n string[] parts = subKeyPath.Split('\\\\');\n string currentPath = \"\";\n \n for (int i = 0; i < parts.Length; i++)\n {\n string part = parts[i];\n \n if (currentPath == \"\")\n {\n currentPath = part;\n }\n else\n {\n currentPath += \"\\\\\" + part;\n }\n \n // Try to open this part of the path\n key = rootKey.OpenSubKey(currentPath, true);\n \n if (key == null)\n {\n // This part doesn't exist, create it with full rights\n RegistrySecurity security = new RegistrySecurity();\n \n // Get current user security identifier - handle null case\n var currentUser = WindowsIdentity.GetCurrent().User;\n if (currentUser != null)\n {\n // Add current user with full control\n security.AddAccessRule(new RegistryAccessRule(\n currentUser,\n RegistryRights.FullControl,\n InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,\n PropagationFlags.None,\n AccessControlType.Allow));\n }\n \n // Add Administrators with full control\n security.AddAccessRule(new RegistryAccessRule(\n new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),\n RegistryRights.FullControl,\n InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,\n PropagationFlags.None,\n AccessControlType.Allow));\n \n // Add SYSTEM with full control\n security.AddAccessRule(new RegistryAccessRule(\n new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),\n RegistryRights.FullControl,\n InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,\n PropagationFlags.None,\n AccessControlType.Allow));\n \n // Create the key with explicit security settings\n key = rootKey.CreateSubKey(currentPath, RegistryKeyPermissionCheck.ReadWriteSubTree, security);\n \n if (key == null)\n {\n _logService.LogError($\"Failed to create registry key: {currentPath}\");\n return null;\n }\n \n // Close intermediate keys to avoid leaks\n if (i < parts.Length - 1)\n {\n key.Close();\n key = null;\n }\n }\n else if (i < parts.Length - 1)\n {\n // Close intermediate keys to avoid leaks\n key.Close();\n key = null;\n }\n }\n \n // At this point, 'key' should be the full path key we wanted to create\n // If it's null, open the full path explicitly\n if (key == null)\n {\n key = rootKey.OpenSubKey(subKeyPath, true);\n }\n \n return key;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error ensuring registry key with full access: {subKeyPath}\", ex);\n return null;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/ProgressIndicator.cs", "using System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// A custom control that displays a progress indicator with status text.\n /// \n public class ProgressIndicator : Control\n {\n static ProgressIndicator()\n {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(ProgressIndicator), new FrameworkPropertyMetadata(typeof(ProgressIndicator)));\n }\n \n /// \n /// When overridden in a derived class, is invoked whenever application code or internal processes call .\n /// \n public override void OnApplyTemplate()\n {\n base.OnApplyTemplate();\n \n // Find the cancel button in the template and hook up the event handler\n if (GetTemplateChild(\"PART_CancelButton\") is Button cancelButton)\n {\n cancelButton.Click -= CancelButton_Click;\n cancelButton.Click += CancelButton_Click;\n }\n }\n \n private void CancelButton_Click(object sender, RoutedEventArgs e)\n {\n // Log the button click for debugging\n System.Diagnostics.Debug.WriteLine(\"Cancel button clicked\");\n \n // First try to execute the command if it exists\n if (CancelCommand != null && CancelCommand.CanExecute(null))\n {\n System.Diagnostics.Debug.WriteLine(\"Executing cancel command\");\n CancelCommand.Execute(null);\n return;\n }\n \n // If command execution fails, use a more direct approach\n System.Diagnostics.Debug.WriteLine(\"Command execution failed, trying direct approach\");\n CancelCurrentTaskDirectly();\n }\n \n /// \n /// Directly cancels the current task by finding the TaskProgressService instance.\n /// \n private void CancelCurrentTaskDirectly()\n {\n try\n {\n // Get the application's main window\n var mainWindow = System.Windows.Application.Current.MainWindow;\n if (mainWindow == null)\n {\n System.Diagnostics.Debug.WriteLine(\"Main window not found\");\n return;\n }\n \n // Get the DataContext of the main window (should be the MainViewModel)\n var mainViewModel = mainWindow.DataContext;\n if (mainViewModel == null)\n {\n System.Diagnostics.Debug.WriteLine(\"Main window DataContext is null\");\n return;\n }\n \n // Use reflection to get the _progressService field\n var type = mainViewModel.GetType();\n var field = type.GetField(\"_progressService\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n \n if (field != null)\n {\n var progressService = field.GetValue(mainViewModel) as Winhance.Core.Features.Common.Interfaces.ITaskProgressService;\n if (progressService != null)\n {\n System.Diagnostics.Debug.WriteLine(\"Found progress service, cancelling task\");\n progressService.CancelCurrentTask();\n \n // Show a message to the user that the task was cancelled\n System.Windows.MessageBox.Show(\"Installation cancelled by user.\", \"Cancelled\", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);\n }\n else\n {\n System.Diagnostics.Debug.WriteLine(\"Progress service is null\");\n }\n }\n else\n {\n System.Diagnostics.Debug.WriteLine(\"_progressService field not found\");\n }\n }\n catch (Exception ex)\n {\n System.Diagnostics.Debug.WriteLine($\"Error in CancelCurrentTaskDirectly: {ex.Message}\");\n }\n }\n\n #region Dependency Properties\n\n /// \n /// Gets or sets the progress value (0-100).\n /// \n public double Progress\n {\n get { return (double)GetValue(ProgressProperty); }\n set { SetValue(ProgressProperty, value); }\n }\n\n /// \n /// Identifies the Progress dependency property.\n /// \n public static readonly DependencyProperty ProgressProperty =\n DependencyProperty.Register(nameof(Progress), typeof(double), typeof(ProgressIndicator), \n new PropertyMetadata(0.0, OnProgressChanged));\n\n /// \n /// Gets or sets the status text.\n /// \n public string StatusText\n {\n get { return (string)GetValue(StatusTextProperty); }\n set { SetValue(StatusTextProperty, value); }\n }\n\n /// \n /// Identifies the StatusText dependency property.\n /// \n public static readonly DependencyProperty StatusTextProperty =\n DependencyProperty.Register(nameof(StatusText), typeof(string), typeof(ProgressIndicator), \n new PropertyMetadata(string.Empty));\n\n /// \n /// Gets or sets whether the progress is indeterminate.\n /// \n public bool IsIndeterminate\n {\n get { return (bool)GetValue(IsIndeterminateProperty); }\n set { SetValue(IsIndeterminateProperty, value); }\n }\n\n /// \n /// Identifies the IsIndeterminate dependency property.\n /// \n public static readonly DependencyProperty IsIndeterminateProperty =\n DependencyProperty.Register(nameof(IsIndeterminate), typeof(bool), typeof(ProgressIndicator), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets whether the control is active.\n /// \n public bool IsActive\n {\n get { return (bool)GetValue(IsActiveProperty); }\n set { SetValue(IsActiveProperty, value); }\n }\n\n /// \n /// Identifies the IsActive dependency property.\n /// \n public static readonly DependencyProperty IsActiveProperty =\n DependencyProperty.Register(nameof(IsActive), typeof(bool), typeof(ProgressIndicator), \n new PropertyMetadata(false));\n\n /// \n /// Gets the progress text (e.g., \"50%\").\n /// \n public string ProgressText\n {\n get { return (string)GetValue(ProgressTextProperty); }\n private set { SetValue(ProgressTextProperty, value); }\n }\n\n /// \n /// Identifies the ProgressText dependency property.\n /// \n public static readonly DependencyProperty ProgressTextProperty =\n DependencyProperty.Register(nameof(ProgressText), typeof(string), typeof(ProgressIndicator), \n new PropertyMetadata(string.Empty));\n \n /// \n /// Gets or sets the command to execute when the cancel button is clicked.\n /// \n public ICommand CancelCommand\n {\n get { return (ICommand)GetValue(CancelCommandProperty); }\n set { SetValue(CancelCommandProperty, value); }\n }\n\n /// \n /// Identifies the CancelCommand dependency property.\n /// \n public static readonly DependencyProperty CancelCommandProperty =\n DependencyProperty.Register(nameof(CancelCommand), typeof(ICommand), typeof(ProgressIndicator), \n new PropertyMetadata(null));\n \n /// \n /// Gets or sets whether to show the cancel button instead of progress text.\n /// \n public bool ShowCancelButton\n {\n get { return (bool)GetValue(ShowCancelButtonProperty); }\n set { SetValue(ShowCancelButtonProperty, value); }\n }\n\n /// \n /// Identifies the ShowCancelButton dependency property.\n /// \n public static readonly DependencyProperty ShowCancelButtonProperty =\n DependencyProperty.Register(nameof(ShowCancelButton), typeof(bool), typeof(ProgressIndicator), \n new PropertyMetadata(false));\n\n #endregion\n\n private static void OnProgressChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is ProgressIndicator control)\n {\n control.UpdateProgressText();\n }\n }\n\n private void UpdateProgressText()\n {\n if (IsIndeterminate || ShowCancelButton)\n {\n ProgressText = string.Empty;\n }\n else\n {\n ProgressText = $\"{Progress:F0}%\";\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/FeatureRemovalService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service for removing Windows optional features from the system.\n/// \npublic class FeatureRemovalService : IFeatureRemovalService\n{\n private readonly ILogService _logService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IScheduledTaskService _scheduledTaskService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The app discovery service.\n /// The scheduled task service.\n public FeatureRemovalService(\n ILogService logService,\n IAppDiscoveryService appDiscoveryService,\n IScheduledTaskService scheduledTaskService)\n {\n _logService = logService;\n _appDiscoveryService = appDiscoveryService;\n _scheduledTaskService = scheduledTaskService;\n }\n\n /// \n public async Task RemoveFeatureAsync(\n FeatureInfo featureInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (featureInfo == null)\n {\n throw new ArgumentNullException(nameof(featureInfo));\n }\n // Call the other overload and return its result\n return await RemoveFeatureAsync(featureInfo.PackageName, progress, cancellationToken);\n }\n\n /// \n public async Task RemoveFeatureAsync(\n string featureName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n try\n {\n progress?.Report(new TaskProgressDetail { Progress = 0, StatusText = $\"Starting removal of {featureName}...\" });\n _logService.LogInformation($\"Removing optional feature: {featureName}\");\n \n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n \n // First, attempt to disable the feature\n powerShell.AddScript(@\"\n param($featureName)\n try {\n # Check if the feature exists and is enabled\n $feature = Get-WindowsOptionalFeature -Online | Where-Object { $_.FeatureName -eq $featureName -and $_.State -eq 'Enabled' }\n \n if ($feature) {\n # Get the full feature name\n $fullFeatureName = $feature.FeatureName\n \n # Disable the feature\n $result = Disable-WindowsOptionalFeature -Online -FeatureName $featureName -NoRestart\n \n return @{\n FullFeatureName = $fullFeatureName\n }\n } else {\n # Feature not found or already disabled\n return @{\n Error = \"\"Feature not found or already disabled\"\"\n FullFeatureName = $null\n }\n }\n }\n catch {\n return @{\n Error = $_.Exception.Message\n FullFeatureName = $null\n }\n }\n \");\n powerShell.AddParameter(\"featureName\", featureName);\n \n var result = await Task.Run(() => powerShell.Invoke());\n \n // Extract any error or the full feature name from the first command\n string? error = null;\n string fullFeatureName = featureName;\n \n if (result != null && result.Count > 0)\n {\n var resultObj = result[0];\n \n // Get any error\n if (resultObj.Properties.Any(p => p.Name == \"Error\"))\n {\n error = resultObj.Properties[\"Error\"]?.Value as string;\n }\n \n // Get the full feature name if available\n if (resultObj.Properties.Any(p => p.Name == \"FullFeatureName\") && \n resultObj.Properties[\"FullFeatureName\"]?.Value != null)\n {\n fullFeatureName = resultObj.Properties[\"FullFeatureName\"].Value.ToString();\n }\n }\n \n // Now check if the feature is still enabled to determine success\n powerShell.Commands.Clear();\n powerShell.AddScript(@\"\n param($featureName)\n $feature = Get-WindowsOptionalFeature -Online | Where-Object { $_.FeatureName -eq $featureName }\n \n if ($feature -ne $null) {\n return @{\n IsEnabled = ($feature.State -eq 'Enabled')\n RebootRequired = $feature.RestartNeeded\n }\n } else {\n return @{\n IsEnabled = $false\n RebootRequired = $false\n }\n }\n \");\n powerShell.AddParameter(\"featureName\", featureName);\n \n var statusResult = await Task.Run(() => powerShell.Invoke());\n \n bool isStillEnabled = false;\n bool rebootRequired = false;\n \n if (statusResult != null && statusResult.Count > 0)\n {\n var statusObj = statusResult[0];\n \n // Check if the feature is still enabled\n if (statusObj.Properties.Any(p => p.Name == \"IsEnabled\") && \n statusObj.Properties[\"IsEnabled\"]?.Value != null)\n {\n isStillEnabled = Convert.ToBoolean(statusObj.Properties[\"IsEnabled\"].Value);\n }\n \n // Check if a reboot is required\n if (statusObj.Properties.Any(p => p.Name == \"RebootRequired\") && \n statusObj.Properties[\"RebootRequired\"]?.Value != null)\n {\n rebootRequired = Convert.ToBoolean(statusObj.Properties[\"RebootRequired\"].Value);\n }\n }\n \n // Success is determined by whether the feature is no longer enabled\n bool success = !isStillEnabled;\n bool overallSuccess = false;\n \n if (success)\n {\n progress?.Report(new TaskProgressDetail { Progress = 100, StatusText = $\"Successfully removed {featureName}\" });\n _logService.LogSuccess($\"Successfully removed optional feature: {featureName}\");\n \n if (rebootRequired)\n {\n progress?.Report(new TaskProgressDetail { StatusText = \"Restart required\", LogLevel = LogLevel.Warning });\n _logService.LogWarning($\"A system restart is required to complete the removal of {featureName}\");\n }\n \n _logService.LogInformation($\"Full feature name: {fullFeatureName}\");\n \n // Update BloatRemoval.ps1 script after successful removal\n try\n {\n var script = await UpdateBloatRemovalScriptAsync(fullFeatureName);\n _logService.LogInformation($\"BloatRemoval.ps1 script updated for feature: {featureName}\");\n \n // Register the scheduled task to run the script at startup\n try\n {\n bool taskRegistered = await RegisterBloatRemovalTaskAsync(script);\n if (taskRegistered)\n {\n _logService.LogSuccess($\"Scheduled task registered for BloatRemoval.ps1\");\n }\n else\n {\n _logService.LogWarning($\"Failed to register scheduled task for BloatRemoval.ps1, but continuing operation\");\n }\n }\n catch (Exception taskEx)\n {\n _logService.LogError($\"Error registering scheduled task: {taskEx.Message}\");\n // Don't fail the removal if task registration fails\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for feature: {featureName}\", ex);\n // Don't fail the removal if script update fails\n }\n \n overallSuccess = true;\n }\n else\n {\n progress?.Report(new TaskProgressDetail { Progress = 0, StatusText = $\"Failed to remove {featureName}: {error}\", LogLevel = LogLevel.Error });\n _logService.LogError($\"Failed to remove optional feature: {featureName}. {error}\");\n }\n \n return overallSuccess; // Return success status\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing optional feature: {featureName}\", ex);\n progress?.Report(new TaskProgressDetail { Progress = 0, StatusText = $\"Error removing {featureName}: {ex.Message}\", LogLevel = LogLevel.Error });\n return false; // Return false on exception\n }\n }\n\n /// \n public Task CanRemoveFeatureAsync(FeatureInfo featureInfo)\n {\n // Basic implementation: Assume all found features can be removed.\n // TODO: Add actual checks if needed (e.g., dependencies, system protection)\n return Task.FromResult(true);\n }\n\n /// \n public async Task> RemoveFeaturesInBatchAsync(\n List features)\n {\n if (features == null)\n {\n throw new ArgumentNullException(nameof(features));\n }\n\n return await RemoveFeaturesInBatchAsync(features.Select(f => f.PackageName).ToList());\n }\n\n /// \n public async Task> RemoveFeaturesInBatchAsync(\n List featureNames)\n {\n var results = new List<(string Name, bool Success, string? Error)>();\n \n try\n {\n _logService.LogInformation($\"Removing {featureNames.Count} Windows optional features\");\n \n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n \n foreach (var feature in featureNames)\n {\n try\n {\n _logService.LogInformation($\"Removing optional feature: {feature}\");\n \n // First, attempt to disable the feature\n powerShell.Commands.Clear();\n powerShell.AddScript(@\"\n param($featureName)\n try {\n # Check if the feature exists and is enabled\n $feature = Get-WindowsOptionalFeature -Online | Where-Object { $_.FeatureName -eq $featureName -and $_.State -eq 'Enabled' }\n \n if ($feature) {\n # Get the full feature name\n $fullFeatureName = $feature.FeatureName\n \n # Disable the feature\n $result = Disable-WindowsOptionalFeature -Online -FeatureName $featureName -NoRestart\n \n return @{\n FullFeatureName = $fullFeatureName\n }\n } else {\n # Feature not found or already disabled\n return @{\n Error = \"\"Feature not found or already disabled\"\"\n FullFeatureName = $null\n }\n }\n }\n catch {\n return @{\n Error = $_.Exception.Message\n FullFeatureName = $null\n }\n }\n \");\n powerShell.AddParameter(\"featureName\", feature);\n \n var result = await Task.Run(() => powerShell.Invoke());\n \n // Extract any error or the full feature name from the first command\n string? error = null;\n string featureFullName = feature;\n \n if (result != null && result.Count > 0)\n {\n var resultObj = result[0];\n \n // Get any error\n if (resultObj.Properties.Any(p => p.Name == \"Error\"))\n {\n error = resultObj.Properties[\"Error\"]?.Value as string;\n }\n \n // Get the full feature name if available\n if (resultObj.Properties.Any(p => p.Name == \"FullFeatureName\") && \n resultObj.Properties[\"FullFeatureName\"]?.Value != null)\n {\n featureFullName = resultObj.Properties[\"FullFeatureName\"].Value.ToString();\n }\n }\n \n // Now check if the feature is still enabled to determine success\n powerShell.Commands.Clear();\n powerShell.AddScript(@\"\n param($featureName)\n $feature = Get-WindowsOptionalFeature -Online | Where-Object { $_.FeatureName -eq $featureName }\n \n if ($feature -ne $null) {\n return @{\n IsEnabled = ($feature.State -eq 'Enabled')\n RebootRequired = $feature.RestartNeeded\n }\n } else {\n return @{\n IsEnabled = $false\n RebootRequired = $false\n }\n }\n \");\n powerShell.AddParameter(\"featureName\", feature);\n \n var statusResult = await Task.Run(() => powerShell.Invoke());\n \n bool isStillEnabled = false;\n bool rebootRequired = false;\n \n if (statusResult != null && statusResult.Count > 0)\n {\n var statusObj = statusResult[0];\n \n // Check if the feature is still enabled\n if (statusObj.Properties.Any(p => p.Name == \"IsEnabled\") && \n statusObj.Properties[\"IsEnabled\"]?.Value != null)\n {\n isStillEnabled = Convert.ToBoolean(statusObj.Properties[\"IsEnabled\"].Value);\n }\n \n // Check if a reboot is required\n if (statusObj.Properties.Any(p => p.Name == \"RebootRequired\") && \n statusObj.Properties[\"RebootRequired\"]?.Value != null)\n {\n rebootRequired = Convert.ToBoolean(statusObj.Properties[\"RebootRequired\"].Value);\n }\n }\n \n // Success is determined by whether the feature is no longer enabled\n bool success = !isStillEnabled;\n \n if (success)\n {\n _logService.LogInformation($\"Full feature name for batch operation: {featureFullName}\");\n \n // Update BloatRemoval.ps1 script for batch operations too\n try\n {\n var script = await UpdateBloatRemovalScriptAsync(featureFullName);\n _logService.LogInformation($\"BloatRemoval.ps1 script updated for feature in batch: {feature}\");\n \n // Register the scheduled task to run the script at startup\n try\n {\n bool taskRegistered = await RegisterBloatRemovalTaskAsync(script);\n if (taskRegistered)\n {\n _logService.LogSuccess($\"Scheduled task registered for BloatRemoval.ps1\");\n }\n else\n {\n _logService.LogWarning($\"Failed to register scheduled task for BloatRemoval.ps1, but continuing operation\");\n }\n }\n catch (Exception taskEx)\n {\n _logService.LogError($\"Error registering scheduled task: {taskEx.Message}\");\n // Don't fail the removal if task registration fails\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for feature in batch: {feature}\", ex);\n // Don't fail the removal if script update fails\n }\n }\n \n results.Add((feature, success, error));\n \n if (success)\n {\n _logService.LogSuccess($\"Successfully removed optional feature: {feature}\");\n if (rebootRequired)\n {\n _logService.LogWarning($\"A system restart is required to complete the removal of {feature}\");\n }\n }\n else\n {\n _logService.LogError($\"Failed to remove optional feature: {feature}. {error}\");\n }\n }\n catch (Exception ex)\n {\n results.Add((feature, false, ex.Message));\n _logService.LogError($\"Error removing optional feature: {feature}\", ex);\n }\n }\n \n return results;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error removing optional features\", ex);\n return featureNames.Select(f => (f, false, $\"Error: {ex.Message}\")).ToList();\n }\n }\n\n // SetExecutionPolicy is now handled by PowerShellFactory\n \n /// \n /// Updates the BloatRemoval.ps1 script to add the removed feature to it.\n /// \n /// The feature name.\n /// The updated removal script.\n private async Task UpdateBloatRemovalScriptAsync(string featureName)\n {\n try\n {\n // Get the script update service\n var scriptUpdateService = GetScriptUpdateService();\n if (scriptUpdateService == null)\n {\n _logService.LogWarning(\"Script update service not available\");\n throw new InvalidOperationException(\"Script update service not available\");\n }\n \n // Update the script\n var appNames = new List { featureName };\n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n \n _logService.LogInformation($\"Updating BloatRemoval.ps1 script for feature: {featureName}\");\n \n try\n {\n var script = await scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n false); // false = removal operation, so add to script\n \n _logService.LogInformation($\"Successfully updated BloatRemoval.ps1 script for feature: {featureName}\");\n return script;\n }\n catch (FileNotFoundException)\n {\n _logService.LogInformation($\"BloatRemoval.ps1 script not found. It will be created when needed.\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in script update service for feature: {featureName}\", ex);\n throw; // Rethrow to be caught by the outer try-catch\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for feature: {featureName}\", ex);\n throw; // Rethrow so the caller can handle it\n }\n }\n \n /// \n /// Registers a scheduled task to run the BloatRemoval script at startup.\n /// \n /// The removal script to register.\n /// True if the task was registered successfully, false otherwise.\n private async Task RegisterBloatRemovalTaskAsync(RemovalScript script)\n {\n try\n {\n if (script == null)\n {\n _logService.LogError(\"Cannot register scheduled task: Script is null\");\n return false;\n }\n \n _logService.LogInformation(\"Registering scheduled task for BloatRemoval.ps1\");\n \n // Register the scheduled task\n bool success = await _scheduledTaskService.RegisterScheduledTaskAsync(script);\n \n if (success)\n {\n _logService.LogSuccess(\"Successfully registered scheduled task for BloatRemoval.ps1\");\n }\n else\n {\n _logService.LogError(\"Failed to register scheduled task for BloatRemoval.ps1\");\n }\n \n return success;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error registering scheduled task for BloatRemoval.ps1\", ex);\n return false;\n }\n }\n \n /// \n /// Gets the script update service.\n /// \n /// The script update service or null if not available.\n private IScriptUpdateService? GetScriptUpdateService()\n {\n try\n {\n // Use the existing _appDiscoveryService that was injected into the constructor\n // instead of creating a new instance\n var scriptContentModifier = new ScriptContentModifier(_logService);\n return new ScriptUpdateService(_logService, _appDiscoveryService, scriptContentModifier);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to get script update service\", ex);\n return null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Services/LogService.cs", "using System;\nusing System.IO;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Services\n{\n public class LogService : ILogService\n {\n private string _logPath;\n private StreamWriter? _logWriter;\n private readonly object _lockObject = new object();\n \n public event EventHandler? LogMessageGenerated;\n\n public LogService()\n {\n _logPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\",\n $\"Winhance_Log_{DateTime.Now:yyyyMMdd_HHmmss}.log\"\n );\n }\n\n public void Log(LogLevel level, string message, Exception? exception = null)\n {\n switch (level)\n {\n case LogLevel.Info:\n LogInformation(message);\n break;\n case LogLevel.Warning:\n LogWarning(message);\n break;\n case LogLevel.Error:\n LogError(message, exception);\n break;\n case LogLevel.Success:\n LogSuccess(message);\n break;\n default:\n LogInformation(message);\n break;\n }\n \n // Raise event for subscribers\n LogMessageGenerated?.Invoke(this, new LogMessageEventArgs(level, message, exception));\n }\n \n // This method should be removed, but it might still be used in some places\n // Redirecting to the standard method with correct parameter order\n public void Log(string message, LogLevel level)\n {\n Log(level, message);\n }\n\n public void StartLog()\n {\n try\n {\n // Ensure directory exists\n var logDirectory = Path.GetDirectoryName(_logPath);\n if (logDirectory != null)\n {\n Directory.CreateDirectory(logDirectory);\n }\n else\n {\n throw new InvalidOperationException(\"Log directory path is null.\");\n }\n\n // Create or overwrite log file\n _logWriter = new StreamWriter(_logPath, false, Encoding.UTF8)\n {\n AutoFlush = true\n };\n\n // Write initial log header\n LogInformation($\"==== Winhance Log Started ====\");\n LogInformation($\"Timestamp: {DateTime.Now}\");\n LogInformation($\"User: {Environment.UserName}\");\n LogInformation($\"Machine: {Environment.MachineName}\");\n LogInformation($\"OS Version: {Environment.OSVersion}\");\n LogInformation(\"===========================\");\n }\n catch (Exception ex)\n {\n // Fallback logging if file write fails\n Console.Error.WriteLine($\"Failed to start log: {ex.Message}\");\n }\n }\n\n public void StopLog()\n {\n lock (_lockObject)\n {\n try\n {\n LogInformation(\"==== Winhance Log Ended ====\");\n _logWriter?.Close();\n _logWriter?.Dispose();\n }\n catch (Exception ex)\n {\n Console.Error.WriteLine($\"Error stopping log: {ex.Message}\");\n }\n }\n }\n\n public void LogInformation(string message)\n {\n WriteLog(message, \"INFO\");\n }\n\n public void LogWarning(string message)\n {\n WriteLog(message, \"WARNING\");\n }\n\n public void LogError(string message, Exception? exception = null)\n {\n string fullMessage = exception != null\n ? $\"{message} - Exception: {exception.Message}\\n{exception.StackTrace}\"\n : message;\n WriteLog(fullMessage, \"ERROR\");\n }\n\n public void LogSuccess(string message)\n {\n WriteLog(message, \"SUCCESS\");\n }\n\n public string GetLogPath()\n {\n return _logPath;\n }\n\n private void WriteLog(string message, string level)\n {\n lock (_lockObject)\n {\n try\n {\n string logEntry = $\"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}\";\n\n // Write to file if log writer is available\n _logWriter?.WriteLine(logEntry);\n\n // Also write to console for immediate visibility\n Console.WriteLine(logEntry);\n }\n catch (Exception ex)\n {\n Console.Error.WriteLine($\"Logging failed: {ex.Message}\");\n }\n }\n }\n\n // Implement IDisposable pattern to ensure logs are stopped\n public void Dispose()\n {\n StopLog();\n GC.SuppressFinalize(this);\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ConfigurationApplierService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for applying configuration settings to different view models.\n /// \n public class ConfigurationApplierService : IConfigurationApplierService\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n private readonly IEnumerable _sectionAppliers;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n /// The section-specific configuration appliers.\n public ConfigurationApplierService(\n IServiceProvider serviceProvider,\n ILogService logService,\n IEnumerable sectionAppliers)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _sectionAppliers = sectionAppliers ?? throw new ArgumentNullException(nameof(sectionAppliers));\n }\n\n /// \n /// Applies configuration settings to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A dictionary of section names and their application result.\n public async Task> ApplySectionsAsync(UnifiedConfigurationFile config, IEnumerable selectedSections)\n {\n var sectionResults = new Dictionary();\n \n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120)); // Increased timeout\n var cancellationToken = cancellationTokenSource.Token;\n \n // Track execution time\n var startTime = DateTime.Now;\n _logService.Log(LogLevel.Info, $\"Starting ApplySectionsAsync at {startTime}\");\n \n foreach (var section in selectedSections)\n {\n var sectionStartTime = DateTime.Now;\n _logService.Log(LogLevel.Info, $\"Processing section: {section} at {sectionStartTime}\");\n \n // Check for cancellation\n if (cancellationToken.IsCancellationRequested)\n {\n _logService.Log(LogLevel.Warning, $\"Skipping section {section} due to timeout\");\n sectionResults[section] = false;\n continue;\n }\n \n // Extract the section from the unified configuration\n var configFile = ExtractSectionFromUnifiedConfiguration(config, section);\n \n if (configFile == null)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to extract section {section} from unified configuration\");\n sectionResults[section] = false;\n continue;\n }\n \n if (configFile.Items == null || !configFile.Items.Any())\n {\n _logService.Log(LogLevel.Warning, $\"Section {section} is empty or not included in the unified configuration\");\n sectionResults[section] = false;\n continue;\n }\n \n _logService.Log(LogLevel.Info, $\"Extracted section {section} with {configFile.Items.Count} items\");\n \n // Apply the configuration to the appropriate view model\n bool sectionResult = false;\n \n try\n {\n // Find the appropriate section applier\n var sectionApplier = _sectionAppliers.FirstOrDefault(a => a.SectionName.Equals(section, StringComparison.OrdinalIgnoreCase));\n \n if (sectionApplier != null)\n {\n _logService.Log(LogLevel.Info, $\"Starting to apply configuration for section {section}\");\n \n // Apply with timeout protection\n var applyTask = sectionApplier.ApplyConfigAsync(configFile);\n \n // Set a section-specific timeout (longer for Optimize section which has power plan operations)\n int timeoutMs = section.Equals(\"Optimize\", StringComparison.OrdinalIgnoreCase) ? 60000 : 30000; // Increased timeouts\n \n _logService.Log(LogLevel.Info, $\"Setting timeout of {timeoutMs}ms for section {section}\");\n \n // Create a separate cancellation token source for this section\n using var sectionCts = new CancellationTokenSource(timeoutMs);\n var sectionCancellationToken = sectionCts.Token;\n \n try\n {\n // Wait for the task to complete or timeout\n var delayTask = Task.Delay(timeoutMs, sectionCancellationToken);\n var completedTask = await Task.WhenAny(applyTask, delayTask);\n \n if (completedTask == applyTask)\n {\n sectionResult = await applyTask;\n _logService.Log(LogLevel.Info, $\"Section {section} applied with result: {sectionResult}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Applying section {section} timed out after {timeoutMs}ms\");\n \n // Try to cancel the operation if possible\n sectionCts.Cancel();\n \n // Log detailed information about the section\n _logService.Log(LogLevel.Warning, $\"Section {section} details: {configFile.Items?.Count ?? 0} items\");\n \n sectionResult = false;\n }\n }\n catch (OperationCanceledException)\n {\n _logService.Log(LogLevel.Warning, $\"Section {section} application was canceled\");\n sectionResult = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No applier found for section: {section}\");\n sectionResult = false;\n }\n \n // If we have items but didn't update any, consider it a success\n // This handles the case where all items are already in the desired state\n if (!sectionResult && configFile.Items != null && configFile.Items.Any())\n {\n _logService.Log(LogLevel.Info, $\"No items were updated in section {section}, but considering it a success since configuration was applied\");\n sectionResult = true;\n }\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, $\"Applying section {section} was canceled due to timeout\");\n sectionResult = false;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying configuration to section {section}: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n sectionResult = false;\n }\n \n sectionResults[section] = sectionResult;\n }\n \n // Calculate and log execution time\n var endTime = DateTime.Now;\n var executionTime = endTime - startTime;\n _logService.Log(LogLevel.Info, $\"Completed ApplySectionsAsync in {executionTime.TotalSeconds:F2} seconds\");\n \n // Log summary of results\n foreach (var result in sectionResults)\n {\n _logService.Log(LogLevel.Info, $\"Section {result.Key}: {(result.Value ? \"Success\" : \"Failed\")}\");\n }\n \n return sectionResults;\n }\n\n private ConfigurationFile ExtractSectionFromUnifiedConfiguration(UnifiedConfigurationFile unifiedConfig, string section)\n {\n try\n {\n var configFile = new ConfigurationFile\n {\n ConfigType = section,\n Items = new List()\n };\n\n switch (section)\n {\n case \"WindowsApps\":\n configFile.Items = unifiedConfig.WindowsApps.Items;\n break;\n case \"ExternalApps\":\n configFile.Items = unifiedConfig.ExternalApps.Items;\n break;\n case \"Customize\":\n configFile.Items = unifiedConfig.Customize.Items;\n break;\n case \"Optimize\":\n configFile.Items = unifiedConfig.Optimize.Items;\n break;\n default:\n _logService.Log(LogLevel.Warning, $\"Unknown section: {section}\");\n return null;\n }\n\n return configFile;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error extracting section {section}: {ex.Message}\");\n return null;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/SoundOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\n\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Sound optimizations.\n /// \n public partial class SoundOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDependencyManager _dependencyManager;\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dependency manager.\n /// The view model locator.\n /// The settings registry.\n public SoundOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDependencyManager dependencyManager,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _dependencyManager = dependencyManager ?? throw new ArgumentNullException(nameof(dependencyManager));\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n }\n\n /// \n /// Loads the Sound optimizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Sound optimizations\n var soundOptimizations = Core.Features.Optimize.Models.SoundOptimizations.GetSoundOptimizations();\n if (soundOptimizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in soundOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = false, // Always initialize as unchecked\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Register the setting in the settings registry if available\n if (_settingsRegistry != null && !string.IsNullOrEmpty(settingItem.Id))\n {\n _settingsRegistry.RegisterSetting(settingItem);\n _logService.Log(LogLevel.Info, $\"Registered setting {settingItem.Id} in settings registry during creation\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for settings\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all Sound optimizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n foreach (var setting in Settings)\n {\n if (setting.RegistrySetting != null)\n {\n // Get status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n setting.Status = status;\n\n // Get current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n setting.CurrentValue = currentValue;\n \n // Set IsRegistryValueNull property based on current value\n setting.IsRegistryValueNull = currentValue == null;\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Sound setting statuses: {ex.Message}\");\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied => \"Applied\",\n RegistrySettingStatus.NotApplied => \"Not Applied\",\n RegistrySettingStatus.Modified => \"Modified\",\n RegistrySettingStatus.Error => \"Error\",\n RegistrySettingStatus.Unknown => \"Unknown\",\n _ => \"Unknown\"\n };\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0) return;\n\n bool allSelected = Settings.All(s => s.IsSelected);\n bool anySelected = Settings.Any(s => s.IsSelected);\n\n IsSelected = allSelected;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScriptGenerationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Service for generating and managing removal scripts.\n /// \n public class ScriptGenerationService : IScriptGenerationService\n {\n private readonly ILogService _logService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IAppRemovalService _appRemovalService;\n private readonly IScriptContentModifier _scriptContentModifier;\n private readonly IScriptUpdateService _scriptUpdateService;\n private readonly IScheduledTaskService _scheduledTaskService;\n private readonly IScriptFactory _scriptFactory;\n private readonly IScriptBuilderService _scriptBuilderService;\n private readonly string _scriptsPath;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The app discovery service.\n /// The app removal service.\n /// The script content modifier.\n /// The script update service.\n /// The scheduled task service.\n /// The script factory.\n /// The script builder service.\n public ScriptGenerationService(\n ILogService logService,\n IAppDiscoveryService appDiscoveryService,\n IAppRemovalService appRemovalService,\n IScriptContentModifier scriptContentModifier,\n IScriptUpdateService scriptUpdateService,\n IScheduledTaskService scheduledTaskService,\n IScriptFactory scriptFactory,\n IScriptBuilderService scriptBuilderService\n )\n {\n _logService = logService;\n _appDiscoveryService = appDiscoveryService;\n _appRemovalService = appRemovalService;\n _scriptContentModifier = scriptContentModifier;\n _scriptUpdateService = scriptUpdateService;\n _scheduledTaskService = scheduledTaskService;\n _scriptFactory = scriptFactory;\n _scriptBuilderService = scriptBuilderService;\n\n _scriptsPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n \"Winhance\",\n \"Scripts\"\n );\n Directory.CreateDirectory(_scriptsPath);\n }\n\n /// \n public async Task CreateBatchRemovalScriptAsync(\n List appNames,\n Dictionary> appsWithRegistry\n )\n {\n try\n {\n _logService.LogInformation(\n $\"Creating batch removal script for {appNames.Count} apps\"\n );\n\n // Get all standard apps to check for subpackages\n var allRemovableApps = (await _appDiscoveryService.GetStandardAppsAsync()).ToList();\n\n // Create a dictionary to store subpackages for each app\n var appSubPackages = new Dictionary();\n\n // Find subpackages for each app in the list\n foreach (var appName in appNames)\n {\n var appInfo = allRemovableApps.FirstOrDefault(a => a.PackageName == appName);\n\n // Explicitly handle Copilot and Xbox packages to ensure subpackages are added\n bool isCopilotOrXbox =\n appName.Contains(\"Copilot\", StringComparison.OrdinalIgnoreCase)\n || appName.Contains(\"Xbox\", StringComparison.OrdinalIgnoreCase);\n\n if (\n appInfo?.SubPackages != null\n && (appInfo.SubPackages.Length > 0 || isCopilotOrXbox)\n )\n {\n appSubPackages[appName] = appInfo.SubPackages ?? new string[0];\n }\n\n // If the app has registry settings but they're not in the appsWithRegistry dictionary,\n // add them now\n if (appInfo?.RegistrySettings != null && appInfo.RegistrySettings.Length > 0)\n {\n if (!appsWithRegistry.ContainsKey(appName))\n {\n appsWithRegistry[appName] = appInfo.RegistrySettings.ToList();\n }\n }\n }\n\n // Check if the BloatRemoval.ps1 file already exists\n string bloatRemovalScriptPath = Path.Combine(_scriptsPath, \"BloatRemoval.ps1\");\n if (File.Exists(bloatRemovalScriptPath))\n {\n _logService.LogInformation(\n \"BloatRemoval.ps1 already exists, updating it with new entries\"\n );\n return await _scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n false // false = removal operation, so add to script\n );\n }\n\n // If the file doesn't exist, create a new one using the script factory\n return _scriptFactory.CreateBatchRemovalScript(\n appNames,\n appsWithRegistry,\n appSubPackages\n );\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error creating batch removal script\", ex);\n throw;\n }\n }\n\n /// \n public async Task CreateBatchRemovalScriptAsync(string scriptPath, AppInfo app)\n {\n try\n {\n _logService.LogInformation(\n $\"Creating removal script for {app.PackageName} at {scriptPath}\"\n );\n\n // Use the script builder service to create the script content\n string content = _scriptBuilderService.BuildSingleAppRemovalScript(app);\n\n await File.WriteAllTextAsync(scriptPath, content);\n _logService.LogSuccess(\n $\"Created removal script for {app.PackageName} at {scriptPath}\"\n );\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error creating removal script for {app.PackageName}\", ex);\n return false;\n }\n }\n\n /// \n public async Task RegisterRemovalTaskAsync(RemovalScript script)\n {\n try\n {\n if (script == null)\n {\n _logService.LogError(\"Cannot register removal task: Script is null\");\n return;\n }\n\n _logService.LogInformation($\"Registering removal task for script: {script.Name}\");\n\n // Ensure the script has been saved\n if (string.IsNullOrEmpty(script.Content))\n {\n _logService.LogWarning($\"Script content is empty for: {script.Name}\");\n }\n\n // Register the scheduled task\n bool success = await _scheduledTaskService.RegisterScheduledTaskAsync(script);\n\n if (success)\n {\n _logService.LogSuccess(\n $\"Successfully registered scheduled task for script: {script.Name}\"\n );\n }\n else\n {\n _logService.LogWarning(\n $\"Failed to register scheduled task for script: {script.Name}, but continuing operation\"\n );\n // Don't throw an exception here, just log a warning and continue\n }\n }\n catch (Exception ex)\n {\n _logService.LogError(\n $\"Error registering removal task for script: {script.Name}\",\n ex\n );\n // Don't rethrow the exception, just log it and continue\n }\n }\n\n /// \n public async Task RegisterRemovalTaskAsync(string taskName, string scriptPath)\n {\n try\n {\n if (string.IsNullOrEmpty(taskName) || string.IsNullOrEmpty(scriptPath))\n {\n _logService.LogError(\n $\"Invalid parameters for task registration. TaskName: {taskName}, ScriptPath: {scriptPath}\"\n );\n return false;\n }\n\n _logService.LogInformation(\n $\"Registering removal task: {taskName} for script: {scriptPath}\"\n );\n\n // Check if the script file exists\n if (!File.Exists(scriptPath))\n {\n _logService.LogError($\"Script file not found at: {scriptPath}\");\n return false;\n }\n\n // Create a RemovalScript object to pass to the scheduled task service\n var script = new RemovalScript\n {\n Name = Path.GetFileNameWithoutExtension(scriptPath),\n Content = await File.ReadAllTextAsync(scriptPath),\n TargetScheduledTaskName = taskName,\n RunOnStartup = true,\n };\n\n // Register the scheduled task\n return await _scheduledTaskService.RegisterScheduledTaskAsync(script);\n }\n catch (Exception ex)\n {\n _logService.LogError(\n $\"Error registering removal task: {taskName} for script: {scriptPath}\",\n ex\n );\n return false;\n }\n }\n\n /// \n public async Task SaveScriptAsync(RemovalScript script)\n {\n try\n {\n string scriptPath = Path.Combine(_scriptsPath, $\"{script.Name}.ps1\");\n await File.WriteAllTextAsync(scriptPath, script.Content);\n _logService.LogInformation($\"Saved script to {scriptPath}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error saving script: {script.Name}\", ex);\n throw;\n }\n }\n\n /// \n public async Task SaveScriptAsync(string scriptPath, string scriptContent)\n {\n try\n {\n await File.WriteAllTextAsync(scriptPath, scriptContent);\n _logService.LogInformation($\"Saved script to {scriptPath}\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error saving script to {scriptPath}\", ex);\n return false;\n }\n }\n\n /// \n public async Task UpdateBloatRemovalScriptForInstalledAppAsync(AppInfo app)\n {\n try\n {\n _logService.LogInformation(\n $\"Updating BloatRemoval script for installed app: {app.PackageName}\"\n );\n\n string bloatRemovalScriptPath = Path.Combine(_scriptsPath, \"BloatRemoval.ps1\");\n if (!File.Exists(bloatRemovalScriptPath))\n {\n _logService.LogWarning(\n $\"BloatRemoval.ps1 not found at {bloatRemovalScriptPath}\"\n );\n return false;\n }\n\n string scriptContent = await File.ReadAllTextAsync(bloatRemovalScriptPath);\n bool scriptModified = false;\n\n // Handle different types of apps\n if (\n app.Type == AppType.OptionalFeature\n || app.PackageName.Equals(\"Recall\", StringComparison.OrdinalIgnoreCase)\n || app.Type == AppType.Capability\n )\n {\n // Handle OptionalFeatures and Capabilities using the ScriptUpdateService\n // This ensures proper handling of install operations (removing from script)\n _logService.LogInformation(\n $\"Using ScriptUpdateService to update BloatRemoval script for {app.Type} {app.PackageName}\"\n );\n\n // Create a list with just this app\n var appNames = new List { app.PackageName };\n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n\n // Get app registry settings if available\n var allRemovableApps = (\n await _appDiscoveryService.GetStandardAppsAsync()\n ).ToList();\n var appDefinition = allRemovableApps.FirstOrDefault(a =>\n a.PackageName.Equals(app.PackageName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (\n appDefinition?.RegistrySettings != null\n && appDefinition.RegistrySettings.Length > 0\n )\n {\n appsWithRegistry[app.PackageName] = appDefinition.RegistrySettings.ToList();\n }\n\n // Update the script with isInstallOperation = true to remove the entry\n await _scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n true // true = install operation, so remove from script\n );\n\n return true;\n }\n else\n {\n // Handle standard package\n scriptContent = _scriptContentModifier.RemovePackageFromScript(\n scriptContent,\n app.PackageName\n );\n\n // Create a list of subpackages to remove\n List subPackagesToRemove = new List();\n\n // Get all standard apps to find the app definition and its subpackages\n var allRemovableApps = (\n await _appDiscoveryService.GetStandardAppsAsync()\n ).ToList();\n\n // Find the app definition that matches the current app\n var appDefinition = allRemovableApps.FirstOrDefault(a =>\n a.PackageName.Equals(app.PackageName, StringComparison.OrdinalIgnoreCase)\n );\n\n // If we found the app definition and it has subpackages, add them to the removal list\n if (appDefinition?.SubPackages != null && appDefinition.SubPackages.Length > 0)\n {\n _logService.LogInformation(\n $\"Found {appDefinition.SubPackages.Length} subpackages for {app.PackageName} in WindowsAppCatalog\"\n );\n subPackagesToRemove.AddRange(appDefinition.SubPackages);\n }\n\n // Remove registry settings for this app from the script\n scriptContent = _scriptContentModifier.RemoveAppRegistrySettingsFromScript(\n scriptContent,\n app.PackageName\n );\n\n // Apply registry settings to delete registry keys from the system\n if (\n appDefinition?.RegistrySettings != null\n && appDefinition.RegistrySettings.Length > 0\n )\n {\n _logService.LogInformation(\n $\"Found {appDefinition.RegistrySettings.Length} registry settings for {app.PackageName}\"\n );\n\n // Create a list of registry settings that delete the keys\n var deleteRegistrySettings = new List();\n\n foreach (var setting in appDefinition.RegistrySettings)\n {\n // Create a new registry setting that deletes the key\n var deleteSetting = new AppRegistrySetting\n {\n Path = setting.Path,\n Name = setting.Name,\n Value = null, // null value means delete the key\n ValueKind = setting.ValueKind,\n };\n\n deleteRegistrySettings.Add(deleteSetting);\n }\n\n // Apply the registry settings to delete the keys\n // TODO: ApplyRegistrySettingsAsync is not on IAppRemovalService.\n // Need to inject IRegistryService or move this logic. Commenting out for now.\n _logService.LogInformation(\n $\"Applying {deleteRegistrySettings.Count} registry settings to delete keys for {app.PackageName}\"\n );\n // var success = await _appRemovalService.ApplyRegistrySettingsAsync(\n // deleteRegistrySettings\n // );\n var success = false; // Assume failure for now as the call is removed\n _logService.LogWarning(\n $\"Skipping registry key deletion for {app.PackageName} as ApplyRegistrySettingsAsync is not available on the interface.\"\n );\n\n if (success) // This block will likely not be hit now\n {\n _logService.LogSuccess(\n $\"Successfully deleted registry keys for {app.PackageName}\"\n );\n }\n else\n {\n _logService.LogWarning(\n $\"Failed to delete some registry keys for {app.PackageName}\"\n );\n }\n }\n\n // Remove all subpackages from the script\n foreach (var subPackage in subPackagesToRemove)\n {\n _logService.LogInformation(\n $\"Removing subpackage: {subPackage} for app: {app.PackageName}\"\n );\n scriptContent = _scriptContentModifier.RemovePackageFromScript(\n scriptContent,\n subPackage\n );\n }\n\n scriptModified = true;\n }\n\n // Save the updated script if it was modified\n if (scriptModified)\n {\n await File.WriteAllTextAsync(bloatRemovalScriptPath, scriptContent);\n _logService.LogSuccess(\n $\"Successfully updated BloatRemoval script for app: {app.PackageName}\"\n );\n }\n else\n {\n _logService.LogInformation(\n $\"No changes needed to BloatRemoval script for app: {app.PackageName}\"\n );\n }\n\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError(\n $\"Error updating BloatRemoval script for app: {app.PackageName}\",\n ex\n );\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/ExplorerOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\n\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Explorer optimizations.\n /// \n public partial class ExplorerOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDependencyManager _dependencyManager;\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dependency manager.\n /// The view model locator.\n /// The settings registry.\n public ExplorerOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDependencyManager dependencyManager,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _dependencyManager = dependencyManager ?? throw new ArgumentNullException(nameof(dependencyManager));\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n }\n\n /// \n /// Loads the Explorer optimizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Explorer optimizations from ExplorerOptimizations\n var explorerOptimizations = Core.Features.Optimize.Models.ExplorerOptimizations.GetExplorerOptimizations();\n if (explorerOptimizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in explorerOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = false, // Always initialize as unchecked\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Register the setting in the settings registry if available\n if (_settingsRegistry != null && !string.IsNullOrEmpty(settingItem.Id))\n {\n _settingsRegistry.RegisterSetting(settingItem);\n _logService.Log(LogLevel.Info, $\"Registered setting {settingItem.Id} in settings registry during creation\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for settings\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all Explorer optimizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n foreach (var setting in Settings)\n {\n if (setting.RegistrySetting != null)\n {\n // Get status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n setting.Status = status;\n\n // Get current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n setting.CurrentValue = currentValue;\n \n // Set IsRegistryValueNull property based on current value\n setting.IsRegistryValueNull = currentValue == null;\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Explorer optimization statuses: {ex.Message}\");\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied => \"Applied\",\n RegistrySettingStatus.NotApplied => \"Not Applied\",\n RegistrySettingStatus.Modified => \"Modified\",\n RegistrySettingStatus.Error => \"Error\",\n RegistrySettingStatus.Unknown => \"Unknown\",\n _ => \"Unknown\"\n };\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0) return;\n\n bool allSelected = Settings.All(s => s.IsSelected);\n bool anySelected = Settings.Any(s => s.IsSelected);\n\n IsSelected = allSelected;\n }\n\n /// \n /// Converts a RegistryHive enum to its string representation (HKCU, HKLM, etc.)\n /// \n /// The registry hive.\n /// The string representation of the registry hive.\n private string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => hive.ToString()\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/CommandService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service for executing system commands related to optimizations.\n /// \n public class CommandService : ICommandService\n {\n private readonly ILogService _logService;\n private readonly ISystemServices _systemServices;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The system services.\n public CommandService(ILogService logService, ISystemServices systemServices)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _systemServices =\n systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n }\n\n /// \n public async Task<(bool Success, string Output, string Error)> ExecuteCommandAsync(\n string command,\n bool requiresElevation = true\n )\n {\n try\n {\n _logService.LogInformation($\"Executing command: {command}\");\n\n // Create a PowerShell instance using the factory\n var powerShell = PowerShellFactory.CreateWindowsPowerShell(\n _logService,\n _systemServices\n );\n\n // Add the command to execute\n powerShell.AddScript(command);\n\n // Execute the command\n var results = await Task.Run(() => powerShell.Invoke());\n\n // Process the results\n var output = string.Join(Environment.NewLine, results.Select(r => r.ToString()));\n var error = string.Join(\n Environment.NewLine,\n powerShell.Streams.Error.ReadAll().Select(e => e.ToString())\n );\n\n // Log the results\n if (string.IsNullOrEmpty(error))\n {\n _logService.LogInformation($\"Command executed successfully: {command}\");\n _logService.LogInformation($\"Command output: {output}\");\n return (true, output, string.Empty);\n }\n else\n {\n _logService.LogWarning($\"Command execution failed: {command}\");\n _logService.LogWarning($\"Error: {error}\");\n return (false, output, error);\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Exception executing command: {command}\");\n _logService.LogError($\"Exception: {ex}\");\n return (false, string.Empty, ex.ToString());\n }\n }\n\n /// \n public async Task<(bool Success, string Message)> ApplyCommandSettingsAsync(\n IEnumerable settings,\n bool isEnabled\n )\n {\n if (settings == null || !settings.Any())\n {\n return (true, \"No command settings to apply.\");\n }\n\n var successCount = 0;\n var failureCount = 0;\n var messages = new List();\n\n foreach (var setting in settings)\n {\n var commandToExecute = isEnabled ? setting.EnabledCommand : setting.DisabledCommand;\n\n if (string.IsNullOrWhiteSpace(commandToExecute))\n {\n _logService.LogWarning($\"Empty command for setting: {setting.Id}\");\n continue;\n }\n\n var (success, output, error) = await ExecuteCommandAsync(\n commandToExecute,\n setting.RequiresElevation\n );\n\n if (success)\n {\n successCount++;\n messages.Add($\"Successfully applied command setting: {setting.Id}\");\n }\n else\n {\n failureCount++;\n messages.Add($\"Failed to apply command setting: {setting.Id}. Error: {error}\");\n }\n }\n\n var overallSuccess = failureCount == 0;\n var message =\n $\"Applied {successCount} command settings successfully, {failureCount} failed.\";\n\n if (messages.Any())\n {\n message += Environment.NewLine + string.Join(Environment.NewLine, messages);\n }\n\n return (overallSuccess, message);\n }\n\n /// \n public async Task IsCommandSettingEnabledAsync(CommandSetting setting)\n {\n try\n {\n _logService.LogInformation($\"Checking state for command setting: {setting.Id}\");\n\n // Check if this is a bcdedit command\n if (setting.EnabledCommand.Contains(\"bcdedit\"))\n {\n return await IsBcdeditSettingEnabledAsync(setting);\n }\n\n // For other types of commands, implement specific checking logic here\n // For now, return false as a default for unhandled command types\n _logService.LogWarning(\n $\"No state checking implementation for command type: {setting.Id}\"\n );\n return false;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking command setting state: {setting.Id}\", ex);\n return false;\n }\n }\n\n /// \n /// Checks if a bcdedit setting is in its enabled state.\n /// \n /// The command setting to check.\n /// True if the setting is in its enabled state, false otherwise.\n private async Task IsBcdeditSettingEnabledAsync(CommandSetting setting)\n {\n // Extract the setting name and value from the command\n string settingName = ExtractBcdeditSettingName(setting.EnabledCommand);\n string expectedValue = ExtractBcdeditSettingValue(setting.EnabledCommand);\n\n if (string.IsNullOrEmpty(settingName))\n {\n _logService.LogWarning(\n $\"Could not extract setting name from bcdedit command: {setting.EnabledCommand}\"\n );\n return false;\n }\n\n // Query the current boot configuration\n var (success, output, error) = await ExecuteCommandAsync(\"bcdedit /enum {current}\");\n\n if (!success || string.IsNullOrEmpty(output))\n {\n _logService.LogWarning($\"Failed to query boot configuration: {error}\");\n return false;\n }\n\n // Parse the output to find the setting\n bool settingExists = output.Contains(settingName, StringComparison.OrdinalIgnoreCase);\n\n // For settings that should be deleted when disabled\n if (setting.DisabledCommand.Contains(\"/deletevalue\"))\n {\n // If the setting exists, check if it has the expected value\n if (settingExists)\n {\n // Find the line containing the setting\n var lines = output.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n var settingLine = lines.FirstOrDefault(l =>\n l.Contains(settingName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (settingLine != null)\n {\n // Extract the current value\n var parts = settingLine.Split(\n new[] { ' ' },\n StringSplitOptions.RemoveEmptyEntries\n );\n if (parts.Length >= 2)\n {\n string currentValue = parts[parts.Length - 1].Trim().ToLowerInvariant();\n expectedValue = expectedValue.ToLowerInvariant();\n\n _logService.LogInformation(\n $\"Found bcdedit setting {settingName} with value {currentValue}, expected {expectedValue}\"\n );\n return currentValue == expectedValue;\n }\n }\n }\n\n // If the setting doesn't exist or we couldn't parse the value, it's not in the enabled state\n return false;\n }\n // For settings that should be set to a different value when disabled\n else if (setting.DisabledCommand.Contains(\"/set\"))\n {\n string disabledValue = ExtractBcdeditSettingValue(setting.DisabledCommand);\n\n // Find the line containing the setting\n if (settingExists)\n {\n var lines = output.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n var settingLine = lines.FirstOrDefault(l =>\n l.Contains(settingName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (settingLine != null)\n {\n // Extract the current value\n var parts = settingLine.Split(\n new[] { ' ' },\n StringSplitOptions.RemoveEmptyEntries\n );\n if (parts.Length >= 2)\n {\n string currentValue = parts[parts.Length - 1].Trim().ToLowerInvariant();\n expectedValue = expectedValue.ToLowerInvariant();\n disabledValue = disabledValue.ToLowerInvariant();\n\n _logService.LogInformation(\n $\"Found bcdedit setting {settingName} with value {currentValue}, expected {expectedValue} for enabled state\"\n );\n return currentValue == expectedValue && currentValue != disabledValue;\n }\n }\n }\n\n return false;\n }\n\n // Default case\n return false;\n }\n\n /// \n /// Extracts the setting name from a bcdedit command.\n /// \n /// The bcdedit command.\n /// The setting name.\n private string ExtractBcdeditSettingName(string command)\n {\n // Handle /set command\n if (command.Contains(\"/set \"))\n {\n var parts = command.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (parts.Length >= 3)\n {\n return parts[2]; // The setting name is the third part in \"bcdedit /set settingname value\"\n }\n }\n // Handle /deletevalue command\n else if (command.Contains(\"/deletevalue \"))\n {\n var parts = command.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (parts.Length >= 3)\n {\n return parts[2]; // The setting name is the third part in \"bcdedit /deletevalue settingname\"\n }\n }\n\n return string.Empty;\n }\n\n /// \n /// Extracts the setting value from a bcdedit command.\n /// \n /// The bcdedit command.\n /// The setting value.\n private string ExtractBcdeditSettingValue(string command)\n {\n // Only handle /set command as /deletevalue doesn't have a value\n if (command.Contains(\"/set \"))\n {\n var parts = command.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (parts.Length >= 4)\n {\n return parts[3]; // The value is the fourth part in \"bcdedit /set settingname value\"\n }\n }\n\n return string.Empty;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/DonationDialog.xaml.cs", "using System;\nusing System.Threading.Tasks;\nusing System.Windows;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Donation dialog that extends CustomDialog with a \"Don't show this again\" checkbox\n /// \n public partial class DonationDialog : Window\n {\n // Default text content for the donation dialog\n private static readonly string DefaultTitle = \"Support Winhance\";\n private static readonly string DefaultSupportMessage = \"Your support helps keep this project going!\";\n private static readonly string DefaultFooterText = \"Click 'Yes' to show your support!\";\n\n public bool DontShowAgain => DontShowAgainCheckBox.IsChecked ?? false;\n\n public DonationDialog()\n {\n InitializeComponent();\n DataContext = this;\n }\n\n private void PrimaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = true;\n Close();\n }\n\n private void SecondaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = false;\n Close();\n }\n \n private void TertiaryButton_Click(object sender, RoutedEventArgs e)\n {\n // Explicitly set DialogResult to null for Cancel\n DialogResult = null;\n Close();\n }\n\n /// \n /// Creates and shows a donation dialog with the specified parameters.\n /// This method ensures the dialog is properly modal and blocks the main window.\n /// \n /// The dialog title (optional - uses default if null)\n /// The support message (optional - uses default if null)\n /// The footer text (optional - uses default if null)\n /// The dialog instance with DialogResult set\n public static async Task ShowDonationDialogAsync(string title = null, string supportMessage = null, string footerText = null)\n {\n try\n {\n var dialog = new DonationDialog\n {\n Title = title ?? DefaultTitle,\n WindowStartupLocation = WindowStartupLocation.CenterOwner,\n ShowInTaskbar = false,\n ResizeMode = ResizeMode.NoResize,\n WindowStyle = WindowStyle.None,\n AllowsTransparency = true\n };\n\n // Set the support message and footer text\n dialog.SupportMessageText.Text = supportMessage ?? DefaultSupportMessage;\n dialog.FooterText.Text = footerText ?? DefaultFooterText;\n \n // Set button content\n dialog.PrimaryButton.Content = \"Yes\";\n dialog.SecondaryButton.Content = \"No\";\n\n // Set the owner to the main window to ensure it appears on top\n if (Application.Current.MainWindow != null && Application.Current.MainWindow != dialog)\n {\n dialog.Owner = Application.Current.MainWindow;\n dialog.Topmost = true; // Ensure it stays on top\n }\n else\n {\n // Try to find the main window another way\n foreach (Window window in Application.Current.Windows)\n {\n if (window != dialog && window.IsVisible)\n {\n dialog.Owner = window;\n dialog.Topmost = true;\n break;\n }\n }\n }\n\n // Make the dialog visible and focused\n dialog.Visibility = Visibility.Visible;\n dialog.Activate();\n dialog.Focus();\n \n // Show the dialog and wait for it to complete\n dialog.ShowDialog();\n \n // Return the dialog\n return dialog;\n }\n catch (Exception ex)\n {\n // Show error message\n MessageBox.Show($\"Error showing donation dialog: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n \n // Create a dummy dialog with error result\n var errorDialog = new DonationDialog();\n errorDialog.DialogResult = false;\n return errorDialog;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Security.AccessControl;\nusing System.Security.Principal;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Provides access to the Windows registry.\n /// This is the main file for the RegistryService, which is split into multiple partial files:\n /// - RegistryServiceCore.cs - Core functionality and constructor\n /// - RegistryServiceKeyOperations.cs - Key creation, deletion, and navigation\n /// - RegistryServiceValueOperations.cs - Value reading and writing\n /// - RegistryServiceStatusMethods.cs - Status checking methods\n /// - RegistryServiceEnsureKey.cs - Key creation with security settings\n /// - RegistryServicePowerShell.cs - PowerShell fallback methods\n /// - RegistryServiceTestMethods.cs - Testing methods\n /// - RegistryServiceCompletion.cs - Helper methods\n /// - RegistryServiceUtilityOperations.cs - Additional utility operations (export, backup, restore)\n /// \n [SupportedOSPlatform(\"windows\")]\n public partial class RegistryService : IRegistryService\n {\n // Cache for registry key existence to avoid repeated checks\n private readonly Dictionary _keyExistsCache = new Dictionary();\n\n // Cache for registry value existence to avoid repeated checks\n private readonly Dictionary _valueExistsCache =\n new Dictionary();\n\n // Cache for registry values to avoid repeated reads\n private readonly Dictionary _valueCache =\n new Dictionary();\n\n /// \n /// Clears all registry caches to ensure fresh reads\n /// \n public void ClearRegistryCaches()\n {\n lock (_keyExistsCache)\n {\n _keyExistsCache.Clear();\n }\n\n lock (_valueExistsCache)\n {\n _valueExistsCache.Clear();\n }\n\n lock (_valueCache)\n {\n _valueCache.Clear();\n }\n\n _logService.Log(LogLevel.Info, \"Registry caches cleared\");\n }\n\n /// \n /// Applies a registry setting.\n /// \n /// The registry setting to apply.\n /// Whether to enable or disable the setting.\n /// True if the operation succeeded; otherwise, false.\n public async Task ApplySettingAsync(RegistrySetting setting, bool isEnabled)\n {\n if (setting == null)\n return false;\n\n try\n {\n string keyPath = $\"{setting.Hive}\\\\{setting.SubKey}\";\n object? valueToSet = null;\n\n _logService.Log(\n LogLevel.Info,\n $\"Applying registry setting: {setting.Name}, IsEnabled={isEnabled}, Path={keyPath}\"\n );\n\n if (isEnabled)\n {\n // When enabling, use EnabledValue if available, otherwise fall back to RecommendedValue\n valueToSet = setting.EnabledValue ?? setting.RecommendedValue;\n _logService.Log(\n LogLevel.Debug,\n $\"Setting {setting.Name} - EnabledValue: {setting.EnabledValue}, RecommendedValue: {setting.RecommendedValue}, Using: {valueToSet}\"\n );\n }\n else\n {\n // When disabling, use DisabledValue if available, otherwise fall back to DefaultValue\n valueToSet = setting.DisabledValue ?? setting.DefaultValue;\n _logService.Log(\n LogLevel.Debug,\n $\"Setting {setting.Name} - DisabledValue: {setting.DisabledValue}, DefaultValue: {setting.DefaultValue}, Using: {valueToSet}\"\n );\n }\n\n if (valueToSet == null)\n {\n // If the value to set is null, delete the value\n _logService.Log(\n LogLevel.Warning,\n $\"Value to set for {setting.Name} is null, deleting the value\"\n );\n return await DeleteValue(setting.Hive, setting.SubKey, setting.Name);\n }\n else\n {\n // Otherwise, set the value\n _logService.Log(\n LogLevel.Info,\n $\"Setting {keyPath}\\\\{setting.Name} to {valueToSet} ({setting.ValueType})\"\n );\n \n // Ensure the key exists before setting the value\n bool keyCreated = CreateKeyIfNotExists(keyPath);\n if (!keyCreated)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to create registry key: {keyPath}, attempting PowerShell fallback\"\n );\n \n // Try to use PowerShell to create the key if direct creation failed\n if (keyPath.Contains(\"Policies\", StringComparison.OrdinalIgnoreCase))\n {\n _logService.Log(\n LogLevel.Info,\n $\"Attempting to create policy registry key using PowerShell: {keyPath}\"\n );\n \n // Use SetValueUsingPowerShell which will create the key as part of setting the value\n return SetValueUsingPowerShell(keyPath, setting.Name, valueToSet, setting.ValueType);\n }\n \n return false;\n }\n \n // Verify the key exists before proceeding\n if (!KeyExists(keyPath))\n {\n _logService.Log(\n LogLevel.Error,\n $\"Registry key still does not exist after creation attempt: {keyPath}\"\n );\n return false;\n }\n \n // Try to set the value\n bool result = SetValue(keyPath, setting.Name, valueToSet, setting.ValueType);\n \n // Verify the value was set correctly\n if (result)\n {\n object? verifyValue = GetValue(keyPath, setting.Name);\n if (verifyValue == null)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Value verification failed - value is null after setting: {keyPath}\\\\{setting.Name}\"\n );\n \n // Try one more time with PowerShell\n return SetValueUsingPowerShell(keyPath, setting.Name, valueToSet, setting.ValueType);\n }\n \n _logService.Log(\n LogLevel.Success,\n $\"Successfully set and verified registry value: {keyPath}\\\\{setting.Name}\"\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to set {keyPath}\\\\{setting.Name} to {valueToSet}\"\n );\n }\n return result;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Error,\n $\"Error applying registry setting {setting.Name}: {ex.Message}\"\n );\n return false;\n }\n }\n\n /// \n /// Applies linked registry settings.\n /// \n /// The linked registry settings to apply.\n /// Whether to enable or disable the settings.\n /// True if the operation succeeded; otherwise, false.\n public async Task ApplyLinkedSettingsAsync(\n LinkedRegistrySettings linkedSettings,\n bool isEnabled\n )\n {\n if (linkedSettings == null || linkedSettings.Settings.Count == 0)\n return false;\n\n try\n {\n _logService.Log(\n LogLevel.Info,\n $\"Applying {linkedSettings.Settings.Count} linked registry settings, IsEnabled={isEnabled}\"\n );\n\n bool allSuccess = true;\n int settingCount = 0;\n int totalSettings = linkedSettings.Settings.Count;\n\n foreach (var setting in linkedSettings.Settings)\n {\n settingCount++;\n _logService.Log(\n LogLevel.Debug,\n $\"Processing linked setting {settingCount}/{totalSettings}: {setting.Name}\"\n );\n\n // Ensure the registry key path exists before applying the setting\n string keyPath = $\"{setting.Hive}\\\\{setting.SubKey}\";\n bool keyExists = KeyExists(keyPath);\n \n if (!keyExists)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Registry key does not exist: {keyPath}, creating it\"\n );\n \n // Try to create the key\n bool keyCreated = CreateKeyIfNotExists(keyPath);\n \n if (!keyCreated)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to create registry key: {keyPath} using standard method, trying PowerShell\"\n );\n \n // If we couldn't create the key, try using PowerShell to create it\n // This will be handled in the ApplySettingAsync method\n }\n }\n\n bool success = await ApplySettingAsync(setting, isEnabled);\n\n if (!success)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to apply linked setting: {setting.Name}\"\n );\n\n // If the logic is All, we need all settings to succeed\n if (linkedSettings.Logic == LinkedSettingsLogic.All)\n {\n allSuccess = false;\n }\n }\n else\n {\n _logService.Log(\n LogLevel.Success,\n $\"Successfully applied linked setting {settingCount}/{totalSettings}: {setting.Name}\"\n );\n }\n }\n\n _logService.Log(\n allSuccess ? LogLevel.Success : LogLevel.Warning,\n $\"Completed applying linked settings with result: {(allSuccess ? \"Success\" : \"Some settings failed\")}\"\n );\n\n return allSuccess;\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Error,\n $\"Error applying linked registry settings: {ex.Message}\"\n );\n return false;\n }\n }\n\n /// \n /// Exports a registry key to a string.\n /// \n /// The registry key path.\n /// The exported registry key as a string, or null if the operation failed.\n public string? ExportKey(string keyPath)\n {\n if (!CheckWindowsPlatform())\n return null;\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Exporting registry key: {keyPath}\");\n\n // Create a temporary file to export the registry key to\n string tempFile = Path.GetTempFileName();\n\n // Export the registry key using reg.exe\n var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"export \\\"{keyPath}\\\" \\\"{tempFile}\\\" /y\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n },\n };\n\n process.Start();\n process.WaitForExit();\n\n if (process.ExitCode != 0)\n {\n string error = process.StandardError.ReadToEnd();\n _logService.Log(\n LogLevel.Error,\n $\"Error exporting registry key {keyPath}: {error}\"\n );\n return null;\n }\n\n // Read the exported registry key from the temporary file\n string exportedKey = File.ReadAllText(tempFile);\n\n // Delete the temporary file\n File.Delete(tempFile);\n\n return exportedKey;\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Error,\n $\"Error exporting registry key {keyPath}: {ex.Message}\"\n );\n return null;\n }\n }\n\n /// \n /// Imports a registry key from a string.\n /// \n /// The registry content to import.\n /// True if the operation succeeded; otherwise, false.\n public bool ImportKey(string registryContent)\n {\n if (!CheckWindowsPlatform())\n return false;\n\n try\n {\n _logService.Log(LogLevel.Info, \"Importing registry key\");\n\n // Create a temporary file to import the registry key from\n string tempFile = Path.GetTempFileName();\n\n // Write the registry content to the temporary file\n File.WriteAllText(tempFile, registryContent);\n\n // Import the registry key using reg.exe\n var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"import \\\"{tempFile}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n },\n };\n\n process.Start();\n process.WaitForExit();\n\n // Delete the temporary file\n File.Delete(tempFile);\n\n if (process.ExitCode != 0)\n {\n string error = process.StandardError.ReadToEnd();\n _logService.Log(LogLevel.Error, $\"Error importing registry key: {error}\");\n return false;\n }\n\n // Clear all caches to ensure fresh reads\n ClearRegistryCaches();\n\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing registry key: {ex.Message}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/PowerShellExecutionService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service that executes PowerShell scripts with progress reporting and cancellation support.\n /// \n public class PowerShellExecutionService : IPowerShellExecutionService, IDisposable\n {\n private readonly ILogService _logService;\n private readonly ISystemServices _systemServices;\n \n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The system services.\n public PowerShellExecutionService(ILogService logService, ISystemServices systemServices)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _systemServices = systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n }\n \n /// \n public async Task ExecuteScriptAsync(\n string script, \n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (string.IsNullOrEmpty(script))\n {\n throw new ArgumentException(\"Script cannot be null or empty.\", nameof(script));\n }\n \n using var powerShell = Utilities.PowerShellFactory.CreateWindowsPowerShell(_logService, _systemServices);\n // No need to set execution policy as it's already done in the factory\n \n powerShell.AddScript(script);\n\n // Set up stream handlers\n // Explicitly type progressAdapter using full namespace\n System.IProgress? progressAdapter = progress != null\n ? new System.Progress(data => MapProgressData(data, progress)) // Also qualify Progress\n : null;\n\n SetupStreamHandlers(powerShell, progressAdapter);\n\n // Execute PowerShell with cancellation support\n return await Task.Run(() => {\n try\n {\n cancellationToken.ThrowIfCancellationRequested();\n var invokeResult = powerShell.Invoke();\n var resultText = string.Join(Environment.NewLine, \n invokeResult.Select(item => item.ToString()));\n \n // Check for errors\n if (powerShell.HadErrors)\n {\n foreach (var error in powerShell.Streams.Error)\n {\n _logService.LogError($\"PowerShell error: {error.Exception?.Message ?? error.ToString()}\", error.Exception);\n \n // This call seems to be the source of CS1061, despite Progress having Report.\n // Let's ensure the object creation is correct.\n progressAdapter?.Report(new PowerShellProgressData\n {\n Message = error.Exception?.Message ?? error.ToString(),\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Error\n });\n }\n }\n \n return resultText;\n }\n catch (Exception ex) when (cancellationToken.IsCancellationRequested)\n {\n _logService.LogWarning($\"PowerShell execution cancelled: {ex.Message}\");\n throw new OperationCanceledException(\"PowerShell execution was cancelled.\", ex, cancellationToken);\n }\n }, cancellationToken);\n }\n \n /// \n public async Task ExecuteScriptFileAsync(\n string scriptPath, \n string arguments = \"\",\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (string.IsNullOrEmpty(scriptPath))\n {\n throw new ArgumentException(\"Script path cannot be null or empty.\", nameof(scriptPath));\n }\n \n if (!File.Exists(scriptPath))\n {\n throw new FileNotFoundException($\"PowerShell script file not found: {scriptPath}\");\n }\n \n string script = await File.ReadAllTextAsync(scriptPath, cancellationToken);\n \n // If we have arguments, add them as parameters\n if (!string.IsNullOrEmpty(arguments))\n {\n script = $\"{script} {arguments}\";\n }\n \n return await ExecuteScriptAsync(script, progress, cancellationToken);\n }\n \n private void SetupStreamHandlers(PowerShell powerShell, IProgress? progress)\n {\n if (progress == null) return;\n \n // Handle progress records\n powerShell.Streams.Progress.DataAdded += (sender, e) => {\n var progressRecord = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n PercentComplete = progressRecord.PercentComplete >= 0 ? progressRecord.PercentComplete : null,\n Activity = progressRecord.Activity,\n StatusDescription = progressRecord.StatusDescription,\n CurrentOperation = progressRecord.CurrentOperation,\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Progress\n });\n\n _logService?.LogInformation($\"PowerShell Progress: {progressRecord.Activity} - {progressRecord.StatusDescription} ({progressRecord.PercentComplete}%)\");\n };\n\n // Handle information stream\n powerShell.Streams.Information.DataAdded += (sender, e) => {\n var info = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n Message = info.MessageData.ToString(),\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Information\n });\n\n _logService?.LogInformation($\"PowerShell Info: {info.MessageData}\");\n };\n\n // Handle verbose stream\n powerShell.Streams.Verbose.DataAdded += (sender, e) => {\n var verbose = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n Message = verbose.Message,\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Verbose\n });\n\n _logService?.Log(LogLevel.Debug, $\"PowerShell Verbose: {verbose.Message}\");\n };\n\n // Handle warning stream\n powerShell.Streams.Warning.DataAdded += (sender, e) => {\n var warning = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n Message = warning.Message,\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Warning\n });\n\n _logService?.LogWarning($\"PowerShell Warning: {warning.Message}\");\n };\n\n // Handle error stream\n powerShell.Streams.Error.DataAdded += (sender, e) => {\n var error = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n Message = error.Exception?.Message ?? error.ToString(),\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Error\n });\n\n _logService?.Log(LogLevel.Error, $\"PowerShell Error: {error.Exception?.Message ?? error.ToString()}\");\n };\n\n // Handle debug stream\n powerShell.Streams.Debug.DataAdded += (sender, e) => {\n var debug = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n Message = debug.Message,\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Debug\n });\n\n _logService?.Log(LogLevel.Debug, $\"PowerShell Debug: {debug.Message}\");\n };\n }\n \n private void MapProgressData(PowerShellProgressData source, IProgress target)\n {\n var detail = new TaskProgressDetail();\n \n // Map PowerShell progress data to task progress detail\n if (source.PercentComplete.HasValue)\n {\n detail.Progress = source.PercentComplete.Value;\n }\n \n if (!string.IsNullOrEmpty(source.Activity))\n {\n detail.StatusText = source.Activity;\n if (!string.IsNullOrEmpty(source.StatusDescription))\n {\n detail.StatusText += $\": {source.StatusDescription}\";\n }\n }\n \n detail.DetailedMessage = source.Message ?? source.CurrentOperation;\n // Map stream type to log level\n switch (source.StreamType)\n {\n case Winhance.Core.Features.Common.Enums.PowerShellStreamType.Error:\n detail.LogLevel = LogLevel.Error;\n break;\n case Winhance.Core.Features.Common.Enums.PowerShellStreamType.Warning:\n detail.LogLevel = LogLevel.Warning;\n break;\n case Winhance.Core.Features.Common.Enums.PowerShellStreamType.Verbose:\n case Winhance.Core.Features.Common.Enums.PowerShellStreamType.Debug:\n detail.LogLevel = LogLevel.Debug;\n break;\n default: // Includes Information and Progress\n detail.LogLevel = LogLevel.Info;\n break;\n }\n \n target.Report(detail);\n }\n \n // SetExecutionPolicy is now handled by PowerShellFactory\n \n /// \n /// Disposes resources used by the service.\n /// \n public void Dispose()\n {\n // Cleanup resources if needed\n GC.SuppressFinalize(this);\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/ViewModelLocator.cs", "using System;\nusing System.Linq;\nusing System.Windows;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Interfaces;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for locating view models in the application.\n /// \n public class ViewModelLocator : IViewModelLocator\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public ViewModelLocator(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Finds a view model of the specified type in the application.\n /// \n /// The type of view model to find.\n /// The view model if found, otherwise null.\n public T? FindViewModel() where T : class\n {\n try\n {\n var app = Application.Current;\n if (app == null) return null;\n\n // Try to find the view model in the main window's DataContext hierarchy\n var mainWindow = app.MainWindow;\n if (mainWindow != null)\n {\n var mainViewModel = FindViewModelInWindow(mainWindow);\n if (mainViewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"Found {typeof(T).Name} in main window's DataContext\");\n return mainViewModel;\n }\n }\n\n // If we can't find it in the main window, try to find it in any open window\n foreach (Window window in app.Windows)\n {\n var viewModel = FindViewModelInWindow(window);\n if (viewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"Found {typeof(T).Name} in window: {window.Title}\");\n return viewModel;\n }\n }\n\n _logService.Log(LogLevel.Warning, $\"Could not find {typeof(T).Name} in any window\");\n return null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error finding view model: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Finds a view model of the specified type in the specified window.\n /// \n /// The type of view model to find.\n /// The window to search in.\n /// The view model if found, otherwise null.\n public T? FindViewModelInWindow(Window window) where T : class\n {\n try\n {\n // Check if the window's DataContext is or contains the view model\n if (window.DataContext is T vm)\n {\n return vm;\n }\n\n // Check if the window's DataContext has a property that is the view model\n if (window.DataContext != null)\n {\n var type = window.DataContext.GetType();\n var properties = type.GetProperties();\n\n foreach (var property in properties)\n {\n if (property.PropertyType == typeof(T))\n {\n return property.GetValue(window.DataContext) as T;\n }\n }\n }\n\n // If not found in the DataContext, search the visual tree\n return FindViewModelInVisualTree(window);\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error finding view model in window: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Finds a view model of the specified type in the visual tree starting from the specified element.\n /// \n /// The type of view model to find.\n /// The starting element.\n /// The view model if found, otherwise null.\n public T? FindViewModelInVisualTree(DependencyObject element) where T : class\n {\n try\n {\n // Check if the element's DataContext is the view model\n if (element is FrameworkElement fe && fe.DataContext is T vm)\n {\n return vm;\n }\n\n // Recursively check children\n int childCount = System.Windows.Media.VisualTreeHelper.GetChildrenCount(element);\n for (int i = 0; i < childCount; i++)\n {\n var child = System.Windows.Media.VisualTreeHelper.GetChild(element, i);\n var result = FindViewModelInVisualTree(child);\n if (result != null)\n {\n return result;\n }\n }\n\n return null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error finding view model in visual tree: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Finds a view model by its name.\n /// \n /// The name of the view model to find.\n /// The view model if found, otherwise null.\n public object? FindViewModelByName(string viewModelName)\n {\n try\n {\n var app = Application.Current;\n if (app == null) return null;\n\n // Try to find the view model in any window's DataContext\n foreach (Window window in app.Windows)\n {\n if (window.DataContext != null)\n {\n var type = window.DataContext.GetType();\n if (type.Name == viewModelName || type.Name == $\"{viewModelName}ViewModel\")\n {\n return window.DataContext;\n }\n\n // Check if the DataContext has a property that is the view model\n var properties = type.GetProperties();\n foreach (var property in properties)\n {\n if (property.Name == viewModelName || property.PropertyType.Name == viewModelName ||\n property.Name == $\"{viewModelName}ViewModel\" || property.PropertyType.Name == $\"{viewModelName}ViewModel\")\n {\n return property.GetValue(window.DataContext);\n }\n }\n }\n }\n\n return null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error finding view model by name: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Gets a property from a view model.\n /// \n /// The type of the property to get.\n /// The view model to get the property from.\n /// The name of the property to get.\n /// The property value if found, otherwise null.\n public T? GetPropertyFromViewModel(object viewModel, string propertyName) where T : class\n {\n try\n {\n var type = viewModel.GetType();\n var property = type.GetProperty(propertyName);\n if (property != null)\n {\n return property.GetValue(viewModel) as T;\n }\n\n return null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting property from view model: {ex.Message}\");\n return null;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/PackageManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Manages packages and applications on the system.\n /// Acts as a facade for more specialized services.\n /// \n public class PackageManager : IPackageManager\n {\n private readonly IAppRemovalService _appRemovalService;\n private readonly AppRemovalServiceAdapter _appRemovalServiceAdapter;\n private readonly ICapabilityRemovalService _capabilityRemovalService;\n private readonly IFeatureRemovalService _featureRemovalService;\n\n /// \n public ILogService LogService { get; }\n\n /// \n public IAppService AppDiscoveryService { get; }\n\n /// \n /// \n /// This property is maintained for backward compatibility.\n /// It returns an adapter that converts IAppRemovalService to IInstallationService<AppInfo>.\n /// New code should use dependency injection to get IAppRemovalService directly.\n /// \n public IInstallationService AppRemovalService => _appRemovalServiceAdapter;\n\n /// \n public ISpecialAppHandlerService SpecialAppHandlerService { get; }\n\n /// \n public IScriptGenerationService ScriptGenerationService { get; }\n\n /// \n public ISystemServices SystemServices { get; }\n\n /// \n public INotificationService NotificationService { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The app discovery service.\n /// The installation service.\n /// The special app handler service.\n /// The script generation service.\n public PackageManager(\n ILogService logService,\n IAppService appDiscoveryService,\n IAppRemovalService appRemovalService,\n ICapabilityRemovalService capabilityRemovalService,\n IFeatureRemovalService featureRemovalService,\n ISpecialAppHandlerService specialAppHandlerService,\n IScriptGenerationService scriptGenerationService,\n ISystemServices systemServices,\n INotificationService notificationService\n )\n {\n LogService = logService;\n AppDiscoveryService = appDiscoveryService;\n _appRemovalService = appRemovalService;\n _appRemovalServiceAdapter = new AppRemovalServiceAdapter(appRemovalService);\n _capabilityRemovalService = capabilityRemovalService;\n _featureRemovalService = featureRemovalService;\n SpecialAppHandlerService = specialAppHandlerService;\n ScriptGenerationService = scriptGenerationService;\n SystemServices = systemServices;\n NotificationService = notificationService;\n }\n\n /// \n public async Task> GetInstallableAppsAsync()\n {\n return await AppDiscoveryService.GetInstallableAppsAsync();\n }\n\n /// \n public async Task> GetStandardAppsAsync()\n {\n return await AppDiscoveryService.GetStandardAppsAsync();\n }\n\n /// \n public async Task> GetCapabilitiesAsync()\n {\n return await AppDiscoveryService.GetCapabilitiesAsync();\n }\n\n /// \n public async Task> GetOptionalFeaturesAsync()\n {\n return await AppDiscoveryService.GetOptionalFeaturesAsync();\n }\n\n /// \n public async Task RemoveAppAsync(string packageName, bool isCapability)\n {\n // Get all standard apps to check the app type\n var allRemovableApps = (await AppDiscoveryService.GetStandardAppsAsync()).ToList();\n var appInfo = allRemovableApps.FirstOrDefault(a => a.PackageName == packageName);\n\n // If not found in standard apps and isCapability is true, create a CapabilityInfo directly\n if (appInfo == null && isCapability)\n {\n LogService.LogInformation(\n $\"App not found in standard apps but isCapability is true. Treating {packageName} as a capability.\"\n );\n return await _capabilityRemovalService.RemoveCapabilityAsync(\n new CapabilityInfo { Name = packageName, PackageName = packageName }\n );\n }\n else if (appInfo == null)\n {\n LogService.LogWarning($\"App not found: {packageName}\");\n return false;\n }\n\n // First check if this is a special app that requires special handling\n if (appInfo.RequiresSpecialHandling && !string.IsNullOrEmpty(appInfo.SpecialHandlerType))\n {\n LogService.LogInformation(\n $\"Using special handler for app: {packageName}, handler type: {appInfo.SpecialHandlerType}\"\n );\n \n bool success = false;\n switch (appInfo.SpecialHandlerType)\n {\n case \"Edge\":\n success = await SpecialAppHandlerService.RemoveEdgeAsync();\n break;\n case \"OneDrive\":\n success = await SpecialAppHandlerService.RemoveOneDriveAsync();\n break;\n case \"OneNote\":\n success = await SpecialAppHandlerService.RemoveOneNoteAsync();\n break;\n default:\n success = await SpecialAppHandlerService.RemoveSpecialAppAsync(\n appInfo.SpecialHandlerType\n );\n break;\n }\n \n if (success)\n {\n LogService.LogSuccess($\"Successfully removed special app: {packageName}\");\n }\n else\n {\n LogService.LogError($\"Failed to remove special app: {packageName}\");\n }\n \n return success; // Exit early, don't continue with standard removal process\n }\n\n // If not a special app, proceed with normal removal based on app type\n bool result = false;\n switch (appInfo.Type)\n {\n case AppType.OptionalFeature:\n result = await _featureRemovalService.RemoveFeatureAsync(\n new FeatureInfo { Name = packageName }\n );\n break;\n case AppType.Capability:\n result = await _capabilityRemovalService.RemoveCapabilityAsync(\n new CapabilityInfo { Name = packageName, PackageName = packageName }\n );\n break;\n \n case AppType.StandardApp:\n default:\n var appResult = await _appRemovalService.RemoveAppAsync(appInfo);\n result = appResult.Success && appResult.Result;\n break;\n }\n\n // Only create and register BloatRemoval script for non-special apps\n if (!appInfo.RequiresSpecialHandling)\n {\n // Prepare data for the correct CreateBatchRemovalScriptAsync overload\n var appNamesList = new List { packageName };\n var appsWithRegistry = new Dictionary>();\n\n if (appInfo?.RegistrySettings != null && appInfo.RegistrySettings.Length > 0)\n {\n appsWithRegistry[packageName] = appInfo.RegistrySettings.ToList();\n }\n\n try\n {\n // Call the overload that returns RemovalScript\n var removalScript = await ScriptGenerationService.CreateBatchRemovalScriptAsync(\n appNamesList,\n appsWithRegistry\n );\n\n // Save the RemovalScript object\n await ScriptGenerationService.SaveScriptAsync(removalScript);\n\n // Register the RemovalScript object\n await ScriptGenerationService.RegisterRemovalTaskAsync(removalScript);\n }\n catch (Exception ex)\n {\n LogService.LogError(\n $\"Failed to create or register removal script for {packageName}\",\n ex\n );\n // Don't change result value, as the app removal itself might have succeeded\n }\n }\n \n return result;\n }\n\n /// \n public async Task IsAppInstalledAsync(\n string packageName,\n CancellationToken cancellationToken = default\n )\n {\n var status = await AppDiscoveryService.GetBatchInstallStatusAsync(\n new[] { packageName }\n );\n return status.TryGetValue(packageName, out var isInstalled) && isInstalled;\n }\n\n /// \n public async Task RemoveEdgeAsync()\n {\n return await SpecialAppHandlerService.RemoveEdgeAsync();\n }\n\n /// \n public async Task RemoveOneDriveAsync()\n {\n return await SpecialAppHandlerService.RemoveOneDriveAsync();\n }\n\n /// \n public async Task RemoveOneNoteAsync()\n {\n return await SpecialAppHandlerService.RemoveOneNoteAsync();\n }\n\n /// \n public async Task RemoveSpecialAppAsync(string appHandlerType)\n {\n return await SpecialAppHandlerService.RemoveSpecialAppAsync(appHandlerType);\n }\n\n /// \n public async Task> RemoveAppsInBatchAsync(\n List<(string PackageName, bool IsCapability, string? SpecialHandlerType)> apps\n )\n {\n var results = new List<(string Name, bool Success, string? Error)>();\n var standardApps = new List();\n var capabilities = new List();\n var features = new List();\n var specialHandlers = new Dictionary>();\n\n // Get all standard apps to check for optional features\n var allRemovableApps = (await AppDiscoveryService.GetStandardAppsAsync()).ToList();\n\n // Categorize apps by type\n foreach (var app in apps)\n {\n if (app.SpecialHandlerType != null)\n {\n if (!specialHandlers.ContainsKey(app.SpecialHandlerType))\n {\n specialHandlers[app.SpecialHandlerType] = new List();\n }\n specialHandlers[app.SpecialHandlerType].Add(app.PackageName);\n }\n else\n {\n // Check app type\n var appInfo = allRemovableApps.FirstOrDefault(a =>\n a.PackageName.Equals(app.PackageName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (appInfo != null)\n {\n switch (appInfo.Type)\n {\n case AppType.OptionalFeature:\n features.Add(new FeatureInfo { Name = app.PackageName });\n break;\n case AppType.Capability:\n capabilities.Add(new CapabilityInfo {\n Name = app.PackageName,\n PackageName = app.PackageName\n });\n break;\n case AppType.StandardApp:\n default:\n standardApps.Add(appInfo);\n break;\n }\n }\n else\n {\n // If we couldn't determine the app type from the app info, use the IsCapability flag\n if (app.IsCapability)\n {\n LogService.LogInformation(\n $\"App not found in standard apps but IsCapability is true. Treating {app.PackageName} as a capability.\"\n );\n capabilities.Add(new CapabilityInfo {\n Name = app.PackageName,\n PackageName = app.PackageName,\n });\n }\n else\n {\n standardApps.Add(new AppInfo { PackageName = app.PackageName });\n }\n }\n }\n }\n\n // Process standard apps\n if (standardApps.Any())\n {\n foreach (var app in standardApps)\n {\n try\n {\n await _appRemovalService.RemoveAppAsync(app); // Pass AppInfo object\n results.Add((app.PackageName, true, null));\n }\n catch (Exception ex)\n {\n results.Add((app.PackageName, false, ex.Message));\n }\n }\n }\n\n // Process capabilities\n if (capabilities.Any())\n {\n foreach (var capability in capabilities)\n {\n try\n {\n await _capabilityRemovalService.RemoveCapabilityAsync(capability); // Pass CapabilityInfo object\n results.Add((capability.Name, true, null));\n }\n catch (Exception ex)\n {\n results.Add((capability.Name, false, ex.Message));\n }\n }\n }\n\n // Process optional features\n if (features.Any())\n {\n foreach (var feature in features)\n {\n try\n {\n await _featureRemovalService.RemoveFeatureAsync(feature); // Pass FeatureInfo object\n results.Add((feature.Name, true, null));\n }\n catch (Exception ex)\n {\n results.Add((feature.Name, false, ex.Message));\n }\n }\n }\n\n // Process special handlers\n foreach (var handler in specialHandlers)\n {\n switch (handler.Key)\n {\n case \"Edge\":\n foreach (var app in handler.Value)\n {\n var success = await SpecialAppHandlerService.RemoveEdgeAsync();\n results.Add((app, success, success ? null : \"Failed to remove Edge\"));\n }\n break;\n case \"OneDrive\":\n foreach (var app in handler.Value)\n {\n var success = await SpecialAppHandlerService.RemoveOneDriveAsync();\n results.Add(\n (app, success, success ? null : \"Failed to remove OneDrive\")\n );\n }\n break;\n case \"OneNote\":\n foreach (var app in handler.Value)\n {\n var success = await SpecialAppHandlerService.RemoveOneNoteAsync();\n results.Add(\n (app, success, success ? null : \"Failed to remove OneNote\")\n );\n }\n break;\n default:\n foreach (var app in handler.Value)\n {\n var success = await SpecialAppHandlerService.RemoveSpecialAppAsync(\n handler.Key\n );\n results.Add(\n (app, success, success ? null : $\"Failed to remove {handler.Key}\")\n );\n }\n break;\n }\n }\n\n // Create batch removal script for successful removals (excluding special apps)\n try\n {\n var successfulApps = results.Where(r => r.Success).Select(r => r.Name).ToList();\n \n // Filter out special apps from the successful apps list\n var nonSpecialSuccessfulAppInfos = allRemovableApps\n .Where(a => successfulApps.Contains(a.PackageName)\n && (!a.RequiresSpecialHandling || string.IsNullOrEmpty(a.SpecialHandlerType))\n )\n .ToList();\n\n LogService.LogInformation(\n $\"Creating batch removal script for {nonSpecialSuccessfulAppInfos.Count} non-special apps\"\n );\n \n foreach (var app in nonSpecialSuccessfulAppInfos)\n {\n try\n {\n await ScriptGenerationService.UpdateBloatRemovalScriptForInstalledAppAsync(app);\n }\n catch (Exception ex)\n {\n LogService.LogWarning(\n $\"Failed to update removal script for {app.PackageName}: {ex.Message}\"\n );\n }\n }\n }\n catch (Exception ex)\n {\n LogService.LogError(\"Failed to create batch removal script\", ex);\n }\n\n return results;\n }\n\n /// \n public async Task RegisterRemovalTaskAsync(RemovalScript script)\n {\n // Call the correct overload that takes a RemovalScript object\n await ScriptGenerationService.RegisterRemovalTaskAsync(script);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppRemovalService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service for removing standard applications from the system.\n/// \npublic class AppRemovalService : IAppRemovalService\n{\n private readonly ILogService _logService;\n private readonly ISpecialAppHandlerService _specialAppHandlerService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IScriptTemplateProvider _scriptTemplateProvider;\n private readonly ISystemServices _systemServices;\n private readonly IRegistryService _registryService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The special app handler service.\n /// The app discovery service.\n /// The script template provider.\n /// The system services.\n public AppRemovalService(\n ILogService logService,\n ISpecialAppHandlerService specialAppHandlerService,\n IAppDiscoveryService appDiscoveryService,\n IScriptTemplateProvider scriptTemplateProvider,\n ISystemServices systemServices,\n IRegistryService registryService)\n {\n _logService = logService;\n _specialAppHandlerService = specialAppHandlerService;\n _appDiscoveryService = appDiscoveryService;\n _scriptTemplateProvider = scriptTemplateProvider;\n _systemServices = systemServices;\n _registryService = registryService;\n }\n\n /// \n public async Task> RemoveAppAsync(\n AppInfo appInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (appInfo == null)\n {\n throw new ArgumentNullException(nameof(appInfo));\n }\n // Call the other overload and return its result\n return await RemoveAppAsync(appInfo.PackageName, progress, cancellationToken);\n }\n\n /// \n /// Removes an application by package name.\n /// \n /// The package name of the application to remove.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n public async Task> RemoveAppAsync(\n string packageName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n try\n {\n _logService.LogInformation($\"Removing app: {packageName}\");\n \n // Get all standard apps to find the app definition\n var allRemovableApps = (await _appDiscoveryService.GetStandardAppsAsync()).ToList();\n \n // Find the app definition that matches the current app\n var appDefinition = allRemovableApps.FirstOrDefault(a =>\n a.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase));\n \n // Get subpackages if any\n string[]? subPackages = appDefinition?.SubPackages;\n if (subPackages != null && subPackages.Length > 0)\n {\n _logService.LogInformation($\"App {packageName} has {subPackages.Length} subpackages that will also be removed\");\n }\n \n // Handle standard app removal\n using var powerShell = PowerShellFactory.CreateForAppxCommands(_logService, _systemServices);\n // No need to set execution policy as it's already done in the factory\n \n powerShell.AddScript(@\"\n param($packageName, $subPackages)\n try {\n $success = $true\n \n # Remove the main app package\n $packagesToRemove = Get-AppxPackage | Where-Object { $_.Name -eq $packageName }\n \n if ($packagesToRemove -ne $null -and $packagesToRemove.Count -gt 0) {\n $packagesToRemove | ForEach-Object {\n Write-Output \"\"Removing package: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }\n }\n \n # Also remove the provisioned package\n $provPackages = Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq $packageName }\n \n if ($provPackages -ne $null -and $provPackages.Count -gt 0) {\n $provPackages | ForEach-Object {\n Write-Output \"\"Removing provisioned package: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }\n }\n \n # If we have subpackages, remove those too\n if ($subPackages -ne $null) {\n foreach ($subPackage in $subPackages) {\n Write-Output \"\"Processing subpackage: $subPackage\"\"\n \n # Remove the subpackage\n $subPackagesToRemove = Get-AppxPackage | Where-Object { $_.Name -eq $subPackage }\n \n if ($subPackagesToRemove -ne $null -and $subPackagesToRemove.Count -gt 0) {\n $subPackagesToRemove | ForEach-Object {\n Write-Output \"\"Removing subpackage: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }\n }\n \n # Also remove the provisioned subpackage\n $subProvPackages = Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq $subPackage }\n \n if ($subProvPackages -ne $null -and $subProvPackages.Count -gt 0) {\n $subProvPackages | ForEach-Object {\n Write-Output \"\"Removing provisioned subpackage: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }\n }\n }\n }\n \n # Check if the main package is still installed\n $stillInstalled = Get-AppxPackage | Where-Object { $_.Name -eq $packageName }\n $mainPackageRemoved = ($stillInstalled -eq $null -or $stillInstalled.Count -eq 0)\n \n # Check if any subpackages are still installed\n $subPackagesRemoved = $true\n if ($subPackages -ne $null) {\n foreach ($subPackage in $subPackages) {\n $stillInstalledSub = Get-AppxPackage | Where-Object { $_.Name -eq $subPackage }\n if ($stillInstalledSub -ne $null -and $stillInstalledSub.Count -gt 0) {\n $subPackagesRemoved = $false\n Write-Output \"\"Subpackage $subPackage is still installed\"\"\n break\n }\n }\n }\n \n # Return true only if both main package and all subpackages are removed\n return $mainPackageRemoved -and $subPackagesRemoved\n }\n catch {\n Write-Error \"\"Error removing package: $_\"\"\n return $false\n }\n \");\n powerShell.AddParameter(\"packageName\", packageName);\n powerShell.AddParameter(\"subPackages\", subPackages);\n \n var result = await Task.Run(() => powerShell.Invoke());\n var success = result.FirstOrDefault();\n \n if (!success)\n {\n _logService.LogError($\"Failed to remove app: {packageName}\");\n }\n else\n {\n _logService.LogSuccess($\"Successfully removed app: {packageName}\");\n \n // Apply registry settings for this app if it has any\n try\n {\n // If we found the app definition and it has registry settings, apply them\n if (appDefinition?.RegistrySettings != null && appDefinition.RegistrySettings.Length > 0)\n {\n _logService.LogInformation($\"Found {appDefinition.RegistrySettings.Length} registry settings for {packageName}\");\n var registrySettings = appDefinition.RegistrySettings.ToList();\n \n // Apply the registry settings\n var settingsApplied = await ApplyRegistrySettingsAsync(registrySettings);\n if (settingsApplied)\n {\n _logService.LogSuccess($\"Successfully applied registry settings for {packageName}\");\n }\n else\n {\n _logService.LogWarning($\"Some registry settings for {packageName} could not be applied\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error applying registry settings for {packageName}\", ex);\n }\n }\n // Return success status after handling registry settings\n return success\n ? OperationResult.Succeeded(true)\n : OperationResult.Failed($\"Failed to remove app: {packageName}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing app: {packageName}\", ex);\n // Return failure with exception details\n return OperationResult.Failed($\"Error removing app: {packageName}\", ex);\n }\n }\n\n /// \n public Task> GenerateRemovalScriptAsync(AppInfo appInfo)\n {\n if (appInfo == null)\n {\n throw new ArgumentNullException(nameof(appInfo));\n }\n\n try\n {\n // Generate a script for removing the app using the pipeline approach\n string script = $@\"\n# Script to remove {appInfo.Name} ({appInfo.PackageName})\n# Generated by Winhance on {DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\")}\n\ntry {{\n # Remove the main app package\n $packagesToRemove = Get-AppxPackage | Where-Object {{ $_.Name -eq '{appInfo.PackageName}' }}\n \n if ($packagesToRemove -ne $null -and $packagesToRemove.Count -gt 0) {{\n $packagesToRemove | ForEach-Object {{\n Write-Output \"\"Removing package: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }}\n }}\n \n # Also remove the provisioned package\n $provPackages = Get-AppxProvisionedPackage -Online | Where-Object {{ $_.DisplayName -eq '{appInfo.PackageName}' }}\n \n if ($provPackages -ne $null -and $provPackages.Count -gt 0) {{\n $provPackages | ForEach-Object {{\n Write-Output \"\"Removing provisioned package: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }}\n }}\";\n\n // Add subpackage removal if the app has subpackages\n if (appInfo.SubPackages != null && appInfo.SubPackages.Length > 0)\n {\n script += $@\"\n \n # Remove subpackages\";\n\n foreach (var subPackage in appInfo.SubPackages)\n {\n script += $@\"\n Write-Output \"\"Processing subpackage: {subPackage}\"\"\n \n # Remove the subpackage\n $subPackagesToRemove = Get-AppxPackage | Where-Object {{ $_.Name -eq '{subPackage}' }}\n \n if ($subPackagesToRemove -ne $null -and $subPackagesToRemove.Count -gt 0) {{\n $subPackagesToRemove | ForEach-Object {{\n Write-Output \"\"Removing subpackage: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }}\n }}\n \n # Also remove the provisioned subpackage\n $subProvPackages = Get-AppxProvisionedPackage -Online | Where-Object {{ $_.DisplayName -eq '{subPackage}' }}\n \n if ($subProvPackages -ne $null -and $subProvPackages.Count -gt 0) {{\n $subProvPackages | ForEach-Object {{\n Write-Output \"\"Removing provisioned subpackage: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }}\n }}\";\n }\n }\n\n // Close the try-catch block\n script += $@\"\n}} catch {{\n # Error handling without output\n}}\n\";\n return Task.FromResult(OperationResult.Succeeded(script));\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error generating removal script for {appInfo.PackageName}\", ex);\n return Task.FromResult(OperationResult.Failed($\"Error generating removal script: {ex.Message}\", ex));\n }\n }\n\n\n /// \n public async Task> RemoveAppsInBatchAsync(\n List apps)\n {\n if (apps == null)\n {\n throw new ArgumentNullException(nameof(apps));\n }\n\n return await RemoveAppsInBatchAsync(apps.Select(a => a.PackageName).ToList());\n }\n\n /// \n public async Task> RemoveAppsInBatchAsync(\n List packageNames)\n {\n var results = new List<(string Name, bool Success, string? Error)>();\n \n try\n {\n _logService.LogInformation($\"Starting batch removal of {packageNames.Count} apps\");\n \n using var powerShell = PowerShellFactory.CreateForAppxCommands(_logService, _systemServices);\n // No need to set execution policy as it's already done in the factory\n \n // Get all standard apps to find app definitions (do this once for the batch)\n var allApps = (await _appDiscoveryService.GetStandardAppsAsync()).ToList();\n \n foreach (var packageName in packageNames)\n {\n try\n {\n _logService.LogInformation($\"Removing app: {packageName}\");\n \n // Find the app definition that matches the current app\n var appDefinition = allApps.FirstOrDefault(a =>\n a.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase));\n \n // Get subpackages if any\n string[]? subPackages = appDefinition?.SubPackages;\n if (subPackages != null && subPackages.Length > 0)\n {\n _logService.LogInformation($\"App {packageName} has {subPackages.Length} subpackages that will also be removed\");\n }\n \n powerShell.Commands.Clear();\n \n powerShell.AddScript(@\"\n param($packageName, $subPackages)\n try {\n $success = $true\n \n # Remove the main app package\n $packagesToRemove = Get-AppxPackage | Where-Object { $_.Name -eq $packageName }\n \n if ($packagesToRemove -ne $null -and $packagesToRemove.Count -gt 0) {\n $packagesToRemove | ForEach-Object {\n Write-Output \"\"Removing package: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }\n }\n \n # Also remove the provisioned package\n $provPackages = Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq $packageName }\n \n if ($provPackages -ne $null -and $provPackages.Count -gt 0) {\n $provPackages | ForEach-Object {\n Write-Output \"\"Removing provisioned package: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }\n }\n \n # If we have subpackages, remove those too\n if ($subPackages -ne $null) {\n foreach ($subPackage in $subPackages) {\n Write-Output \"\"Processing subpackage: $subPackage\"\"\n \n # Remove the subpackage\n $subPackagesToRemove = Get-AppxPackage | Where-Object { $_.Name -eq $subPackage }\n \n if ($subPackagesToRemove -ne $null -and $subPackagesToRemove.Count -gt 0) {\n $subPackagesToRemove | ForEach-Object {\n Write-Output \"\"Removing subpackage: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }\n }\n \n # Also remove the provisioned subpackage\n $subProvPackages = Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq $subPackage }\n \n if ($subProvPackages -ne $null -and $subProvPackages.Count -gt 0) {\n $subProvPackages | ForEach-Object {\n Write-Output \"\"Removing provisioned subpackage: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }\n }\n }\n }\n \n # Check if the main package is still installed\n $stillInstalled = Get-AppxPackage | Where-Object { $_.Name -eq $packageName }\n $mainPackageRemoved = ($stillInstalled -eq $null -or $stillInstalled.Count -eq 0)\n \n # Check if any subpackages are still installed\n $subPackagesRemoved = $true\n if ($subPackages -ne $null) {\n foreach ($subPackage in $subPackages) {\n $stillInstalledSub = Get-AppxPackage | Where-Object { $_.Name -eq $subPackage }\n if ($stillInstalledSub -ne $null -and $stillInstalledSub.Count -gt 0) {\n $subPackagesRemoved = $false\n Write-Output \"\"Subpackage $subPackage is still installed\"\"\n break\n }\n }\n }\n \n # Return true only if both main package and all subpackages are removed\n return $mainPackageRemoved -and $subPackagesRemoved\n }\n catch {\n Write-Error \"\"Error removing package: $_\"\"\n return $false\n }\n \");\n powerShell.AddParameter(\"packageName\", packageName);\n powerShell.AddParameter(\"subPackages\", subPackages);\n \n var result = await Task.Run(() => powerShell.Invoke());\n var success = result.FirstOrDefault();\n results.Add((packageName, success, success ? null : \"Failed to remove app\"));\n _logService.LogInformation($\"Removal of {packageName} {(success ? \"succeeded\" : \"failed\")}\");\n \n // Apply registry settings for this app if it has any and removal was successful\n if (success)\n {\n try\n {\n // If we found the app definition and it has registry settings, apply them\n if (appDefinition?.RegistrySettings != null && appDefinition.RegistrySettings.Length > 0)\n {\n _logService.LogInformation($\"Found {appDefinition.RegistrySettings.Length} registry settings for {packageName}\");\n var registrySettings = appDefinition.RegistrySettings.ToList();\n \n // Apply the registry settings\n var settingsApplied = await ApplyRegistrySettingsAsync(registrySettings);\n if (settingsApplied)\n {\n _logService.LogSuccess($\"Successfully applied registry settings for {packageName}\");\n }\n else\n {\n _logService.LogWarning($\"Some registry settings for {packageName} could not be applied\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error applying registry settings for {packageName}\", ex);\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing app {packageName}\", ex);\n results.Add((packageName, false, $\"Error: {ex.Message}\"));\n }\n }\n \n return results;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error removing standard apps\", ex);\n return packageNames.Select(p => (p, false, $\"Error: {ex.Message}\")).ToList();\n }\n }\n\n /// \n public async Task ApplyRegistrySettingsAsync(List settings)\n {\n try\n {\n _logService.LogInformation($\"Applying {settings.Count} registry settings\");\n \n bool allSucceeded = true;\n \n foreach (var setting in settings)\n {\n try\n {\n _logService.LogInformation($\"Applying registry setting: {setting.Path}\\\\{setting.Name}\");\n \n bool success;\n if (setting.Value == null)\n {\n // If value is null, delete the registry value\n _logService.LogInformation($\"Deleting registry value: {setting.Path}\\\\{setting.Name}\");\n success = _registryService.DeleteValue(setting.Path, setting.Name);\n }\n else\n {\n // If value is not null, set the registry value\n // First ensure the key exists\n if (!_registryService.KeyExists(setting.Path))\n {\n _registryService.CreateKey(setting.Path);\n }\n \n // Set the registry value\n success = _registryService.SetValue(setting.Path, setting.Name, setting.Value, setting.ValueKind);\n }\n \n if (!success)\n {\n _logService.LogError($\"Failed to apply registry setting: {setting.Path}\\\\{setting.Name}\");\n allSucceeded = false;\n }\n else\n {\n _logService.LogSuccess($\"Successfully applied registry setting: {setting.Path}\\\\{setting.Name}\");\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error applying registry setting: {setting.Path}\\\\{setting.Name}\", ex);\n allSucceeded = false;\n }\n }\n \n return allSucceeded;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error applying registry settings\", ex);\n return false;\n }\n }\n\n // SetExecutionPolicy is now handled by PowerShellFactory\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/Methods/WinGetVerificationMethod.cs", "using System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods\n{\n /// \n /// Verifies software installations by querying WinGet.\n /// \n public class WinGetVerificationMethod : VerificationMethodBase\n {\n private const string WinGetExe = \"winget.exe\";\n private static readonly string[] WinGetPaths = new[]\n {\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n @\"Microsoft\\WindowsApps\"\n ),\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n @\"WindowsApps\\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe\"\n ),\n };\n\n /// \n /// Initializes a new instance of the class.\n /// \n public WinGetVerificationMethod()\n : base(\"WinGet\", priority: 5) // Higher priority as it's the most reliable source\n { }\n\n /// \n protected override async Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken\n )\n {\n // First try with the exact match approach using winget list\n try\n {\n var exactMatchResult = await ExecuteWinGetCommandAsync(\n \"list\",\n $\"--id {packageId} --exact\",\n cancellationToken\n );\n\n // Check if the package is found in the output\n if (\n exactMatchResult.ExitCode == 0\n && !string.IsNullOrWhiteSpace(exactMatchResult.Output)\n && exactMatchResult.Output.Contains(packageId)\n )\n {\n // Extract version if possible\n string version = \"unknown\";\n string source = \"unknown\";\n\n var lines = exactMatchResult.Output.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n if (lines.Length >= 2)\n {\n var parts = lines[1]\n .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (parts.Length > 1)\n version = parts[1];\n if (parts.Length > 2)\n source = parts[2];\n }\n\n return new VerificationResult\n {\n IsVerified = true,\n Message =\n $\"Found in WinGet: {packageId} (Version: {version}, Source: {source})\",\n MethodUsed = \"WinGet\",\n AdditionalInfo = new\n {\n PackageId = packageId,\n Version = version,\n Source = source,\n },\n };\n }\n\n // If exact match failed, try a more flexible approach with just the package ID\n var flexibleResult = await ExecuteWinGetCommandAsync(\n \"list\",\n $\"\\\"{packageId}\\\"\",\n cancellationToken\n );\n\n if (\n flexibleResult.ExitCode == 0\n && !string.IsNullOrWhiteSpace(flexibleResult.Output)\n )\n {\n // Check if any line contains the package ID\n var lines = flexibleResult.Output.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n foreach (var line in lines)\n {\n if (line.IndexOf(packageId, StringComparison.OrdinalIgnoreCase) >= 0)\n {\n // Found a match\n var parts = line.Split(\n new[] { ' ' },\n StringSplitOptions.RemoveEmptyEntries\n );\n string version = parts.Length > 1 ? parts[1] : \"unknown\";\n string source = parts.Length > 2 ? parts[2] : \"unknown\";\n\n return new VerificationResult\n {\n IsVerified = true,\n Message =\n $\"Found in WinGet: {packageId} (Version: {version}, Source: {source})\",\n MethodUsed = \"WinGet\",\n AdditionalInfo = new\n {\n PackageId = packageId,\n Version = version,\n Source = source,\n },\n };\n }\n }\n }\n\n // If we got here, the package wasn't found\n return VerificationResult.Failure($\"Package '{packageId}' not found via WinGet\");\n }\n catch (Exception ex)\n {\n return VerificationResult.Failure($\"Error querying WinGet: {ex.Message}\");\n }\n }\n\n /// \n protected override async Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken\n )\n {\n var result = await VerifyPresenceAsync(packageId, cancellationToken)\n .ConfigureAwait(false);\n if (!result.IsVerified)\n return result;\n\n // Extract the version from the additional info\n var installedVersion = (string)((dynamic)result.AdditionalInfo)?.Version;\n if (string.IsNullOrEmpty(installedVersion))\n return VerificationResult.Failure(\n $\"Could not determine installed version for '{packageId}'\",\n \"WinGet\"\n );\n\n // Simple version comparison (this could be enhanced with proper version comparison logic)\n if (!installedVersion.Equals(version, StringComparison.OrdinalIgnoreCase))\n return VerificationResult.Failure(\n $\"Version mismatch for '{packageId}'. Installed: {installedVersion}, Expected: {version}\",\n \"WinGet\"\n );\n\n return result;\n }\n\n private static async Task<(int ExitCode, string Output)> ExecuteWinGetCommandAsync(\n string command,\n string arguments,\n CancellationToken cancellationToken\n )\n {\n var winGetPath = FindWinGetPath();\n if (string.IsNullOrEmpty(winGetPath))\n throw new InvalidOperationException(\n \"WinGet is not installed or could not be found\"\n );\n\n var startInfo = new ProcessStartInfo\n {\n FileName = winGetPath,\n Arguments = $\"{command} {arguments}\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n StandardOutputEncoding = Encoding.UTF8,\n StandardErrorEncoding = Encoding.UTF8,\n };\n\n using (var process = new Process { StartInfo = startInfo })\n using (var outputWaitHandle = new System.Threading.ManualResetEvent(false))\n using (var errorWaitHandle = new System.Threading.ManualResetEvent(false))\n {\n var output = new StringBuilder();\n var error = new StringBuilder();\n\n process.OutputDataReceived += (sender, e) =>\n {\n if (e.Data != null)\n output.AppendLine(e.Data);\n else\n outputWaitHandle.Set();\n };\n\n process.ErrorDataReceived += (sender, e) =>\n {\n if (e.Data != null)\n error.AppendLine(e.Data);\n else\n errorWaitHandle.Set();\n };\n\n process.Start();\n process.BeginOutputReadLine();\n process.BeginErrorReadLine();\n\n // Wait for the process to exit or the cancellation token to be triggered\n await Task.Run(\n () =>\n {\n while (!process.WaitForExit(100))\n {\n if (cancellationToken.IsCancellationRequested)\n {\n try\n {\n process.Kill();\n }\n catch\n { /* Ignore */\n }\n cancellationToken.ThrowIfCancellationRequested();\n }\n }\n },\n cancellationToken\n )\n .ConfigureAwait(false);\n\n outputWaitHandle.WaitOne(TimeSpan.FromSeconds(5));\n errorWaitHandle.WaitOne(TimeSpan.FromSeconds(5));\n\n // If there was an error, include it in the output\n if (!string.IsNullOrWhiteSpace(error.ToString()))\n output.AppendLine(\"Error: \").Append(error);\n\n return (process.ExitCode, output.ToString().Trim());\n }\n }\n\n private static string FindWinGetPath()\n {\n // Check if winget is in the PATH\n var pathEnv = Environment.GetEnvironmentVariable(\"PATH\") ?? string.Empty;\n if (\n pathEnv\n .Split(Path.PathSeparator)\n .Any(p => !string.IsNullOrEmpty(p) && File.Exists(Path.Combine(p, WinGetExe)))\n )\n {\n return WinGetExe;\n }\n\n // Check common installation paths\n foreach (var basePath in WinGetPaths)\n {\n var fullPath = Path.Combine(basePath, WinGetExe);\n if (File.Exists(fullPath))\n return fullPath;\n }\n\n return null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/InternetConnectivityService.cs", "using System;\nusing System.Net.Http;\nusing System.Net.NetworkInformation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service for checking and monitoring internet connectivity.\n /// \n public class InternetConnectivityService : IInternetConnectivityService, IDisposable\n {\n // List of reliable domains to check for internet connectivity\n private static readonly string[] _connectivityCheckUrls = new string[]\n {\n \"https://www.microsoft.com\",\n \"https://www.google.com\",\n \"https://www.cloudflare.com\",\n };\n\n // HttpClient for internet connectivity checks\n private readonly HttpClient _httpClient;\n\n // Cache the internet connectivity status to avoid frequent checks\n private bool? _cachedInternetStatus = null;\n private DateTime _lastInternetCheckTime = DateTime.MinValue;\n private readonly TimeSpan _internetStatusCacheDuration = TimeSpan.FromSeconds(10); // Cache for 10 seconds\n private readonly ILogService _logService;\n \n // Monitoring-related fields\n private CancellationTokenSource _monitoringCts;\n private Task _monitoringTask;\n private bool _isMonitoring;\n private int _monitoringIntervalSeconds;\n\n /// \n /// Event that is raised when the internet connectivity status changes.\n /// \n public event EventHandler ConnectivityChanged;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public InternetConnectivityService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n\n // Initialize HttpClient with a timeout\n _httpClient = new HttpClient();\n _httpClient.Timeout = TimeSpan.FromSeconds(5); // Short timeout for connectivity checks\n }\n\n /// \n /// Checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// True if internet is connected, false otherwise.\n public bool IsInternetConnected(bool forceCheck = false)\n {\n try\n {\n // Return cached result if it's still valid and force check is not requested\n if (\n !forceCheck\n && _cachedInternetStatus.HasValue\n && (DateTime.Now - _lastInternetCheckTime) < _internetStatusCacheDuration\n )\n {\n _logService.LogInformation(\n $\"Using cached internet connectivity status: {_cachedInternetStatus.Value}\"\n );\n return _cachedInternetStatus.Value;\n }\n\n // First check: NetworkInterface.GetIsNetworkAvailable()\n bool isNetworkAvailable = NetworkInterface.GetIsNetworkAvailable();\n if (!isNetworkAvailable)\n {\n _logService.LogInformation(\n \"Network is not available according to NetworkInterface.GetIsNetworkAvailable()\"\n );\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n return false;\n }\n\n // Second check: Ping network interfaces\n bool hasInternetAccess = false;\n try\n {\n NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();\n foreach (NetworkInterface ni in interfaces)\n {\n if (\n ni.OperationalStatus == OperationalStatus.Up\n && (\n ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211\n || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet\n )\n && ni.GetIPProperties().GatewayAddresses.Count > 0\n )\n {\n hasInternetAccess = true;\n break;\n }\n }\n\n if (!hasInternetAccess)\n {\n _logService.LogInformation(\n \"No active network interfaces with gateway addresses found\"\n );\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.LogWarning($\"Error checking network interfaces: {ex.Message}\");\n // Continue to the next check even if this one fails\n }\n\n // Third check: Try to connect to reliable domains\n foreach (string url in _connectivityCheckUrls)\n {\n try\n {\n // Make a HEAD request to minimize data transfer\n var request = new HttpRequestMessage(HttpMethod.Head, url);\n var response = _httpClient.SendAsync(request).GetAwaiter().GetResult();\n\n if (response.IsSuccessStatusCode)\n {\n _logService.LogInformation($\"Successfully connected to {url}\");\n _cachedInternetStatus = true;\n _lastInternetCheckTime = DateTime.Now;\n return true;\n }\n }\n catch (Exception ex)\n {\n _logService.LogInformation($\"Failed to connect to {url}: {ex.Message}\");\n // Try the next URL\n }\n }\n\n // If we get here, all connectivity checks failed\n _logService.LogWarning(\"All internet connectivity checks failed\");\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n return false;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking internet connectivity\", ex);\n return false;\n }\n }\n\n /// \n /// Asynchronously checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// Cancellation token for the operation.\n /// True if internet is connected, false otherwise.\n public async Task IsInternetConnectedAsync(\n bool forceCheck = false,\n CancellationToken cancellationToken = default,\n bool userInitiatedCancellation = false\n )\n {\n try\n {\n // Check for cancellation before doing anything\n if (cancellationToken.IsCancellationRequested)\n {\n _logService.LogInformation(userInitiatedCancellation ? \"Internet connectivity check was cancelled by user\" : \"Internet connectivity check was cancelled as part of operation cancellation\");\n throw new OperationCanceledException(cancellationToken);\n }\n \n // Return cached result if it's still valid and force check is not requested\n if (\n !forceCheck\n && _cachedInternetStatus.HasValue\n && (DateTime.Now - _lastInternetCheckTime) < _internetStatusCacheDuration\n )\n {\n _logService.LogInformation(\n $\"Using cached internet connectivity status: {_cachedInternetStatus.Value}\"\n );\n return _cachedInternetStatus.Value;\n }\n\n // First check: NetworkInterface.GetIsNetworkAvailable()\n bool isNetworkAvailable = NetworkInterface.GetIsNetworkAvailable();\n if (!isNetworkAvailable)\n {\n _logService.LogInformation(\n \"Network is not available according to NetworkInterface.GetIsNetworkAvailable()\"\n );\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false));\n \n return false;\n }\n\n // Second check: Ping network interfaces\n bool hasInternetAccess = false;\n try\n {\n // Check for cancellation before network interface check\n if (cancellationToken.IsCancellationRequested)\n {\n _logService.LogInformation(userInitiatedCancellation ? \"Internet connectivity check was cancelled by user\" : \"Internet connectivity check was cancelled as part of operation cancellation\");\n throw new OperationCanceledException(cancellationToken);\n }\n \n NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();\n foreach (NetworkInterface ni in interfaces)\n {\n if (\n ni.OperationalStatus == OperationalStatus.Up\n && (\n ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211\n || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet\n )\n && ni.GetIPProperties().GatewayAddresses.Count > 0\n )\n {\n hasInternetAccess = true;\n break;\n }\n }\n\n if (!hasInternetAccess)\n {\n _logService.LogInformation(\n \"No active network interfaces with gateway addresses found\"\n );\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false));\n \n return false;\n }\n }\n catch (OperationCanceledException)\n {\n // This is a user-initiated cancellation, not a connectivity issue\n _logService.LogInformation(userInitiatedCancellation ? \"Internet connectivity check was cancelled by user\" : \"Internet connectivity check was cancelled as part of operation cancellation\");\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false, userInitiatedCancellation));\n \n throw; // Re-throw to be handled by the caller\n }\n catch (Exception ex)\n {\n _logService.LogWarning($\"Error checking network interfaces: {ex.Message}\");\n // Continue to the next check even if this one fails\n }\n\n // Third check: Try to connect to reliable domains\n foreach (string url in _connectivityCheckUrls)\n {\n try\n {\n // Check for cancellation before making the request\n if (cancellationToken.IsCancellationRequested)\n {\n // This is a user-initiated cancellation, not a connectivity issue\n _logService.LogInformation(userInitiatedCancellation ? \"Internet connectivity check was cancelled by user\" : \"Internet connectivity check was cancelled as part of operation cancellation\");\n throw new OperationCanceledException(cancellationToken);\n }\n \n // Make a HEAD request to minimize data transfer\n var request = new HttpRequestMessage(HttpMethod.Head, url);\n var response = await _httpClient.SendAsync(request, cancellationToken);\n\n if (response.IsSuccessStatusCode)\n {\n _logService.LogInformation($\"Successfully connected to {url}\");\n _cachedInternetStatus = true;\n _lastInternetCheckTime = DateTime.Now;\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(true));\n \n return true;\n }\n }\n catch (OperationCanceledException)\n {\n // This is a user-initiated cancellation, not a connectivity issue\n _logService.LogInformation(userInitiatedCancellation ? \"Internet connectivity check was cancelled by user\" : \"Internet connectivity check was cancelled as part of operation cancellation\");\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false, userInitiatedCancellation));\n \n throw; // Re-throw to be handled by the caller\n }\n catch (Exception ex)\n {\n _logService.LogInformation($\"Failed to connect to {url}: {ex.Message}\");\n // Try the next URL\n }\n }\n\n // If we get here, all connectivity checks failed\n _logService.LogWarning(\"All internet connectivity checks failed\");\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false));\n \n return false;\n }\n catch (OperationCanceledException)\n {\n // This is a user-initiated cancellation, not a connectivity issue\n _logService.LogInformation(\"Internet connectivity check was cancelled by user\");\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false, true));\n \n throw; // Re-throw to be handled by the caller\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking internet connectivity\", ex);\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false));\n \n return false;\n }\n }\n \n /// \n /// Starts monitoring internet connectivity at the specified interval.\n /// \n /// The interval in seconds between connectivity checks.\n /// Cancellation token to stop monitoring.\n /// A task representing the monitoring operation.\n public async Task StartMonitoringAsync(int intervalSeconds = 5, CancellationToken cancellationToken = default)\n {\n if (_isMonitoring)\n {\n _logService.LogWarning(\"Internet connectivity monitoring is already active\");\n return;\n }\n \n _monitoringIntervalSeconds = intervalSeconds;\n _monitoringCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n _isMonitoring = true;\n \n _logService.LogInformation($\"Starting internet connectivity monitoring with {intervalSeconds} second interval\");\n \n _monitoringTask = Task.Run(async () =>\n {\n try\n {\n bool? lastStatus = null;\n \n while (!_monitoringCts.Token.IsCancellationRequested)\n {\n try\n {\n bool currentStatus = await IsInternetConnectedAsync(true, _monitoringCts.Token);\n \n // Only raise the event if the status has changed\n if (lastStatus == null || lastStatus.Value != currentStatus)\n {\n _logService.LogInformation($\"Internet connectivity status changed: {currentStatus}\");\n lastStatus = currentStatus;\n }\n \n // Wait for the specified interval\n await Task.Delay(TimeSpan.FromSeconds(_monitoringIntervalSeconds), _monitoringCts.Token);\n }\n catch (OperationCanceledException)\n {\n // Check if this is a user-initiated cancellation or just the monitoring being stopped\n if (_monitoringCts.Token.IsCancellationRequested)\n {\n _logService.LogInformation(\"Internet connectivity monitoring was cancelled\");\n break;\n }\n \n // If it's a user-initiated cancellation during a connectivity check, continue monitoring\n _logService.LogInformation(\"Internet connectivity check was cancelled by user, continuing monitoring\");\n await Task.Delay(TimeSpan.FromSeconds(_monitoringIntervalSeconds), _monitoringCts.Token);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error during internet connectivity monitoring\", ex);\n await Task.Delay(TimeSpan.FromSeconds(_monitoringIntervalSeconds), _monitoringCts.Token);\n }\n }\n }\n catch (OperationCanceledException)\n {\n // Expected when monitoring is stopped\n _logService.LogInformation(\"Internet connectivity monitoring was stopped\");\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error in internet connectivity monitoring task\", ex);\n }\n finally\n {\n _isMonitoring = false;\n }\n }, _monitoringCts.Token);\n \n await Task.CompletedTask;\n }\n \n /// \n /// Stops monitoring internet connectivity.\n /// \n public void StopMonitoring()\n {\n if (!_isMonitoring)\n {\n return;\n }\n \n _logService.LogInformation(\"Stopping internet connectivity monitoring\");\n \n try\n {\n _monitoringCts?.Cancel();\n _monitoringCts?.Dispose();\n _monitoringCts = null;\n _monitoringTask = null;\n _isMonitoring = false;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error stopping internet connectivity monitoring\", ex);\n }\n }\n \n /// \n /// Raises the ConnectivityChanged event.\n /// \n /// The event arguments.\n protected virtual void OnConnectivityChanged(ConnectivityChangedEventArgs args)\n {\n if (_isMonitoring)\n {\n ConnectivityChanged?.Invoke(this, args);\n }\n }\n \n /// \n /// Disposes the resources used by the service.\n /// \n public void Dispose()\n {\n StopMonitoring();\n _httpClient?.Dispose();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/ViewModels/ExplorerCustomizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Customize.Enums;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Customize.ViewModels\n{\n /// \n /// ViewModel for Explorer customizations.\n /// \n public partial class ExplorerCustomizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDialogService _dialogService;\n\n /// \n /// Gets the command to execute an action.\n /// \n [RelayCommand]\n public async Task ExecuteAction(ApplicationAction? action)\n {\n if (action == null) return;\n\n try\n {\n // Execute the registry action if present\n if (action.RegistrySetting != null)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(action.RegistrySetting.Hive);\n string fullPath = $\"{hiveString}\\\\{action.RegistrySetting.SubKey}\";\n _registryService.SetValue(\n fullPath,\n action.RegistrySetting.Name,\n action.RegistrySetting.RecommendedValue,\n action.RegistrySetting.ValueType);\n }\n\n // Execute the command action if present\n if (action.CommandAction != null)\n {\n // Execute the command\n // This would typically be handled by a command execution service\n }\n\n // Refresh the status after applying the action\n await CheckSettingStatusesAsync();\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error executing action: {ex.Message}\");\n }\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dialog service.\n public ExplorerCustomizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDialogService dialogService)\n : base(progressService, registryService, logService)\n {\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n }\n\n /// \n /// Loads the Explorer customizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Explorer customizations from ExplorerCustomizations\n var explorerCustomizations = Core.Features.Customize.Models.ExplorerCustomizations.GetExplorerCustomizations();\n if (explorerCustomizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in explorerCustomizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n ControlType = setting.ControlType\n };\n\n // Add any actions\n var actionsProperty = setting.GetType().GetProperty(\"Actions\");\n if (actionsProperty != null && \n actionsProperty.GetValue(setting) is IEnumerable actions && \n actions.Any())\n {\n // We need to handle this differently since the Actions property doesn't exist in ApplicationSetting\n // This is a temporary workaround until we refactor the code properly\n }\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for settings\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all Explorer customizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n foreach (var setting in Settings)\n {\n // Get status\n if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n // For linked registry settings, use GetLinkedSettingsStatusAsync\n var linkedStatus = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n setting.Status = linkedStatus;\n \n // Update IsSelected based on status - this is crucial for the initial toggle state\n setting.IsUpdatingFromCode = true;\n setting.IsSelected = linkedStatus == RegistrySettingStatus.Applied;\n setting.IsUpdatingFromCode = false;\n }\n else\n {\n // For single registry setting\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n setting.Status = status;\n }\n\n // Get current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n setting.CurrentValue = currentValue;\n\n // Set IsRegistryValueNull property based on current value for single registry setting\n if (setting.LinkedRegistrySettings == null || setting.LinkedRegistrySettings.Settings.Count == 0)\n {\n // Special handling for specific Explorer items that should not show warning icons\n if (setting.Name == \"3D Objects\" || \n setting.Name == \"Gallery in Navigation Pane\" || \n setting.Name == \"Home in Navigation Pane\")\n {\n // Don't show warning icon for these specific items\n setting.IsRegistryValueNull = false;\n }\n else\n {\n setting.IsRegistryValueNull = currentValue == null;\n }\n }\n\n // Update LinkedRegistrySettingsWithValues for tooltip display\n var linkedRegistrySettingsWithValues = new ObservableCollection();\n \n // Get the LinkedRegistrySettings property\n var linkedRegistrySettings = setting.LinkedRegistrySettings;\n \n if (linkedRegistrySettings != null && linkedRegistrySettings.Settings.Count > 0)\n {\n // For linked settings, get fresh values from registry\n bool anyNull = false;\n foreach (var regSetting in linkedRegistrySettings.Settings)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(regSetting.Hive);\n var regCurrentValue = _registryService.GetValue(\n $\"{hiveString}\\\\{regSetting.SubKey}\",\n regSetting.Name);\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n linkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // For linked settings, set IsRegistryValueNull if any value is null\n // Special handling for specific Explorer items that should not show warning icons\n if (setting.Name == \"3D Objects\" || \n setting.Name == \"Gallery in Navigation Pane\" || \n setting.Name == \"Home in Navigation Pane\")\n {\n // Don't show warning icon for these specific items\n setting.IsRegistryValueNull = false;\n }\n else\n {\n setting.IsRegistryValueNull = anyNull;\n }\n }\n else if (setting.RegistrySetting != null)\n {\n // For single setting\n linkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n }\n \n setting.LinkedRegistrySettingsWithValues = linkedRegistrySettingsWithValues;\n\n // Set status message\n string statusMessage = GetStatusMessage(setting);\n setting.StatusMessage = statusMessage;\n\n // Set the IsUpdatingFromCode flag to prevent automatic application\n setting.IsUpdatingFromCode = true;\n\n try\n {\n // Update IsSelected based on status\n bool shouldBeSelected = setting.Status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {setting.Status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n // Reset the flag\n setting.IsUpdatingFromCode = false;\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Explorer customization statuses: {ex.Message}\");\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n var status = setting.Status;\n string message = status switch\n {\n RegistrySettingStatus.Applied => \"Setting is applied with recommended value\",\n RegistrySettingStatus.NotApplied => \"Setting is not applied or using default value\",\n RegistrySettingStatus.Modified => \"Setting has a custom value different from recommended\",\n RegistrySettingStatus.Error => \"Error checking setting status\",\n _ => \"Unknown status\"\n };\n\n // Add current value if available\n var currentValue = setting.CurrentValue;\n if (currentValue != null)\n {\n message += $\"\\nCurrent value: {currentValue}\";\n }\n\n // Add recommended value if available\n var registrySetting = setting.RegistrySetting;\n if (registrySetting?.RecommendedValue != null)\n {\n message += $\"\\nRecommended value: {registrySetting.RecommendedValue}\";\n }\n\n // Add default value if available\n if (registrySetting?.DefaultValue != null)\n {\n message += $\"\\nDefault value: {registrySetting.DefaultValue}\";\n }\n\n return message;\n }\n\n // ApplySelectedSettingsAsync and RestoreDefaultsAsync methods removed as part of the refactoring\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/CapabilityInstallationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that enables Windows capabilities.\n/// \npublic class CapabilityInstallationService : BaseInstallationService, ICapabilityInstallationService\n{\n private readonly CapabilityCatalog _capabilityCatalog;\n private readonly IScriptUpdateService _scriptUpdateService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The PowerShell execution service.\n /// The script update service.\n public CapabilityInstallationService(\n ILogService logService,\n IPowerShellExecutionService powerShellService,\n IScriptUpdateService scriptUpdateService\n ) : base(logService, powerShellService)\n {\n // Create a default capability catalog\n _capabilityCatalog = CapabilityCatalog.CreateDefault();\n _scriptUpdateService = scriptUpdateService ?? throw new ArgumentNullException(nameof(scriptUpdateService));\n }\n\n /// \n public Task> InstallCapabilityAsync(\n CapabilityInfo capabilityInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default\n )\n {\n return InstallItemAsync(capabilityInfo, progress, cancellationToken);\n }\n\n /// \n public Task> CanInstallCapabilityAsync(CapabilityInfo capabilityInfo)\n {\n return CanInstallItemAsync(capabilityInfo);\n }\n\n /// \n protected override async Task> PerformInstallationAsync(\n CapabilityInfo capabilityInfo,\n IProgress? progress,\n CancellationToken cancellationToken)\n {\n var result = await InstallCapabilityAsync(capabilityInfo.PackageName, progress, cancellationToken);\n \n // Only update BloatRemoval.ps1 script if installation was successful\n if (result.Success)\n {\n try\n {\n _logService.LogInformation($\"Starting BloatRemoval.ps1 script update for {capabilityInfo.Name}\");\n \n // Update the BloatRemoval.ps1 script to remove the installed capability from the removal list\n var appNames = new List { capabilityInfo.PackageName };\n _logService.LogInformation($\"Removing capability name from BloatRemoval.ps1: {capabilityInfo.PackageName}\");\n \n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n\n // Add registry settings if present\n if (capabilityInfo.RegistrySettings != null && capabilityInfo.RegistrySettings.Length > 0)\n {\n _logService.LogInformation($\"Adding {capabilityInfo.RegistrySettings.Length} registry settings for {capabilityInfo.Name}\");\n appsWithRegistry.Add(capabilityInfo.PackageName, new List(capabilityInfo.RegistrySettings));\n }\n\n _logService.LogInformation($\"Updating BloatRemoval.ps1 to remove {capabilityInfo.Name} from removal list\");\n \n // Check if the capability name already includes a version (~~~~)\n string fullCapabilityName = capabilityInfo.PackageName;\n if (!fullCapabilityName.Contains(\"~~~~\"))\n {\n // We don't have a version in the package name, but we might be able to extract it from installed capabilities\n _logService.LogInformation($\"Package name doesn't include version information: {fullCapabilityName}\");\n _logService.LogInformation($\"Using package name as is: {fullCapabilityName}\");\n }\n else\n {\n _logService.LogInformation($\"Using full capability name with version: {fullCapabilityName}\");\n }\n \n // Always use the package name as provided\n appNames = new List { fullCapabilityName };\n \n var scriptResult = await _scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n true); // true = install operation, so remove from script\n \n _logService.LogInformation($\"Successfully updated BloatRemoval.ps1 script - {capabilityInfo.Name} will no longer be removed\");\n _logService.LogInformation($\"Script update result: {scriptResult?.Name ?? \"null\"}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for {capabilityInfo.Name}\", ex);\n _logService.LogError($\"Exception details: {ex.Message}\");\n _logService.LogError($\"Stack trace: {ex.StackTrace}\");\n // Don't fail the installation if script update fails\n }\n }\n else\n {\n _logService.LogInformation($\"Skipping BloatRemoval.ps1 update because installation of {capabilityInfo.Name} was not successful\");\n }\n \n return result;\n }\n\n /// \n /// Installs a Windows capability by name.\n /// \n /// The name of the capability to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n private async Task> InstallCapabilityAsync(\n string capabilityName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default\n )\n {\n try\n {\n // Get the friendly name of the capability from the catalog\n string friendlyName = GetFriendlyName(capabilityName);\n \n // Set a more descriptive initial status using the friendly name\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Enabling {friendlyName}...\",\n DetailedMessage = $\"Starting to enable capability: {capabilityName}\",\n }\n );\n\n _logService.LogInformation($\"Attempting to enable capability: {capabilityName}\");\n \n // Create a progress handler that overrides the generic \"Operation: Running\" text\n var progressHandler = new Progress(detail => {\n // If we get a generic \"Operation: Running\" status, replace it with our more descriptive one\n if (detail.StatusText != null && detail.StatusText.StartsWith(\"Operation:\"))\n {\n // Keep the percentage but replace the generic text with the friendly name\n detail.StatusText = $\"Enabling {friendlyName}...\";\n if (detail.Progress.HasValue)\n {\n detail.StatusText = $\"Enabling {friendlyName}... ({detail.Progress:F0}%)\";\n }\n }\n \n // Forward the updated progress to the original progress reporter\n progress?.Report(detail);\n });\n\n // Define the PowerShell script - Embed capabilityName, output parseable string\n // Output format: STATUS|Message|RebootRequired (e.g., SUCCESS|Installed 1 of 1|True)\n string script = $@\"\n try {{\n $capabilityNamePattern = '{capabilityName}*' # Embed pattern directly\n Write-Information \"\"Searching for capability: $capabilityNamePattern\"\"\n # Progress reporting needs to be handled by the caller based on script output or duration\n\n # Find matching capabilities\n $capabilities = Get-WindowsCapability -Online | Where-Object {{ $_.Name -like $capabilityNamePattern -and $_.State -ne 'Installed' }}\n\n if ($capabilities.Count -eq 0) {{\n # Check if it's already installed\n $alreadyInstalled = Get-WindowsCapability -Online | Where-Object {{ $_.Name -like $capabilityNamePattern -and $_.State -eq 'Installed' }}\n if ($alreadyInstalled) {{\n return \"\"SUCCESS|Capability already installed|False\"\"\n }} else {{\n Write-Warning \"\"No matching capabilities found: $capabilityNamePattern\"\"\n return \"\"FAILURE|No matching capabilities found\"\"\n }}\n }}\n\n $totalCapabilities = $capabilities.Count\n $rebootRequired = $false\n $installedCount = 0\n $errorMessages = @()\n\n foreach ($capability in $capabilities) {{\n Write-Information \"\"Installing capability: $($capability.Name)\"\"\n try {{\n $result = Add-WindowsCapability -Online -Name $capability.Name\n if ($result.RestartNeeded) {{\n $rebootRequired = $true\n }}\n $installedCount++\n }}\n catch {{\n $errMsg = \"\"Failed to install capability: $($capability.Name). $($_.Exception.Message)\"\"\n Write-Error $errMsg\n $errorMessages += $errMsg\n }}\n }}\n\n if ($installedCount -gt 0) {{\n $rebootNeededStr = if ($rebootRequired) {{ 'True' }} else {{ 'False' }}\n $finalMessage = \"\"Successfully installed $installedCount of $totalCapabilities capabilities.\"\"\n if ($errorMessages.Count -gt 0) {{\n $finalMessage += \"\" Errors: $($errorMessages -join '; ')\"\"\n }}\n return \"\"SUCCESS|$finalMessage|$rebootNeededStr\"\"\n }} else {{\n $finalMessage = \"\"Failed to install any capabilities.\"\"\n if ($errorMessages.Count -gt 0) {{\n $finalMessage += \"\" Errors: $($errorMessages -join '; ')\"\"\n }}\n return \"\"FAILURE|$finalMessage\"\"\n }}\n }}\n catch {{\n Write-Error \"\"Error enabling capability: $($_.Exception.Message)\"\"\n return \"\"FAILURE|$($_.Exception.Message)\"\"\n }}\n \";\n\n // Execute PowerShell using the correct interface method with our custom progress handler\n string resultString = await _powerShellService.ExecuteScriptAsync(\n script,\n progressHandler, // Use our custom progress handler instead of passing progress directly\n cancellationToken);\n\n // Process the result string\n if (!string.IsNullOrEmpty(resultString))\n {\n var parts = resultString.Split('|');\n if (parts.Length >= 2)\n {\n string status = parts[0];\n string message = parts[1];\n bool rebootRequired = parts.Length > 2 && bool.TryParse(parts[2], out bool req) && req;\n\n if (status.Equals(\"SUCCESS\", StringComparison.OrdinalIgnoreCase))\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 100,\n StatusText = $\"Successfully enabled {GetFriendlyName(capabilityName)}\",\n DetailedMessage = message\n });\n _logService.LogSuccess($\"Successfully enabled capability: {capabilityName}. {message}\");\n\n if (rebootRequired)\n {\n progress?.Report(new TaskProgressDetail\n {\n StatusText = \"A system restart is required to complete the installation\",\n DetailedMessage = \"Please restart your computer to complete the installation\",\n LogLevel = LogLevel.Warning\n });\n _logService.LogWarning($\"A system restart is required for {GetFriendlyName(capabilityName)}\");\n }\n return OperationResult.Succeeded(true); // Indicate success\n }\n else // FAILURE\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0, // Indicate failure\n StatusText = $\"Failed to enable {GetFriendlyName(capabilityName)}\",\n DetailedMessage = message,\n LogLevel = LogLevel.Error\n });\n _logService.LogError($\"Failed to enable capability: {capabilityName}. {message}\");\n return OperationResult.Failed(message); // Indicate failure with message\n }\n }\n else\n {\n // Handle unexpected script output format\n _logService.LogError($\"Unexpected script output format for {capabilityName}: {resultString}\");\n progress?.Report(new TaskProgressDetail { StatusText = \"Error processing script result\", LogLevel = LogLevel.Error });\n return OperationResult.Failed(\"Unexpected script output format: \" + resultString); // Indicate failure with message\n }\n }\n else\n {\n // Handle case where script returned empty string\n _logService.LogError($\"Empty result returned when enabling capability: {capabilityName}\");\n progress?.Report(new TaskProgressDetail { StatusText = \"Script returned no result\", LogLevel = LogLevel.Error });\n return OperationResult.Failed(\"Script returned no result\"); // Indicate failure with message\n }\n }\n catch (OperationCanceledException)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Operation cancelled when enabling {GetFriendlyName(capabilityName)}\",\n DetailedMessage = \"The operation was cancelled by the user\",\n LogLevel = LogLevel.Warning,\n }\n );\n\n _logService.LogWarning($\"Operation cancelled when enabling capability: {capabilityName}\");\n return OperationResult.Failed(\"The operation was cancelled by the user\"); // Return cancellation result\n }\n catch (Exception ex)\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Error enabling {GetFriendlyName(capabilityName)}\",\n DetailedMessage = $\"Exception: {ex.Message}\",\n LogLevel = LogLevel.Error\n });\n _logService.LogError($\"Error enabling capability: {capabilityName}\", ex);\n return OperationResult.Failed($\"Error enabling capability: {ex.Message}\", ex); // Indicate failure with exception\n }\n }\n\n // Note: CheckInstalled is not part of the ICapabilityInstallationService interface\n // It should likely be moved or removed if not used elsewhere.\n // For now, commenting it out to fix build errors.\n /*\n public bool CheckInstalled(CapabilityInfo capabilityInfo)\n {\n // ... (Implementation needs fixing similar to InstallCapabilityAsync)\n }\n */\n\n // Note: InstallCapabilitiesAsync is not part of the ICapabilityInstallationService interface\n // It should likely be moved or removed if not used elsewhere.\n // For now, commenting it out to fix build errors.\n /*\n public Task InstallCapabilitiesAsync(IEnumerable capabilities)\n {\n return InstallCapabilitiesAsync(capabilities, null, default);\n }\n\n public async Task InstallCapabilitiesAsync(\n IEnumerable capabilities,\n IProgress? progress,\n CancellationToken cancellationToken)\n {\n // ... (Implementation needs fixing similar to InstallCapabilityAsync)\n }\n */\n\n // Note: RemoveCapabilitiesAsync is not part of the ICapabilityInstallationService interface\n // It should likely be moved or removed if not used elsewhere.\n // For now, commenting it out to fix build errors.\n /*\n public async Task RemoveCapabilitiesAsync(IEnumerable capabilities)\n {\n // ... (Implementation needs fixing similar to InstallCapabilityAsync)\n }\n\n private async Task RemoveCapabilityAsync(CapabilityInfo capabilityInfo)\n {\n // ... (Implementation needs fixing similar to InstallCapabilityAsync)\n }\n */\n\n /// \n /// Gets the friendly name of a capability from its package name.\n /// \n /// The package name of the capability.\n /// The friendly name of the capability, or the package name if not found.\n private string GetFriendlyName(string packageName)\n {\n // Remove any version information from the package name (e.g., \"Media.WindowsMediaPlayer~~~~0.0.12.0\" -> \"Media.WindowsMediaPlayer\")\n string basePackageName = packageName.Split('~')[0];\n \n // Look up the capability in the catalog by its package name\n var capability = _capabilityCatalog.Capabilities.FirstOrDefault(c =>\n c.PackageName.Equals(basePackageName, StringComparison.OrdinalIgnoreCase));\n \n // Return the friendly name if found, otherwise return the package name\n return capability?.Name ?? packageName;\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Models/ApplicationSettingItem.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Services;\nusing Microsoft.Win32;\n\nnamespace Winhance.WPF.Features.Common.Models\n{\n /// \n /// Base class for application setting items used in both Optimization and Customization features.\n /// \n public partial class ApplicationSettingItem : ObservableObject, ISettingItem, ISearchable\n {\n private readonly IRegistryService? _registryService;\n private readonly ICommandService? _commandService;\n private readonly IDialogService? _dialogService;\n private readonly ILogService? _logService;\n private bool _isUpdatingFromCode;\n\n /// \n /// Gets or sets a value indicating whether the IsSelected property is being updated from code.\n /// This is used to prevent automatic application of settings when loading.\n /// \n public bool IsUpdatingFromCode\n {\n get => _isUpdatingFromCode;\n set => _isUpdatingFromCode = value;\n }\n\n [ObservableProperty]\n private string _id = string.Empty;\n\n [ObservableProperty]\n private string _name = string.Empty;\n\n [ObservableProperty]\n private string _fullName = string.Empty;\n\n partial void OnNameChanged(string value) => UpdateFullName();\n\n private void UpdateFullName()\n {\n FullName = Name;\n }\n\n [ObservableProperty]\n private string _description = string.Empty;\n\n [ObservableProperty]\n private bool _isSelected;\n\n partial void OnIsSelectedChanged(bool value)\n {\n // Skip if we're updating from code\n if (IsUpdatingFromCode)\n {\n return;\n }\n\n // Store the current selection state to restore after applying\n bool currentSelection = value;\n\n // Apply the setting when IsSelected changes\n ApplySetting();\n \n // Ensure the toggle stays in the state the user selected\n if (IsSelected != currentSelection)\n {\n IsUpdatingFromCode = true;\n try\n {\n IsSelected = currentSelection;\n }\n finally\n {\n IsUpdatingFromCode = false;\n }\n }\n }\n\n [ObservableProperty]\n private bool _isGroupHeader;\n\n [ObservableProperty]\n private bool _isVisible = true;\n\n [ObservableProperty]\n private string _groupName = string.Empty;\n\n [ObservableProperty]\n private RegistrySettingStatus _status = RegistrySettingStatus.Unknown;\n\n [ObservableProperty]\n private string _statusMessage = string.Empty;\n\n [ObservableProperty]\n private object? _currentValue;\n\n [ObservableProperty]\n private object? _selectedValue;\n\n [ObservableProperty]\n private bool _isRegistryValueNull;\n\n [ObservableProperty]\n private ControlType _controlType = ControlType.BinaryToggle;\n\n [ObservableProperty]\n private int? _sliderSteps;\n\n [ObservableProperty]\n private int _sliderValue;\n\n [ObservableProperty]\n private ObservableCollection _sliderLabels = new();\n\n [ObservableProperty]\n private bool _isApplying;\n\n /// \n /// Gets or sets the registry setting.\n /// \n public RegistrySetting? RegistrySetting { get; set; }\n\n private LinkedRegistrySettings? _linkedRegistrySettings;\n\n /// \n /// Gets or sets the linked registry settings.\n /// \n public LinkedRegistrySettings? LinkedRegistrySettings \n { \n get => _linkedRegistrySettings;\n set\n {\n _linkedRegistrySettings = value;\n \n // Populate LinkedRegistrySettingsWithValues when LinkedRegistrySettings is assigned\n if (value != null && value.Settings.Count > 0)\n {\n LinkedRegistrySettingsWithValues.Clear();\n foreach (var setting in value.Settings)\n {\n LinkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(setting, null));\n }\n }\n }\n }\n\n /// \n /// Gets or sets the linked registry settings with values.\n /// \n public ObservableCollection LinkedRegistrySettingsWithValues { get; set; } = new();\n\n /// \n /// Gets or sets the command settings.\n /// \n public List CommandSettings { get; set; } = new List();\n\n /// \n /// Gets or sets the dependencies between settings.\n /// \n public List Dependencies { get; set; } = new List();\n\n /// \n /// Gets or sets the dropdown options.\n /// \n public ObservableCollection DropdownOptions { get; set; } = new();\n\n /// \n /// Gets or sets the selected dropdown option.\n /// \n [ObservableProperty]\n private string _selectedDropdownOption = string.Empty;\n \n /// \n /// Gets a value indicating whether there are no settings to display.\n /// \n public bool HasNoSettings\n {\n get\n {\n // True if there are no registry settings and no command settings\n bool hasRegistrySettings = RegistrySetting != null || (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0);\n bool hasCommandSettings = CommandSettings != null && CommandSettings.Count > 0;\n \n return !hasRegistrySettings && !hasCommandSettings;\n }\n }\n \n /// \n /// Gets a value indicating whether this setting only has command settings (no registry settings).\n /// \n public bool HasCommandSettingsOnly\n {\n get\n {\n // True if there are command settings but no registry settings\n bool hasRegistrySettings = RegistrySetting != null || (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0);\n bool hasCommandSettings = CommandSettings != null && CommandSettings.Count > 0;\n \n return hasCommandSettings && !hasRegistrySettings;\n }\n }\n\n /// \n /// Gets or sets a value indicating whether this is a grouped setting that contains child settings.\n /// \n public bool IsGroupedSetting { get; set; }\n\n /// \n /// Gets or sets the child settings for a grouped setting.\n /// \n public ObservableCollection ChildSettings { get; set; } = new ObservableCollection();\n\n /// \n /// Gets or sets a dictionary of custom properties.\n /// \n public Dictionary CustomProperties { get; set; } = new Dictionary();\n\n /// \n /// Gets the collection of actions associated with this setting.\n /// \n public List Actions { get; } = new List();\n\n /// \n /// Gets or sets the command to apply the setting.\n /// \n public ICommand ApplySettingCommand { get; private set; }\n\n /// \n /// Gets or sets the command to restore the setting to its default value.\n /// \n public ICommand RestoreDefaultCommand { get; private set; }\n\n /// \n /// Gets or sets a value indicating whether this setting is only for Windows 11.\n /// \n public bool IsWindows11Only { get; set; }\n\n /// \n /// Gets or sets a value indicating whether this setting is only for Windows 10.\n /// \n public bool IsWindows10Only { get; set; }\n\n /// \n /// Gets or sets the setting type.\n /// \n public string SettingType { get; set; } = string.Empty;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public ApplicationSettingItem()\n {\n ApplySettingCommand = new RelayCommand(ApplySetting);\n RestoreDefaultCommand = new RelayCommand(RestoreDefault);\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The registry service.\n /// The dialog service.\n /// The log service.\n /// The command service.\n public ApplicationSettingItem(IRegistryService? registryService, IDialogService? dialogService, ILogService? logService, ICommandService? commandService = null)\n : this()\n {\n _registryService = registryService;\n _dialogService = dialogService;\n _logService = logService;\n _commandService = commandService;\n }\n\n /// \n /// Applies the setting.\n /// \n public async void ApplySetting()\n {\n // Skip if we're updating from code\n if (IsUpdatingFromCode)\n {\n return;\n }\n \n // Apply registry settings if available\n if (_registryService != null)\n {\n ApplyRegistrySettings();\n }\n \n // Apply command settings if available\n if (_commandService != null && CommandSettings.Any())\n {\n await ApplyCommandSettingsAsync();\n }\n }\n \n /// \n /// Applies the registry settings.\n /// \n private void ApplyRegistrySettings()\n {\n if (_registryService == null)\n {\n return;\n }\n\n // Apply the setting\n if (RegistrySetting != null)\n {\n try\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(RegistrySetting.Hive);\n\n // Get the appropriate value based on the toggle state\n object valueToApply = IsSelected \n ? (RegistrySetting.EnabledValue ?? RegistrySetting.RecommendedValue) \n : (RegistrySetting.DisabledValue ?? RegistrySetting.DefaultValue);\n\n // Apply the setting\n _registryService.SetValue(\n $\"{hiveString}\\\\{RegistrySetting.SubKey}\",\n RegistrySetting.Name,\n valueToApply,\n RegistrySetting.ValueType);\n\n // Update the current value and linked registry settings with values\n CurrentValue = valueToApply;\n \n // Update the linked registry settings with values collection\n LinkedRegistrySettingsWithValues.Clear();\n LinkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(RegistrySetting, CurrentValue));\n\n // Update status without changing IsSelected\n Status = IsSelected ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n StatusMessage = Status == RegistrySettingStatus.Applied ? \"Applied\" : \"Not Applied\";\n\n // Log the action\n _logService?.Log(LogLevel.Info, $\"Applied setting {Name}: {(IsSelected ? \"Enabled\" : \"Disabled\")}\");\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Error applying setting {Name}: {ex.Message}\");\n }\n }\n else if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n try\n {\n // Clear the existing values\n LinkedRegistrySettingsWithValues.Clear();\n \n // Apply all linked settings\n foreach (var setting in LinkedRegistrySettings.Settings)\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(setting.Hive);\n\n // Get the appropriate value based on the toggle state\n object valueToApply = IsSelected \n ? (setting.EnabledValue ?? setting.RecommendedValue) \n : (setting.DisabledValue ?? setting.DefaultValue);\n \n // Apply the setting\n _registryService.SetValue(\n $\"{hiveString}\\\\{setting.SubKey}\",\n setting.Name,\n valueToApply,\n setting.ValueType);\n \n // Add to the linked registry settings with values collection\n LinkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(setting, valueToApply));\n }\n\n // Update status without changing IsSelected\n Status = IsSelected ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n StatusMessage = Status == RegistrySettingStatus.Applied ? \"Applied\" : \"Not Applied\";\n\n // Log the action\n _logService?.Log(LogLevel.Info, $\"Applied linked settings for {Name}: {(IsSelected ? \"Enabled\" : \"Disabled\")}\");\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Error applying linked settings for {Name}: {ex.Message}\");\n }\n }\n\n // Don't call RefreshStatus() here to avoid triggering additional registry operations\n }\n \n /// \n /// Applies the command settings.\n /// \n private async Task ApplyCommandSettingsAsync()\n {\n if (_commandService == null || !CommandSettings.Any())\n {\n return;\n }\n \n try\n {\n // Apply the command settings based on the toggle state\n var (success, message) = await _commandService.ApplyCommandSettingsAsync(CommandSettings, IsSelected);\n \n if (success)\n {\n // Update status without changing IsSelected\n Status = IsSelected ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n StatusMessage = Status == RegistrySettingStatus.Applied ? \"Applied\" : \"Not Applied\";\n \n // Log the action\n _logService?.Log(LogLevel.Info, $\"Applied command settings for {Name}: {(IsSelected ? \"Enabled\" : \"Disabled\")}\");\n }\n else\n {\n // Log the error\n _logService?.Log(LogLevel.Error, $\"Error applying command settings for {Name}: {message}\");\n }\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Exception applying command settings for {Name}: {ex.Message}\");\n }\n }\n\n /// \n /// Restores the setting to its default value.\n /// \n public void RestoreDefault()\n {\n if (_registryService == null)\n {\n return;\n }\n\n // Skip if we're updating from code\n if (IsUpdatingFromCode)\n {\n return;\n }\n\n // Restore the setting to its default value\n if (RegistrySetting != null)\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(RegistrySetting.Hive);\n\n // Apply the setting\n _registryService.SetValue(\n $\"{hiveString}\\\\{RegistrySetting.SubKey}\",\n RegistrySetting.Name,\n RegistrySetting.DefaultValue,\n RegistrySetting.ValueType);\n\n // Log the action\n _logService?.Log(LogLevel.Info, $\"Restored setting {Name} to default value\");\n }\n else if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n // Apply all linked settings\n foreach (var setting in LinkedRegistrySettings.Settings)\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(setting.Hive);\n\n // Apply the setting\n _registryService.SetValue(\n $\"{hiveString}\\\\{setting.SubKey}\",\n setting.Name,\n setting.DefaultValue,\n setting.ValueType);\n }\n\n // Log the action\n _logService?.Log(LogLevel.Info, $\"Restored linked settings for {Name} to default values\");\n }\n\n // Update IsSelected based on status\n IsUpdatingFromCode = true;\n try\n {\n IsSelected = Status == RegistrySettingStatus.Applied;\n }\n finally\n {\n IsUpdatingFromCode = false;\n }\n\n // Refresh the status\n _ = RefreshStatus();\n }\n \n /// \n /// Refreshes the status of command settings.\n /// \n /// A task representing the asynchronous operation.\n private async Task RefreshCommandSettingsStatusAsync()\n {\n if (_commandService == null || !CommandSettings.Any())\n {\n return;\n }\n \n try\n {\n // For now, we'll assume command settings are not applied by default\n // In the future, this could be enhanced to check the actual system state\n bool isEnabled = false;\n \n // If there are primary command settings, check their status\n var primarySetting = CommandSettings.FirstOrDefault(s => s.IsPrimary);\n if (primarySetting != null)\n {\n isEnabled = await _commandService.IsCommandSettingEnabledAsync(primarySetting);\n }\n \n // Update status\n Status = isEnabled ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n StatusMessage = Status == RegistrySettingStatus.Applied ? \"Applied\" : \"Not Applied\";\n \n // Update IsSelected based on status\n IsUpdatingFromCode = true;\n try\n {\n IsSelected = Status == RegistrySettingStatus.Applied;\n }\n finally\n {\n IsUpdatingFromCode = false;\n }\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Error refreshing command settings status for {Name}: {ex.Message}\");\n }\n }\n\n /// \n /// Refreshes the status of the setting.\n /// \n /// A task representing the asynchronous operation.\n public async Task RefreshStatus()\n {\n // Refresh registry settings status if available\n if (_registryService != null)\n {\n await RefreshRegistrySettingsStatusAsync();\n }\n \n // Refresh command settings status if available\n if (_commandService != null && CommandSettings.Any())\n {\n await RefreshCommandSettingsStatusAsync();\n }\n }\n \n /// \n /// Refreshes the status of registry settings.\n /// \n /// A task representing the asynchronous operation.\n private async Task RefreshRegistrySettingsStatusAsync()\n {\n if (_registryService == null)\n {\n return;\n }\n\n // Get the status\n if (RegistrySetting != null)\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(RegistrySetting.Hive);\n\n // Get the current value\n var currentValue = _registryService.GetValue(\n $\"{hiveString}\\\\{RegistrySetting.SubKey}\",\n RegistrySetting.Name);\n\n // Update the current value\n CurrentValue = currentValue;\n \n // Update the linked registry settings with values collection\n LinkedRegistrySettingsWithValues.Clear();\n LinkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(RegistrySetting, currentValue));\n\n // Determine if the value is null\n IsRegistryValueNull = currentValue == null;\n\n // Determine the status\n if (currentValue == null)\n {\n // The value doesn't exist\n Status = RegistrySetting.DefaultValue == null\n ? RegistrySettingStatus.Applied\n : RegistrySettingStatus.NotApplied;\n }\n else\n {\n // Check if it matches the enabled value first\n if (RegistrySetting.EnabledValue != null && currentValue.Equals(RegistrySetting.EnabledValue))\n {\n Status = RegistrySettingStatus.Applied;\n }\n // Then check if it matches the disabled value\n else if (RegistrySetting.DisabledValue != null && currentValue.Equals(RegistrySetting.DisabledValue))\n {\n Status = RegistrySettingStatus.NotApplied;\n }\n // Finally, fall back to recommended value for backward compatibility\n else if (currentValue.Equals(RegistrySetting.RecommendedValue))\n {\n // If RecommendedValue equals EnabledValue, mark as Applied\n // If RecommendedValue equals DisabledValue, mark as NotApplied\n if (RegistrySetting.EnabledValue != null && RegistrySetting.RecommendedValue.Equals(RegistrySetting.EnabledValue))\n {\n Status = RegistrySettingStatus.Applied;\n }\n else\n {\n Status = RegistrySettingStatus.NotApplied;\n }\n }\n else\n {\n Status = RegistrySettingStatus.NotApplied;\n }\n }\n\n // Update the status message\n StatusMessage = Status == RegistrySettingStatus.Applied\n ? \"Applied\"\n : \"Not Applied\";\n\n // Update the IsSelected property - only during initial load\n if (IsUpdatingFromCode)\n {\n IsSelected = Status == RegistrySettingStatus.Applied;\n }\n }\n else if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n // Clear the existing values\n LinkedRegistrySettingsWithValues.Clear();\n \n // Check all linked settings\n bool allApplied = true;\n bool anyApplied = false;\n bool allNull = true;\n bool anyNull = false;\n\n foreach (var setting in LinkedRegistrySettings.Settings)\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(setting.Hive);\n\n // Special handling for Remove action type\n bool isRemoveAction = setting.ActionType == RegistryActionType.Remove;\n \n // Get the current value\n var currentValue = _registryService.GetValue(\n $\"{hiveString}\\\\{setting.SubKey}\",\n setting.Name);\n \n // Add to the linked registry settings with values collection\n LinkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(setting, currentValue));\n\n // Check if the value is null\n if (currentValue == null)\n {\n anyNull = true;\n }\n else\n {\n allNull = false;\n }\n\n // Determine if the value is applied\n bool isApplied;\n \n // For Remove action type, null means the key/value doesn't exist, which means it's applied\n if (isRemoveAction)\n {\n isApplied = currentValue == null;\n }\n else if (currentValue == null)\n {\n // The value doesn't exist\n isApplied = setting.DefaultValue == null;\n }\n else\n {\n // Check if it matches the enabled value first\n if (setting.EnabledValue != null && currentValue.Equals(setting.EnabledValue))\n {\n isApplied = true;\n }\n // Then check if it matches the disabled value\n else if (setting.DisabledValue != null && currentValue.Equals(setting.DisabledValue))\n {\n isApplied = false;\n }\n // Finally, fall back to recommended value for backward compatibility\n else if (currentValue.Equals(setting.RecommendedValue))\n {\n // If RecommendedValue equals EnabledValue, mark as Applied\n // If RecommendedValue equals DisabledValue, mark as NotApplied\n if (setting.EnabledValue != null && setting.RecommendedValue.Equals(setting.EnabledValue))\n {\n isApplied = true;\n }\n else\n {\n isApplied = false;\n }\n }\n else\n {\n isApplied = false;\n }\n }\n\n // Update the status\n if (isApplied)\n {\n anyApplied = true;\n }\n else\n {\n allApplied = false;\n }\n }\n\n // Determine the status based on the logic\n if (LinkedRegistrySettings.Logic == LinkedSettingsLogic.All)\n {\n // All settings must be applied\n Status = allApplied\n ? RegistrySettingStatus.Applied\n : RegistrySettingStatus.NotApplied;\n \n // For ActionType = Remove settings, we need to invert the IsRegistryValueNull logic\n // because null means the key/value doesn't exist, which is the desired state\n bool allRemoveActions = LinkedRegistrySettings.Settings.All(s => s.ActionType == RegistryActionType.Remove);\n if (allRemoveActions)\n {\n // For Remove actions, we want to show the warning when values exist (not null)\n IsRegistryValueNull = !allNull;\n }\n else\n {\n IsRegistryValueNull = allNull;\n }\n }\n else\n {\n // Any setting must be applied\n Status = anyApplied\n ? RegistrySettingStatus.Applied\n : RegistrySettingStatus.NotApplied;\n \n // For ActionType = Remove settings, we need to invert the IsRegistryValueNull logic\n bool allRemoveActions = LinkedRegistrySettings.Settings.All(s => s.ActionType == RegistryActionType.Remove);\n if (allRemoveActions)\n {\n // For Remove actions, we want to show the warning when values exist (not null)\n IsRegistryValueNull = !anyNull;\n }\n else\n {\n IsRegistryValueNull = anyNull;\n }\n }\n\n // Update the status message\n StatusMessage = Status == RegistrySettingStatus.Applied\n ? \"Applied\"\n : \"Not Applied\";\n\n // Update the IsSelected property - only during initial load\n if (IsUpdatingFromCode)\n {\n IsSelected = Status == RegistrySettingStatus.Applied;\n }\n }\n }\n\n /// \n /// Gets the registry hive string.\n /// \n /// The registry hive.\n /// The registry hive string.\n private string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => throw new ArgumentOutOfRangeException(nameof(hive), hive, null)\n };\n }\n\n /// \n /// Determines if the object matches the given search term.\n /// \n /// The search term to match against.\n /// True if the object matches the search term, false otherwise.\n public virtual bool MatchesSearch(string searchTerm)\n {\n if (string.IsNullOrWhiteSpace(searchTerm))\n {\n return true;\n }\n\n searchTerm = searchTerm.ToLowerInvariant();\n\n foreach (var propertyName in GetSearchableProperties())\n {\n var property = GetType().GetProperty(propertyName);\n if (property != null)\n {\n var value = property.GetValue(this)?.ToString();\n if (!string.IsNullOrWhiteSpace(value) && value.ToLowerInvariant().Contains(searchTerm))\n {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /// \n /// Gets the searchable properties of the object.\n /// \n /// An array of property names that should be searched.\n public virtual string[] GetSearchableProperties()\n {\n return new[] { nameof(Name), nameof(Description), nameof(GroupName) };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/StartMenuCustomizations.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Services;\nusing Winhance.Core.Features.Customize.Enums;\n\nnamespace Winhance.Core.Features.Customize.Models;\n\npublic static class StartMenuCustomizations\n{\n private const string Win10StartLayoutPath = @\"C:\\Windows\\StartMenuLayout.xml\";\n private const string Win11StartBinPath =\n @\"AppData\\Local\\Packages\\Microsoft.Windows.StartMenuExperienceHost_cw5n1h2txyewy\\LocalState\\start2.bin\";\n\n public static CustomizationGroup GetStartMenuCustomizations()\n {\n return new CustomizationGroup\n {\n Name = \"Start Menu\",\n Category = CustomizationCategory.StartMenu,\n Settings = new List\n {\n new CustomizationSetting\n {\n Id = \"show-recently-added-apps\",\n Name = \"Show Recently Added Apps\",\n Description = \"Controls visibility of recently added apps in Start Menu\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Start Menu Settings\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Policies\\\\Microsoft\\\\Windows\\\\Explorer\",\n Name = \"HideRecentlyAddedApps\",\n RecommendedValue = 0,\n EnabledValue = 0, // When toggle is ON, recently added apps are shown\n DisabledValue = 1, // When toggle is OFF, recently added apps are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Controls visibility of recently added apps in Start Menu\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\Explorer\",\n Name = \"HideRecentlyAddedApps\",\n RecommendedValue = 0,\n EnabledValue = 0, // When toggle is ON, recently added apps are shown\n DisabledValue = 1, // When toggle is OFF, recently added apps are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Controls visibility of recently added apps in Start Menu\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"start-menu-layout\",\n Name = \"Set 'More Pins' Layout\",\n Description = \"Controls Start Menu layout configuration\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Layout\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"StartMenu\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"Start_Layout\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, more pins layout is used\n DisabledValue = 0, // When toggle is OFF, default layout is used\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // For backward compatibility\n Description = \"Controls Start Menu layout configuration\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"start-menu-recommendations\",\n Name = \"Show Recommended Tips, Shortcuts etc.\",\n Description = \"Controls recommendations for tips and shortcuts\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Start Menu Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"Start_IrisRecommendations\",\n RecommendedValue = 1,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls recommendations for tips and shortcuts\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"taskbar-clear-mfu\",\n Name = \"Show Most Used Apps\",\n Description = \"Controls frequently used programs list visibility\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Start Menu\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"StartMenu\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Start\",\n Name = \"ShowFrequentList\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, frequently used programs list is shown\n DisabledValue = 0, // When toggle is OFF, frequently used programs list is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls frequently used programs list visibility\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"power-lock-option\",\n Name = \"Lock Option\",\n Description = \"Controls whether the lock option is shown in the Start menu\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Start Menu\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\FlyoutMenuSettings\",\n Name = \"ShowLockOption\",\n RecommendedValue = 1,\n EnabledValue = 1, // Show lock option\n DisabledValue = 0, // Hide lock option\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description =\n \"Controls whether the lock option is shown in the Start menu\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"show-recommended-files\",\n Name = \"Show Recommended Files\",\n Description = \"Controls visibility of recommended files in Start Menu\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Start Menu Settings\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"Start_TrackDocs\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, recommended files are shown\n DisabledValue = 0, // When toggle is OFF, recommended files are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls visibility of recommended files in Start Menu\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n },\n };\n }\n\n public static void ApplyStartMenuLayout(bool isWindows11, ISystemServices windowsService)\n {\n if (isWindows11)\n {\n ApplyWindows11Layout();\n }\n else\n {\n ApplyWindows10Layout(windowsService);\n }\n }\n\n private static void ApplyWindows10Layout(ISystemServices windowsService)\n {\n // Delete existing layout file\n if (File.Exists(Win10StartLayoutPath))\n {\n File.Delete(Win10StartLayoutPath);\n }\n\n // Create new layout file\n File.WriteAllText(Win10StartLayoutPath, StartMenuLayouts.Windows10Layout);\n\n // Use the improved RefreshWindowsGUI method to restart Explorer and apply changes\n // This will ensure Explorer is restarted properly with retry logic and fallback\n var result = windowsService.RefreshWindowsGUI(true).GetAwaiter().GetResult();\n if (!result)\n {\n throw new Exception(\"Failed to refresh Windows GUI after applying Start Menu layout\");\n }\n }\n\n private static void ApplyWindows11Layout()\n {\n string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);\n string start2BinPath = Path.Combine(userProfile, Win11StartBinPath);\n string tempPath = Path.GetTempPath();\n\n // Delete existing start2.bin if it exists\n if (File.Exists(start2BinPath))\n {\n File.Delete(start2BinPath);\n }\n\n // Create temp file with cert content\n string tempTxtPath = Path.Combine(tempPath, \"start2.txt\");\n string tempBinPath = Path.Combine(tempPath, \"start2.bin\");\n\n try\n {\n // Write certificate content to temp file\n File.WriteAllText(tempTxtPath, StartMenuLayouts.Windows11StartBinCertificate);\n\n // Use certutil to decode the certificate\n using (var process = new System.Diagnostics.Process())\n {\n process.StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"certutil.exe\",\n Arguments = $\"-decode \\\"{tempTxtPath}\\\" \\\"{tempBinPath}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n CreateNoWindow = true,\n };\n\n process.Start();\n process.WaitForExit();\n }\n\n // Ensure directory exists\n Directory.CreateDirectory(Path.GetDirectoryName(start2BinPath)!);\n\n // Copy the decoded binary to the Start Menu location\n File.Copy(tempBinPath, start2BinPath, true);\n }\n finally\n {\n // Clean up temp files\n if (File.Exists(tempTxtPath))\n File.Delete(tempTxtPath);\n if (File.Exists(tempBinPath))\n File.Delete(tempBinPath);\n }\n }\n\n /// \n /// Cleans the Start Menu for Windows 10 or Windows 11.\n /// \n /// Whether the system is Windows 11.\n /// The system services.\n public static void CleanStartMenu(bool isWindows11, ISystemServices windowsService)\n {\n if (isWindows11)\n {\n CleanWindows11StartMenu();\n }\n else\n {\n CleanWindows10StartMenu(windowsService);\n }\n }\n\n /// \n /// Cleans the Windows 11 Start Menu by replacing the start2.bin file.\n /// \n private static void CleanWindows11StartMenu()\n {\n // This is essentially the same as ApplyWindows11Layout since we're replacing the start2.bin file\n string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);\n string start2BinPath = Path.Combine(userProfile, Win11StartBinPath);\n string tempPath = Path.GetTempPath();\n\n // Delete existing start2.bin if it exists\n if (File.Exists(start2BinPath))\n {\n File.Delete(start2BinPath);\n }\n\n // Create temp file with cert content\n string tempTxtPath = Path.Combine(tempPath, \"start2.txt\");\n string tempBinPath = Path.Combine(tempPath, \"start2.bin\");\n\n try\n {\n // Write certificate content to temp file\n File.WriteAllText(tempTxtPath, StartMenuLayouts.Windows11StartBinCertificate);\n\n // Use certutil to decode the certificate\n using (var process = new System.Diagnostics.Process())\n {\n process.StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"certutil.exe\",\n Arguments = $\"-decode \\\"{tempTxtPath}\\\" \\\"{tempBinPath}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n CreateNoWindow = true,\n };\n\n process.Start();\n process.WaitForExit();\n }\n\n // Ensure directory exists\n Directory.CreateDirectory(Path.GetDirectoryName(start2BinPath)!);\n\n // Copy the decoded binary to the Start Menu location\n File.Copy(tempBinPath, start2BinPath, true);\n }\n finally\n {\n // Clean up temp files\n if (File.Exists(tempTxtPath))\n File.Delete(tempTxtPath);\n if (File.Exists(tempBinPath))\n File.Delete(tempBinPath);\n }\n }\n\n /// \n /// Cleans the Windows 10 Start Menu by creating and then removing a StartMenuLayout.xml file.\n /// \n /// The system services.\n private static void CleanWindows10StartMenu(ISystemServices windowsService)\n {\n try\n {\n // Delete existing layout file if it exists\n if (File.Exists(Win10StartLayoutPath))\n {\n File.Delete(Win10StartLayoutPath);\n }\n\n // Create new layout file with clean layout\n File.WriteAllText(Win10StartLayoutPath, StartMenuLayouts.Windows10Layout);\n\n // Set registry values to lock the Start Menu layout\n using (\n var key = Registry.LocalMachine.CreateSubKey(\n @\"SOFTWARE\\Policies\\Microsoft\\Windows\\Explorer\"\n )\n )\n {\n if (key != null)\n {\n key.SetValue(\"LockedStartLayout\", 1, RegistryValueKind.DWord);\n key.SetValue(\"StartLayoutFile\", Win10StartLayoutPath, RegistryValueKind.String);\n }\n }\n\n using (\n var key = Registry.CurrentUser.CreateSubKey(\n @\"SOFTWARE\\Policies\\Microsoft\\Windows\\Explorer\"\n )\n )\n {\n if (key != null)\n {\n key.SetValue(\"LockedStartLayout\", 1, RegistryValueKind.DWord);\n key.SetValue(\"StartLayoutFile\", Win10StartLayoutPath, RegistryValueKind.String);\n }\n }\n\n // Use the improved RefreshWindowsGUI method to restart Explorer and apply changes\n // This will ensure Explorer is restarted properly with retry logic and fallback\n var result = windowsService.RefreshWindowsGUI(true).GetAwaiter().GetResult();\n if (!result)\n {\n throw new Exception(\n \"Failed to refresh Windows GUI after applying Start Menu layout\"\n );\n }\n\n // Wait for changes to take effect\n System.Threading.Thread.Sleep(3000);\n\n // Disable the locked Start Menu layout\n using (\n var key = Registry.LocalMachine.CreateSubKey(\n @\"SOFTWARE\\Policies\\Microsoft\\Windows\\Explorer\"\n )\n )\n {\n if (key != null)\n {\n key.SetValue(\"LockedStartLayout\", 0, RegistryValueKind.DWord);\n }\n }\n\n using (\n var key = Registry.CurrentUser.CreateSubKey(\n @\"SOFTWARE\\Policies\\Microsoft\\Windows\\Explorer\"\n )\n )\n {\n if (key != null)\n {\n key.SetValue(\"LockedStartLayout\", 0, RegistryValueKind.DWord);\n }\n }\n\n // Use the improved RefreshWindowsGUI method again to apply the final changes\n result = windowsService.RefreshWindowsGUI(true).GetAwaiter().GetResult();\n if (!result)\n {\n throw new Exception(\n \"Failed to refresh Windows GUI after unlocking Start Menu layout\"\n );\n }\n\n // Delete the layout file\n if (File.Exists(Win10StartLayoutPath))\n {\n File.Delete(Win10StartLayoutPath);\n }\n }\n catch (Exception ex)\n {\n // Log the exception or handle it as needed\n System.Diagnostics.Debug.WriteLine(\n $\"Error cleaning Windows 10 Start Menu: {ex.Message}\"\n );\n throw new Exception($\"Error cleaning Windows 10 Start Menu: {ex.Message}\", ex);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/FeatureInstallationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that enables Windows optional features.\n/// \npublic class FeatureInstallationService : BaseInstallationService, IFeatureInstallationService\n{\n private readonly FeatureCatalog _featureCatalog;\n private readonly IScriptUpdateService _scriptUpdateService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The PowerShell execution service.\n /// The script update service.\n public FeatureInstallationService(\n ILogService logService,\n IPowerShellExecutionService powerShellService,\n IScriptUpdateService scriptUpdateService)\n : base(logService, powerShellService)\n {\n // Create a default feature catalog\n _featureCatalog = FeatureCatalog.CreateDefault();\n _scriptUpdateService = scriptUpdateService ?? throw new ArgumentNullException(nameof(scriptUpdateService));\n }\n\n /// \n public Task> InstallFeatureAsync(\n FeatureInfo featureInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n return InstallItemAsync(featureInfo, progress, cancellationToken);\n }\n\n /// \n public Task> CanInstallFeatureAsync(FeatureInfo featureInfo)\n {\n return CanInstallItemAsync(featureInfo);\n }\n\n /// \n protected override async Task> PerformInstallationAsync(\n FeatureInfo featureInfo,\n IProgress? progress,\n CancellationToken cancellationToken)\n {\n var result = await InstallFeatureAsync(featureInfo.PackageName, progress, cancellationToken);\n \n // Only update BloatRemoval.ps1 script if installation was successful\n if (result.Success)\n {\n try\n {\n _logService.LogInformation($\"Starting BloatRemoval.ps1 script update for {featureInfo.Name}\");\n \n // Update the BloatRemoval.ps1 script to remove the installed feature from the removal list\n var appNames = new List { featureInfo.PackageName };\n _logService.LogInformation($\"Removing feature name from BloatRemoval.ps1: {featureInfo.PackageName}\");\n \n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n\n // Add registry settings if present\n if (featureInfo.RegistrySettings != null && featureInfo.RegistrySettings.Length > 0)\n {\n _logService.LogInformation($\"Adding {featureInfo.RegistrySettings.Length} registry settings for {featureInfo.Name}\");\n appsWithRegistry.Add(featureInfo.PackageName, new List(featureInfo.RegistrySettings));\n }\n\n _logService.LogInformation($\"Updating BloatRemoval.ps1 to remove {featureInfo.Name} from removal list\");\n \n // Make sure we're explicitly identifying this as an optional feature\n _logService.LogInformation($\"Ensuring {featureInfo.Name} is identified as an optional feature\");\n \n var scriptResult = await _scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n true); // true = install operation, so remove from script\n \n _logService.LogInformation($\"Successfully updated BloatRemoval.ps1 script - {featureInfo.Name} will no longer be removed\");\n _logService.LogInformation($\"Script update result: {scriptResult?.Name ?? \"null\"}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for {featureInfo.Name}\", ex);\n _logService.LogError($\"Exception details: {ex.Message}\");\n _logService.LogError($\"Stack trace: {ex.StackTrace}\");\n // Don't fail the installation if script update fails\n }\n }\n else\n {\n _logService.LogInformation($\"Skipping BloatRemoval.ps1 update because installation of {featureInfo.Name} was not successful\");\n }\n \n return result;\n }\n\n\n /// \n /// Installs a Windows optional feature by name.\n /// \n /// The name of the feature to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n private async Task> InstallFeatureAsync(\n string featureName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n try\n {\n // Get the friendly name of the feature from the catalog\n string friendlyName = GetFriendlyName(featureName);\n \n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Enabling {friendlyName}...\",\n DetailedMessage = $\"Starting to enable optional feature: {featureName}\"\n });\n\n _logService.LogInformation($\"Attempting to enable optional feature: {featureName}\");\n \n // Create a progress handler that overrides the generic \"Operation: Running\" text\n var progressHandler = new Progress(detail => {\n // If we get a generic \"Operation: Running\" status, replace it with our more descriptive one\n if (detail.StatusText != null && detail.StatusText.StartsWith(\"Operation:\"))\n {\n // Keep the percentage but replace the generic text with the friendly name\n detail.StatusText = $\"Enabling {friendlyName}...\";\n if (detail.Progress.HasValue)\n {\n detail.StatusText = $\"Enabling {friendlyName}... ({detail.Progress:F0}%)\";\n }\n }\n \n // Forward the updated progress to the original progress reporter\n progress?.Report(detail);\n });\n\n // Define the PowerShell script - Embed featureName, output parseable string\n // Output format: STATUS|Message|RebootRequired (e.g., SUCCESS|Feature enabled|True)\n string script = $@\"\n try {{\n $featureName = '{featureName}' # Embed featureName directly\n Write-Information \"\"Checking feature status: $featureName\"\"\n # Progress reporting needs to be handled by the caller based on script output or duration\n\n # Check if the feature exists\n $feature = Get-WindowsOptionalFeature -Online -FeatureName $featureName -ErrorAction SilentlyContinue\n\n if (-not $feature) {{\n Write-Warning \"\"Feature not found: $featureName\"\"\n return \"\"FAILURE|Feature not found: $featureName\"\"\n }}\n\n # Check if the feature is already enabled\n if ($feature.State -eq 'Enabled') {{\n Write-Information \"\"Feature is already enabled: $featureName\"\"\n return \"\"SUCCESS|Feature is already enabled|False\"\"\n }}\n\n Write-Information \"\"Enabling feature: $featureName\"\"\n\n # Enable the feature\n $result = Enable-WindowsOptionalFeature -Online -FeatureName $featureName -NoRestart\n\n # Check if the feature was enabled successfully\n $feature = Get-WindowsOptionalFeature -Online -FeatureName $featureName\n\n if ($feature.State -eq 'Enabled') {{\n $rebootNeeded = if ($result.RestartNeeded) {{ 'True' }} else {{ 'False' }}\n return \"\"SUCCESS|Feature enabled successfully|$rebootNeeded\"\"\n }} else {{\n Write-Warning \"\"Failed to enable feature: $featureName\"\"\n return \"\"FAILURE|Failed to enable feature\"\"\n }}\n }}\n catch {{\n Write-Error \"\"Error enabling feature: $($_.Exception.Message)\"\"\n return \"\"FAILURE|$($_.Exception.Message)\"\"\n }}\n \";\n\n // Execute PowerShell using the correct interface method with our custom progress handler\n string resultString = await _powerShellService.ExecuteScriptAsync(\n script,\n progressHandler, // Use our custom progress handler instead of passing progress directly\n cancellationToken);\n\n // Process the result string\n if (!string.IsNullOrEmpty(resultString))\n {\n var parts = resultString.Split('|');\n if (parts.Length >= 2)\n {\n string status = parts[0];\n string message = parts[1];\n bool rebootRequired = parts.Length > 2 && bool.TryParse(parts[2], out bool req) && req;\n\n if (status.Equals(\"SUCCESS\", StringComparison.OrdinalIgnoreCase))\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 100,\n StatusText = $\"Successfully enabled {GetFriendlyName(featureName)}\",\n DetailedMessage = message\n });\n _logService.LogSuccess($\"Successfully enabled optional feature: {featureName}. {message}\");\n\n if (rebootRequired)\n {\n progress?.Report(new TaskProgressDetail\n {\n StatusText = \"A system restart is required to complete the installation\",\n DetailedMessage = \"Please restart your computer to complete the installation\",\n LogLevel = LogLevel.Warning\n });\n _logService.LogWarning($\"A system restart is required for {GetFriendlyName(featureName)}\");\n }\n return OperationResult.Succeeded(true); // Indicate success\n }\n else // FAILURE\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0, // Indicate failure\n StatusText = $\"Failed to enable {GetFriendlyName(featureName)}\",\n DetailedMessage = message,\n LogLevel = LogLevel.Error\n });\n _logService.LogError($\"Failed to enable optional feature: {featureName}. {message}\");\n return OperationResult.Failed(message); // Indicate failure with message\n }\n }\n else\n {\n // Handle unexpected script output format\n _logService.LogError($\"Unexpected script output format for {featureName}: {resultString}\");\n progress?.Report(new TaskProgressDetail { StatusText = \"Error processing script result\", LogLevel = LogLevel.Error });\n return OperationResult.Failed(\"Unexpected script output format: \" + resultString); // Indicate failure with message\n }\n }\n else\n {\n // Handle case where script returned empty string\n _logService.LogError($\"Empty result returned when enabling optional feature: {featureName}\");\n progress?.Report(new TaskProgressDetail { StatusText = \"Script returned no result\", LogLevel = LogLevel.Error });\n return OperationResult.Failed(\"Script returned no result\"); // Indicate failure with message\n }\n }\n catch (OperationCanceledException)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Operation cancelled when enabling {GetFriendlyName(featureName)}\",\n DetailedMessage = \"The operation was cancelled by the user\",\n LogLevel = LogLevel.Warning,\n }\n );\n\n _logService.LogWarning($\"Operation cancelled when enabling optional feature: {featureName}\");\n return OperationResult.Failed(\"The operation was cancelled by the user\"); // Return cancellation result\n }\n catch (Exception ex)\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Error enabling {GetFriendlyName(featureName)}\",\n DetailedMessage = $\"Exception: {ex.Message}\",\n LogLevel = LogLevel.Error\n });\n _logService.LogError($\"Error enabling optional feature: {featureName}\", ex);\n return OperationResult.Failed($\"Error enabling optional feature: {ex.Message}\", ex); // Indicate failure with exception\n }\n }\n\n /// \n /// Gets the friendly name of a feature from its package name.\n /// \n /// The package name of the feature.\n /// The friendly name of the feature, or the package name if not found.\n private string GetFriendlyName(string packageName)\n {\n // Look up the feature in the catalog by its package name\n var feature = _featureCatalog.Features.FirstOrDefault(f => \n f.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase));\n \n // Return the friendly name if found, otherwise return the package name\n return feature?.Name ?? packageName;\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/TaskProgressService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Threading;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service that manages task progress reporting across the application.\n /// \n public class TaskProgressService : ITaskProgressService\n {\n private readonly ILogService _logService;\n private int _currentProgress;\n private string _currentStatusText;\n private bool _isTaskRunning;\n private bool _isIndeterminate;\n private List _logMessages = new List();\n private CancellationTokenSource _cancellationSource;\n\n /// \n /// Gets whether a task is currently running.\n /// \n public bool IsTaskRunning => _isTaskRunning;\n\n /// \n /// Gets the current progress value (0-100).\n /// \n public int CurrentProgress => _currentProgress;\n\n /// \n /// Gets the current status text.\n /// \n public string CurrentStatusText => _currentStatusText;\n\n /// \n /// Gets whether the current task is in indeterminate mode.\n /// \n public bool IsIndeterminate => _isIndeterminate;\n\n /// \n /// Gets the cancellation token source for the current task.\n /// \n public CancellationTokenSource? CurrentTaskCancellationSource => _cancellationSource;\n\n /// \n /// Event raised when progress changes.\n /// \n public event EventHandler? ProgressUpdated;\n\n /// \n /// Event raised when progress changes (compatibility with App.xaml.cs).\n /// \n public event EventHandler? ProgressChanged;\n\n /// \n /// Event raised when a log message is added.\n /// \n public event EventHandler? LogMessageAdded;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public TaskProgressService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _currentProgress = 0;\n _currentStatusText = string.Empty;\n _isTaskRunning = false;\n _isIndeterminate = false;\n }\n\n /// \n /// Starts a new task with the specified name.\n /// \n /// The name of the task.\n /// Whether the task progress is indeterminate.\n /// A cancellation token source for the task.\n public CancellationTokenSource StartTask(string taskName, bool isIndeterminate = false)\n {\n // Cancel any existing task\n CancelCurrentTask();\n\n if (string.IsNullOrEmpty(taskName))\n {\n throw new ArgumentException(\"Task name cannot be null or empty.\", nameof(taskName));\n }\n\n _cancellationSource = new CancellationTokenSource();\n _currentProgress = 0;\n _currentStatusText = taskName;\n _isTaskRunning = true;\n _isIndeterminate = isIndeterminate;\n _logMessages.Clear();\n\n _logService.Log(LogLevel.Info, $\"Task started: {taskName}\"); // Corrected Log call\n AddLogMessage($\"Task started: {taskName}\");\n OnProgressChanged(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = taskName,\n IsIndeterminate = isIndeterminate,\n }\n );\n\n return _cancellationSource;\n }\n\n /// \n /// Updates the progress of the current task.\n /// \n /// The progress percentage (0-100).\n /// The status text.\n public void UpdateProgress(int progressPercentage, string? statusText = null)\n {\n if (!_isTaskRunning)\n {\n Debug.WriteLine(\"Warning: Attempting to update progress when no task is running.\");\n return;\n }\n\n if (progressPercentage < 0 || progressPercentage > 100)\n {\n throw new ArgumentOutOfRangeException(\n nameof(progressPercentage),\n \"Progress must be between 0 and 100.\"\n );\n }\n\n _currentProgress = progressPercentage;\n if (!string.IsNullOrEmpty(statusText))\n {\n _currentStatusText = statusText;\n _logService.Log(\n LogLevel.Info,\n $\"Task progress ({progressPercentage}%): {statusText}\"\n ); // Corrected Log call\n AddLogMessage($\"Task progress ({progressPercentage}%): {statusText}\");\n }\n else\n {\n _logService.Log(LogLevel.Info, $\"Task progress: {progressPercentage}%\"); // Corrected Log call\n AddLogMessage($\"Task progress: {progressPercentage}%\");\n }\n OnProgressChanged(\n new TaskProgressDetail\n {\n Progress = progressPercentage,\n StatusText = _currentStatusText,\n }\n );\n }\n\n /// \n /// Updates the progress with detailed information.\n /// \n /// The detailed progress information.\n public void UpdateDetailedProgress(TaskProgressDetail detail)\n {\n if (!_isTaskRunning)\n {\n Debug.WriteLine(\n \"Warning: Attempting to update detailed progress when no task is running.\"\n );\n return;\n }\n\n if (detail.Progress.HasValue)\n {\n if (detail.Progress.Value < 0 || detail.Progress.Value > 100)\n {\n throw new ArgumentOutOfRangeException(\n nameof(detail.Progress),\n \"Progress must be between 0 and 100.\"\n );\n }\n\n _currentProgress = (int)detail.Progress.Value;\n }\n\n if (!string.IsNullOrEmpty(detail.StatusText))\n {\n _currentStatusText = detail.StatusText;\n }\n\n _isIndeterminate = detail.IsIndeterminate;\n if (!string.IsNullOrEmpty(detail.DetailedMessage))\n {\n _logService.Log(detail.LogLevel, detail.DetailedMessage); // Corrected Log call\n AddLogMessage(detail.DetailedMessage);\n }\n OnProgressChanged(detail);\n }\n\n /// \n /// Completes the current task.\n /// \n public void CompleteTask()\n {\n if (!_isTaskRunning)\n {\n Debug.WriteLine(\"Warning: Attempting to complete a task when no task is running.\");\n return;\n }\n\n _currentProgress = 100;\n\n _isTaskRunning = false;\n _isIndeterminate = false;\n\n _logService.Log(LogLevel.Info, $\"Task completed: {_currentStatusText}\"); // Corrected Log call\n AddLogMessage($\"Task completed: {_currentStatusText}\");\n\n OnProgressChanged(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = _currentStatusText,\n DetailedMessage = \"Task completed\",\n }\n );\n\n // Dispose cancellation token source\n _cancellationSource?.Dispose();\n _cancellationSource = null;\n }\n\n /// \n /// Adds a log message.\n /// \n /// The message content.\n public void AddLogMessage(string message)\n {\n if (string.IsNullOrEmpty(message))\n return;\n\n _logMessages.Add(message);\n LogMessageAdded?.Invoke(this, message);\n }\n\n /// \n /// Cancels the current task.\n /// \n public void CancelCurrentTask()\n {\n if (_cancellationSource != null && !_cancellationSource.IsCancellationRequested)\n {\n _cancellationSource.Cancel();\n AddLogMessage(\"Task cancelled by user\");\n\n // Don't dispose here, as the task might still be using it\n // It will be disposed in CompleteTask or when a new task starts\n }\n }\n\n /// \n /// Creates a progress reporter for detailed progress.\n /// \n /// The progress reporter.\n public IProgress CreateDetailedProgress()\n {\n return new Progress(UpdateDetailedProgress);\n }\n\n /// \n /// Creates a progress reporter for PowerShell progress.\n /// \n /// The progress reporter.\n public IProgress CreatePowerShellProgress()\n {\n return new Progress(UpdateDetailedProgress);\n }\n\n /// \n /// Creates a progress adapter for PowerShell progress data.\n /// \n /// A progress adapter for PowerShell progress data.\n public IProgress CreatePowerShellProgressAdapter()\n {\n return new Progress(data =>\n {\n var detail = new TaskProgressDetail();\n\n // Map PowerShell progress data to task progress detail\n if (data.PercentComplete.HasValue)\n {\n detail.Progress = data.PercentComplete.Value;\n }\n\n if (!string.IsNullOrEmpty(data.Activity))\n {\n detail.StatusText = data.Activity;\n if (!string.IsNullOrEmpty(data.StatusDescription))\n {\n detail.StatusText += $\": {data.StatusDescription}\";\n }\n }\n\n detail.DetailedMessage = data.Message ?? data.CurrentOperation;\n\n // Map stream type to log level\n switch (data.StreamType)\n {\n case PowerShellStreamType.Error:\n detail.LogLevel = LogLevel.Error;\n break;\n case PowerShellStreamType.Warning:\n detail.LogLevel = LogLevel.Warning;\n break;\n case PowerShellStreamType.Verbose:\n case PowerShellStreamType.Debug:\n detail.LogLevel = LogLevel.Debug;\n break;\n default:\n detail.LogLevel = LogLevel.Info;\n break;\n }\n\n UpdateDetailedProgress(detail);\n });\n }\n\n /// \n /// Raises the ProgressUpdated event.\n /// \n protected virtual void OnProgressChanged(TaskProgressDetail detail)\n {\n ProgressUpdated?.Invoke(this, detail);\n ProgressChanged?.Invoke(\n this,\n TaskProgressEventArgs.FromTaskProgressDetail(detail, _isTaskRunning)\n );\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScheduledTaskService.cs", "using System;\nusing System.IO;\nusing System.Management.Automation;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Service for registering and managing scheduled tasks for script execution.\n /// \n public class ScheduledTaskService : IScheduledTaskService\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public ScheduledTaskService(ILogService logService)\n {\n _logService = logService;\n }\n\n /// \n public async Task RegisterScheduledTaskAsync(RemovalScript script)\n {\n try\n {\n _logService.LogInformation($\"Registering scheduled task for script: {script?.Name ?? \"Unknown\"}\");\n \n // Ensure the script and script path are valid\n if (script == null)\n {\n _logService.LogError(\"Script object is null\");\n return false;\n }\n\n // Ensure the script name is not empty\n if (string.IsNullOrEmpty(script.Name))\n {\n _logService.LogError(\"Script name is empty\");\n return false;\n }\n\n // Ensure the script path exists\n string scriptPath = script.ScriptPath;\n if (!File.Exists(scriptPath))\n {\n _logService.LogError($\"Script file not found at: {scriptPath}\");\n \n // Try to save the script if it doesn't exist but has content\n if (!string.IsNullOrEmpty(script.Content))\n {\n try\n {\n string directoryPath = Path.GetDirectoryName(scriptPath);\n if (!Directory.Exists(directoryPath))\n {\n Directory.CreateDirectory(directoryPath);\n }\n \n File.WriteAllText(scriptPath, script.Content);\n _logService.LogInformation($\"Created script file at: {scriptPath}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to create script file: {ex.Message}\");\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n // Create the scheduled task using a direct PowerShell command\n string taskName = !string.IsNullOrEmpty(script.TargetScheduledTaskName) \n ? script.TargetScheduledTaskName \n : $\"Winhance\\\\{script.Name}\";\n\n // Create a simple PowerShell script that registers the task\n string psScript = $@\"\n# Register the scheduled task\n$scriptPath = '{scriptPath.Replace(\"'\", \"''\")}' # Escape single quotes\n$taskName = '{taskName.Replace(\"'\", \"''\")}'\n\n# Check if the task already exists and remove it\ntry {{\n $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue\n if ($existingTask) {{\n Write-Output \"\"Removing existing task: $taskName\"\"\n Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction Stop\n }}\n}} catch {{\n Write-Output \"\"Error removing existing task: $($_.Exception.Message)\"\"\n}}\n\n# Create the action to run the PowerShell script\ntry {{\n $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument \"\"-ExecutionPolicy Bypass -File `\"\"$scriptPath`\"\"\"\"\n $trigger = New-ScheduledTaskTrigger -AtStartup\n $settings = New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries\n \n # Register the task\n Register-ScheduledTask -TaskName $taskName `\n -Action $action `\n -Trigger $trigger `\n -User \"\"SYSTEM\"\" `\n -RunLevel Highest `\n -Settings $settings `\n -Force -ErrorAction Stop\n \n Write-Output \"\"Successfully registered scheduled task: $taskName\"\"\n exit 0\n}} catch {{\n Write-Output \"\"Error registering scheduled task: $($_.Exception.Message)\"\"\n exit 1\n}}\n\";\n\n // Save the script to a temporary file\n string tempScriptPath = Path.Combine(Path.GetTempPath(), $\"RegisterTask_{Guid.NewGuid()}.ps1\");\n File.WriteAllText(tempScriptPath, psScript);\n\n try\n {\n // Execute the script with elevated privileges\n using var process = new System.Diagnostics.Process();\n process.StartInfo.FileName = \"powershell.exe\";\n process.StartInfo.Arguments = $\"-ExecutionPolicy Bypass -File \\\"{tempScriptPath}\\\"\";\n process.StartInfo.UseShellExecute = true;\n process.StartInfo.Verb = \"runas\"; // Run as administrator\n process.StartInfo.CreateNoWindow = false;\n process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\n \n process.Start();\n await process.WaitForExitAsync();\n \n // Check if the process exited successfully\n if (process.ExitCode == 0)\n {\n _logService.LogSuccess($\"Successfully registered scheduled task: {taskName}\");\n return true;\n }\n else\n {\n _logService.LogError($\"Failed to register scheduled task: {taskName}, exit code: {process.ExitCode}\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error executing scheduled task registration script: {ex.Message}\");\n return false;\n }\n finally\n {\n // Clean up the temporary script\n try\n {\n if (File.Exists(tempScriptPath))\n {\n File.Delete(tempScriptPath);\n }\n }\n catch\n {\n // Ignore errors when deleting the temp file\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error registering scheduled task for script: {script?.Name ?? \"Unknown\"}\", ex);\n return false;\n }\n }\n\n /// \n public async Task UnregisterScheduledTaskAsync(string taskName)\n {\n try\n {\n _logService.LogInformation($\"Unregistering scheduled task: {taskName}\");\n \n // Create a simple PowerShell script that unregisters the task\n string psScript = $@\"\n# Unregister the scheduled task\n$taskName = '{taskName.Replace(\"'\", \"''\")}'\n\ntry {{\n $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue\n if ($existingTask) {{\n Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction Stop\n Write-Output \"\"Successfully unregistered task: $taskName\"\"\n exit 0\n }} else {{\n Write-Output \"\"Task not found: $taskName\"\"\n exit 0 # Not an error if the task doesn't exist\n }}\n}} catch {{\n Write-Output \"\"Error unregistering task: $($_.Exception.Message)\"\"\n exit 1\n}}\n\";\n\n // Save the script to a temporary file\n string tempScriptPath = Path.Combine(Path.GetTempPath(), $\"UnregisterTask_{Guid.NewGuid()}.ps1\");\n File.WriteAllText(tempScriptPath, psScript);\n\n try\n {\n // Execute the script with elevated privileges\n using var process = new System.Diagnostics.Process();\n process.StartInfo.FileName = \"powershell.exe\";\n process.StartInfo.Arguments = $\"-ExecutionPolicy Bypass -File \\\"{tempScriptPath}\\\"\";\n process.StartInfo.UseShellExecute = true;\n process.StartInfo.Verb = \"runas\"; // Run as administrator\n process.StartInfo.CreateNoWindow = false;\n process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\n \n process.Start();\n await process.WaitForExitAsync();\n \n // Check if the process exited successfully\n if (process.ExitCode == 0)\n {\n _logService.LogSuccess($\"Successfully unregistered scheduled task: {taskName}\");\n return true;\n }\n else\n {\n _logService.LogError($\"Failed to unregister scheduled task: {taskName}, exit code: {process.ExitCode}\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error executing scheduled task unregistration script: {ex.Message}\");\n return false;\n }\n finally\n {\n // Clean up the temporary script\n try\n {\n if (File.Exists(tempScriptPath))\n {\n File.Delete(tempScriptPath);\n }\n }\n catch\n {\n // Ignore errors when deleting the temp file\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error unregistering scheduled task: {taskName}\", ex);\n return false;\n }\n }\n\n /// \n public async Task IsTaskRegisteredAsync(string taskName)\n {\n try\n {\n // Create a simple PowerShell script that checks if the task exists\n string psScript = $@\"\n# Check if the scheduled task exists\n$taskName = '{taskName.Replace(\"'\", \"''\")}'\n\ntry {{\n $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue\n if ($existingTask) {{\n Write-Output \"\"Task exists: $taskName\"\"\n exit 0 # Exit code 0 means the task exists\n }} else {{\n Write-Output \"\"Task does not exist: $taskName\"\"\n exit 1 # Exit code 1 means the task does not exist\n }}\n}} catch {{\n Write-Output \"\"Error checking task: $($_.Exception.Message)\"\"\n exit 2 # Exit code 2 means an error occurred\n}}\n\";\n\n // Save the script to a temporary file\n string tempScriptPath = Path.Combine(Path.GetTempPath(), $\"CheckTask_{Guid.NewGuid()}.ps1\");\n File.WriteAllText(tempScriptPath, psScript);\n\n try\n {\n // Execute the script\n using var process = new System.Diagnostics.Process();\n process.StartInfo.FileName = \"powershell.exe\";\n process.StartInfo.Arguments = $\"-ExecutionPolicy Bypass -File \\\"{tempScriptPath}\\\"\";\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.CreateNoWindow = true;\n \n process.Start();\n await process.WaitForExitAsync();\n \n // Check the exit code to determine if the task exists\n return process.ExitCode == 0;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error executing scheduled task check script: {ex.Message}\");\n return false;\n }\n finally\n {\n // Clean up the temporary script\n try\n {\n if (File.Exists(tempScriptPath))\n {\n File.Delete(tempScriptPath);\n }\n }\n catch\n {\n // Ignore errors when deleting the temp file\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking if task exists: {taskName}\", ex);\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppInstallationCoordinatorService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Coordinates the installation of applications, handling connectivity monitoring,\n /// user notifications, and installation state management.\n /// \n public class AppInstallationCoordinatorService : IAppInstallationCoordinatorService\n {\n private readonly IAppInstallationService _appInstallationService;\n private readonly IInternetConnectivityService _connectivityService;\n private readonly ILogService _logService;\n private readonly INotificationService _notificationService;\n private readonly IDialogService _dialogService;\n \n /// \n /// Event that is raised when the installation status changes.\n /// \n public event EventHandler InstallationStatusChanged;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The application installation service.\n /// The internet connectivity service.\n /// The logging service.\n /// The notification service.\n /// The dialog service.\n public AppInstallationCoordinatorService(\n IAppInstallationService appInstallationService,\n IInternetConnectivityService connectivityService,\n ILogService logService,\n INotificationService notificationService = null,\n IDialogService dialogService = null)\n {\n _appInstallationService = appInstallationService ?? throw new ArgumentNullException(nameof(appInstallationService));\n _connectivityService = connectivityService ?? throw new ArgumentNullException(nameof(connectivityService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _notificationService = notificationService;\n _dialogService = dialogService;\n }\n\n /// \n /// Installs an application with connectivity monitoring and proper cancellation handling.\n /// \n /// The application information.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the installation operation with the result.\n public async Task InstallAppAsync(\n AppInfo appInfo,\n IProgress progress,\n CancellationToken cancellationToken = default)\n {\n if (appInfo == null)\n throw new ArgumentNullException(nameof(appInfo));\n \n // Create a linked cancellation token source that will be cancelled if either:\n // 1. The original cancellation token is cancelled (user initiated)\n // 2. We detect a connectivity issue and cancel the installation\n using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n \n // Update status\n var initialStatus = $\"Installing {appInfo.Name}...\";\n RaiseStatusChanged(appInfo, initialStatus);\n \n // Start connectivity monitoring\n var connectivityMonitoringTask = StartConnectivityMonitoring(appInfo, linkedCts);\n \n try\n {\n // Perform the installation\n var installationResult = await _appInstallationService.InstallAppAsync(\n appInfo, \n progress, \n linkedCts.Token);\n \n // Stop connectivity monitoring\n linkedCts.Cancel();\n try { await connectivityMonitoringTask; } catch (OperationCanceledException) { /* Expected */ }\n \n if (installationResult.Success)\n {\n var successMessage = $\"Successfully installed {appInfo.Name}\";\n RaiseStatusChanged(appInfo, successMessage, true, true);\n \n return new InstallationCoordinationResult\n {\n Success = true,\n AppInfo = appInfo\n };\n }\n else\n {\n var errorMessage = installationResult.ErrorMessage ?? $\"Failed to install {appInfo.Name}\";\n RaiseStatusChanged(appInfo, errorMessage, true, false);\n \n return new InstallationCoordinationResult\n {\n Success = false,\n ErrorMessage = errorMessage,\n AppInfo = appInfo\n };\n }\n }\n catch (OperationCanceledException)\n {\n // Stop connectivity monitoring\n linkedCts.Cancel();\n try { await connectivityMonitoringTask; } catch (OperationCanceledException) { /* Expected */ }\n \n // Determine if this was a user cancellation or a connectivity issue\n bool wasConnectivityIssue = await connectivityMonitoringTask.ContinueWith(t => \n {\n // If the task completed normally, check its result\n if (t.Status == TaskStatus.RanToCompletion)\n {\n return t.Result;\n }\n // If the task was cancelled, assume it was a user cancellation\n return false;\n });\n \n if (wasConnectivityIssue)\n {\n var connectivityMessage = $\"Installation of {appInfo.Name} was stopped due to internet connectivity issues\";\n RaiseStatusChanged(appInfo, connectivityMessage, true, false, false, true);\n \n return new InstallationCoordinationResult\n {\n Success = false,\n WasCancelled = false,\n WasConnectivityIssue = true,\n ErrorMessage = \"Internet connection lost during installation. Please check your network connection and try again.\",\n AppInfo = appInfo\n };\n }\n else\n {\n var cancelMessage = $\"Installation of {appInfo.Name} was cancelled by user\";\n RaiseStatusChanged(appInfo, cancelMessage, true, false, true);\n \n return new InstallationCoordinationResult\n {\n Success = false,\n WasCancelled = true,\n WasConnectivityIssue = false,\n ErrorMessage = \"Installation was cancelled by user\",\n AppInfo = appInfo\n };\n }\n }\n catch (Exception ex)\n {\n // Stop connectivity monitoring\n linkedCts.Cancel();\n try { await connectivityMonitoringTask; } catch (OperationCanceledException) { /* Expected */ }\n \n // Log the error\n _logService.LogError($\"Error installing {appInfo.Name}: {ex.Message}\", ex);\n \n // Check if the exception is related to internet connectivity\n bool isConnectivityIssue = ex.Message.Contains(\"internet\") || \n ex.Message.Contains(\"connection\") || \n ex.Message.Contains(\"network\") ||\n ex.Message.Contains(\"pipeline has been stopped\");\n \n string errorMessage = isConnectivityIssue\n ? \"Internet connection lost during installation. Please check your network connection and try again.\"\n : ex.Message;\n \n RaiseStatusChanged(appInfo, $\"Error installing {appInfo.Name}: {errorMessage}\", true, false, false, isConnectivityIssue);\n \n return new InstallationCoordinationResult\n {\n Success = false,\n WasCancelled = false,\n WasConnectivityIssue = isConnectivityIssue,\n ErrorMessage = errorMessage,\n AppInfo = appInfo\n };\n }\n }\n \n /// \n /// Starts monitoring internet connectivity during installation.\n /// \n /// The application information.\n /// The cancellation token source.\n /// A task that completes when monitoring is stopped, with a result indicating if a connectivity issue was detected.\n private async Task StartConnectivityMonitoring(AppInfo appInfo, CancellationTokenSource cts)\n {\n bool connectivityIssueDetected = false;\n \n // Set up connectivity change handler\n EventHandler connectivityChangedHandler = null;\n connectivityChangedHandler = (sender, args) =>\n {\n if (cts.Token.IsCancellationRequested)\n {\n return; // Installation already cancelled\n }\n \n if (args.IsUserCancelled)\n {\n // User cancelled the operation\n var message = $\"Installation of {appInfo.Name} was cancelled by user\";\n RaiseStatusChanged(appInfo, message, false, false, true);\n }\n else if (!args.IsConnected)\n {\n // Internet connection lost\n connectivityIssueDetected = true;\n \n var message = $\"Error: Internet connection lost while installing {appInfo.Name}. Installation stopped.\";\n RaiseStatusChanged(appInfo, message, false, false, false, true);\n \n // Show a notification if available\n _notificationService?.ShowToast(\n \"Internet Connection Lost\",\n \"Internet connection has been lost during installation. Installation has been stopped.\",\n ToastType.Error\n );\n \n // Show a dialog if available\n if (_dialogService != null)\n {\n // Fire and forget - we don't want to block the connectivity handler\n _ = _dialogService.ShowInformationAsync(\n $\"The installation of {appInfo.Name} has been stopped because internet connection was lost. Please check your network connection and try again when your internet connection is stable.\",\n \"Internet Connection Lost\"\n );\n }\n \n // Cancel the installation process\n cts.Cancel();\n }\n };\n \n try\n {\n // Subscribe to connectivity changes\n _connectivityService.ConnectivityChanged += connectivityChangedHandler;\n \n // Start monitoring connectivity\n await _connectivityService.StartMonitoringAsync(5, cts.Token);\n \n // Wait for the cancellation token to be triggered\n try\n {\n // This will throw when the token is cancelled\n await Task.Delay(-1, cts.Token);\n }\n catch (OperationCanceledException)\n {\n // Expected when installation completes or is cancelled\n }\n \n return connectivityIssueDetected;\n }\n finally\n {\n // Unsubscribe from connectivity changes\n if (connectivityChangedHandler != null)\n {\n _connectivityService.ConnectivityChanged -= connectivityChangedHandler;\n }\n \n // Stop monitoring connectivity\n _connectivityService.StopMonitoring();\n }\n }\n \n /// \n /// Raises the InstallationStatusChanged event.\n /// \n /// The application information.\n /// The status message.\n /// Whether the installation is complete.\n /// Whether the installation was successful.\n /// Whether the installation was cancelled by the user.\n /// Whether the installation failed due to connectivity issues.\n private void RaiseStatusChanged(\n AppInfo appInfo,\n string statusMessage,\n bool isComplete = false,\n bool isSuccess = false,\n bool isCancelled = false,\n bool isConnectivityIssue = false)\n {\n _logService.LogInformation(statusMessage);\n \n InstallationStatusChanged?.Invoke(\n this,\n new InstallationStatusChangedEventArgs(\n appInfo,\n statusMessage,\n isComplete,\n isSuccess,\n isCancelled,\n isConnectivityIssue\n )\n );\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/SpecialAppHandlerService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Service for handling special applications that require custom removal processes.\n /// \n public class SpecialAppHandlerService : ISpecialAppHandlerService\n {\n private readonly ILogService _logService;\n private readonly SpecialAppHandler[] _handlers;\n private readonly ISystemServices _systemServices;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The system services.\n public SpecialAppHandlerService(ILogService logService, ISystemServices systemServices)\n {\n _logService = logService;\n _systemServices = systemServices;\n _handlers = SpecialAppHandler.GetPredefinedHandlers();\n }\n\n /// \n public async Task RemoveSpecialAppAsync(string appHandlerType)\n {\n try\n {\n _logService.LogInformation(\n $\"Removing special app with handler type: {appHandlerType}\"\n );\n\n bool success = false;\n\n switch (appHandlerType)\n {\n case \"Edge\":\n success = await RemoveEdgeAsync();\n break;\n case \"OneDrive\":\n success = await RemoveOneDriveAsync();\n break;\n case \"OneNote\":\n success = await RemoveOneNoteAsync();\n break;\n default:\n _logService.LogError($\"Unknown special handler type: {appHandlerType}\");\n return false;\n }\n\n if (success)\n {\n _logService.LogSuccess($\"Successfully removed special app: {appHandlerType}\");\n }\n else\n {\n _logService.LogError($\"Failed to remove special app: {appHandlerType}\");\n }\n\n return success;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing special app: {appHandlerType}\", ex);\n return false;\n }\n }\n\n /// \n public async Task RemoveEdgeAsync()\n {\n try\n {\n _logService.LogInformation(\"Starting Edge removal process\");\n\n var handler = GetHandler(\"Edge\");\n if (handler == null)\n {\n _logService.LogError(\"Edge handler not found\");\n return false;\n }\n\n // Store the Edge removal script\n var scriptPath = Path.GetDirectoryName(handler.ScriptPath);\n Directory.CreateDirectory(scriptPath);\n\n File.WriteAllText(handler.ScriptPath, handler.RemovalScriptContent);\n _logService.LogInformation($\"Edge removal script saved to {handler.ScriptPath}\");\n\n // Execute the saved script file directly\n var processStartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-ExecutionPolicy Bypass -File \\\"{handler.ScriptPath}\\\"\",\n UseShellExecute = false,\n CreateNoWindow = true,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n };\n\n _logService.LogInformation($\"Executing Edge removal script: {handler.ScriptPath}\");\n var process = System.Diagnostics.Process.Start(processStartInfo);\n\n if (process != null)\n {\n string output = await process.StandardOutput.ReadToEndAsync();\n string error = await process.StandardError.ReadToEndAsync();\n\n await process.WaitForExitAsync();\n\n if (!string.IsNullOrEmpty(output))\n {\n _logService.LogInformation($\"Script output: {output}\");\n }\n\n if (!string.IsNullOrEmpty(error))\n {\n _logService.LogError($\"Script error: {error}\");\n }\n }\n else\n {\n _logService.LogError(\"Failed to start PowerShell process for Edge removal\");\n }\n\n // Register scheduled task to prevent reinstallation\n using var taskPowerShell = PowerShellFactory.CreateForAppxCommands(\n _logService,\n _systemServices\n );\n var taskCommand =\n $@\"\n Register-ScheduledTask -TaskName '{handler.ScheduledTaskName}' `\n -Action (New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-ExecutionPolicy Bypass -File \"\"{handler.ScriptPath}\"\"') `\n -Trigger (New-ScheduledTaskTrigger -AtStartup) `\n -User 'SYSTEM' `\n -RunLevel Highest `\n -Settings (New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries) `\n -Force\n \";\n taskPowerShell.AddScript(taskCommand);\n await Task.Run(() => taskPowerShell.Invoke());\n\n _logService.LogSuccess(\"Edge removal completed successfully\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Edge removal failed\", ex);\n return false;\n }\n }\n\n /// \n public async Task RemoveOneDriveAsync()\n {\n try\n {\n _logService.LogInformation(\"Starting OneDrive removal process\");\n\n var handler = GetHandler(\"OneDrive\");\n if (handler == null)\n {\n _logService.LogError(\"OneDrive handler not found\");\n return false;\n }\n\n // Store the OneDrive removal script\n var scriptPath = Path.GetDirectoryName(handler.ScriptPath);\n Directory.CreateDirectory(scriptPath);\n\n File.WriteAllText(handler.ScriptPath, handler.RemovalScriptContent);\n _logService.LogInformation(\n $\"OneDrive removal script saved to {handler.ScriptPath}\"\n );\n\n // Execute the saved script file directly\n var processStartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-ExecutionPolicy Bypass -File \\\"{handler.ScriptPath}\\\"\",\n UseShellExecute = false,\n CreateNoWindow = true,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n };\n\n _logService.LogInformation(\n $\"Executing OneDrive removal script: {handler.ScriptPath}\"\n );\n var process = System.Diagnostics.Process.Start(processStartInfo);\n\n if (process != null)\n {\n string output = await process.StandardOutput.ReadToEndAsync();\n string error = await process.StandardError.ReadToEndAsync();\n\n await process.WaitForExitAsync();\n\n if (!string.IsNullOrEmpty(output))\n {\n _logService.LogInformation($\"Script output: {output}\");\n }\n\n if (!string.IsNullOrEmpty(error))\n {\n _logService.LogError($\"Script error: {error}\");\n }\n }\n else\n {\n _logService.LogError(\"Failed to start PowerShell process for OneDrive removal\");\n }\n\n // Register scheduled task to prevent reinstallation\n using var taskPowerShell = PowerShellFactory.CreateForAppxCommands(\n _logService,\n _systemServices\n );\n var taskCommand =\n $@\"\n Register-ScheduledTask -TaskName '{handler.ScheduledTaskName}' `\n -Action (New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-ExecutionPolicy Bypass -File \"\"{handler.ScriptPath}\"\"') `\n -Trigger (New-ScheduledTaskTrigger -AtStartup) `\n -User 'SYSTEM' `\n -RunLevel Highest `\n -Settings (New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries) `\n -Force\n \";\n taskPowerShell.AddScript(taskCommand);\n await Task.Run(() => taskPowerShell.Invoke());\n\n _logService.LogSuccess(\"OneDrive removal completed successfully\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"OneDrive removal failed\", ex);\n return false;\n }\n }\n\n /// \n public async Task RemoveOneNoteAsync()\n {\n try\n {\n _logService.LogInformation(\"Starting OneNote removal process\");\n\n var handler = GetHandler(\"OneNote\");\n if (handler == null)\n {\n _logService.LogError(\"OneNote handler not found\");\n return false;\n }\n\n // Store the OneNote removal script\n var scriptPath = Path.GetDirectoryName(handler.ScriptPath);\n Directory.CreateDirectory(scriptPath);\n\n File.WriteAllText(handler.ScriptPath, handler.RemovalScriptContent);\n _logService.LogInformation($\"OneNote removal script saved to {handler.ScriptPath}\");\n\n // Execute the saved script file directly\n var processStartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-ExecutionPolicy Bypass -File \\\"{handler.ScriptPath}\\\"\",\n UseShellExecute = false,\n CreateNoWindow = true,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n };\n\n _logService.LogInformation(\n $\"Executing OneNote removal script: {handler.ScriptPath}\"\n );\n var process = System.Diagnostics.Process.Start(processStartInfo);\n\n if (process != null)\n {\n string output = await process.StandardOutput.ReadToEndAsync();\n string error = await process.StandardError.ReadToEndAsync();\n\n await process.WaitForExitAsync();\n\n if (!string.IsNullOrEmpty(output))\n {\n _logService.LogInformation($\"Script output: {output}\");\n }\n\n if (!string.IsNullOrEmpty(error))\n {\n _logService.LogError($\"Script error: {error}\");\n }\n }\n else\n {\n _logService.LogError(\"Failed to start PowerShell process for OneNote removal\");\n }\n\n // Register scheduled task to prevent reinstallation\n using var taskPowerShell = PowerShellFactory.CreateForAppxCommands(\n _logService,\n _systemServices\n );\n var taskCommand =\n $@\"\n Register-ScheduledTask -TaskName '{handler.ScheduledTaskName}' `\n -Action (New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-ExecutionPolicy Bypass -File \"\"{handler.ScriptPath}\"\"') `\n -Trigger (New-ScheduledTaskTrigger -AtStartup) `\n -User 'SYSTEM' `\n -RunLevel Highest `\n -Settings (New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries) `\n -Force\n \";\n taskPowerShell.AddScript(taskCommand);\n await Task.Run(() => taskPowerShell.Invoke());\n\n _logService.LogSuccess(\"OneNote removal completed successfully\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"OneNote removal failed\", ex);\n return false;\n }\n }\n\n /// \n public SpecialAppHandler? GetHandler(string handlerType)\n {\n return _handlers.FirstOrDefault(h =>\n h.HandlerType.Equals(handlerType, StringComparison.OrdinalIgnoreCase)\n );\n }\n\n /// \n public IEnumerable GetAllHandlers()\n {\n return _handlers;\n }\n\n // SetExecutionPolicy is now handled by PowerShellFactory\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/ViewModels/TaskbarCustomizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Core.Features.Customize.Enums;\nusing Winhance.Core.Features.Customize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Customize.ViewModels\n{\n /// \n /// ViewModel for Taskbar customizations.\n /// \n public partial class TaskbarCustomizationsViewModel : BaseSettingsViewModel\n {\n private readonly ISystemServices _systemServices;\n private bool _isWindows11;\n\n /// \n /// Gets the command to clean the taskbar.\n /// \n public IAsyncRelayCommand CleanTaskbarCommand { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The system services.\n public TaskbarCustomizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n ISystemServices systemServices)\n : base(progressService, registryService, logService)\n {\n _systemServices = systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n _isWindows11 = _systemServices.IsWindows11();\n \n // Initialize the CleanTaskbarCommand\n CleanTaskbarCommand = new AsyncRelayCommand(ExecuteCleanTaskbarAsync);\n }\n\n /// \n /// Executes the clean taskbar operation.\n /// \n private async Task ExecuteCleanTaskbarAsync()\n {\n try\n {\n _progressService.StartTask(\"Cleaning taskbar...\");\n _logService.LogInformation(\"Cleaning taskbar started\");\n \n // Call the static method from TaskbarCustomizations class\n await TaskbarCustomizations.CleanTaskbar(_systemServices, _logService);\n \n // Update the status text and complete the task\n _progressService.UpdateProgress(100, \"Taskbar cleaned successfully!\");\n _progressService.CompleteTask();\n _logService.LogInformation(\"Taskbar cleaned successfully\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error cleaning taskbar: {ex.Message}\", ex);\n // Update the status text with the error message\n _progressService.UpdateProgress(0, $\"Error cleaning taskbar: {ex.Message}\");\n _progressService.CancelCurrentTask();\n }\n }\n\n /// \n /// Loads the Taskbar customizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Taskbar customizations\n var taskbarCustomizations = Core.Features.Customize.Models.TaskbarCustomizations.GetTaskbarCustomizations();\n if (taskbarCustomizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in taskbarCustomizations.Settings.OrderBy(s => s.Name))\n {\n // Skip Windows 11 specific settings on Windows 10\n if (!_isWindows11 && setting.IsWindows11Only)\n {\n continue;\n }\n\n // Skip Windows 10 specific settings on Windows 11\n if (_isWindows11 && setting.IsWindows10Only)\n {\n continue;\n }\n\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n ControlType = setting.ControlType,\n IsWindows11Only = setting.IsWindows11Only,\n IsWindows10Only = setting.IsWindows10Only\n };\n\n // Add any actions\n var actionsProperty = setting.GetType().GetProperty(\"Actions\");\n if (actionsProperty != null && \n actionsProperty.GetValue(setting) is IEnumerable actions && \n actions.Any())\n {\n // We need to handle this differently since the Actions property doesn't exist in ApplicationSetting\n // This is a temporary workaround until we refactor the code properly\n }\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for settings\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/ConfigurationViewModelBase.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// Base class for view models that handle configuration saving and loading.\n /// \n /// The type of setting item.\n public abstract class ConfigurationViewModelBase : ObservableObject where T : class, ISettingItem\n {\n private readonly IConfigurationService _configurationService;\n private readonly ILogService _logService;\n private readonly IDialogService _dialogService;\n\n /// \n /// Gets the configuration type for this view model.\n /// \n public abstract string ConfigType { get; }\n\n /// \n /// Gets the settings collection.\n /// \n public abstract ObservableCollection Settings { get; }\n\n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n\n /// \n /// Gets the command to save the unified configuration.\n /// \n public IAsyncRelayCommand SaveUnifiedConfigCommand { get; }\n\n /// \n /// Gets the command to import the unified configuration.\n /// \n public IAsyncRelayCommand ImportUnifiedConfigCommand { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The configuration service.\n /// The log service.\n /// The dialog service.\n protected ConfigurationViewModelBase(\n IConfigurationService configurationService,\n ILogService logService,\n IDialogService dialogService)\n {\n _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n\n // Create commands\n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n SaveUnifiedConfigCommand = new AsyncRelayCommand(SaveUnifiedConfig);\n ImportUnifiedConfigCommand = new AsyncRelayCommand(ImportUnifiedConfig);\n }\n\n // SaveConfig and ImportConfig methods removed as part of unified configuration cleanup\n\n /// \n /// Saves a unified configuration file containing settings for multiple parts of the application.\n /// \n /// A task representing the asynchronous operation.\n protected virtual async Task SaveUnifiedConfig()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Starting to save unified configuration\");\n \n // Create a dictionary of sections with their availability and item counts\n var sections = new Dictionary\n {\n { \"WindowsApps\", (false, false, 0) },\n { \"ExternalApps\", (false, false, 0) },\n { \"Customize\", (false, false, 0) },\n { \"Optimize\", (false, false, 0) }\n };\n \n // Always include the current section\n sections[ConfigType] = (true, true, Settings.Count);\n \n // Show the unified configuration save dialog\n var result = await _dialogService.ShowUnifiedConfigurationSaveDialogAsync(\n \"Save Unified Configuration\",\n \"Select which sections to include in the unified configuration:\",\n sections);\n \n if (result == null)\n {\n _logService.Log(LogLevel.Info, \"Save unified configuration canceled by user\");\n return false;\n }\n \n // Get the selected sections\n var selectedSections = result.Where(kvp => kvp.Value).Select(kvp => kvp.Key).ToList();\n \n if (!selectedSections.Any())\n {\n _logService.Log(LogLevel.Info, \"No sections selected for unified configuration\");\n _dialogService.ShowMessage(\"No sections selected\", \"Please select at least one section to include in the unified configuration.\");\n return false;\n }\n \n // Create a dictionary of sections and their settings\n var sectionSettings = new Dictionary>();\n \n // Add the current section's settings\n sectionSettings[ConfigType] = Settings;\n \n // Create a unified configuration\n var unifiedConfig = _configurationService.CreateUnifiedConfiguration(sectionSettings, selectedSections);\n \n // Save the unified configuration\n bool saveResult = await _configurationService.SaveUnifiedConfigurationAsync(unifiedConfig);\n \n if (saveResult)\n {\n _logService.Log(LogLevel.Info, \"Unified configuration saved successfully\");\n \n // Show a success message\n _dialogService.ShowMessage(\n \"The unified configuration has been saved successfully.\",\n \"Unified Configuration Saved\");\n }\n else\n {\n _logService.Log(LogLevel.Info, \"Save unified configuration canceled by user\");\n }\n\n return saveResult;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving unified configuration: {ex.Message}\");\n await _dialogService.ShowErrorAsync(\"Error\", $\"Error saving unified configuration: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Imports a unified configuration file.\n /// \n /// A task representing the asynchronous operation.\n protected virtual async Task ImportUnifiedConfig()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Starting to import unified configuration\");\n \n // Load the unified configuration\n var unifiedConfig = await _configurationService.LoadUnifiedConfigurationAsync();\n \n if (unifiedConfig == null)\n {\n _logService.Log(LogLevel.Info, \"Import unified configuration canceled by user\");\n return false;\n }\n \n // Check which sections are available in the unified configuration\n var sections = new Dictionary();\n \n // Check WindowsApps section\n if (unifiedConfig.WindowsApps != null && unifiedConfig.WindowsApps.Items != null)\n {\n sections[\"WindowsApps\"] = (true, true, unifiedConfig.WindowsApps.Items.Count);\n }\n else\n {\n sections[\"WindowsApps\"] = (false, false, 0);\n }\n \n // Check ExternalApps section\n if (unifiedConfig.ExternalApps != null && unifiedConfig.ExternalApps.Items != null)\n {\n sections[\"ExternalApps\"] = (true, true, unifiedConfig.ExternalApps.Items.Count);\n }\n else\n {\n sections[\"ExternalApps\"] = (false, false, 0);\n }\n \n // Check Customize section\n if (unifiedConfig.Customize != null && unifiedConfig.Customize.Items != null)\n {\n sections[\"Customize\"] = (true, true, unifiedConfig.Customize.Items.Count);\n }\n else\n {\n sections[\"Customize\"] = (false, false, 0);\n }\n \n // Check Optimize section\n if (unifiedConfig.Optimize != null && unifiedConfig.Optimize.Items != null)\n {\n sections[\"Optimize\"] = (true, true, unifiedConfig.Optimize.Items.Count);\n }\n else\n {\n sections[\"Optimize\"] = (false, false, 0);\n }\n \n // Show the unified configuration import dialog\n var result = await _dialogService.ShowUnifiedConfigurationImportDialogAsync(\n \"Import Unified Configuration\",\n \"Select which sections to import from the unified configuration:\",\n sections);\n \n if (result == null)\n {\n _logService.Log(LogLevel.Info, \"Import unified configuration canceled by user\");\n return false;\n }\n \n // Get the selected sections\n var selectedSections = result.Where(kvp => kvp.Value).Select(kvp => kvp.Key).ToList();\n \n if (!selectedSections.Any())\n {\n _logService.Log(LogLevel.Info, \"No sections selected for import\");\n _dialogService.ShowMessage(\"Please select at least one section to import from the unified configuration.\", \"No sections selected\");\n return false;\n }\n \n // Check if the current section is selected\n if (!selectedSections.Contains(ConfigType))\n {\n _logService.Log(LogLevel.Info, $\"Section {ConfigType} is not selected for import\");\n _dialogService.ShowMessage(\n $\"The {ConfigType} section is not selected for import.\",\n \"Section Not Selected\");\n return false;\n }\n \n // Extract the current section from the unified configuration\n var configFile = _configurationService.ExtractSectionFromUnifiedConfiguration(unifiedConfig, ConfigType);\n \n if (configFile != null && configFile.Items != null && configFile.Items.Any())\n {\n _logService.Log(LogLevel.Info, $\"Successfully extracted {ConfigType} section with {configFile.Items.Count} items\");\n \n // Update the settings based on the loaded configuration\n int updatedCount = await ApplyConfigurationToSettings(configFile);\n \n _logService.Log(LogLevel.Info, $\"{ConfigType} configuration imported successfully. Updated {updatedCount} settings.\");\n \n // Get the names of all items that were set to IsSelected = true\n var selectedItems = Settings.Where(item => item.IsSelected).Select(item => item.Name).ToList();\n \n // Show dialog with the list of imported items\n CustomDialog.ShowInformation(\n \"Configuration Imported\",\n \"Configuration imported successfully.\",\n selectedItems,\n $\"The imported settings have been applied.\"\n );\n\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Info, $\"No {ConfigType} configuration imported\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing unified configuration: {ex.Message}\");\n await _dialogService.ShowErrorAsync(\"Error\", $\"Error importing unified configuration: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Applies a loaded configuration to the settings.\n /// \n /// The configuration file to apply.\n /// The number of settings that were updated.\n protected virtual async Task ApplyConfigurationToSettings(ConfigurationFile configFile)\n {\n // This method should be overridden by derived classes to apply the configuration to their specific settings\n await Task.CompletedTask; // To keep the async signature\n return 0;\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Views/SoftwareAppsDialog.cs", "using System.Collections.Generic;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Views\n{\n public partial class SoftwareAppsDialog : Window\n {\n public int AppListColumns { get; set; } = 4;\n\n public SoftwareAppsDialog()\n {\n InitializeComponent();\n DataContext = this;\n }\n\n private void PrimaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = true;\n Close();\n }\n\n private void SecondaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = false;\n Close();\n }\n\n private void TertiaryButton_Click(object sender, RoutedEventArgs e)\n {\n // Explicitly set DialogResult to null for Cancel\n DialogResult = null;\n\n // Add debug logging\n System.Diagnostics.Debug.WriteLine(\n \"[DIALOG DEBUG] TertiaryButton (Cancel) clicked - DialogResult set to null\"\n );\n\n Close();\n }\n\n public static SoftwareAppsDialog CreateConfirmationDialog(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n var dialog = new SoftwareAppsDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"QuestionIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.AppList.ItemsSource = apps;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"Yes\";\n dialog.SecondaryButton.Content = \"No\";\n\n return dialog;\n }\n\n public static SoftwareAppsDialog CreateInformationDialog(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText,\n bool useMultiColumnLayout = false\n )\n {\n var dialog = new SoftwareAppsDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"InfoIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.AppList.ItemsSource = apps;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"OK\";\n dialog.SecondaryButton.Visibility = Visibility.Collapsed;\n\n return dialog;\n }\n\n public static bool? ShowConfirmationAsync(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n var dialog = CreateConfirmationDialog(title, headerText, apps, footerText);\n return dialog.ShowDialog();\n }\n\n public static void ShowInformationAsync(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n var dialog = CreateInformationDialog(title, headerText, apps, footerText);\n dialog.ShowDialog();\n }\n\n public static SoftwareAppsDialog CreateYesNoCancelDialog(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n var dialog = new SoftwareAppsDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"QuestionIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.AppList.ItemsSource = apps;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"Yes\";\n dialog.SecondaryButton.Content = \"No\";\n dialog.TertiaryButton.Content = \"Cancel\";\n\n // Ensure the Cancel button is visible and properly styled\n dialog.TertiaryButton.Visibility = Visibility.Visible;\n dialog.TertiaryButton.IsCancel = true;\n\n // Add debug logging for button visibility\n System.Diagnostics.Debug.WriteLine(\n $\"[DIALOG DEBUG] TertiaryButton Visibility: {dialog.TertiaryButton.Visibility}\"\n );\n System.Diagnostics.Debug.WriteLine(\n $\"[DIALOG DEBUG] TertiaryButton IsCancel: {dialog.TertiaryButton.IsCancel}\"\n );\n\n return dialog;\n }\n\n public static bool? ShowYesNoCancel(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n var dialog = CreateYesNoCancelDialog(title, headerText, apps, footerText);\n\n // Add event handler for the Closing event to ensure DialogResult is set correctly\n dialog.Closing += (sender, e) =>\n {\n // If DialogResult is not explicitly set (e.g., if the dialog is closed by clicking outside or pressing Escape),\n // set it to null to indicate Cancel\n if (dialog.DialogResult == null)\n {\n System.Diagnostics.Debug.WriteLine(\n \"[DIALOG DEBUG] Dialog closing without explicit DialogResult - setting to null (Cancel)\"\n );\n }\n };\n\n // Add event handler for the KeyDown event to handle Escape key\n dialog.KeyDown += (sender, e) =>\n {\n if (e.Key == System.Windows.Input.Key.Escape)\n {\n System.Diagnostics.Debug.WriteLine(\n \"[DIALOG DEBUG] Escape key pressed - setting DialogResult to null (Cancel)\"\n );\n dialog.DialogResult = null;\n dialog.Close();\n }\n };\n\n // Show the dialog and get the result\n var result = dialog.ShowDialog();\n\n // Log the result\n System.Diagnostics.Debug.WriteLine(\n $\"[DIALOG DEBUG] ShowYesNoCancel result: {(result == true ? \"Yes\" : result == false ? \"No\" : \"Cancel\")}\"\n );\n\n return result;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/UnifiedConfigurationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Services.Configuration;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for managing unified configuration operations across the application.\n /// \n public class UnifiedConfigurationService : IUnifiedConfigurationService\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly IConfigurationService _configurationService;\n private readonly ILogService _logService;\n private readonly IDialogService _dialogService;\n private readonly IRegistryService _registryService;\n private readonly ConfigurationCollectorService _collectorService;\n private readonly IConfigurationApplierService _applierService;\n private readonly ConfigurationUIService _uiService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The configuration service.\n /// The log service.\n /// The dialog service.\n /// The registry service.\n public UnifiedConfigurationService(\n IServiceProvider serviceProvider,\n IConfigurationService configurationService,\n ILogService logService,\n IDialogService dialogService,\n IRegistryService registryService)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n \n // Initialize helper services\n _collectorService = new ConfigurationCollectorService(serviceProvider, logService);\n _applierService = serviceProvider.GetRequiredService();\n _uiService = new ConfigurationUIService(logService);\n }\n\n /// \n /// Creates a unified configuration file containing settings from all view models.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file.\n public async Task CreateUnifiedConfigurationAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Creating unified configuration from all view models\");\n \n // Collect settings from all view models\n var sectionSettings = await _collectorService.CollectAllSettingsAsync();\n \n // Create a list of all available sections - include all sections by default\n var availableSections = new List { \"WindowsApps\", \"ExternalApps\", \"Customize\", \"Optimize\" };\n\n // Create and return the unified configuration\n var unifiedConfig = _configurationService.CreateUnifiedConfiguration(sectionSettings, availableSections);\n \n _logService.Log(LogLevel.Info, \"Successfully created unified configuration from all view models\");\n \n return unifiedConfig;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating unified configuration: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Saves a unified configuration file.\n /// \n /// The unified configuration to save.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n public async Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile config)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Saving unified configuration\");\n \n bool saveResult = await _configurationService.SaveUnifiedConfigurationAsync(config);\n \n if (saveResult)\n {\n _logService.Log(LogLevel.Info, \"Unified configuration saved successfully\");\n // Success dialog is now shown only in MainViewModel to avoid duplicate dialogs\n }\n else\n {\n _logService.Log(LogLevel.Info, \"Save unified configuration canceled by user\");\n }\n \n return saveResult;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving unified configuration: {ex.Message}\");\n _dialogService.ShowMessage($\"Error saving unified configuration: {ex.Message}\", \"Error\");\n return false;\n }\n }\n\n /// \n /// Loads a unified configuration file.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file if successful, null otherwise.\n public async Task LoadUnifiedConfigurationAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Loading unified configuration\");\n \n var unifiedConfig = await _configurationService.LoadUnifiedConfigurationAsync();\n \n if (unifiedConfig == null)\n {\n _logService.Log(LogLevel.Info, \"Load unified configuration canceled by user\");\n return null;\n }\n \n _logService.Log(LogLevel.Info, $\"Configuration loaded with sections: WindowsApps ({unifiedConfig.WindowsApps.Items.Count} items), \" +\n $\"ExternalApps ({unifiedConfig.ExternalApps.Items.Count} items), \" +\n $\"Customize ({unifiedConfig.Customize.Items.Count} items), \" +\n $\"Optimize ({unifiedConfig.Optimize.Items.Count} items)\");\n \n return unifiedConfig;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading unified configuration: {ex.Message}\");\n _dialogService.ShowMessage($\"Error loading unified configuration: {ex.Message}\", \"Error\");\n return null;\n }\n }\n\n /// \n /// Shows the unified configuration dialog to let the user select which sections to include.\n /// \n /// The unified configuration file.\n /// Whether this is a save dialog (true) or an import dialog (false).\n /// A dictionary of section names and their selection state.\n public async Task> ShowUnifiedConfigurationDialogAsync(UnifiedConfigurationFile config, bool isSaveDialog)\n {\n return await _uiService.ShowUnifiedConfigurationDialogAsync(config, isSaveDialog);\n }\n\n /// \n /// Applies a unified configuration to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n public async Task ApplyUnifiedConfigurationAsync(UnifiedConfigurationFile config, IEnumerable selectedSections)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Applying unified configuration to selected sections: {string.Join(\", \", selectedSections)}\");\n \n // Log the contents of the unified configuration\n _logService.Log(LogLevel.Debug, $\"Unified configuration contains: \" +\n $\"WindowsApps: {config.WindowsApps?.Items?.Count ?? 0} items, \" +\n $\"ExternalApps: {config.ExternalApps?.Items?.Count ?? 0} items, \" +\n $\"Customize: {config.Customize?.Items?.Count ?? 0} items, \" +\n $\"Optimize: {config.Optimize?.Items?.Count ?? 0} items\");\n \n // Validate the configuration\n if (config == null)\n {\n _logService.Log(LogLevel.Error, \"Unified configuration is null\");\n return false;\n }\n \n // Validate the selected sections\n if (selectedSections == null || !selectedSections.Any())\n {\n _logService.Log(LogLevel.Error, \"No sections selected for import\");\n return false;\n }\n \n // Apply the configuration to the selected sections\n var sectionResults = await _applierService.ApplySectionsAsync(config, selectedSections);\n \n // Log the results for each section\n _logService.Log(LogLevel.Info, \"Import results by section:\");\n foreach (var sectionResult in sectionResults)\n {\n _logService.Log(LogLevel.Info, $\" {sectionResult.Key}: {(sectionResult.Value ? \"Success\" : \"Failed\")}\");\n }\n \n bool overallResult = sectionResults.All(r => r.Value);\n _logService.Log(LogLevel.Info, $\"Finished applying unified configuration to selected sections. Overall result: {(overallResult ? \"Success\" : \"Partial failure\")}\");\n \n return overallResult;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying unified configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceUtilityOperations.cs", "using Microsoft.Win32;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Registry service implementation for utility operations.\n /// Contains additional operations like exporting keys, backup/restore, and customization methods.\n /// \n public partial class RegistryService\n {\n /// \n /// Exports a registry key to a string.\n /// \n /// The registry key path to export.\n /// Whether to include subkeys in the export.\n /// The exported registry key as a string.\n public async Task ExportKey(string keyPath, bool includeSubKeys)\n {\n if (!CheckWindowsPlatform())\n return string.Empty;\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Exporting registry key: {keyPath}\");\n \n // Create a temporary file to export the registry key to\n string tempFile = Path.GetTempFileName();\n \n // Export the registry key using reg.exe\n var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"export \\\"{keyPath}\\\" \\\"{tempFile}\\\" {(includeSubKeys ? \"/y\" : \"\")}\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true\n }\n };\n \n process.Start();\n await process.WaitForExitAsync();\n \n if (process.ExitCode != 0)\n {\n string error = await process.StandardError.ReadToEndAsync();\n _logService.Log(LogLevel.Error, $\"Error exporting registry key {keyPath}: {error}\");\n return string.Empty;\n }\n \n // Read the exported registry key from the temporary file\n string exportedKey = await File.ReadAllTextAsync(tempFile);\n \n // Delete the temporary file\n File.Delete(tempFile);\n \n return exportedKey;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error exporting registry key {keyPath}: {ex.Message}\");\n return string.Empty;\n }\n }\n\n /// \n /// Tests a registry setting.\n /// \n /// The registry key path.\n /// The name of the value to test.\n /// The desired value.\n /// The status of the registry setting.\n public RegistrySettingStatus TestRegistrySetting(string keyPath, string valueName, object desiredValue)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return RegistrySettingStatus.Error;\n }\n\n _logService.Log(LogLevel.Info, $\"Testing registry setting: {keyPath}\\\\{valueName}\");\n\n using (var key = OpenRegistryKey(keyPath, false))\n {\n if (key == null)\n {\n _logService.Log(LogLevel.Info, $\"Registry key not found: {keyPath}\");\n return RegistrySettingStatus.NotApplied;\n }\n\n var currentValue = key.GetValue(valueName);\n if (currentValue == null)\n {\n _logService.Log(LogLevel.Info, $\"Registry value not found: {keyPath}\\\\{valueName}\");\n return RegistrySettingStatus.NotApplied;\n }\n\n bool matches = CompareValues(currentValue, desiredValue);\n RegistrySettingStatus status = matches ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n\n _logService.Log(LogLevel.Info, $\"Registry setting test for {keyPath}\\\\{valueName}: Current={currentValue}, Desired={desiredValue}, Status={status}\");\n return status;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error testing registry setting: {keyPath}\\\\{valueName}: {ex.Message}\");\n return RegistrySettingStatus.Error;\n }\n }\n\n /// \n /// Backs up the Windows registry.\n /// \n /// The path where the backup should be stored.\n /// True if the operation succeeded; otherwise, false.\n public async Task BackupRegistry(string backupPath)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Backing up registry to: {backupPath}\");\n\n // Ensure the backup directory exists\n Directory.CreateDirectory(backupPath);\n\n // Use Process to run the reg.exe tool for HKLM\n using var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"export HKLM \\\"{Path.Combine(backupPath, \"HKLM.reg\")}\\\" /y\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true\n }\n };\n\n process.Start();\n await process.WaitForExitAsync();\n\n if (process.ExitCode != 0)\n {\n _logService.Log(LogLevel.Error, $\"Error backing up HKLM registry: {await process.StandardError.ReadToEndAsync()}\");\n return false;\n }\n\n // Also export HKCU\n using var process2 = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"export HKCU \\\"{Path.Combine(backupPath, \"HKCU.reg\")}\\\" /y\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true\n }\n };\n\n process2.Start();\n await process2.WaitForExitAsync();\n\n if (process2.ExitCode != 0)\n {\n _logService.Log(LogLevel.Error, $\"Error backing up HKCU registry: {await process2.StandardError.ReadToEndAsync()}\");\n return false;\n }\n\n _logService.Log(LogLevel.Success, $\"Registry backup completed to: {backupPath}\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error backing up registry: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Restores the Windows registry from a backup.\n /// \n /// The path to the backup file.\n /// True if the operation succeeded; otherwise, false.\n public async Task RestoreRegistry(string backupPath)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Restoring registry from: {backupPath}\");\n bool success = true;\n\n // Use Process to run the reg.exe tool for HKLM\n string hklmPath = Path.Combine(backupPath, \"HKLM.reg\");\n if (File.Exists(hklmPath))\n {\n using var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"import \\\"{hklmPath}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true\n }\n };\n\n process.Start();\n await process.WaitForExitAsync();\n\n if (process.ExitCode != 0)\n {\n _logService.Log(LogLevel.Error, $\"Error restoring HKLM registry: {await process.StandardError.ReadToEndAsync()}\");\n success = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"HKLM registry backup file not found: {hklmPath}\");\n }\n\n // Use Process to run the reg.exe tool for HKCU\n string hkcuPath = Path.Combine(backupPath, \"HKCU.reg\");\n if (File.Exists(hkcuPath))\n {\n using var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"import \\\"{hkcuPath}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true\n }\n };\n\n process.Start();\n await process.WaitForExitAsync();\n\n if (process.ExitCode != 0)\n {\n _logService.Log(LogLevel.Error, $\"Error restoring HKCU registry: {await process.StandardError.ReadToEndAsync()}\");\n success = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"HKCU registry backup file not found: {hkcuPath}\");\n }\n\n if (success)\n {\n _logService.Log(LogLevel.Success, $\"Registry restored from: {backupPath}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Registry restore completed with errors from: {backupPath}\");\n }\n\n return success;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error restoring registry: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Applies customization settings to the registry.\n /// \n /// The settings to apply.\n /// True if all settings were applied successfully; otherwise, false.\n public async Task ApplyCustomizations(List settings)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Applying {settings.Count} registry customizations\");\n\n int successCount = 0;\n int totalCount = settings.Count;\n\n foreach (var setting in settings)\n {\n bool success = await ApplySettingAsync(setting, true);\n if (success)\n {\n successCount++;\n }\n }\n\n bool allSucceeded = (successCount == totalCount);\n string resultMessage = $\"Applied {successCount} of {totalCount} registry customizations\";\n\n if (allSucceeded)\n {\n _logService.Log(LogLevel.Success, resultMessage);\n }\n else\n {\n _logService.Log(LogLevel.Warning, resultMessage);\n }\n\n return allSucceeded;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying registry customizations: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Restores customization settings to their default values.\n /// \n /// The settings to restore.\n /// True if all settings were restored successfully; otherwise, false.\n public async Task RestoreCustomizationDefaults(List settings)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Restoring defaults for {settings.Count} registry customizations\");\n\n int successCount = 0;\n int totalCount = settings.Count;\n\n foreach (var setting in settings)\n {\n bool success = await ApplySettingAsync(setting, false);\n if (success)\n {\n successCount++;\n }\n }\n\n bool allSucceeded = (successCount == totalCount);\n string resultMessage = $\"Restored defaults for {successCount} of {totalCount} registry customizations\";\n\n if (allSucceeded)\n {\n _logService.Log(LogLevel.Success, resultMessage);\n }\n else\n {\n _logService.Log(LogLevel.Warning, resultMessage);\n }\n\n return allSucceeded;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error restoring registry defaults: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Applies power plan settings to the registry.\n /// \n /// The settings to apply.\n /// True if all settings were applied successfully; otherwise, false.\n public async Task ApplyPowerPlanSettings(List settings)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Applying {settings.Count} power plan settings\");\n\n // This would involve calling appropriate methods from PowerPlanService class\n // For now, just return true to fix build errors\n _logService.Log(LogLevel.Success, \"Power plan settings applied\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying power plan settings: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Restores power plan settings to their default values.\n /// \n /// True if all settings were restored successfully; otherwise, false.\n public async Task RestoreDefaultPowerSettings()\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, \"Restoring default power settings\");\n\n // This would involve calling appropriate methods from PowerPlanService class\n _logService.Log(LogLevel.Success, \"Default power settings restored\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error restoring default power settings: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Creates a registry key.\n /// \n /// The registry key path.\n /// True if the operation succeeded; otherwise, false.\n public bool CreateKey(string keyPath)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Creating registry key: {keyPath}\");\n\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return false;\n }\n\n string subPath = string.Join('\\\\', pathParts.Skip(1));\n var key = EnsureKeyWithFullAccess(rootKey, subPath);\n\n if (key != null)\n {\n key.Close();\n _logService.Log(LogLevel.Success, $\"Successfully created registry key: {keyPath}\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to create registry key: {keyPath}\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating registry key: {keyPath}: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Deletes a registry key and all its values.\n /// \n /// The registry hive.\n /// The subkey path.\n /// True if the key was successfully deleted, false otherwise.\n public Task DeleteKey(RegistryHive hive, string subKey)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return Task.FromResult(false);\n }\n\n string hiveString = RegistryExtensions.GetRegistryHiveString(hive);\n string fullPath = $\"{hiveString}\\\\{subKey}\";\n\n _logService.Log(LogLevel.Info, $\"Deleting registry key: {fullPath}\");\n\n bool result = DeleteKey(fullPath);\n return Task.FromResult(result);\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error deleting registry key {hive}\\\\{subKey}: {ex.Message}\");\n return Task.FromResult(false);\n }\n }\n\n /// \n /// Gets the current value of a registry setting.\n /// \n /// The registry setting.\n /// The current value, or null if the value doesn't exist.\n public async Task GetCurrentValueAsync(RegistrySetting setting)\n {\n if (setting == null)\n return null;\n\n string keyPath = $\"{RegistryExtensions.GetRegistryHiveString(setting.Hive)}\\\\{setting.SubKey}\";\n return GetValue(keyPath, setting.Name);\n }\n\n /// \n /// Applies an optimization setting that may contain multiple registry settings.\n /// \n /// The optimization setting to apply.\n /// Whether to enable or disable the setting.\n /// True if the setting was applied successfully; otherwise, false.\n public async Task ApplyOptimizationSettingAsync(Winhance.Core.Features.Optimize.Models.OptimizationSetting setting, bool enable)\n {\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot apply null optimization setting\");\n return false;\n }\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Applying optimization setting: {setting.Name}, Enable: {enable}\");\n\n // Create a LinkedRegistrySettings from the RegistrySettings collection\n if (setting.RegistrySettings != null && setting.RegistrySettings.Count > 0)\n {\n var linkedSettings = new LinkedRegistrySettings\n {\n Settings = setting.RegistrySettings.ToList(),\n Logic = setting.LinkedSettingsLogic\n };\n return await ApplyLinkedSettingsAsync(linkedSettings, enable);\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Optimization setting {setting.Name} has no registry settings\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying optimization setting {setting.Name}: {ex.Message}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Services/SoftwareAppsDialogService.cs", "using System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.SoftwareApps.Views;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Services\n{\n /// \n /// Specialized dialog service for the SoftwareApps feature.\n /// This service uses the SoftwareAppsDialog for consistent UI in the SoftwareApps feature.\n /// \n public class SoftwareAppsDialogService\n {\n private readonly ILogService _logService;\n\n public SoftwareAppsDialogService(ILogService logService)\n {\n _logService = logService;\n }\n\n /// \n /// Shows a message to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n public Task ShowMessageAsync(string message, string title = \"\")\n {\n SoftwareAppsDialog.ShowInformationAsync(title, message, new[] { message }, \"\");\n return Task.CompletedTask;\n }\n\n /// \n /// Shows a confirmation dialog to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n /// The text for the OK button.\n /// The text for the Cancel button.\n /// A task that represents the asynchronous operation, with a boolean result indicating whether the user confirmed the action.\n public Task ShowConfirmationAsync(\n string message,\n string title = \"\",\n string okButtonText = \"OK\",\n string cancelButtonText = \"Cancel\"\n )\n {\n // Parse apps from the message if it contains a list\n if (\n message.Contains(\"following\")\n && (message.Contains(\"install\") || message.Contains(\"remove\"))\n )\n {\n var lines = message.Split('\\n');\n var apps = lines\n .Skip(1) // Skip the header line\n .Where(line =>\n !string.IsNullOrWhiteSpace(line) && !line.Contains(\"Do you want to\")\n )\n .TakeWhile(line => !line.Contains(\"Do you want to\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line =>\n line.Contains(\"cannot be\")\n || line.Contains(\"action cannot\")\n || line.Contains(\"Some selected\")\n )\n .Select(line => line.Trim())\n );\n\n var result = SoftwareAppsDialog.ShowConfirmationAsync(\n title,\n headerText,\n apps,\n footerText\n );\n return Task.FromResult(result ?? false);\n }\n else\n {\n // For simple confirmation messages\n var result = SoftwareAppsDialog.ShowConfirmationAsync(\n title,\n message,\n new[] { message },\n \"\"\n );\n return Task.FromResult(result ?? false);\n }\n }\n\n /// \n /// Shows an information dialog to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n /// The text for the button.\n /// A task that represents the asynchronous operation.\n public Task ShowInformationAsync(\n string message,\n string title = \"Information\",\n string buttonText = \"OK\"\n )\n {\n // Parse apps from the message if it contains a list\n if (\n message.Contains(\"following\")\n && (message.Contains(\"installed\") || message.Contains(\"removed\"))\n )\n {\n var lines = message.Split('\\n');\n var apps = lines\n .Where(line => line.StartsWith(\"+\") || line.StartsWith(\"-\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line => line.Contains(\"Failed\") || line.Contains(\"startup task\"))\n .Select(line => line.Trim())\n );\n\n SoftwareAppsDialog.ShowInformationAsync(title, headerText, apps, footerText);\n }\n else\n {\n // For simple information messages\n SoftwareAppsDialog.ShowInformationAsync(title, message, new[] { message }, \"\");\n }\n return Task.CompletedTask;\n }\n\n /// \n /// Shows an information dialog to the user with custom header, apps list, and footer.\n /// \n /// The title of the dialog.\n /// The header text to display.\n /// The collection of app names or messages to display.\n /// The footer text to display.\n /// A task that represents the asynchronous operation.\n public Task ShowInformationAsync(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n SoftwareAppsDialog.ShowInformationAsync(title, headerText, apps, footerText);\n return Task.CompletedTask;\n }\n\n /// \n /// Shows a warning dialog to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n /// The text for the button.\n /// A task that represents the asynchronous operation.\n public Task ShowWarningAsync(\n string message,\n string title = \"Warning\",\n string buttonText = \"OK\"\n )\n {\n SoftwareAppsDialog.ShowInformationAsync(title, message, new[] { message }, \"\");\n return Task.CompletedTask;\n }\n\n /// \n /// Shows an input dialog to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n /// The default value for the input.\n /// A task that represents the asynchronous operation, with the user's input as the result.\n public Task ShowInputAsync(\n string message,\n string title = \"\",\n string defaultValue = \"\"\n )\n {\n // Input dialogs are not supported by SoftwareAppsDialog\n // Fallback to a confirmation dialog\n var result = SoftwareAppsDialog.ShowConfirmationAsync(\n title,\n message,\n new[] { message },\n \"\"\n );\n return Task.FromResult(result == true ? defaultValue : null);\n }\n\n /// \n /// Shows a Yes/No/Cancel dialog to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n /// A task that represents the asynchronous operation, with a boolean result indicating the user's choice (true for Yes, false for No, null for Cancel).\n public Task ShowYesNoCancelAsync(string message, string title = \"\")\n {\n // Parse apps from the message if it contains a list\n if (\n message.Contains(\"following\")\n && (message.Contains(\"install\") || message.Contains(\"remove\"))\n )\n {\n var lines = message.Split('\\n');\n var apps = lines\n .Where(line => line.StartsWith(\"+\") || line.StartsWith(\"-\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line =>\n line.Contains(\"cannot be\")\n || line.Contains(\"action cannot\")\n || line.Contains(\"Some selected\")\n )\n .Select(line => line.Trim())\n );\n\n var result = SoftwareAppsDialog.ShowYesNoCancel(\n title,\n headerText,\n apps,\n footerText\n );\n return Task.FromResult(result);\n }\n else\n {\n // For simple messages\n var result = SoftwareAppsDialog.ShowYesNoCancel(\n title,\n message,\n new[] { message },\n \"\"\n );\n return Task.FromResult(result);\n }\n }\n\n /// \n /// Shows an operation result dialog to the user.\n /// \n /// The type of operation (e.g., \"Install\", \"Remove\").\n /// The number of successful operations.\n /// The total number of operations.\n /// The list of successfully processed items.\n /// The list of failed items.\n /// The list of skipped items.\n /// Whether there were connectivity issues.\n public void ShowOperationResult(\n string operationType,\n int successCount,\n int totalCount,\n IEnumerable successItems,\n IEnumerable failedItems = null,\n IEnumerable skippedItems = null,\n bool hasConnectivityIssues = false,\n bool isUserCancelled = false\n )\n {\n // Get the past tense form of the operation type\n string GetPastTense(string op)\n {\n if (string.IsNullOrEmpty(op))\n return string.Empty;\n\n return op.Equals(\"Remove\", System.StringComparison.OrdinalIgnoreCase)\n ? \"removed\"\n : $\"{op.ToLower()}ed\";\n }\n\n // Check if any failures are due to internet connectivity issues or user cancellation\n bool isFailure = successCount < totalCount;\n\n string title;\n if (isUserCancelled)\n {\n title = \"Installation Aborted\";\n }\n else if (hasConnectivityIssues)\n {\n title = \"Internet Connection Lost\";\n }\n else\n {\n title = isFailure\n ? $\"{operationType} Operation Failed\"\n : $\"{operationType} Results\";\n }\n\n string headerText;\n if (isUserCancelled)\n {\n headerText = $\"Installation aborted by user\";\n }\n else if (hasConnectivityIssues)\n {\n headerText = \"Installation stopped due to internet connection loss\";\n }\n else\n {\n headerText =\n successCount > 0 && successCount == totalCount\n ? $\"The following items were successfully {GetPastTense(operationType)}:\"\n : (\n successCount > 0\n ? $\"Successfully {GetPastTense(operationType)} {successCount} of {totalCount} items.\"\n : $\"Unable to {operationType.ToLowerInvariant()} {totalCount} of {totalCount} items.\"\n );\n }\n\n // Create list of items for the dialog\n var resultItems = new List();\n\n // For connectivity issues or user cancellation, add a clear explanation\n if (isUserCancelled)\n {\n resultItems.Add(\"The installation process was cancelled by the user.\");\n resultItems.Add(\"\");\n if (successCount > 0)\n {\n resultItems.Add(\"Successfully installed items:\");\n }\n }\n else if (hasConnectivityIssues)\n {\n resultItems.Add(\n \"The installation process was stopped because the internet connection was lost.\"\n );\n resultItems.Add(\n \"This is required to ensure installations complete properly and prevent corrupted installations.\"\n );\n resultItems.Add(\"\");\n resultItems.Add(\"Failed items:\");\n }\n\n // Add successful items directly to the list\n if (successItems != null && successItems.Any())\n {\n if (!hasConnectivityIssues) // Only show success items if not a connectivity issue\n {\n foreach (var item in successItems)\n {\n resultItems.Add(item);\n }\n }\n }\n else if (!hasConnectivityIssues) // Only show this message if not a connectivity issue\n {\n resultItems.Add($\"No items were {GetPastTense(operationType)}.\");\n }\n\n // Add skipped items if any\n if (skippedItems != null && skippedItems.Any() && !hasConnectivityIssues) // Only show if not a connectivity issue\n {\n resultItems.Add($\"Skipped items: {skippedItems.Count()}\");\n foreach (var item in skippedItems.Take(5))\n {\n resultItems.Add($\" - {item}\");\n }\n if (skippedItems.Count() > 5)\n {\n resultItems.Add($\" - ... and {skippedItems.Count() - 5} more\");\n }\n }\n\n // Add failed items if any\n if (failedItems != null && failedItems.Any())\n {\n if (!hasConnectivityIssues) // Only show the header if not already shown for connectivity issues\n {\n resultItems.Add($\"Failed items: {failedItems.Count()}\");\n }\n\n foreach (var item in failedItems.Take(5))\n {\n resultItems.Add($\" - {item}\");\n }\n if (failedItems.Count() > 5)\n {\n resultItems.Add($\" - ... and {failedItems.Count() - 5} more\");\n }\n }\n\n // Create footer text\n string footerText;\n if (isUserCancelled)\n {\n footerText =\n successCount > 0\n ? $\"Some items were successfully {GetPastTense(operationType)} before cancellation.\"\n : $\"No items were {GetPastTense(operationType)} before cancellation.\";\n }\n else if (hasConnectivityIssues)\n {\n footerText =\n \"Please check your network connection and try again when your internet connection is stable.\";\n }\n else\n {\n // Check if we have any connectivity-related failures\n bool hasConnectivityFailures =\n failedItems != null\n && failedItems.Any(item =>\n item.Contains(\"internet\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\"connection\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\"network\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\n \"pipeline has been stopped\",\n StringComparison.OrdinalIgnoreCase\n )\n );\n\n footerText =\n successCount == totalCount\n ? $\"All items were successfully {GetPastTense(operationType)}.\"\n : (\n successCount > 0\n ? (\n hasConnectivityFailures\n ? $\"Some items could not be {GetPastTense(operationType)}. Please check your internet connection and try again.\"\n : $\"Some items could not be {GetPastTense(operationType)}. Please try again later.\"\n )\n : (\n hasConnectivityFailures\n ? $\"Installation failed. Please check your internet connection and try again.\"\n : $\"Installation failed. Please try again later.\"\n )\n );\n }\n\n // Show the information dialog\n SoftwareAppsDialog.ShowInformationAsync(title, headerText, resultItems, footerText);\n }\n\n /// \n /// Gets the past tense form of an operation type\n /// \n /// The operation type (e.g., \"Install\", \"Remove\")\n /// The past tense form of the operation type\n private string GetPastTense(string operationType)\n {\n if (string.IsNullOrEmpty(operationType))\n return string.Empty;\n\n return operationType.Equals(\"Remove\", StringComparison.OrdinalIgnoreCase)\n ? \"removed\"\n : $\"{operationType.ToLower()}ed\";\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/InstallationOrchestrator.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Exceptions;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Orchestrates the installation and removal of applications, capabilities, and features.\n/// \npublic class InstallationOrchestrator : IInstallationOrchestrator\n{\n private readonly IAppInstallationService _appInstallationService;\n private readonly ICapabilityInstallationService _capabilityInstallationService;\n private readonly IFeatureInstallationService _featureInstallationService;\n private readonly IAppRemovalService _appRemovalService;\n private readonly ICapabilityRemovalService _capabilityRemovalService;\n private readonly IFeatureRemovalService _featureRemovalService;\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The app installation service.\n /// The capability installation service.\n /// The feature installation service.\n /// The app removal service.\n /// The capability removal service.\n /// The feature removal service.\n /// The log service.\n public InstallationOrchestrator(\n IAppInstallationService appInstallationService,\n ICapabilityInstallationService capabilityInstallationService,\n IFeatureInstallationService featureInstallationService,\n IAppRemovalService appRemovalService,\n ICapabilityRemovalService capabilityRemovalService,\n IFeatureRemovalService featureRemovalService,\n ILogService logService)\n {\n _appInstallationService = appInstallationService ?? throw new ArgumentNullException(nameof(appInstallationService));\n _capabilityInstallationService = capabilityInstallationService ?? throw new ArgumentNullException(nameof(capabilityInstallationService));\n _featureInstallationService = featureInstallationService ?? throw new ArgumentNullException(nameof(featureInstallationService));\n _appRemovalService = appRemovalService ?? throw new ArgumentNullException(nameof(appRemovalService));\n _capabilityRemovalService = capabilityRemovalService ?? throw new ArgumentNullException(nameof(capabilityRemovalService));\n _featureRemovalService = featureRemovalService ?? throw new ArgumentNullException(nameof(featureRemovalService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Installs an application, capability, or feature.\n /// \n /// The item to install.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the asynchronous operation.\n public async Task InstallAsync(\n IInstallableItem item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (item == null)\n {\n throw new ArgumentNullException(nameof(item));\n }\n\n _logService.LogInformation($\"Installing {item.DisplayName}\");\n\n try\n {\n if (item is AppInfo appInfo)\n {\n await _appInstallationService.InstallAppAsync(appInfo, progress, cancellationToken);\n }\n else if (item is CapabilityInfo capabilityInfo)\n {\n // Assuming InstallCapabilityAsync should be called for single items\n await _capabilityInstallationService.InstallCapabilityAsync(capabilityInfo, progress, cancellationToken);\n }\n else if (item is FeatureInfo featureInfo)\n {\n // Corrected method name\n await _featureInstallationService.InstallFeatureAsync(featureInfo, progress, cancellationToken);\n }\n else\n {\n throw new ArgumentException($\"Unsupported item type: {item.GetType().Name}\", nameof(item));\n }\n\n _logService.LogSuccess($\"Successfully installed {item.DisplayName}\");\n }\n catch (Exception ex) when (ex is not InstallationException)\n {\n _logService.LogError($\"Failed to install {item.DisplayName}\", ex);\n throw new InstallationException(item.DisplayName, $\"Installation failed for {item.DisplayName}\", false, ex);\n }\n }\n\n /// \n /// Removes an application, capability, or feature.\n /// \n /// The item to remove.\n /// A task representing the asynchronous operation.\n public async Task RemoveAsync(IInstallableItem item)\n {\n if (item == null)\n {\n throw new ArgumentNullException(nameof(item));\n }\n\n _logService.LogInformation($\"Removing {item.DisplayName}\");\n\n try\n {\n if (item is AppInfo appInfo)\n {\n await _appRemovalService.RemoveAppAsync(appInfo);\n }\n else if (item is CapabilityInfo capabilityInfo)\n {\n await _capabilityRemovalService.RemoveCapabilityAsync(capabilityInfo);\n }\n else if (item is FeatureInfo featureInfo)\n {\n await _featureRemovalService.RemoveFeatureAsync(featureInfo);\n }\n else\n {\n throw new ArgumentException($\"Unsupported item type: {item.GetType().Name}\", nameof(item));\n }\n\n _logService.LogSuccess($\"Successfully removed {item.DisplayName}\");\n }\n catch (Exception ex) when (ex is not RemovalException)\n {\n _logService.LogError($\"Failed to remove {item.DisplayName}\", ex);\n throw new RemovalException(item.DisplayName, ex.Message, true, ex);\n }\n }\n\n /// \n /// Installs multiple items in batch.\n /// \n /// The items to install.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the asynchronous operation.\n public async Task InstallBatchAsync(\n IEnumerable items,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (items == null)\n {\n throw new ArgumentNullException(nameof(items));\n }\n\n var itemsList = new List(items);\n _logService.LogInformation($\"Installing {itemsList.Count} items in batch\");\n\n int totalItems = itemsList.Count;\n int completedItems = 0;\n\n foreach (var item in itemsList)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n _logService.LogWarning(\"Batch installation cancelled\");\n break;\n }\n\n try\n {\n // Create a progress wrapper that scales the progress to the current item's portion\n var itemProgress = progress != null\n ? new Progress(detail =>\n {\n // Scale the progress to the current item's portion of the total\n double scaledProgress = (completedItems * 100.0 + (detail.Progress ?? 0)) / totalItems;\n \n progress.Report(new TaskProgressDetail\n {\n Progress = scaledProgress,\n StatusText = $\"[{completedItems + 1}/{totalItems}] {detail.StatusText}\",\n DetailedMessage = detail.DetailedMessage,\n LogLevel = detail.LogLevel\n });\n })\n : null;\n\n await InstallAsync(item, itemProgress, cancellationToken);\n completedItems++;\n\n // Report overall progress\n progress?.Report(new TaskProgressDetail\n {\n Progress = completedItems * 100.0 / totalItems,\n StatusText = $\"Completed {completedItems} of {totalItems} items\",\n DetailedMessage = $\"Successfully installed {item.DisplayName}\"\n });\n }\n catch (Exception ex) when (ex is not InstallationException)\n {\n _logService.LogError($\"Error installing {item.DisplayName}\", ex);\n \n // Report error but continue with next item\n progress?.Report(new TaskProgressDetail\n {\n Progress = completedItems * 100.0 / totalItems,\n StatusText = $\"Error installing {item.DisplayName}\",\n DetailedMessage = ex.Message,\n LogLevel = Winhance.Core.Features.Common.Enums.LogLevel.Error\n });\n\n throw new InstallationException($\"Error installing {item.DisplayName}: {ex.Message}\", ex);\n }\n }\n\n _logService.LogInformation($\"Batch installation completed. {completedItems} of {totalItems} items installed successfully.\");\n }\n\n /// \n /// Removes multiple items in batch.\n /// \n /// The items to remove.\n /// A list of results indicating success or failure for each item.\n public async Task> RemoveBatchAsync(\n IEnumerable items)\n {\n if (items == null)\n {\n throw new ArgumentNullException(nameof(items));\n }\n\n var itemsList = new List(items);\n _logService.LogInformation($\"Removing {itemsList.Count} items in batch\");\n\n var results = new List<(string Name, bool Success, string? Error)>();\n\n foreach (var item in itemsList)\n {\n try\n {\n await RemoveAsync(item);\n results.Add((item.DisplayName, true, null));\n }\n catch (Exception ex) when (ex is not RemovalException)\n {\n _logService.LogError($\"Error removing {item.DisplayName}\", ex);\n results.Add((item.DisplayName, false, new RemovalException(item.DisplayName, ex.Message, true, ex).Message));\n }\n }\n\n int successCount = results.Count(r => r.Success);\n _logService.LogInformation($\"Batch removal completed. {successCount} of {results.Count} items removed successfully.\");\n\n return results;\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/UacSettingsService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading.Tasks;\nusing Newtonsoft.Json;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for managing UAC settings persistence.\n /// \n public class UacSettingsService : IUacSettingsService\n {\n private const string CustomUacSettingsKey = \"CustomUacSettings\";\n private readonly UserPreferencesService _userPreferencesService;\n private readonly ILogService _logService;\n \n // Cache for custom UAC settings during the current session\n private CustomUacSettings _cachedSettings;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The user preferences service.\n /// The log service.\n public UacSettingsService(UserPreferencesService userPreferencesService, ILogService logService)\n {\n _userPreferencesService = userPreferencesService ?? throw new ArgumentNullException(nameof(userPreferencesService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Saves custom UAC settings.\n /// \n /// The ConsentPromptBehaviorAdmin registry value.\n /// The PromptOnSecureDesktop registry value.\n /// A task representing the asynchronous operation.\n public async Task SaveCustomUacSettingsAsync(int consentPromptValue, int secureDesktopValue)\n {\n try\n {\n // Create a CustomUacSettings object\n var settings = new CustomUacSettings(consentPromptValue, secureDesktopValue);\n \n // Cache the settings\n _cachedSettings = settings;\n \n // Save to user preferences\n await _userPreferencesService.SetPreferenceAsync(CustomUacSettingsKey, settings);\n \n _logService.Log(LogLevel.Info, \n $\"Saved custom UAC settings: ConsentPrompt={consentPromptValue}, SecureDesktop={secureDesktopValue}\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving custom UAC settings: {ex.Message}\");\n }\n }\n\n /// \n /// Loads custom UAC settings.\n /// \n /// A CustomUacSettings object if settings exist, null otherwise.\n public async Task LoadCustomUacSettingsAsync()\n {\n try\n {\n // Try to get from cache first\n if (_cachedSettings != null)\n {\n return _cachedSettings;\n }\n \n // Try to load from preferences\n var settings = await _userPreferencesService.GetPreferenceAsync(CustomUacSettingsKey, default(CustomUacSettings));\n if (settings != null)\n {\n // Cache the settings\n _cachedSettings = settings;\n return settings;\n }\n \n return null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading custom UAC settings: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Checks if custom UAC settings exist.\n /// \n /// True if custom settings exist, false otherwise.\n public async Task HasCustomUacSettingsAsync()\n {\n try\n {\n // Check cache first\n if (_cachedSettings != null)\n {\n return true;\n }\n \n // Check user preferences\n var settings = await _userPreferencesService.GetPreferenceAsync(CustomUacSettingsKey, null);\n return settings != null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking for custom UAC settings: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Gets custom UAC settings if they exist.\n /// \n /// The ConsentPromptBehaviorAdmin registry value.\n /// The PromptOnSecureDesktop registry value.\n /// True if custom settings were retrieved, false otherwise.\n public bool TryGetCustomUacValues(out int consentPromptValue, out int secureDesktopValue)\n {\n // Initialize out parameters\n consentPromptValue = 0;\n secureDesktopValue = 0;\n \n try\n {\n // Check cache first\n if (_cachedSettings != null)\n {\n consentPromptValue = _cachedSettings.ConsentPromptValue;\n secureDesktopValue = _cachedSettings.SecureDesktopValue;\n return true;\n }\n \n // Try to load from preferences (completely synchronously)\n string preferencesFilePath = GetPreferencesFilePath();\n if (File.Exists(preferencesFilePath))\n {\n try\n {\n string json = File.ReadAllText(preferencesFilePath);\n var preferences = JsonConvert.DeserializeObject>(json);\n \n if (preferences != null && preferences.ContainsKey(CustomUacSettingsKey))\n {\n var settingsToken = preferences[CustomUacSettingsKey];\n var settings = JsonConvert.DeserializeObject(settingsToken.ToString());\n \n if (settings != null)\n {\n // Cache the settings\n _cachedSettings = settings;\n \n consentPromptValue = settings.ConsentPromptValue;\n secureDesktopValue = settings.SecureDesktopValue;\n return true;\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error reading preferences file: {ex.Message}\");\n }\n }\n \n return false;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting custom UAC values: {ex.Message}\");\n\n return false;\n }\n }\n \n /// \n /// Gets the path to the user preferences file.\n /// \n /// The full path to the user preferences file.\n private string GetPreferencesFilePath()\n {\n // Get the LocalApplicationData folder (e.g., C:\\Users\\Username\\AppData\\Local)\n string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n \n // Combine with Winhance/Config\n string appDataPath = Path.Combine(localAppData, \"Winhance\", \"Config\");\n \n // Ensure the directory exists\n if (!Directory.Exists(appDataPath))\n {\n Directory.CreateDirectory(appDataPath);\n }\n \n // Return the full path to the preferences file\n return Path.Combine(appDataPath, \"UserPreferences.json\");\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/DialogService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n public class DialogService : IDialogService\n {\n public void ShowMessage(string message, string title = \"\")\n {\n // Use CustomDialog for all messages\n CustomDialog.ShowInformation(title, title, message, \"\");\n }\n\n public Task ShowConfirmationAsync(\n string message,\n string title = \"\",\n string okButtonText = \"OK\",\n string cancelButtonText = \"Cancel\"\n )\n {\n // For regular confirmation messages without app lists\n if (\n !message.Contains(\"following\")\n || (!message.Contains(\"install\") && !message.Contains(\"remove\"))\n )\n {\n return Task.FromResult(\n MessageBox.Show(\n message,\n title,\n MessageBoxButton.YesNo,\n MessageBoxImage.Question\n ) == MessageBoxResult.Yes\n );\n }\n\n // Parse apps from the message\n var lines = message.Split('\\n');\n var apps = lines\n .Where(line => line.StartsWith(\"+\") || line.StartsWith(\"-\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line =>\n line.Contains(\"cannot be\")\n || line.Contains(\"action cannot\")\n || line.Contains(\"Some selected\")\n )\n .Select(line => line.Trim())\n );\n\n var result = CustomDialog.ShowConfirmation(title, headerText, apps, footerText);\n return Task.FromResult(result ?? false);\n }\n\n public Task ShowErrorAsync(string message, string title = \"Error\", string buttonText = \"OK\")\n {\n // Use CustomDialog for all error messages\n CustomDialog.ShowInformation(title, title, message, \"\");\n return Task.CompletedTask;\n }\n\n public Task ShowInformationAsync(\n string message,\n string title = \"Information\",\n string buttonText = \"OK\"\n )\n {\n // For messages with app lists (special handling)\n if (message.Contains(\"following\") && \n (message.Contains(\"installed\") || message.Contains(\"removed\")))\n {\n // Parse apps from the message\n var lines = message.Split('\\n');\n var apps = lines\n .Where(line => line.StartsWith(\"+\") || line.StartsWith(\"-\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line => line.Contains(\"Failed\") || line.Contains(\"startup task\"))\n .Select(line => line.Trim())\n );\n\n CustomDialog.ShowInformation(title, headerText, apps, footerText);\n return Task.CompletedTask;\n }\n \n // For all other information messages, use CustomDialog\n CustomDialog.ShowInformation(title, title, message, \"\");\n return Task.CompletedTask;\n }\n\n public Task ShowWarningAsync(\n string message,\n string title = \"Warning\",\n string buttonText = \"OK\"\n )\n {\n MessageBox.Show(message, title, MessageBoxButton.OK, MessageBoxImage.Warning);\n return Task.CompletedTask;\n }\n\n public Task ShowInputAsync(\n string message,\n string title = \"\",\n string defaultValue = \"\"\n )\n {\n var result = MessageBox.Show(\n message,\n title,\n MessageBoxButton.OKCancel,\n MessageBoxImage.Question\n );\n return Task.FromResult(result == MessageBoxResult.OK ? defaultValue : null);\n }\n\n public Task ShowYesNoCancelAsync(string message, string title = \"\")\n {\n // For theme change messages (special case for \"Choose Your Mode\" combobox)\n if (message.Contains(\"theme wallpaper\") || title.Contains(\"Theme\"))\n {\n // Create a list with a single item for the message\n var messageList = new List { message };\n\n // Use the CustomDialog.ShowConfirmation method (Yes/No only)\n var themeDialogResult = CustomDialog.ShowConfirmation(\n title,\n \"Theme Change\",\n messageList,\n \"\"\n );\n\n // Convert to bool? (Yes/No only, no Cancel)\n return Task.FromResult(themeDialogResult);\n }\n // For regular messages without app lists\n else if (\n !message.Contains(\"following\")\n || (!message.Contains(\"install\") && !message.Contains(\"remove\"))\n )\n {\n var result = MessageBox.Show(\n message,\n title,\n MessageBoxButton.YesNoCancel,\n MessageBoxImage.Question\n );\n bool? boolResult = result switch\n {\n MessageBoxResult.Yes => true,\n MessageBoxResult.No => false,\n _ => null,\n };\n return Task.FromResult(boolResult);\n }\n\n // Parse apps from the message\n var lines = message.Split('\\n');\n var apps = lines\n .Where(line => line.StartsWith(\"+\") || line.StartsWith(\"-\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line =>\n line.Contains(\"cannot be\")\n || line.Contains(\"action cannot\")\n || line.Contains(\"Some selected\")\n )\n .Select(line => line.Trim())\n );\n\n // Use the CustomDialog.ShowYesNoCancel method\n var dialogResult = CustomDialog.ShowYesNoCancel(title, headerText, apps, footerText);\n return Task.FromResult(dialogResult);\n }\n\n public async Task> ShowUnifiedConfigurationSaveDialogAsync(\n string title,\n string description,\n Dictionary sections\n )\n {\n // Create the dialog\n var dialog = new UnifiedConfigurationDialog(title, description, sections, true);\n\n // Set the owner to the current active window\n dialog.Owner = Application.Current.MainWindow;\n\n // Show the dialog\n var result = dialog.ShowDialog();\n\n // Return the result if the user clicked OK, otherwise return null\n if (result == true)\n {\n return dialog.GetResult();\n }\n\n return null;\n }\n\n public async Task> ShowUnifiedConfigurationImportDialogAsync(\n string title,\n string description,\n Dictionary sections\n )\n {\n // Create the dialog\n var dialog = new UnifiedConfigurationDialog(title, description, sections, false);\n\n // Set the owner to the current active window\n dialog.Owner = Application.Current.MainWindow;\n\n // Show the dialog\n var result = dialog.ShowDialog();\n\n // Return the result if the user clicked OK, otherwise return null\n if (result == true)\n {\n return dialog.GetResult();\n }\n\n return null;\n }\n\n /// \n /// Displays a donation dialog.\n /// \n /// The title of the dialog box.\n /// The support message to display.\n /// The footer text.\n /// A task representing the asynchronous operation, with a tuple containing the dialog result (whether the user clicked Yes or No) and whether the \"Don't show again\" checkbox was checked.\n public async Task<(bool? Result, bool DontShowAgain)> ShowDonationDialogAsync(\n string title,\n string supportMessage,\n string footerText\n )\n {\n try\n {\n // Use the DonationDialog.ShowDonationDialogAsync method\n var dialog = await DonationDialog.ShowDonationDialogAsync(\n title,\n supportMessage,\n footerText\n );\n\n // Return the dialog result and the DontShowAgain value as a tuple\n return (dialog?.DialogResult, dialog?.DontShowAgain ?? false);\n }\n catch (Exception ex)\n {\n // Log the error\n System.Diagnostics.Debug.WriteLine($\"Error showing donation dialog: {ex.Message}\");\n return (false, false);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServicePowerShell.cs", "using Microsoft.Win32;\nusing System;\nusing System.Diagnostics;\nusing System.Text;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n public partial class RegistryService\n {\n /// \n /// Sets a registry value using PowerShell with elevated privileges.\n /// This is a fallback method for when the standard .NET Registry API fails.\n /// \n /// The full path to the registry key.\n /// The name of the registry value.\n /// The value to set.\n /// The type of the registry value.\n /// True if the value was successfully set, false otherwise.\n private bool SetValueUsingPowerShell(string keyPath, string valueName, object value, RegistryValueKind valueKind)\n {\n try\n {\n _logService.LogInformation($\"Attempting to set registry value using PowerShell: {keyPath}\\\\{valueName}\");\n\n // Format the PowerShell command based on the value type\n string psCommand = FormatPowerShellCommand(keyPath, valueName, value, valueKind);\n\n // Create a PowerShell process with elevated privileges\n var startInfo = new ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-NoProfile -ExecutionPolicy Bypass -Command \\\"{psCommand}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n Verb = \"runas\" // Run as administrator\n };\n\n _logService.LogInformation($\"Executing PowerShell command: {psCommand}\");\n\n using var process = new Process { StartInfo = startInfo };\n \n try\n {\n process.Start();\n }\n catch (Exception ex)\n {\n _logService.LogWarning($\"Failed to start PowerShell with admin rights: {ex.Message}. Trying without elevation...\");\n \n // Try again without elevation\n startInfo.Verb = null;\n using var nonElevatedProcess = new Process { StartInfo = startInfo };\n nonElevatedProcess.Start();\n \n string nonElevatedOutput = nonElevatedProcess.StandardOutput.ReadToEnd();\n string nonElevatedError = nonElevatedProcess.StandardError.ReadToEnd();\n \n nonElevatedProcess.WaitForExit();\n \n if (nonElevatedProcess.ExitCode == 0)\n {\n _logService.LogSuccess($\"Successfully set registry value using non-elevated PowerShell: {keyPath}\\\\{valueName}\");\n \n // Clear the cache for this value\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueCache)\n {\n if (_valueCache.ContainsKey(fullValuePath))\n {\n _valueCache.Remove(fullValuePath);\n }\n }\n \n return true;\n }\n \n _logService.LogWarning($\"Non-elevated PowerShell also failed: {nonElevatedError}\");\n return false;\n }\n \n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n \n process.WaitForExit();\n\n if (process.ExitCode == 0)\n {\n _logService.LogSuccess($\"Successfully set registry value using PowerShell: {keyPath}\\\\{valueName}\");\n \n // Clear the cache for this value\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueCache)\n {\n if (_valueCache.ContainsKey(fullValuePath))\n {\n _valueCache.Remove(fullValuePath);\n }\n }\n \n return true;\n }\n else\n {\n _logService.LogWarning($\"PowerShell failed to set registry value: {error}\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error using PowerShell to set registry value: {ex.Message}\", ex);\n return false;\n }\n }\n\n /// \n /// Formats a PowerShell command to set a registry value.\n /// \n private string FormatPowerShellCommand(string keyPath, string valueName, object value, RegistryValueKind valueKind)\n {\n // Split the key path into hive and subkey\n string[] pathParts = keyPath.Split('\\\\');\n string hive = pathParts[0];\n string subKey = string.Join('\\\\', pathParts.Skip(1));\n\n // Map the registry hive to PowerShell drive\n string psDrive = hive switch\n {\n \"HKCU\" or \"HKEY_CURRENT_USER\" => \"HKCU:\",\n \"HKLM\" or \"HKEY_LOCAL_MACHINE\" => \"HKLM:\",\n \"HKCR\" or \"HKEY_CLASSES_ROOT\" => \"HKCR:\",\n \"HKU\" or \"HKEY_USERS\" => \"HKU:\",\n \"HKCC\" or \"HKEY_CURRENT_CONFIG\" => \"HKCC:\",\n _ => throw new ArgumentException($\"Unsupported registry hive: {hive}\")\n };\n\n // Format the value based on its type\n string valueArg = FormatValueForPowerShell(value, valueKind);\n string typeArg = GetPowerShellTypeArg(valueKind);\n\n // Build the PowerShell command with enhanced error handling and permissions\n var sb = new StringBuilder();\n \n // Add error handling\n sb.Append(\"$ErrorActionPreference = 'Stop'; \");\n sb.Append(\"try { \");\n \n // First, ensure the key exists with proper permissions\n sb.Append($\"if (-not (Test-Path -Path '{psDrive}\\\\{subKey}')) {{ \");\n \n // Create the key with force to ensure all parent keys are created\n sb.Append($\"New-Item -Path '{psDrive}\\\\{subKey}' -Force | Out-Null; \");\n \n // For policy keys, try to set appropriate permissions\n if (subKey.Contains(\"Policies\", StringComparison.OrdinalIgnoreCase))\n {\n sb.Append($\"$acl = Get-Acl -Path '{psDrive}\\\\{subKey}'; \");\n sb.Append(\"$rule = New-Object System.Security.AccessControl.RegistryAccessRule('CURRENT_USER', 'FullControl', 'Allow'); \");\n sb.Append(\"$acl.SetAccessRule($rule); \");\n sb.Append($\"try {{ Set-Acl -Path '{psDrive}\\\\{subKey}' -AclObject $acl }} catch {{ Write-Host 'Could not set ACL, continuing anyway...' }}; \");\n }\n \n sb.Append(\"} \");\n \n // Then set the value\n sb.Append($\"Set-ItemProperty -Path '{psDrive}\\\\{subKey}' -Name '{valueName}' -Value {valueArg} {typeArg} -Force; \");\n \n // Verify the value was set correctly\n sb.Append($\"$setVal = Get-ItemProperty -Path '{psDrive}\\\\{subKey}' -Name '{valueName}' -ErrorAction SilentlyContinue; \");\n sb.Append(\"if ($setVal -eq $null) { throw 'Value was not set properly' }; \");\n \n // Close the try block and add catch\n sb.Append(\"} catch { Write-Error $_.Exception.Message; exit 1 }\");\n\n return sb.ToString();\n }\n\n /// \n /// Formats a value for use with PowerShell.\n /// \n private string FormatValueForPowerShell(object value, RegistryValueKind valueKind)\n {\n return valueKind switch\n {\n RegistryValueKind.DWord or RegistryValueKind.QWord => value.ToString(),\n RegistryValueKind.String or RegistryValueKind.ExpandString => $\"'{value}'\",\n RegistryValueKind.MultiString => $\"@('{string.Join(\"','\", (string[])value)})'\",\n RegistryValueKind.Binary => $\"([byte[]]@({string.Join(\",\", (byte[])value)}))\",\n _ => $\"'{value}'\"\n };\n }\n\n /// \n /// Gets the PowerShell type argument for a registry value kind.\n /// \n private string GetPowerShellTypeArg(RegistryValueKind valueKind)\n {\n return valueKind switch\n {\n RegistryValueKind.String => \"-Type String\",\n RegistryValueKind.ExpandString => \"-Type ExpandString\",\n RegistryValueKind.Binary => \"-Type Binary\",\n RegistryValueKind.DWord => \"-Type DWord\",\n RegistryValueKind.MultiString => \"-Type MultiString\",\n RegistryValueKind.QWord => \"-Type QWord\",\n _ => \"\"\n };\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceStatusMethods.cs", "using Microsoft.Win32;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n public partial class RegistryService\n {\n public async Task GetSettingStatusAsync(RegistrySetting setting)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return RegistrySettingStatus.Error;\n }\n\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot get status for null registry setting\");\n return RegistrySettingStatus.Unknown;\n }\n\n string hiveString = RegistryExtensions.GetRegistryHiveString(setting.Hive);\n string fullPath = $\"{hiveString}\\\\{setting.SubKey}\";\n string fullValuePath = $\"{fullPath}\\\\{setting.Name}\";\n\n _logService.Log(LogLevel.Info, $\"Checking registry setting status: {fullValuePath}\");\n\n // Check if the key exists (using cache)\n bool keyExists;\n lock (_keyExistsCache)\n {\n if (!_keyExistsCache.TryGetValue(fullPath, out keyExists))\n {\n keyExists = KeyExists(fullPath);\n _keyExistsCache[fullPath] = keyExists;\n }\n }\n\n // Handle non-existence of the key\n if (!keyExists)\n {\n // For Remove actions, non-existence of the key is considered \"Applied\"\n if (setting.ActionType == RegistryActionType.Remove)\n {\n return RegistrySettingStatus.Applied;\n }\n\n // For settings where absence means enabled (like HttpAcceptLanguageOptOut)\n if (setting.AbsenceMeansEnabled)\n {\n _logService.Log(LogLevel.Info, $\"Key does not exist and AbsenceMeansEnabled is true - marking as Applied\");\n return RegistrySettingStatus.Applied;\n }\n\n // Default behavior: absence means not applied\n return RegistrySettingStatus.NotApplied;\n }\n\n // Check if the value exists (using cache)\n bool valueExists;\n lock (_valueExistsCache)\n {\n if (!_valueExistsCache.TryGetValue(fullValuePath, out valueExists))\n {\n valueExists = ValueExists(fullPath, setting.Name);\n _valueExistsCache[fullValuePath] = valueExists;\n }\n }\n\n // Handle non-existence of the value\n if (!valueExists)\n {\n // For Remove actions, non-existence of the value is considered \"Applied\"\n if (setting.ActionType == RegistryActionType.Remove)\n {\n return RegistrySettingStatus.Applied;\n }\n\n // For settings where absence means enabled (like HttpAcceptLanguageOptOut)\n if (setting.AbsenceMeansEnabled)\n {\n _logService.Log(LogLevel.Info, $\"Value does not exist and AbsenceMeansEnabled is true - marking as Applied\");\n return RegistrySettingStatus.Applied;\n }\n\n // Default behavior: absence means not applied\n return RegistrySettingStatus.NotApplied;\n }\n\n // If we're here and the action type is Remove, the key/value still exists\n if (setting.ActionType == RegistryActionType.Remove)\n {\n // Special case for 3D Objects toggle which is opposite of normal Remove action\n // When the key exists, 3D Objects is shown (Applied)\n if (setting.Name == \"{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}\")\n {\n _logService.Log(LogLevel.Info, $\"3D Objects key exists - marking as Applied\");\n return RegistrySettingStatus.Applied;\n }\n \n // For normal Remove actions, key existing means not applied\n return RegistrySettingStatus.NotApplied;\n }\n\n // Get the current value (using cache)\n object? currentValue;\n lock (_valueCache)\n {\n if (!_valueCache.TryGetValue(fullValuePath, out currentValue))\n {\n currentValue = GetValue(fullPath, setting.Name);\n _valueCache[fullValuePath] = currentValue;\n }\n }\n\n // If the value is null, consider it not applied\n if (currentValue == null)\n {\n return RegistrySettingStatus.NotApplied;\n }\n\n // Compare with enabled value (use EnabledValue if available, otherwise fall back to RecommendedValue)\n object valueToCompare = setting.EnabledValue ?? setting.RecommendedValue;\n bool matchesEnabled = CompareValues(currentValue, valueToCompare);\n if (matchesEnabled)\n {\n return RegistrySettingStatus.Applied;\n }\n\n // If there's a disabled value specified, check if it matches that\n object? disabledValue = setting.DisabledValue ?? setting.DefaultValue;\n if (disabledValue != null)\n {\n bool matchesDisabled = CompareValues(currentValue, disabledValue);\n if (matchesDisabled)\n {\n return RegistrySettingStatus.NotApplied;\n }\n }\n\n // If it doesn't match recommended or default, it's modified\n return RegistrySettingStatus.Modified;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking registry setting status: {ex.Message}\");\n return RegistrySettingStatus.Error;\n }\n }\n\n public async Task> GetSettingsStatusAsync(IEnumerable settings)\n {\n var results = new Dictionary();\n\n if (settings == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot get status for null registry settings collection\");\n return results;\n }\n\n foreach (var setting in settings)\n {\n if (setting == null || string.IsNullOrEmpty(setting.Name))\n {\n continue;\n }\n\n var status = await GetSettingStatusAsync(setting);\n results[setting.Name] = status;\n }\n\n return results;\n }\n\n public async Task GetLinkedSettingsStatusAsync(LinkedRegistrySettings linkedSettings)\n {\n if (linkedSettings == null || linkedSettings.Settings.Count == 0)\n return RegistrySettingStatus.Unknown;\n\n try\n {\n List statuses = new List();\n \n // Special case: If all settings have ActionType = Remove, we need to handle differently\n bool allRemoveActions = linkedSettings.Settings.All(s => s.ActionType == RegistryActionType.Remove);\n \n if (allRemoveActions)\n {\n // For Remove actions, we need to check if all keys/values don't exist (for All logic)\n // or if any key/value doesn't exist (for Any logic)\n bool allKeysRemoved = true;\n bool anyKeyRemoved = false;\n \n foreach (var setting in linkedSettings.Settings)\n {\n string fullPath = $\"{RegistryExtensions.GetRegistryHiveString(setting.Hive)}\\\\{setting.SubKey}\";\n string fullValuePath = $\"{fullPath}\\\\{setting.Name}\";\n \n // Check if the key exists\n bool keyExists = KeyExists(fullPath);\n \n // For Remove actions, if the key doesn't exist, it's considered \"removed\" (Applied)\n if (!keyExists)\n {\n anyKeyRemoved = true;\n }\n else\n {\n // Key exists, now check if the value exists\n bool valueExists = ValueExists(fullPath, setting.Name);\n \n if (!valueExists)\n {\n anyKeyRemoved = true;\n }\n else\n {\n // Special case for 3D Objects toggle which is opposite of normal Remove action\n // When the key exists, 3D Objects is shown (should be considered Applied)\n if (setting.Name == \"{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}\")\n {\n _logService.Log(LogLevel.Info, $\"3D Objects key exists in linked settings - special handling\");\n // For 3D Objects, we want to return Applied when the key exists\n // So we don't set allKeysRemoved to false here\n continue;\n }\n \n allKeysRemoved = false;\n }\n }\n }\n \n // Determine status based on the logic\n if (linkedSettings.Logic == LinkedSettingsLogic.All)\n {\n return allKeysRemoved ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n }\n else\n {\n return anyKeyRemoved ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n }\n }\n \n // Normal case: Process each setting individually\n foreach (var setting in linkedSettings.Settings)\n {\n var status = await GetSettingStatusAsync(setting);\n statuses.Add(status);\n }\n\n // Check if any settings have an error status\n if (statuses.Contains(RegistrySettingStatus.Error))\n {\n return RegistrySettingStatus.Error;\n }\n\n // Check if any settings have an unknown status\n if (statuses.Contains(RegistrySettingStatus.Unknown))\n {\n return RegistrySettingStatus.Unknown;\n }\n\n // Count how many settings are applied\n int appliedCount = statuses.Count(s => s == RegistrySettingStatus.Applied);\n int notAppliedCount = statuses.Count(s => s == RegistrySettingStatus.NotApplied);\n int modifiedCount = statuses.Count(s => s == RegistrySettingStatus.Modified);\n\n // Determine the overall status based on the logic type\n switch (linkedSettings.Logic)\n {\n case LinkedSettingsLogic.All:\n // All settings must be applied for the overall status to be Applied\n if (appliedCount == statuses.Count)\n {\n return RegistrySettingStatus.Applied;\n }\n else if (notAppliedCount == statuses.Count)\n {\n return RegistrySettingStatus.NotApplied;\n }\n else\n {\n return RegistrySettingStatus.Modified;\n }\n\n case LinkedSettingsLogic.Any:\n // Any applied setting means the overall status is Applied\n if (appliedCount > 0)\n {\n return RegistrySettingStatus.Applied;\n }\n else if (notAppliedCount == statuses.Count)\n {\n return RegistrySettingStatus.NotApplied;\n }\n else\n {\n return RegistrySettingStatus.Modified;\n }\n\n case LinkedSettingsLogic.Primary:\n // Find the primary setting\n var primarySetting = linkedSettings.Settings.FirstOrDefault(s => s.IsPrimary);\n if (primarySetting != null)\n {\n // Return the status of the primary setting\n return await GetSettingStatusAsync(primarySetting);\n }\n else\n {\n // If no primary setting is found, fall back to All logic\n if (appliedCount == statuses.Count)\n {\n return RegistrySettingStatus.Applied;\n }\n else if (notAppliedCount == statuses.Count)\n {\n return RegistrySettingStatus.NotApplied;\n }\n else\n {\n return RegistrySettingStatus.Modified;\n }\n }\n\n default:\n // Default to Any logic\n if (appliedCount > 0)\n {\n return RegistrySettingStatus.Applied;\n }\n else if (notAppliedCount == statuses.Count)\n {\n return RegistrySettingStatus.NotApplied;\n }\n else\n {\n return RegistrySettingStatus.Modified;\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking linked registry settings status: {ex.Message}\");\n return RegistrySettingStatus.Error;\n }\n }\n\n public async Task GetOptimizationSettingStatusAsync(Winhance.Core.Features.Optimize.Models.OptimizationSetting setting)\n {\n if (setting == null)\n {\n return RegistrySettingStatus.Unknown;\n }\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Checking status for optimization setting: {setting.Name}\");\n\n // If the setting has registry settings collection, create a LinkedRegistrySettings and use that\n if (setting.RegistrySettings != null && setting.RegistrySettings.Count > 0)\n {\n var linkedSettings = new LinkedRegistrySettings\n {\n Settings = setting.RegistrySettings.ToList(),\n Logic = setting.LinkedSettingsLogic\n };\n return await GetLinkedSettingsStatusAsync(linkedSettings);\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Optimization setting {setting.Name} has no registry settings\");\n return RegistrySettingStatus.Unknown;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking optimization setting status: {ex.Message}\");\n return RegistrySettingStatus.Error;\n }\n }\n\n /// \n /// Helper method to compare registry values, handling different types.\n /// \n private bool CompareValues(object? currentValue, object? desiredValue)\n {\n if (currentValue == null && desiredValue == null)\n {\n return true;\n }\n\n if (currentValue == null || desiredValue == null)\n {\n return false;\n }\n\n // Handle different types of registry values\n if (currentValue is int intValue && desiredValue is int desiredIntValue)\n {\n return intValue == desiredIntValue;\n }\n else if (currentValue is string strValue && desiredValue is string desiredStrValue)\n {\n return strValue.Equals(desiredStrValue, StringComparison.OrdinalIgnoreCase);\n }\n else if (currentValue is byte[] byteArrayValue && desiredValue is byte[] desiredByteArrayValue)\n {\n return byteArrayValue.SequenceEqual(desiredByteArrayValue);\n }\n else\n {\n // For other types, use the default Equals method\n return currentValue.Equals(desiredValue);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/PowerShellScriptBuilderService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Service for building PowerShell script content.\n /// \n public class PowerShellScriptBuilderService : IScriptBuilderService\n {\n private readonly IScriptTemplateProvider _templateProvider;\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The template provider.\n /// The logging service.\n public PowerShellScriptBuilderService(\n IScriptTemplateProvider templateProvider,\n ILogService logService)\n {\n _templateProvider = templateProvider ?? throw new ArgumentNullException(nameof(templateProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string BuildPackageRemovalScript(IEnumerable packageNames)\n {\n if (packageNames == null || !packageNames.Any())\n {\n return string.Empty;\n }\n\n var sb = new StringBuilder();\n sb.AppendLine(\"# Remove packages\");\n \n string template = _templateProvider.GetPackageRemovalTemplate();\n \n foreach (var packageName in packageNames)\n {\n sb.AppendLine();\n sb.AppendLine($\"# Remove {packageName}\");\n sb.AppendLine(string.Format(template, packageName));\n }\n\n return sb.ToString();\n }\n\n /// \n public string BuildCapabilityRemovalScript(IEnumerable capabilityNames)\n {\n if (capabilityNames == null || !capabilityNames.Any())\n {\n return string.Empty;\n }\n\n var sb = new StringBuilder();\n sb.AppendLine(\"# Remove capabilities\");\n \n string template = _templateProvider.GetCapabilityRemovalTemplate();\n \n foreach (var capabilityName in capabilityNames)\n {\n sb.AppendLine();\n sb.AppendLine($\"# Remove {capabilityName}\");\n sb.AppendLine(string.Format(template, capabilityName));\n }\n\n return sb.ToString();\n }\n\n /// \n public string BuildFeatureRemovalScript(IEnumerable featureNames)\n {\n if (featureNames == null || !featureNames.Any())\n {\n return string.Empty;\n }\n\n var sb = new StringBuilder();\n sb.AppendLine(\"# Disable Optional Features\");\n \n string template = _templateProvider.GetFeatureRemovalTemplate();\n \n foreach (var featureName in featureNames)\n {\n sb.AppendLine();\n sb.AppendLine($\"# Disable {featureName}\");\n sb.AppendLine(string.Format(template, featureName));\n }\n\n return sb.ToString();\n }\n\n /// \n public string BuildRegistryScript(Dictionary> registrySettings)\n {\n if (registrySettings == null || !registrySettings.Any())\n {\n return string.Empty;\n }\n\n var sb = new StringBuilder();\n sb.AppendLine(\"# Registry settings\");\n\n foreach (var appEntry in registrySettings)\n {\n string appName = appEntry.Key;\n List settings = appEntry.Value;\n\n if (settings == null || !settings.Any())\n {\n continue;\n }\n\n sb.AppendLine();\n sb.AppendLine($\"# Registry settings for {appName}\");\n\n foreach (var setting in settings)\n {\n string path = setting.Path;\n string name = setting.Name;\n string valueKind = GetRegTypeString(setting.ValueKind);\n string value = setting.Value?.ToString() ?? string.Empty;\n\n // Check if this is a delete operation (value is null or empty)\n bool isDelete = string.IsNullOrEmpty(value);\n string template = _templateProvider.GetRegistrySettingTemplate(isDelete);\n\n if (isDelete)\n {\n sb.AppendLine(string.Format(template, path, name));\n }\n else\n {\n // Format the value based on its type\n string formattedValue = FormatRegistryValue(value, setting.ValueKind);\n sb.AppendLine(string.Format(template, path, name, valueKind, formattedValue));\n }\n }\n }\n\n return sb.ToString();\n }\n\n /// \n public string BuildCompleteRemovalScript(\n IEnumerable packageNames,\n IEnumerable capabilityNames,\n IEnumerable featureNames,\n Dictionary> registrySettings,\n Dictionary subPackages)\n {\n var sb = new StringBuilder();\n\n // Add script header\n sb.Append(_templateProvider.GetScriptHeader(\"BloatRemoval\"));\n\n // Add packages section\n var allPackages = new List();\n \n // Add main packages\n if (packageNames != null)\n {\n allPackages.AddRange(packageNames);\n }\n \n // Add subpackages\n if (subPackages != null)\n {\n foreach (var subPackageEntry in subPackages)\n {\n if (subPackageEntry.Value != null)\n {\n allPackages.AddRange(subPackageEntry.Value);\n }\n }\n }\n \n // Remove duplicates\n allPackages = allPackages.Distinct().ToList();\n \n // Update the packages array in the script\n if (allPackages.Any())\n {\n sb.AppendLine(\"# Remove packages\");\n sb.AppendLine(\"$packages = @(\");\n \n for (int i = 0; i < allPackages.Count; i++)\n {\n string package = allPackages[i];\n if (i < allPackages.Count - 1)\n {\n sb.AppendLine($\" '{package}',\");\n }\n else\n {\n sb.AppendLine($\" '{package}'\");\n }\n }\n \n sb.AppendLine(\")\");\n sb.AppendLine();\n sb.AppendLine(\"foreach ($package in $packages) {\");\n sb.AppendLine(\" Get-AppxPackage -AllUsers -Name $package | \");\n sb.AppendLine(\" ForEach-Object {\");\n sb.AppendLine(\" Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\");\n sb.AppendLine(\" }\");\n sb.AppendLine(\" Get-AppxProvisionedPackage -Online | \");\n sb.AppendLine(\" Where-Object { $_.DisplayName -eq $package } | \");\n sb.AppendLine(\" ForEach-Object {\");\n sb.AppendLine(\" Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\");\n sb.AppendLine(\" }\");\n sb.AppendLine(\"}\");\n sb.AppendLine();\n }\n \n // Add capabilities section\n if (capabilityNames != null && capabilityNames.Any())\n {\n sb.AppendLine(\"# Remove capabilities\");\n sb.AppendLine(\"$capabilities = @(\");\n \n var capabilitiesList = capabilityNames.ToList();\n for (int i = 0; i < capabilitiesList.Count; i++)\n {\n string capability = capabilitiesList[i];\n if (i < capabilitiesList.Count - 1)\n {\n sb.AppendLine($\" '{capability}',\");\n }\n else\n {\n sb.AppendLine($\" '{capability}'\");\n }\n }\n \n sb.AppendLine(\")\");\n sb.AppendLine();\n sb.AppendLine(\"foreach ($capability in $capabilities) {\");\n sb.AppendLine(\" Get-WindowsCapability -Online | Where-Object { $_.Name -like \\\"$capability*\\\" } | Remove-WindowsCapability -Online\");\n sb.AppendLine(\"}\");\n sb.AppendLine();\n }\n \n // Add features section\n if (featureNames != null && featureNames.Any())\n {\n sb.AppendLine(\"# Disable Optional Features\");\n sb.AppendLine(\"$optionalFeatures = @(\");\n \n var featuresList = featureNames.ToList();\n for (int i = 0; i < featuresList.Count; i++)\n {\n string feature = featuresList[i];\n if (i < featuresList.Count - 1)\n {\n sb.AppendLine($\" '{feature}',\");\n }\n else\n {\n sb.AppendLine($\" '{feature}'\");\n }\n }\n \n sb.AppendLine(\")\");\n sb.AppendLine();\n sb.AppendLine(\"foreach ($feature in $optionalFeatures) {\");\n sb.AppendLine(\" Write-Host \\\"Disabling optional feature: $feature\\\" -ForegroundColor Yellow\");\n sb.AppendLine(\" Disable-WindowsOptionalFeature -Online -FeatureName $feature -NoRestart | Out-Null\");\n sb.AppendLine(\"}\");\n sb.AppendLine();\n }\n \n // Add registry settings\n if (registrySettings != null && registrySettings.Any())\n {\n sb.AppendLine(\"# Registry settings\");\n \n foreach (var appEntry in registrySettings)\n {\n string appName = appEntry.Key;\n List settings = appEntry.Value;\n \n if (settings == null || !settings.Any())\n {\n continue;\n }\n \n sb.AppendLine();\n sb.AppendLine($\"# Registry settings for {appName}\");\n \n foreach (var setting in settings)\n {\n string path = setting.Path;\n string name = setting.Name;\n string valueKind = GetRegTypeString(setting.ValueKind);\n string value = setting.Value?.ToString() ?? string.Empty;\n \n // Check if this is a delete operation (value is null or empty)\n bool isDelete = string.IsNullOrEmpty(value);\n string template = _templateProvider.GetRegistrySettingTemplate(isDelete);\n \n if (isDelete)\n {\n sb.AppendLine(string.Format(template, path, name));\n }\n else\n {\n // Format the value based on its type\n string formattedValue = FormatRegistryValue(value, setting.ValueKind);\n sb.AppendLine(string.Format(template, path, name, valueKind, formattedValue));\n }\n }\n }\n \n sb.AppendLine();\n }\n \n // Add script footer\n sb.Append(_templateProvider.GetScriptFooter());\n \n return sb.ToString();\n }\n\n /// \n public string BuildSingleAppRemovalScript(AppInfo app)\n {\n if (app == null)\n {\n throw new ArgumentNullException(nameof(app));\n }\n\n var sb = new StringBuilder();\n \n sb.AppendLine($\"# Removal script for {app.Name} ({app.PackageName})\");\n sb.AppendLine($\"# Generated on {DateTime.Now}\");\n sb.AppendLine();\n sb.AppendLine(\"try {\");\n sb.AppendLine($\" Write-Host \\\"Removing {app.Name}...\\\" -ForegroundColor Yellow\");\n sb.AppendLine();\n \n // Add the appropriate removal command based on the app type\n switch (app.Type)\n {\n case AppType.StandardApp:\n string packageTemplate = _templateProvider.GetPackageRemovalTemplate();\n sb.AppendLine(\" # Remove the app package\");\n sb.AppendLine(\" \" + string.Format(packageTemplate, app.PackageName));\n break;\n \n case AppType.Capability:\n string capabilityTemplate = _templateProvider.GetCapabilityRemovalTemplate();\n sb.AppendLine(\" # Remove the capability\");\n sb.AppendLine(\" \" + string.Format(capabilityTemplate, app.PackageName));\n break;\n \n case AppType.OptionalFeature:\n string featureTemplate = _templateProvider.GetFeatureRemovalTemplate();\n sb.AppendLine(\" # Disable the optional feature\");\n sb.AppendLine(\" \" + string.Format(featureTemplate, app.PackageName));\n break;\n \n default:\n // Default to package removal\n string defaultTemplate = _templateProvider.GetPackageRemovalTemplate();\n sb.AppendLine(\" # Remove the app\");\n sb.AppendLine(\" \" + string.Format(defaultTemplate, app.PackageName));\n break;\n }\n \n sb.AppendLine();\n sb.AppendLine($\" Write-Host \\\"{app.Name} removed successfully.\\\" -ForegroundColor Green\");\n sb.AppendLine(\"} catch {\");\n sb.AppendLine($\" Write-Host \\\"Error removing {app.Name}: $($_.Exception.Message)\\\" -ForegroundColor Red\");\n sb.AppendLine(\"}\");\n \n return sb.ToString();\n }\n\n /// \n /// Formats a registry value based on its type.\n /// \n /// The value to format.\n /// The type of the value.\n /// The formatted value.\n private string FormatRegistryValue(string value, Microsoft.Win32.RegistryValueKind valueKind)\n {\n switch (valueKind)\n {\n case Microsoft.Win32.RegistryValueKind.String:\n case Microsoft.Win32.RegistryValueKind.ExpandString:\n return $\"\\\"{value}\\\"\";\n \n case Microsoft.Win32.RegistryValueKind.DWord:\n case Microsoft.Win32.RegistryValueKind.QWord:\n return value;\n \n case Microsoft.Win32.RegistryValueKind.Binary:\n // Format as hex string\n return value;\n \n case Microsoft.Win32.RegistryValueKind.MultiString:\n // Format as comma-separated string\n return $\"\\\"{value}\\\"\";\n \n default:\n return value;\n }\n }\n\n /// \n /// Converts a RegistryValueKind to the corresponding reg.exe type string.\n /// \n /// The registry value kind.\n /// The reg.exe type string.\n private string GetRegTypeString(Microsoft.Win32.RegistryValueKind valueKind)\n {\n return valueKind switch\n {\n Microsoft.Win32.RegistryValueKind.String => \"SZ\",\n Microsoft.Win32.RegistryValueKind.ExpandString => \"EXPAND_SZ\",\n Microsoft.Win32.RegistryValueKind.Binary => \"BINARY\",\n Microsoft.Win32.RegistryValueKind.DWord => \"DWORD\",\n Microsoft.Win32.RegistryValueKind.MultiString => \"MULTI_SZ\",\n Microsoft.Win32.RegistryValueKind.QWord => \"QWORD\",\n _ => \"SZ\"\n };\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppLoadingService.cs", "using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Helpers;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n public class AppLoadingService : IAppLoadingService\n {\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IPackageManager _packageManager;\n private readonly ILogService _logService;\n private readonly ConcurrentDictionary _statusCache = new();\n\n public AppLoadingService(\n IAppDiscoveryService appDiscoveryService,\n IPackageManager packageManager,\n ILogService logService)\n {\n _appDiscoveryService = appDiscoveryService;\n _packageManager = packageManager;\n _logService = logService;\n }\n\n /// \n public async Task>> LoadAppsAsync()\n {\n try\n {\n var apps = await _appDiscoveryService.GetStandardAppsAsync();\n return OperationResult>.Succeeded(apps);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to load standard apps\", ex);\n return OperationResult>.Failed(\"Failed to load standard apps\", ex);\n }\n }\n\n // Removed LoadInstallableAppsAsync as it's not in the interface\n\n public async Task> LoadCapabilitiesAsync()\n {\n try\n {\n // This is a placeholder implementation\n // In a real implementation, this would query the system for available capabilities\n _logService.LogInformation(\"Loading Windows capabilities\");\n \n // Return an empty list for now\n return Enumerable.Empty();\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to load capabilities\", ex);\n return Enumerable.Empty();\n }\n }\n\n public async Task GetItemInstallStatusAsync(IInstallableItem item)\n {\n ValidationHelper.NotNull(item, nameof(item));\n ValidationHelper.NotNullOrEmpty(item.PackageId, nameof(item.PackageId));\n\n if (_statusCache.TryGetValue(item.PackageId, out var cachedStatus))\n {\n return cachedStatus;\n }\n\n var isInstalled = await _packageManager.IsAppInstalledAsync(item.PackageId);\n _statusCache[item.PackageId] = isInstalled;\n return isInstalled;\n }\n\n // Added missing GetInstallStatusAsync method\n /// \n public async Task> GetInstallStatusAsync(string appId)\n {\n try\n {\n ValidationHelper.NotNullOrEmpty(appId, nameof(appId));\n\n // Use the existing cache logic, assuming 'true' maps to Success\n if (_statusCache.TryGetValue(appId, out var cachedStatus))\n {\n return OperationResult.Succeeded(\n cachedStatus ? InstallStatus.Success : InstallStatus.NotFound\n );\n }\n\n var isInstalled = await _packageManager.IsAppInstalledAsync(appId);\n _statusCache[appId] = isInstalled;\n return OperationResult.Succeeded(\n isInstalled ? InstallStatus.Success : InstallStatus.NotFound\n );\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to get installation status for app {appId}\", ex);\n return OperationResult.Failed($\"Failed to get installation status: {ex.Message}\", ex);\n }\n }\n\n // Added missing SetInstallStatusAsync method\n /// \n public Task> SetInstallStatusAsync(string appId, InstallStatus status)\n {\n try\n {\n ValidationHelper.NotNullOrEmpty(appId, nameof(appId));\n // This service primarily reads status; setting might not be its responsibility\n // or might require interaction with the package manager.\n // For now, just update the cache.\n _logService.LogWarning($\"Attempting to set install status for {appId} to {status} (cache only).\");\n _statusCache[appId] = (status == InstallStatus.Success); // Corrected enum member\n return Task.FromResult(OperationResult.Succeeded(true)); // Assume cache update is always successful\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to set installation status for app {appId}\", ex);\n return Task.FromResult(OperationResult.Failed($\"Failed to set installation status: {ex.Message}\", ex));\n }\n }\n\n\n public async Task> GetBatchInstallStatusAsync(IEnumerable packageIds)\n {\n ValidationHelper.NotNull(packageIds, nameof(packageIds));\n \n var distinctIds = packageIds\n .Where(id => !string.IsNullOrWhiteSpace(id))\n .Distinct()\n .ToList();\n\n if (distinctIds.Count == 0)\n throw new ArgumentException(\"Must provide at least one valid package ID\", nameof(packageIds));\n var results = new Dictionary();\n\n foreach (var id in distinctIds)\n {\n if (_statusCache.TryGetValue(id, out var cachedStatus))\n {\n results[id] = cachedStatus;\n }\n else\n {\n var isInstalled = await _packageManager.IsAppInstalledAsync(id);\n _statusCache[id] = isInstalled;\n results[id] = isInstalled;\n }\n }\n\n return results;\n } // Removed extra closing brace here\n\n\n /// \n public async Task> RefreshInstallationStatusAsync(IEnumerable apps)\n {\n try\n {\n ValidationHelper.NotNull(apps, nameof(apps));\n\n var packageIds = apps\n .Where(app => app != null && !string.IsNullOrWhiteSpace(app.PackageID)) // Use PackageID from AppInfo\n .Select(app => app.PackageID)\n .Distinct();\n \n if (!packageIds.Any())\n {\n return OperationResult.Succeeded(true); // No apps to refresh\n }\n \n var statuses = await GetBatchInstallStatusAsync(packageIds);\n\n foreach (var app in apps) // Iterate through AppInfo\n {\n if (app != null && statuses.TryGetValue(app.PackageID, out var isInstalled)) // Use PackageID\n {\n _statusCache[app.PackageID] = isInstalled; // Use PackageID\n // Optionally update the IsInstalled property on the AppInfo object itself\n // app.IsInstalled = isInstalled; // This depends if AppInfo is mutable and if this side-effect is desired\n }\n }\n \n return OperationResult.Succeeded(true);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to refresh installation status\", ex);\n return OperationResult.Failed(\"Failed to refresh installation status\", ex);\n }\n }\n\n public void ClearStatusCache()\n {\n _statusCache.Clear();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/BaseInstallationService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Base class for installation services that provides common functionality.\n /// \n /// The type of item to install, which must implement IInstallableItem.\n public abstract class BaseInstallationService : IInstallationService where T : IInstallableItem\n {\n protected readonly ILogService _logService;\n protected readonly IPowerShellExecutionService _powerShellService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The PowerShell execution service.\n protected BaseInstallationService(\n ILogService logService,\n IPowerShellExecutionService powerShellService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _powerShellService = powerShellService ?? throw new ArgumentNullException(nameof(powerShellService));\n }\n\n /// \n public Task> InstallAsync(\n T item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n return InstallItemAsync(item, progress, cancellationToken);\n }\n\n /// \n public Task> CanInstallAsync(T item)\n {\n return CanInstallItemAsync(item);\n }\n\n /// \n /// Internal method to install an item.\n /// \n /// The item to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n protected async Task> InstallItemAsync(\n T item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (item == null)\n {\n throw new ArgumentNullException(nameof(item));\n }\n\n try\n {\n // Report initial progress\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Starting installation of {item.DisplayName}...\",\n DetailedMessage = $\"Preparing to install {item.DisplayName}\",\n }\n );\n\n _logService.LogInformation($\"Attempting to install {item.DisplayName} ({item.PackageId})\");\n\n // Perform the actual installation\n var result = await PerformInstallationAsync(item, progress, cancellationToken);\n\n if (result.Success)\n {\n // Report completion\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = $\"{item.DisplayName} installed successfully!\",\n DetailedMessage = $\"Successfully installed {item.DisplayName}\",\n }\n );\n\n if (item.RequiresRestart)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n StatusText = \"A system restart is required to complete the installation\",\n DetailedMessage = \"Please restart your computer to complete the installation\",\n LogLevel = LogLevel.Warning,\n }\n );\n _logService.LogWarning($\"A system restart is required for {item.DisplayName}\");\n }\n\n _logService.LogSuccess($\"Successfully installed {item.DisplayName}\");\n }\n\n return result;\n }\n catch (OperationCanceledException)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Installation of {item.DisplayName} was cancelled\",\n DetailedMessage = \"The installation was cancelled by the user\",\n LogLevel = LogLevel.Warning,\n }\n );\n \n _logService.LogWarning($\"Operation cancelled when installing {item.DisplayName}\");\n return OperationResult.Failed(\"The installation was cancelled by the user\");\n }\n catch (Exception ex)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Error installing {item.DisplayName}: {ex.Message}\",\n DetailedMessage = $\"Exception during installation: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n _logService.LogError($\"Error installing {item.DisplayName}\", ex);\n return OperationResult.Failed($\"Error installing {item.DisplayName}: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Checks if an item can be installed.\n /// \n /// The item to check.\n /// An operation result indicating if the item can be installed, with error details if not.\n protected Task> CanInstallItemAsync(T item)\n {\n if (item == null)\n {\n return Task.FromResult(OperationResult.Failed(\"Item information cannot be null\"));\n }\n\n // Basic implementation: Assume all items can be installed for now.\n // Derived classes can override this method to provide specific checks.\n return Task.FromResult(OperationResult.Succeeded(true));\n }\n\n /// \n /// Performs the actual installation of the item.\n /// \n /// The item to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n protected abstract Task> PerformInstallationAsync(\n T item,\n IProgress? progress,\n CancellationToken cancellationToken);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/BaseInstallationViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.SoftwareApps.Services;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n /// \n /// Base view model for installation operations.\n /// Provides common functionality for both WindowsAppsViewModel and ExternalAppsViewModel.\n /// \n /// The type of app (WindowsApp or ExternalApp)\n public abstract class BaseInstallationViewModel : SearchableViewModel\n where T : class, ISearchable\n {\n protected readonly IAppInstallationService _appInstallationService;\n protected readonly IAppInstallationCoordinatorService _appInstallationCoordinatorService;\n protected readonly IInternetConnectivityService _connectivityService;\n protected readonly SoftwareAppsDialogService _dialogService;\n\n /// \n /// Gets or sets the reason for cancellation if an operation was cancelled.\n /// \n protected CancellationReason CurrentCancellationReason { get; set; } =\n CancellationReason.None;\n\n /// \n /// Gets or sets the status text.\n /// \n public string StatusText { get; set; } = \"Ready\";\n\n /// \n /// Gets or sets a value indicating whether the view model is initialized.\n /// \n public bool IsInitialized { get; set; } = false;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The search service.\n /// The package manager.\n /// The app installation service.\n /// The app installation coordinator service.\n /// The internet connectivity service.\n /// The specialized dialog service for software apps.\n protected BaseInstallationViewModel(\n ITaskProgressService progressService,\n ISearchService searchService,\n IPackageManager packageManager,\n IAppInstallationService appInstallationService,\n IAppInstallationCoordinatorService appInstallationCoordinatorService,\n IInternetConnectivityService connectivityService,\n SoftwareAppsDialogService dialogService\n )\n : base(progressService, searchService, packageManager)\n {\n _appInstallationService =\n appInstallationService\n ?? throw new ArgumentNullException(nameof(appInstallationService));\n _appInstallationCoordinatorService =\n appInstallationCoordinatorService\n ?? throw new ArgumentNullException(nameof(appInstallationCoordinatorService));\n _connectivityService =\n connectivityService ?? throw new ArgumentNullException(nameof(connectivityService));\n _dialogService =\n dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n }\n\n /// \n /// Loads apps and checks their installation status.\n /// \n /// A task representing the asynchronous operation.\n public async Task LoadAppsAndCheckInstallationStatusAsync()\n {\n if (IsInitialized)\n {\n System.Diagnostics.Debug.WriteLine(\n $\"{GetType().Name} already initialized, skipping LoadAppsAndCheckInstallationStatusAsync\"\n );\n return;\n }\n\n System.Diagnostics.Debug.WriteLine(\n $\"Starting {GetType().Name} LoadAppsAndCheckInstallationStatusAsync\"\n );\n await LoadItemsAsync();\n await CheckInstallationStatusAsync();\n\n // Mark as initialized after loading is complete\n IsInitialized = true;\n System.Diagnostics.Debug.WriteLine(\n $\"Completed {GetType().Name} LoadAppsAndCheckInstallationStatusAsync\"\n );\n }\n\n /// \n /// Checks if internet connectivity is available.\n /// \n /// Whether to show a dialog if connectivity is not available.\n /// True if internet is connected, false otherwise.\n protected async Task CheckInternetConnectivityAsync(bool showDialog = true)\n {\n bool isInternetConnected = await _connectivityService.IsInternetConnectedAsync(true);\n if (!isInternetConnected && showDialog)\n {\n StatusText = \"No internet connection available. Installation cannot proceed.\";\n\n // Show dialog informing the user about the connectivity issue\n await ShowNoInternetConnectionDialogAsync();\n }\n return isInternetConnected;\n }\n\n /// \n /// Shows a confirmation dialog for an operation.\n /// \n /// Type of operation (Install/Remove)\n /// List of apps selected for the operation\n /// List of apps that will be skipped (optional)\n /// Dialog result (true if confirmed, false if canceled)\n protected async Task ShowOperationConfirmationDialogAsync(\n string operationType,\n IEnumerable selectedApps,\n IEnumerable? skippedApps = null\n )\n {\n string title = $\"Confirm {operationType}\";\n string headerText = $\"The following items will be {GetPastTense(operationType)}:\";\n\n // Create list of app names for the dialog\n var appNames = selectedApps.Select(a => GetAppName(a)).ToList();\n\n // Create footer text\n string footerText = \"Do you want to continue?\";\n\n // If there are skipped apps, add information about them\n if (skippedApps != null && skippedApps.Any())\n {\n var skippedNames = skippedApps.Select(a => GetAppName(a)).ToList();\n footerText =\n $\"Note: The following {skippedApps.Count()} item(s) cannot be {GetPastTense(operationType)} and will be skipped:\\n\";\n footerText += string.Join(\", \", skippedNames);\n footerText +=\n $\"\\n\\nDo you want to continue with the remaining {selectedApps.Count()} item(s)?\";\n }\n\n // Build the message\n string message = $\"{headerText}\\n\";\n foreach (var name in appNames)\n {\n message += $\"{name}\\n\";\n }\n message += $\"\\n{footerText}\";\n\n // Show the confirmation dialog\n return await _dialogService.ShowConfirmationAsync(message, title);\n }\n\n /// \n /// Centralized method to handle the entire cancellation process.\n /// This method manages the cancellation state, logs the cancellation event,\n /// shows the appropriate dialog, and ensures proper cleanup.\n /// \n /// True if the cancellation was due to connectivity issues, false if user-initiated.\n /// A task that represents the asynchronous operation.\n protected async Task HandleCancellationAsync(bool isConnectivityIssue)\n {\n // Set the appropriate cancellation reason (state management)\n CurrentCancellationReason = isConnectivityIssue\n ? CancellationReason.InternetConnectivityLost\n : CancellationReason.UserCancelled;\n\n // Log the cancellation (diagnostics)\n System.Diagnostics.Debug.WriteLine(\n $\"[DEBUG] Installation {(isConnectivityIssue ? \"stopped due to connectivity loss\" : \"cancelled by user\")} - showing dialog\"\n );\n\n // Show the appropriate dialog (UI presentation - delegated to specialized method)\n await ShowCancellationDialogAsync(!isConnectivityIssue, isConnectivityIssue);\n\n // Reset cancellation reason after showing dialog (cleanup)\n CurrentCancellationReason = CancellationReason.None;\n }\n\n /// \n /// Shows an operation result dialog after operations complete.\n /// \n /// Type of operation (Install/Remove)\n /// Number of successful operations\n /// Total number of operations attempted\n /// List of successfully processed items\n /// List of failed items (optional)\n /// List of skipped items (optional)\n protected void ShowOperationResultDialog(\n string operationType,\n int successCount,\n int totalCount,\n IEnumerable successItems,\n IEnumerable? failedItems = null,\n IEnumerable? skippedItems = null\n )\n {\n // Determine if this was a user-initiated cancellation or connectivity issue\n bool isUserCancelled = CurrentCancellationReason == CancellationReason.UserCancelled;\n bool isConnectivityIssue =\n CurrentCancellationReason == CancellationReason.InternetConnectivityLost;\n\n // If the operation was cancelled by the user, use CustomDialog for a simpler message\n if (isUserCancelled)\n {\n string title = \"Installation Aborted by User\";\n string headerText = \"Installation aborted by user\";\n string message = \"The installation process was cancelled by the user.\";\n string footerText =\n successCount > 0\n ? $\"Some items were successfully {GetPastTense(operationType)} before cancellation.\"\n : $\"No items were {GetPastTense(operationType)} before cancellation.\";\n\n // Use CustomDialog directly instead of SoftwareAppsDialog\n CustomDialog.ShowInformation(title, headerText, message, footerText);\n\n // Reset cancellation reason after showing dialog\n CurrentCancellationReason = CancellationReason.None;\n return;\n }\n // If the operation was cancelled due to connectivity issues\n else if (isConnectivityIssue)\n {\n // Use the dialog service with the connectivity issue flag\n _dialogService.ShowOperationResult(\n operationType,\n successCount,\n totalCount,\n successItems,\n failedItems,\n skippedItems,\n true, // Connectivity issue flag\n false // Not a user cancellation\n );\n\n // Reset cancellation reason after showing dialog\n CurrentCancellationReason = CancellationReason.None;\n return;\n }\n\n // For normal operation results (no cancellation)\n // Check if any failures are due to internet connectivity issues\n bool hasConnectivityIssues = false;\n if (failedItems != null)\n {\n hasConnectivityIssues = failedItems.Any(item =>\n item.Contains(\"internet\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\"connection\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\"network\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\n \"pipeline has been stopped\",\n StringComparison.OrdinalIgnoreCase\n )\n );\n }\n\n // For normal operation results, use the dialog service\n _dialogService.ShowOperationResult(\n operationType,\n successCount,\n totalCount,\n successItems,\n failedItems,\n skippedItems,\n hasConnectivityIssues,\n false // Not a user cancellation\n );\n }\n\n /// \n /// Shows a dialog informing the user that no internet connection is available.\n /// \n protected Task ShowNoInternetConnectionDialogAsync()\n {\n // Use CustomDialog directly instead of SoftwareAppsDialog\n CustomDialog.ShowInformation(\n \"Internet Connection Required\",\n \"No internet connection available\",\n \"Internet connection is required to install apps.\",\n \"Please check your network connection and try again.\"\n );\n return Task.CompletedTask;\n }\n\n /// \n /// Shows a dialog informing the user that no items were selected for an operation.\n /// \n /// The action being performed (e.g., \"installation\", \"removal\")\n protected Task ShowNoItemsSelectedDialogAsync(string action)\n {\n return _dialogService.ShowInformationAsync(\n $\"No items were selected for {action}.\",\n $\"No Items Selected\",\n $\"Check the boxes next to the items you want to {action} and try again.\"\n );\n }\n\n /// \n /// Shows a confirmation dialog for an operation on multiple items.\n /// \n /// The action being performed (e.g., \"install\", \"remove\")\n /// The names of the items\n /// The number of items\n /// True if confirmed, false otherwise\n protected Task ShowConfirmItemsDialogAsync(\n string action,\n IEnumerable itemNames,\n int count\n )\n {\n var formattedItemNames = itemNames.Select(name => $\" {name}\");\n\n return _dialogService.ShowConfirmationAsync(\n $\"The following items will be {action}ed:\\n\"\n + string.Join(\"\\n\", formattedItemNames)\n + $\"\\n\\nDo you want to {action} {count} item(s)?\",\n $\"Confirm {CapitalizeFirstLetter(action)}\"\n );\n }\n\n /// \n /// Shows a dialog informing the user that items cannot be reinstalled.\n /// \n /// The names of the items that cannot be reinstalled\n /// Whether this is for a single item or multiple items\n protected Task ShowCannotReinstallDialogAsync(IEnumerable itemNames, bool isSingle)\n {\n string title = isSingle ? \"Cannot Install Item\" : \"Cannot Install Items\";\n string message = isSingle\n ? $\"{itemNames.First()} cannot be reinstalled.\"\n : \"None of the selected items can be reinstalled.\";\n\n return _dialogService.ShowInformationAsync(\n message,\n title,\n \"These items are already installed and cannot be reinstalled.\"\n );\n }\n\n /// \n /// Shows a dialog informing the user about the operation results.\n /// \n /// The action that was performed (e.g., \"install\", \"remove\")\n /// The number of successful operations\n /// The total number of operations attempted\n /// The names of successfully processed items\n /// The names of failed items (optional)\n protected Task ShowOperationResultDialogAsync(\n string action,\n int successCount,\n int totalCount,\n IEnumerable successItems,\n IEnumerable? failedItems = null\n )\n {\n string title = $\"{CapitalizeFirstLetter(action)} Results\";\n string message = $\"{successCount} of {totalCount} items were successfully {action}ed.\";\n\n return _dialogService.ShowInformationAsync(\n message,\n title,\n $\"The operation completed with {successCount} successes and {totalCount - successCount} failures.\"\n );\n }\n\n /// \n /// Shows a dialog informing the user about installation cancellation.\n /// Uses CustomDialog directly to ensure proper text formatting for long messages.\n /// \n /// True if the cancellation was initiated by the user, false otherwise.\n /// True if the cancellation was due to connectivity issues, false otherwise.\n /// A task that represents the asynchronous operation.\n protected Task ShowCancellationDialogAsync(bool isUserCancelled, bool isConnectivityIssue)\n {\n string title = isUserCancelled ? \"Installation Aborted\" : \"Internet Connection Lost\";\n\n string headerText = isUserCancelled\n ? \"Installation aborted by user\"\n : \"Installation stopped due to internet connection loss\";\n\n string message = isUserCancelled\n ? \"The installation process was cancelled by the user.\"\n : \"The installation process was stopped because the internet connection was lost.\\nThis is required to ensure installations complete properly and prevent corrupted installations.\";\n\n string footerText = isUserCancelled\n ? \"You can restart the installation when you're ready.\"\n : \"Please check your network connection and try again when your internet connection is stable.\";\n\n // Use CustomDialog directly instead of SoftwareAppsDialog\n CustomDialog.ShowInformation(title, headerText, message, footerText);\n return Task.CompletedTask;\n }\n\n /// \n /// Gets the past tense form of an operation type\n /// \n /// The operation type (e.g., \"Install\", \"Remove\")\n /// The past tense form of the operation type\n protected string GetPastTense(string operationType)\n {\n if (string.IsNullOrEmpty(operationType))\n return string.Empty;\n\n return operationType.Equals(\"Remove\", StringComparison.OrdinalIgnoreCase)\n ? \"removed\"\n : $\"{operationType.ToLower()}ed\";\n }\n\n /// \n /// Gets the name of an app.\n /// \n /// The app.\n /// The name of the app.\n protected abstract string GetAppName(T app);\n\n /// \n /// Converts an app to an AppInfo object.\n /// \n /// The app to convert.\n /// The AppInfo object.\n protected abstract AppInfo ToAppInfo(T app);\n\n /// \n /// Gets the selected apps.\n /// \n /// The selected apps.\n protected abstract IEnumerable GetSelectedApps();\n\n /// \n /// Sets the installation status of an app.\n /// \n /// The app.\n /// Whether the app is installed.\n protected abstract void SetInstallationStatus(T app, bool isInstalled);\n\n /// \n /// Capitalizes the first letter of a string.\n /// \n /// The input string\n /// The string with the first letter capitalized\n protected string CapitalizeFirstLetter(string input)\n {\n if (string.IsNullOrEmpty(input))\n return string.Empty;\n\n return char.ToUpper(input[0]) + input.Substring(1);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/PowerShellHelper.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Helper class for common PowerShell execution patterns.\n /// \n public static class PowerShellHelper\n {\n /// \n /// Executes a PowerShell script with progress reporting and error handling.\n /// \n /// The PowerShell instance to use.\n /// The script to execute.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// The collection of PSObjects returned by the script.\n public static async Task> ExecuteScriptAsync(\n this PowerShell powerShell,\n string script,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (powerShell == null)\n {\n throw new ArgumentNullException(nameof(powerShell));\n }\n\n if (string.IsNullOrWhiteSpace(script))\n {\n throw new ArgumentException(\"Script cannot be null or empty\", nameof(script));\n }\n\n powerShell.AddScript(script);\n\n // Add event handlers for progress reporting\n if (progress != null)\n {\n powerShell.Streams.Information.DataAdded += (sender, e) =>\n {\n var info = powerShell.Streams.Information[e.Index];\n progress.Report(new TaskProgressDetail\n {\n DetailedMessage = info.MessageData.ToString(),\n LogLevel = LogLevel.Info\n });\n };\n\n powerShell.Streams.Error.DataAdded += (sender, e) =>\n {\n var error = powerShell.Streams.Error[e.Index];\n progress.Report(new TaskProgressDetail\n {\n DetailedMessage = error.Exception?.Message ?? error.ToString(),\n LogLevel = LogLevel.Error\n });\n };\n\n powerShell.Streams.Warning.DataAdded += (sender, e) =>\n {\n var warning = powerShell.Streams.Warning[e.Index];\n progress.Report(new TaskProgressDetail\n {\n DetailedMessage = warning.Message,\n LogLevel = LogLevel.Warning\n });\n };\n\n powerShell.Streams.Progress.DataAdded += (sender, e) =>\n {\n var progressRecord = powerShell.Streams.Progress[e.Index];\n var percentComplete = progressRecord.PercentComplete;\n if (percentComplete >= 0 && percentComplete <= 100)\n {\n progress.Report(new TaskProgressDetail\n {\n Progress = percentComplete,\n StatusText = progressRecord.Activity,\n DetailedMessage = progressRecord.StatusDescription\n });\n }\n };\n }\n\n // Execute the script\n return await Task.Run(() => powerShell.Invoke(), cancellationToken);\n }\n\n /// \n /// Executes a PowerShell script asynchronously.\n /// \n /// The PowerShell instance to use.\n /// Optional cancellation token.\n /// The data collection of PSObjects returned by the script.\n public static async Task> InvokeAsync(\n this PowerShell powerShell,\n CancellationToken cancellationToken = default)\n {\n if (powerShell == null)\n {\n throw new ArgumentNullException(nameof(powerShell));\n }\n\n var output = new PSDataCollection();\n var asyncResult = powerShell.BeginInvoke(null, output);\n\n await Task.Run(() =>\n {\n while (!asyncResult.IsCompleted)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n powerShell.Stop();\n cancellationToken.ThrowIfCancellationRequested();\n }\n Thread.Sleep(100);\n }\n powerShell.EndInvoke(asyncResult);\n }, cancellationToken);\n\n return output;\n }\n\n /// \n /// Parses a result string in the format \"STATUS|Message|RebootRequired\".\n /// \n /// The result string to parse.\n /// The name of the item being installed.\n /// Optional progress reporter.\n /// The log service for logging.\n /// An operation result indicating success or failure with error details.\n public static OperationResult ParseResultString(\n string resultString,\n string itemName,\n IProgress? progress = null,\n ILogService? logService = null)\n {\n if (string.IsNullOrEmpty(resultString))\n {\n progress?.Report(new TaskProgressDetail\n {\n StatusText = \"Script returned no result\",\n LogLevel = LogLevel.Error\n });\n logService?.LogError($\"Empty result returned when processing: {itemName}\");\n return OperationResult.Failed(\"Script returned no result\");\n }\n\n var parts = resultString.Split('|');\n if (parts.Length < 2)\n {\n progress?.Report(new TaskProgressDetail\n {\n StatusText = \"Error processing script result\",\n LogLevel = LogLevel.Error\n });\n logService?.LogError($\"Unexpected script output format for {itemName}: {resultString}\");\n return OperationResult.Failed(\"Unexpected script output format: \" + resultString);\n }\n\n string status = parts[0];\n string message = parts[1];\n bool rebootRequired = parts.Length > 2 && bool.TryParse(parts[2], out bool req) && req;\n\n if (status.Equals(\"SUCCESS\", StringComparison.OrdinalIgnoreCase))\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 100,\n StatusText = $\"Successfully processed: {itemName}\",\n DetailedMessage = message\n });\n logService?.LogSuccess($\"Successfully processed: {itemName}. {message}\");\n\n if (rebootRequired)\n {\n progress?.Report(new TaskProgressDetail\n {\n StatusText = \"A system restart is required to complete the installation\",\n DetailedMessage = \"Please restart your computer to complete the installation\",\n LogLevel = LogLevel.Warning\n });\n logService?.LogWarning($\"A system restart is required for {itemName}\");\n }\n return OperationResult.Succeeded(true);\n }\n else // FAILURE\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Failed to process: {itemName}\",\n DetailedMessage = message,\n LogLevel = LogLevel.Error\n });\n logService?.LogError($\"Failed to process: {itemName}. {message}\");\n return OperationResult.Failed(message);\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/BaseSettingsViewModel.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Extensions;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// Base class for settings view models.\n /// \n /// The type of settings.\n public partial class BaseSettingsViewModel : ObservableObject\n where T : ApplicationSettingItem\n {\n protected readonly ITaskProgressService _progressService;\n protected readonly IRegistryService _registryService;\n protected readonly ILogService _logService;\n\n /// \n /// Gets the collection of settings.\n /// \n public ObservableCollection Settings { get; } = new();\n\n /// \n /// Gets or sets a value indicating whether the settings are being loaded.\n /// \n [ObservableProperty]\n private bool _isLoading;\n\n /// \n /// Gets or sets a value indicating whether all settings are selected.\n /// \n [ObservableProperty]\n private bool _isSelected;\n\n /// \n /// Gets or sets a value indicating whether the view model has visible settings.\n /// \n [ObservableProperty]\n private bool _hasVisibleSettings = true;\n\n /// \n /// Gets or sets the category name for this settings view model.\n /// \n [ObservableProperty]\n private string _categoryName = string.Empty;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n protected BaseSettingsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService\n )\n {\n _progressService =\n progressService ?? throw new ArgumentNullException(nameof(progressService));\n _registryService =\n registryService ?? throw new ArgumentNullException(nameof(registryService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Loads the settings.\n /// \n /// A task representing the asynchronous operation.\n public virtual async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load settings (to be implemented by derived classes)\n await Task.CompletedTask;\n\n // Refresh status for all settings after loading\n await RefreshAllSettingsStatusAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Refreshes the status of all settings.\n /// \n /// A task representing the asynchronous operation.\n protected async Task RefreshAllSettingsStatusAsync()\n {\n foreach (var setting in Settings)\n {\n await setting.RefreshStatus();\n }\n }\n\n /// \n /// Checks the status of all settings.\n /// \n /// A task representing the asynchronous operation.\n public virtual async Task CheckSettingStatusesAsync()\n {\n _logService.Log(\n LogLevel.Info,\n $\"Checking status of {Settings.Count} settings in {GetType().Name}\"\n );\n\n foreach (var setting in Settings)\n {\n if (setting.IsGroupHeader)\n {\n continue;\n }\n\n // Direct method call without reflection\n await setting.RefreshStatus();\n }\n\n // Update the overall IsSelected state\n UpdateIsSelectedState();\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n protected void UpdateIsSelectedState()\n {\n var nonHeaderSettings = Settings.Where(s => !s.IsGroupHeader).ToList();\n if (nonHeaderSettings.Count == 0)\n {\n IsSelected = false;\n return;\n }\n\n IsSelected = nonHeaderSettings.All(s => s.IsSelected);\n }\n\n /// \n /// Executes the specified action asynchronously.\n /// \n /// The name of the action to execute.\n /// A task representing the asynchronous operation.\n public virtual async Task ExecuteActionAsync(string actionName)\n {\n _logService.Log(LogLevel.Info, $\"Executing action: {actionName}\");\n\n // Find the setting with the specified action\n foreach (var setting in Settings)\n {\n var action = setting.Actions.FirstOrDefault(a => a.Name == actionName);\n if (action != null)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Found action {actionName} in setting {setting.Name}\"\n );\n\n await ExecuteActionAsync(action);\n return;\n }\n }\n\n _logService.Log(LogLevel.Warning, $\"Action {actionName} not found\");\n }\n\n /// \n /// Executes the specified action asynchronously.\n /// \n /// The action to execute.\n /// A task representing the asynchronous operation.\n public virtual async Task ExecuteActionAsync(ApplicationAction action)\n {\n if (action == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot execute null action\");\n return;\n }\n\n _logService.Log(LogLevel.Info, $\"Executing action: {action.Name}\");\n\n // Execute the registry action if present\n if (action.RegistrySetting != null)\n {\n string hiveString = action.RegistrySetting.Hive.ToString();\n if (hiveString == \"LocalMachine\")\n hiveString = \"HKLM\";\n else if (hiveString == \"CurrentUser\")\n hiveString = \"HKCU\";\n else if (hiveString == \"ClassesRoot\")\n hiveString = \"HKCR\";\n else if (hiveString == \"Users\")\n hiveString = \"HKU\";\n else if (hiveString == \"CurrentConfig\")\n hiveString = \"HKCC\";\n\n string fullPath = $\"{hiveString}\\\\{action.RegistrySetting.SubKey}\";\n _registryService.SetValue(\n fullPath,\n action.RegistrySetting.Name,\n action.RegistrySetting.RecommendedValue,\n action.RegistrySetting.ValueType\n );\n }\n\n // Execute custom action if present\n if (action.CustomAction != null)\n {\n await action.CustomAction();\n }\n\n _logService.Log(LogLevel.Info, $\"Action '{action.Name}' executed successfully\");\n }\n\n /// \n /// Applies the setting asynchronously.\n /// \n /// The setting to apply.\n /// A task representing the asynchronous operation.\n protected virtual async Task ApplySettingAsync(T setting)\n {\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot apply null setting\");\n return;\n }\n\n _logService.Log(LogLevel.Info, $\"Applying setting: {setting.Name}\");\n\n // Apply the setting based on its properties\n if (setting.RegistrySetting != null)\n {\n // Apply registry setting\n string hiveString = GetRegistryHiveString(setting.RegistrySetting.Hive);\n _registryService.SetValue(\n $\"{hiveString}\\\\{setting.RegistrySetting.SubKey}\",\n setting.RegistrySetting.Name,\n setting.IsSelected\n ? setting.RegistrySetting.RecommendedValue\n : setting.RegistrySetting.DefaultValue,\n setting.RegistrySetting.ValueType\n );\n }\n else if (\n setting.LinkedRegistrySettings != null\n && setting.LinkedRegistrySettings.Settings.Count > 0\n )\n {\n // Apply linked registry settings\n await _registryService.ApplyLinkedSettingsAsync(\n setting.LinkedRegistrySettings,\n setting.IsSelected\n );\n }\n\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} applied successfully\");\n\n // Add a small delay to ensure registry changes are processed\n await Task.Delay(50);\n }\n\n /// \n /// Gets the registry hive string.\n /// \n /// The registry hive.\n /// The registry hive string.\n private string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => throw new ArgumentOutOfRangeException(nameof(hive), hive, null),\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/Methods/AppxPackageVerificationMethod.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Management;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods\n{\n /// \n /// Verifies UWP app installations by querying the AppX package manager.\n /// \n public class AppxPackageVerificationMethod : VerificationMethodBase\n {\n /// \n /// Initializes a new instance of the class.\n /// \n public AppxPackageVerificationMethod()\n : base(\"AppxPackage\", priority: 15) { }\n\n /// \n protected override async Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken\n )\n {\n return await Task.Run(\n () =>\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n try\n {\n var packages = GetAppxPackages();\n var matchingPackage = packages.FirstOrDefault(p =>\n p.Name.Equals(packageId, StringComparison.OrdinalIgnoreCase)\n || p.PackageFullName.StartsWith(\n packageId,\n StringComparison.OrdinalIgnoreCase\n )\n );\n\n if (matchingPackage != null)\n {\n return new VerificationResult\n {\n IsVerified = true,\n Message =\n $\"Found UWP package: {matchingPackage.Name} (Version: {matchingPackage.Version})\",\n MethodUsed = \"AppxPackage\",\n AdditionalInfo = matchingPackage,\n };\n }\n\n return VerificationResult.Failure(\n $\"UWP package '{packageId}' not found\"\n );\n }\n catch (Exception ex)\n {\n return VerificationResult.Failure(\n $\"Error checking UWP packages: {ex.Message}\"\n );\n }\n },\n cancellationToken\n )\n .ConfigureAwait(false);\n }\n\n /// \n protected override async Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken\n )\n {\n var result = await VerifyPresenceAsync(packageId, cancellationToken)\n .ConfigureAwait(false);\n if (!result.IsVerified)\n return result;\n\n // Extract the version from the additional info\n var installedVersion = (result.AdditionalInfo as AppxPackageInfo)?.Version;\n if (string.IsNullOrEmpty(installedVersion))\n return VerificationResult.Failure(\n $\"Could not determine installed version for UWP package '{packageId}'\",\n \"AppxPackage\"\n );\n\n // Simple version comparison (this could be enhanced with proper version comparison logic)\n if (!installedVersion.Equals(version, StringComparison.OrdinalIgnoreCase))\n return VerificationResult.Failure(\n $\"Version mismatch for UWP package '{packageId}'. Installed: {installedVersion}, Expected: {version}\",\n \"AppxPackage\"\n );\n\n return result;\n }\n\n private static List GetAppxPackages()\n {\n var packages = new List();\n\n try\n {\n // Method 1: Using Get-AppxPackage via PowerShell (more reliable for current user)\n using (var ps = System.Management.Automation.PowerShell.Create())\n {\n var results = ps.AddCommand(\"Get-AppxPackage\").Invoke();\n foreach (var result in results)\n {\n packages.Add(\n new AppxPackageInfo\n {\n Name = result.Properties[\"Name\"]?.Value?.ToString(),\n PackageFullName = result\n .Properties[\"PackageFullName\"]\n ?.Value?.ToString(),\n Version = result.Properties[\"Version\"]?.Value?.ToString(),\n InstallLocation = result\n .Properties[\"InstallLocation\"]\n ?.Value?.ToString(),\n }\n );\n }\n }\n }\n catch\n {\n // Fall back to WMI if PowerShell fails\n try\n {\n var searcher = new ManagementObjectSearcher(\"SELECT * FROM Win32_Product\");\n foreach (var obj in searcher.Get().Cast())\n {\n packages.Add(\n new AppxPackageInfo\n {\n Name = obj[\"Name\"]?.ToString(),\n Version = obj[\"Version\"]?.ToString(),\n InstallLocation = obj[\"InstallLocation\"]?.ToString(),\n }\n );\n }\n }\n catch\n {\n // If both methods fail, return an empty list\n }\n }\n\n return packages;\n }\n }\n\n /// \n /// Represents information about an AppX package.\n /// \n public class AppxPackageInfo\n {\n /// \n /// Gets or sets the name of the package.\n /// \n public string Name { get; set; }\n\n /// \n /// Gets or sets the full name of the package.\n /// \n public string PackageFullName { get; set; }\n\n /// \n /// Gets or sets the version of the package.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets the installation location of the package.\n /// \n public string InstallLocation { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/CompositeInstallationVerifier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification\n{\n /// \n /// Coordinates multiple verification methods to determine if a package is installed.\n /// \n public class CompositeInstallationVerifier : IInstallationVerifier\n {\n private readonly IEnumerable _verificationMethods;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The verification methods to use.\n public CompositeInstallationVerifier(IEnumerable verificationMethods)\n {\n _verificationMethods =\n verificationMethods?.OrderBy(m => m.Priority).ToList()\n ?? throw new ArgumentNullException(nameof(verificationMethods));\n }\n\n /// \n public async Task VerifyInstallationAsync(\n string packageId,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n // Add a short delay before verification to allow Windows to complete registration\n await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken).ConfigureAwait(false);\n\n var results = new List();\n VerificationResult successfulResult = null;\n\n // Try verification with up to 3 attempts with increasing delays\n for (int attempt = 1; attempt <= 3; attempt++)\n {\n // Clear previous results for each attempt\n results.Clear();\n successfulResult = null;\n \n foreach (var method in _verificationMethods)\n {\n try\n {\n var result = await method\n .VerifyAsync(packageId, cancellationToken: cancellationToken)\n .ConfigureAwait(false);\n\n results.Add(result);\n\n if (result.IsVerified)\n {\n successfulResult = result;\n break; // Stop at first successful verification\n }\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n results.Add(\n VerificationResult.Failure($\"Error in {method.Name}: {ex.Message}\")\n );\n }\n }\n\n // If we found a successful result, return it immediately\n if (successfulResult != null)\n return successfulResult;\n \n // If this isn't the last attempt, wait before trying again\n if (attempt < 3)\n {\n // Exponential backoff: 1s, then 2s\n await Task.Delay(TimeSpan.FromSeconds(attempt), cancellationToken).ConfigureAwait(false);\n }\n }\n\n // If we get here, all attempts failed\n var errorMessages = results\n .Where(r => !r.IsVerified && !string.IsNullOrEmpty(r.Message))\n .Select(r => r.Message)\n .ToList();\n\n return new VerificationResult\n {\n IsVerified = false,\n Message =\n $\"Package '{packageId}' not found after multiple attempts. Details: {string.Join(\"; \", errorMessages)}\",\n MethodUsed = \"Composite\",\n AdditionalInfo = new { PackageId = packageId, VerificationResults = results },\n };\n }\n\n /// \n public async Task VerifyInstallationAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n if (string.IsNullOrWhiteSpace(version))\n throw new ArgumentException(\n \"Version cannot be null or whitespace.\",\n nameof(version)\n );\n\n var results = new List();\n VerificationResult successfulResult = null;\n\n foreach (var method in _verificationMethods)\n {\n try\n {\n var result = await method\n .VerifyAsync(packageId, version, cancellationToken)\n .ConfigureAwait(false);\n\n results.Add(result);\n\n if (result.IsVerified)\n {\n successfulResult = result;\n // Don't break here, as we want to try all methods to find an exact version match\n }\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n results.Add(\n VerificationResult.Failure($\"Error in {method.Name}: {ex.Message}\")\n );\n }\n }\n\n // If we found a successful result, return it\n if (successfulResult != null)\n return successfulResult;\n\n // Check if any method found the package but with a different version\n var versionMismatch = results.FirstOrDefault(r =>\n r.IsVerified\n && r.AdditionalInfo is IDictionary info\n && info.ContainsKey(\"Version\")\n && info[\"Version\"]?.ToString() != version\n );\n\n if (versionMismatch != null)\n {\n var installedVersion =\n (versionMismatch.AdditionalInfo as IDictionary)?[\n \"Version\"\n ]?.ToString() ?? \"unknown\";\n return VerificationResult.Failure(\n $\"Version mismatch for '{packageId}'. Installed: {installedVersion}, Expected: {version}\",\n versionMismatch.MethodUsed\n );\n }\n\n // Otherwise, return a composite result with all the failures\n var errorMessages = results\n .Where(r => !r.IsVerified && !string.IsNullOrEmpty(r.Message))\n .Select(r => r.Message)\n .ToList();\n\n return new VerificationResult\n {\n IsVerified = false,\n Message =\n $\"Package '{packageId}' version '{version}' not found. Details: {string.Join(\"; \", errorMessages)}\",\n MethodUsed = \"Composite\",\n AdditionalInfo = new\n {\n PackageId = packageId,\n Version = version,\n VerificationResults = results,\n },\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Customize/Services/ThemeService.cs", "using System;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.Customize.Models;\n\nnamespace Winhance.Infrastructure.Features.Customize.Services\n{\n /// \n /// Service for theme-related operations.\n /// \n public class ThemeService : IThemeService\n {\n private readonly IRegistryService _registryService;\n private readonly ILogService _logService;\n private readonly IWallpaperService _wallpaperService;\n private readonly ISystemServices _systemServices;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The registry service.\n /// The log service.\n /// The wallpaper service.\n /// The system services.\n public ThemeService(\n IRegistryService registryService,\n ILogService logService,\n IWallpaperService wallpaperService,\n ISystemServices systemServices)\n {\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _wallpaperService = wallpaperService ?? throw new ArgumentNullException(nameof(wallpaperService));\n _systemServices = systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n }\n\n /// \n public bool IsDarkModeEnabled()\n {\n try\n {\n string keyPath = $\"HKCU\\\\{WindowsThemeSettings.Registry.ThemesPersonalizeSubKey}\";\n var value = _registryService.GetValue(keyPath, WindowsThemeSettings.Registry.AppsUseLightThemeName);\n bool isDarkMode = value != null && (int)value == 0;\n\n _logService.Log(LogLevel.Info, $\"Dark mode check completed. Is Dark Mode: {isDarkMode}\");\n return isDarkMode;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking dark mode status: {ex.Message}\");\n return false;\n }\n }\n\n /// \n public string GetCurrentThemeName()\n {\n return IsDarkModeEnabled() ? \"Dark Mode\" : \"Light Mode\";\n }\n\n /// \n public bool SetThemeMode(bool isDarkMode)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Setting theme mode to {(isDarkMode ? \"dark\" : \"light\")}\");\n\n string keyPath = $\"HKCU\\\\{WindowsThemeSettings.Registry.ThemesPersonalizeSubKey}\";\n int valueToSet = isDarkMode ? 0 : 1;\n\n // Set both registry values\n bool appsSuccess = _registryService.SetValue(\n keyPath,\n WindowsThemeSettings.Registry.AppsUseLightThemeName,\n valueToSet,\n Microsoft.Win32.RegistryValueKind.DWord);\n\n bool systemSuccess = _registryService.SetValue(\n keyPath,\n WindowsThemeSettings.Registry.SystemUsesLightThemeName,\n valueToSet,\n Microsoft.Win32.RegistryValueKind.DWord);\n\n bool success = appsSuccess && systemSuccess;\n if (success)\n {\n _logService.Log(LogLevel.Success, $\"Theme mode set to {(isDarkMode ? \"dark\" : \"light\")}\");\n }\n else\n {\n _logService.Log(LogLevel.Error, \"Failed to set theme mode\");\n }\n\n return success;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting theme mode: {ex.Message}\");\n return false;\n }\n }\n\n /// \n public async Task ApplyThemeAsync(bool isDarkMode, bool changeWallpaper)\n {\n try\n {\n // Apply theme in registry\n bool themeSuccess = SetThemeMode(isDarkMode);\n if (!themeSuccess)\n {\n return false;\n }\n\n // Change wallpaper if requested\n if (changeWallpaper)\n {\n _logService.Log(LogLevel.Info, $\"Changing wallpaper for {(isDarkMode ? \"dark\" : \"light\")} mode\");\n // Check Windows version directly instead of using ISystemServices\n bool isWindows11 = Environment.OSVersion.Version.Build >= 22000;\n await _wallpaperService.SetDefaultWallpaperAsync(isWindows11, isDarkMode);\n }\n\n // Use the improved RefreshWindowsGUI method to refresh the UI\n bool refreshResult = await _systemServices.RefreshWindowsGUI(true);\n if (!refreshResult)\n {\n _logService.Log(LogLevel.Warning, \"Failed to refresh Windows GUI after applying theme\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Theme applied successfully: {(isDarkMode ? \"Dark\" : \"Light\")} Mode\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying theme: {ex.Message}\");\n return false;\n }\n }\n\n /// \n public async Task RefreshGUIAsync(bool restartExplorer)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Refreshing GUI with WindowsSystemService (restartExplorer: {restartExplorer})\");\n \n // Use the improved implementation from WindowsSystemService\n bool result = await _systemServices.RefreshWindowsGUI(restartExplorer);\n \n if (result)\n {\n _logService.Log(LogLevel.Info, \"Windows GUI refresh completed successfully\");\n }\n else\n {\n _logService.Log(LogLevel.Error, \"Failed to refresh Windows GUI\");\n }\n \n return result;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error refreshing GUI: {ex.Message}\");\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGetInstallationServiceAdapter.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Infrastructure.Features.Common.Services;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Adapter that implements the legacy IWinGetInstallationService using the new IWinGetInstaller.\n /// \n public class WinGetInstallationServiceAdapter : IWinGetInstallationService, IDisposable\n {\n private readonly IWinGetInstaller _winGetInstaller;\n private readonly ITaskProgressService _taskProgressService;\n private bool _disposed;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The WinGet installer service.\n /// The task progress service.\n public WinGetInstallationServiceAdapter(\n IWinGetInstaller winGetInstaller,\n ITaskProgressService taskProgressService)\n {\n _winGetInstaller = winGetInstaller ?? throw new ArgumentNullException(nameof(winGetInstaller));\n _taskProgressService = taskProgressService ?? throw new ArgumentNullException(nameof(taskProgressService));\n }\n\n /// \n public async Task InstallWithWingetAsync(\n string packageName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default,\n string? displayName = null)\n {\n if (string.IsNullOrWhiteSpace(packageName))\n throw new ArgumentException(\"Package name cannot be null or empty\", nameof(packageName));\n\n var displayNameToUse = displayName ?? packageName;\n var progressWrapper = new ProgressAdapter(progress);\n \n try\n {\n // Report initial progress\n progressWrapper.Report(0, $\"Starting installation of {displayNameToUse}...\");\n\n // Check if WinGet is installed first\n bool wingetInstalled = await IsWinGetInstalledAsync().ConfigureAwait(false);\n if (!wingetInstalled)\n {\n progressWrapper.Report(10, \"WinGet is not installed. Installing WinGet first...\");\n \n // Install WinGet\n await InstallWinGetAsync(progress).ConfigureAwait(false);\n \n // Verify WinGet installation was successful\n wingetInstalled = await IsWinGetInstalledAsync().ConfigureAwait(false);\n if (!wingetInstalled)\n {\n progressWrapper.Report(0, \"Failed to install WinGet. Cannot proceed with application installation.\");\n return false;\n }\n \n progressWrapper.Report(30, $\"WinGet installed successfully. Continuing with {displayNameToUse} installation...\");\n }\n\n // Now use the WinGet installer to install the package\n var result = await _winGetInstaller.InstallPackageAsync(\n packageName,\n new InstallationOptions\n {\n // Configure installation options as needed\n Silent = true\n },\n displayNameToUse, // Pass the display name to use in progress reporting\n cancellationToken)\n .ConfigureAwait(false);\n\n if (result.Success)\n {\n progressWrapper.Report(100, $\"Successfully installed {displayNameToUse}\");\n return true;\n }\n \n progressWrapper.Report(0, $\"Failed to install {displayNameToUse}: {result.Message}\");\n return false;\n }\n catch (Exception ex)\n {\n progressWrapper.Report(0, $\"Error installing {displayNameToUse}: {ex.Message}\");\n throw;\n }\n }\n\n /// \n public async Task InstallWinGetAsync(IProgress? progress = null)\n {\n // Check if WinGet is already installed\n if (await IsWinGetInstalledAsync().ConfigureAwait(false))\n {\n progress?.Report(new TaskProgressDetail { StatusText = \"WinGet is already installed\" });\n return;\n }\n\n var progressWrapper = new ProgressAdapter(progress);\n \n try\n {\n progressWrapper.Report(0, \"Downloading WinGet installer...\");\n \n // Force a search operation which will trigger WinGet installation if it's not found\n // This leverages the WinGetInstaller's built-in mechanism to install WinGet when needed\n try \n {\n // We use a simple search operation to trigger the WinGet installation process\n // The dot (.) is a simple search term that will match everything\n progressWrapper.Report(20, \"Installing WinGet...\");\n \n var searchResult = await _winGetInstaller.SearchPackagesAsync(\n \".\", // Simple search term\n null, // No search options\n CancellationToken.None)\n .ConfigureAwait(false);\n \n progressWrapper.Report(80, \"WinGet installation in progress...\");\n \n // If we get here, WinGet should be installed\n progressWrapper.Report(100, \"WinGet installed successfully\");\n }\n catch (Exception ex)\n {\n progressWrapper.Report(0, $\"Error installing WinGet: {ex.Message}\");\n throw;\n }\n \n // Verify WinGet installation\n bool isInstalled = await IsWinGetInstalledAsync().ConfigureAwait(false);\n if (!isInstalled)\n {\n progressWrapper.Report(0, \"WinGet installation verification failed\");\n throw new InvalidOperationException(\"WinGet installation could not be verified\");\n }\n }\n catch (Exception ex)\n {\n progressWrapper.Report(0, $\"Error installing WinGet: {ex.Message}\");\n throw;\n }\n }\n\n /// \n public async Task IsWinGetInstalledAsync()\n {\n try\n {\n // Try to list packages to check if WinGet is working\n var result = await _winGetInstaller.SearchPackagesAsync(\".\").ConfigureAwait(false);\n return result != null;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n /// \n /// Releases the unmanaged resources used by the \n /// and optionally releases the managed resources.\n /// \n /// True to release both managed and unmanaged resources; false to release only unmanaged resources.\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n // Dispose managed resources here if needed\n }\n\n _disposed = true;\n }\n }\n\n /// \n /// Adapter to convert between IProgress and IProgress\n /// \n private class ProgressAdapter\n {\n private readonly IProgress? _progress;\n\n public ProgressAdapter(IProgress? progress)\n {\n _progress = progress;\n }\n\n public void Report(int progress, string status)\n {\n _progress?.Report(new TaskProgressDetail\n {\n Progress = progress,\n StatusText = status,\n LogLevel = progress == 100 ? LogLevel.Info : LogLevel.Debug\n });\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Utilities/WinGetOutputParser.cs", "using System;\nusing System.IO;\nusing System.Text.RegularExpressions;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Utilities\n{\n /// \n /// Parses WinGet command output and generates appropriate progress updates.\n /// \n public class WinGetOutputParser\n {\n private readonly ILogService _logService;\n private InstallationState _currentState = InstallationState.Starting;\n private string _downloadFileName;\n private bool _isVerifying;\n private string _lastProgressLine;\n private int _lastPercentage;\n private bool _hasStarted = false;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// Optional log service for debugging.\n public WinGetOutputParser(ILogService logService = null)\n {\n _logService = logService;\n }\n\n /// \n /// Parses a line of WinGet output and generates an appropriate progress update.\n /// Uses an indeterminate progress indicator and displays raw WinGet output.\n /// \n /// The line of output to parse.\n /// An InstallationProgress object with the current progress information, or null if no update is needed.\n public InstallationProgress ParseOutputLine(string outputLine)\n {\n if (string.IsNullOrWhiteSpace(outputLine))\n {\n return null;\n }\n\n _logService?.LogInformation($\"WinGet output: {outputLine}\");\n \n // If this is the first output line, transition from Starting state\n if (!_hasStarted)\n {\n _hasStarted = true;\n _currentState = InstallationState.Resolving;\n \n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = 0,\n IsIndeterminate = true,\n };\n }\n\n // Check for verification messages\n if (outputLine.Contains(\"Verifying\"))\n {\n _logService?.LogInformation(\"Verification step detected\");\n _currentState = InstallationState.Verifying;\n _isVerifying = true;\n\n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = 0,\n IsIndeterminate = true,\n };\n }\n\n // Check for installation messages\n if (\n outputLine.Contains(\"Installing\")\n || outputLine.Contains(\"installation\")\n || (_isVerifying && !outputLine.Contains(\"Verifying\"))\n )\n {\n _logService?.LogInformation(\"Installation step detected\");\n _currentState = InstallationState.Installing;\n _isVerifying = false;\n\n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = 0,\n IsIndeterminate = true,\n };\n }\n\n // Check for download information\n if (\n (\n outputLine.Contains(\"Downloading\")\n || outputLine.Contains(\"download\")\n || outputLine.Contains(\"KB\")\n || outputLine.Contains(\"MB\")\n || outputLine.Contains(\"GB\")\n )\n )\n {\n _logService?.LogInformation($\"Download information detected: {outputLine}\");\n\n // Set the current state to Downloading\n _currentState = InstallationState.Downloading;\n\n // Create a progress update with a generic downloading message\n return new InstallationProgress\n {\n Status = \"Downloading package files. This might take a while, please wait...\",\n Percentage = 0, // Not used in indeterminate mode\n IsIndeterminate = true, // Use indeterminate progress\n // Set Operation to help identify this is a download operation\n Operation = \"Downloading\"\n };\n }\n\n // Check for installation status\n if (outputLine.Contains(\"%\"))\n {\n var percentageMatch = Regex.Match(outputLine, @\"(\\d+)%\");\n if (percentageMatch.Success)\n {\n int percentage = int.Parse(percentageMatch.Groups[1].Value);\n _lastPercentage = percentage;\n _lastProgressLine = outputLine;\n\n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = percentage,\n IsIndeterminate = false,\n };\n }\n }\n\n // Check for completion\n if (\n outputLine.Contains(\"Successfully installed\")\n || outputLine.Contains(\"completed successfully\")\n || outputLine.Contains(\"installation complete\")\n )\n {\n _logService?.LogInformation(\"Installation completed successfully\");\n _currentState = InstallationState.Completing;\n\n return new InstallationProgress\n {\n Status = \"Installation completed successfully!\",\n Percentage = 100,\n IsIndeterminate = false,\n // Note: The installation is complete, but we don't have an IsComplete property\n // so we just set the percentage to 100 and a clear status message\n };\n }\n\n // Check for errors\n if (\n outputLine.Contains(\"error\")\n || outputLine.Contains(\"failed\")\n || outputLine.Contains(\"Error:\")\n || outputLine.Contains(\"Failed:\")\n )\n {\n _logService?.LogError($\"Installation error detected: {outputLine}\");\n\n return new InstallationProgress\n {\n Status = $\"Error: {outputLine.Trim()}\",\n Percentage = 0,\n IsIndeterminate = false,\n // Note: We don't have HasError or ErrorMessage properties\n // so we just include the error in the Status\n };\n }\n\n // For other lines, return the last progress if available\n if (!string.IsNullOrEmpty(_lastProgressLine) && _lastPercentage > 0)\n {\n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = _lastPercentage,\n IsIndeterminate = false,\n };\n }\n\n // For other lines, just return the current state\n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = 0,\n IsIndeterminate = true,\n };\n }\n\n /// \n /// Gets a status message appropriate for the current installation state.\n /// \n private string GetStatusMessage(InstallationState state)\n {\n switch (state)\n {\n case InstallationState.Starting:\n return \"Preparing for installation...\";\n case InstallationState.Resolving:\n return \"Resolving package dependencies...\";\n case InstallationState.Downloading:\n return \"Downloading package files. This might take a while, please wait...\";\n case InstallationState.Verifying:\n return \"Verifying package integrity...\";\n case InstallationState.Installing:\n return \"Installing application...\";\n case InstallationState.Configuring:\n return \"Configuring application settings...\";\n case InstallationState.Completing:\n return \"Finalizing installation...\";\n default:\n return \"Processing...\";\n }\n }\n }\n\n /// \n /// Represents the different states of a WinGet installation process.\n /// \n public enum InstallationState\n {\n /// \n /// The installation process is starting.\n /// \n Starting,\n\n /// \n /// The package dependencies are being resolved.\n /// \n Resolving,\n\n /// \n /// Package files are being downloaded.\n /// \n Downloading,\n\n /// \n /// Package integrity is being verified.\n /// \n Verifying,\n\n /// \n /// The application is being installed.\n /// \n Installing,\n\n /// \n /// The application is being configured.\n /// \n Configuring,\n\n /// \n /// The installation process is completing.\n /// \n Completing,\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/SoftwareAppsViewModel.cs", "using System;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n /// \n /// ViewModel for the SoftwareAppsView that coordinates WindowsApps and ExternalApps sections.\n /// \n public partial class SoftwareAppsViewModel : BaseViewModel\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly IPackageManager _packageManager;\n\n [ObservableProperty]\n private string _statusText =\n \"Manage Windows Apps, Capabilities & Features and Install External Software\";\n\n [ObservableProperty]\n private WindowsAppsViewModel _windowsAppsViewModel;\n\n [ObservableProperty]\n private ExternalAppsViewModel _externalAppsViewModel;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The package manager.\n /// The service provider for dependency resolution.\n public SoftwareAppsViewModel(\n ITaskProgressService progressService,\n IPackageManager packageManager,\n IServiceProvider serviceProvider\n )\n : base(progressService)\n {\n _packageManager =\n packageManager ?? throw new ArgumentNullException(nameof(packageManager));\n _serviceProvider =\n serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n\n // Resolve the dependencies via DI container\n WindowsAppsViewModel = _serviceProvider.GetRequiredService();\n ExternalAppsViewModel = _serviceProvider.GetRequiredService();\n }\n\n /// \n /// Initializes child view models and prepares the view.\n /// \n [RelayCommand]\n public async Task Initialize()\n {\n StatusText = \"Initializing Software Apps...\";\n IsLoading = true;\n\n try\n {\n // Initialize WindowsAppsViewModel if not already initialized\n if (!WindowsAppsViewModel.IsInitialized)\n {\n await WindowsAppsViewModel.LoadAppsAndCheckInstallationStatusAsync();\n }\n\n // Initialize ExternalAppsViewModel if not already initialized\n if (!ExternalAppsViewModel.IsInitialized)\n {\n await ExternalAppsViewModel.LoadAppsAndCheckInstallationStatusAsync();\n }\n\n StatusText =\n \"Manage Windows Apps, Capabilities & Features and Install External Software\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Error initializing: {ex.Message}\";\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Called when the view is navigated to.\n /// \n /// Navigation parameter.\n public override async void OnNavigatedTo(object parameter)\n {\n try\n {\n // Initialize when navigated to this view\n await Initialize();\n }\n catch (Exception ex)\n {\n StatusText = $\"Error during navigation: {ex.Message}\";\n // Log the error or handle it appropriately\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/PowerShellScriptFactory.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Factory for creating PowerShell script objects.\n /// \n public class PowerShellScriptFactory : IScriptFactory\n {\n private readonly IScriptBuilderService _scriptBuilder;\n private readonly ILogService _logService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The script builder service.\n /// The logging service.\n /// The app discovery service.\n public PowerShellScriptFactory(\n IScriptBuilderService scriptBuilder,\n ILogService logService,\n IAppDiscoveryService appDiscoveryService)\n {\n _scriptBuilder = scriptBuilder ?? throw new ArgumentNullException(nameof(scriptBuilder));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _appDiscoveryService = appDiscoveryService ?? throw new ArgumentNullException(nameof(appDiscoveryService));\n }\n\n /// \n public RemovalScript CreateBatchRemovalScript(\n List appNames,\n Dictionary> appsWithRegistry,\n Dictionary appSubPackages = null)\n {\n try\n {\n _logService.LogInformation($\"Creating batch removal script for {appNames.Count} apps\");\n\n // Categorize apps into packages, capabilities, and features\n var (packages, capabilities, features) = CategorizeApps(appNames);\n\n // Build the script content\n string scriptContent = _scriptBuilder.BuildCompleteRemovalScript(\n packages,\n capabilities,\n features,\n appsWithRegistry,\n appSubPackages);\n\n // Return the RemovalScript object\n return new RemovalScript\n {\n Name = \"BloatRemoval\",\n Content = scriptContent,\n TargetScheduledTaskName = \"Winhance\\\\BloatRemoval\",\n RunOnStartup = true\n };\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error creating batch removal script\", ex);\n throw;\n }\n }\n\n /// \n public RemovalScript CreateSingleAppRemovalScript(AppInfo app)\n {\n try\n {\n _logService.LogInformation($\"Creating single app removal script for {app.PackageName}\");\n\n // Build the script content\n string scriptContent = _scriptBuilder.BuildSingleAppRemovalScript(app);\n\n // Return the RemovalScript object\n return new RemovalScript\n {\n Name = $\"Remove_{app.PackageName.Replace(\".\", \"_\")}\",\n Content = scriptContent,\n TargetScheduledTaskName = $\"Winhance\\\\Remove_{app.PackageName.Replace(\".\", \"_\")}\",\n RunOnStartup = false\n };\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error creating single app removal script for {app.PackageName}\", ex);\n throw;\n }\n }\n\n /// \n /// Categorizes apps into packages, capabilities, and features.\n /// \n /// The app names to categorize.\n /// A tuple containing lists of packages, capabilities, and features.\n private (List, List, List) CategorizeApps(List appNames)\n {\n var packages = new List();\n var capabilities = new List();\n var features = new List();\n\n // Get all standard apps to check their types\n var allApps = _appDiscoveryService.GetStandardAppsAsync().GetAwaiter().GetResult();\n var appInfoDict = allApps.ToDictionary(a => a.PackageName, a => a);\n\n foreach (var appName in appNames)\n {\n if (appInfoDict.TryGetValue(appName, out var appInfo))\n {\n switch (appInfo.Type)\n {\n case AppType.StandardApp:\n packages.Add(appName);\n break;\n case AppType.Capability:\n capabilities.Add(appName);\n break;\n case AppType.OptionalFeature:\n features.Add(appName);\n break;\n default:\n // Default to package if type is unknown\n packages.Add(appName);\n break;\n }\n }\n else\n {\n // If app is not found in the dictionary, assume it's a package\n packages.Add(appName);\n }\n }\n\n return (packages, capabilities, features);\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/Methods/FileSystemVerificationMethod.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods\n{\n /// \n /// Verifies software installations by checking common installation directories.\n /// \n public class FileSystemVerificationMethod : VerificationMethodBase\n {\n private static readonly string[] CommonInstallPaths = new[]\n {\n Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)),\n Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)),\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Programs\"\n ),\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),\n @\"Microsoft\\Windows\\Start Menu\\Programs\"\n ),\n };\n\n /// \n /// Initializes a new instance of the class.\n /// \n public FileSystemVerificationMethod()\n : base(\"FileSystem\", priority: 20) { }\n\n /// \n protected override async Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken\n )\n {\n return await Task.Run(\n () =>\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n // First try: Check if the app is in PATH (for CLI tools)\n try\n {\n var pathEnv = Environment.GetEnvironmentVariable(\"PATH\") ?? string.Empty;\n var paths = pathEnv.Split(Path.PathSeparator);\n \n\n foreach (var path in paths)\n {\n if (string.IsNullOrEmpty(path))\n continue;\n \n\n var exePath = Path.Combine(path, $\"{packageId}.exe\");\n if (File.Exists(exePath))\n {\n return new VerificationResult\n {\n IsVerified = true,\n Message = $\"Found in PATH: {exePath}\",\n MethodUsed = \"FileSystem\",\n AdditionalInfo = new\n {\n InstallPath = path,\n ExecutablePath = exePath,\n },\n };\n }\n }\n }\n catch (Exception)\n {\n // Ignore PATH check errors and continue with other methods\n }\n\n // Second try: Check common installation directories\n foreach (var basePath in CommonInstallPaths)\n {\n if (!Directory.Exists(basePath))\n continue;\n\n try\n {\n // Check for exact match in directory names\n var matchingDirs = Directory\n .EnumerateDirectories(\n basePath,\n \"*\",\n SearchOption.TopDirectoryOnly\n )\n .Where(d =>\n Path.GetFileName(d)\n ?.Equals(packageId, StringComparison.OrdinalIgnoreCase)\n == true\n || Path.GetFileName(d)\n ?.Contains(\n packageId,\n StringComparison.OrdinalIgnoreCase\n ) == true\n )\n .ToList();\n\n if (matchingDirs.Any())\n {\n return new VerificationResult\n {\n IsVerified = true,\n Message = $\"Found in file system: {matchingDirs.First()}\",\n MethodUsed = \"FileSystem\",\n AdditionalInfo = new\n {\n InstallPath = matchingDirs.First(),\n AllMatchingPaths = matchingDirs.ToArray(),\n },\n };\n }\n \n\n // Check for Microsoft Store apps in Packages directory\n if (basePath.Contains(\"LocalApplicationData\"))\n {\n var packagesPath = Path.Combine(basePath, \"Packages\");\n if (Directory.Exists(packagesPath))\n {\n var storeAppDirs = Directory\n .EnumerateDirectories(\n packagesPath,\n \"*\",\n SearchOption.TopDirectoryOnly\n )\n .Where(d =>\n Path.GetFileName(d)\n ?.IndexOf(packageId, StringComparison.OrdinalIgnoreCase) >= 0\n )\n .ToList();\n \n\n foreach (var dir in storeAppDirs)\n {\n var manifestPath = Path.Combine(dir, \"AppxManifest.xml\");\n if (File.Exists(manifestPath))\n {\n return new VerificationResult\n {\n IsVerified = true,\n Message = $\"Found Microsoft Store app: {dir}\",\n MethodUsed = \"FileSystem\",\n AdditionalInfo = new\n {\n InstallPath = dir,\n ManifestPath = manifestPath,\n },\n };\n }\n }\n }\n }\n }\n catch (UnauthorizedAccessException)\n {\n // Skip directories we can't access\n continue;\n }\n catch (Exception)\n {\n // Skip directories with other errors\n continue;\n }\n }\n\n return VerificationResult.Failure(\n $\"Package '{packageId}' not found in common installation directories\"\n );\n },\n cancellationToken\n )\n .ConfigureAwait(false);\n }\n\n /// \n protected override async Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken\n )\n {\n // For file system, we can't reliably determine version from directory name\n // So we'll just check for presence and let other methods verify version\n return await VerifyPresenceAsync(packageId, cancellationToken).ConfigureAwait(false);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/VersionService.cs", "using System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Net.Http;\nusing System.Reflection;\nusing System.Text.Json;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n public class VersionService : IVersionService\n {\n private readonly ILogService _logService;\n private readonly HttpClient _httpClient;\n private readonly string _latestReleaseApiUrl = \"https://api.github.com/repos/memstechtips/Winhance/releases/latest\";\n private readonly string _latestReleaseDownloadUrl = \"https://github.com/memstechtips/Winhance/releases/latest/download/Winhance.Installer.exe\";\n private readonly string _userAgent = \"Winhance-Update-Checker\";\n \n public VersionService(ILogService logService)\n {\n _logService = logService;\n _httpClient = new HttpClient();\n _httpClient.DefaultRequestHeaders.Add(\"User-Agent\", _userAgent);\n }\n \n public VersionInfo GetCurrentVersion()\n {\n try\n {\n // Get the assembly version\n Assembly assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();\n string? location = assembly.Location;\n \n if (string.IsNullOrEmpty(location))\n {\n _logService.Log(LogLevel.Error, \"Could not determine assembly location for version check\");\n return CreateDefaultVersion();\n }\n \n // Get the assembly file version which will be in the format v25.05.02\n FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(location);\n string fileVersion = fileVersionInfo.FileVersion ?? \"v0.0.0\";\n \n // If the version doesn't start with 'v', add it\n if (!fileVersion.StartsWith(\"v\"))\n {\n fileVersion = $\"v{fileVersion}\";\n }\n \n return VersionInfo.FromTag(fileVersion);\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting current version: {ex.Message}\", ex);\n return CreateDefaultVersion();\n }\n }\n \n public async Task CheckForUpdateAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Checking for updates...\");\n \n // Get the latest release information from GitHub API\n HttpResponseMessage response = await _httpClient.GetAsync(_latestReleaseApiUrl);\n response.EnsureSuccessStatusCode();\n \n string responseBody = await response.Content.ReadAsStringAsync();\n using JsonDocument doc = JsonDocument.Parse(responseBody);\n \n // Extract the tag name (version) from the response\n string tagName = doc.RootElement.GetProperty(\"tag_name\").GetString() ?? \"v0.0.0\";\n string htmlUrl = doc.RootElement.GetProperty(\"html_url\").GetString() ?? string.Empty;\n DateTime publishedAt = doc.RootElement.TryGetProperty(\"published_at\", out JsonElement publishedElement) && \n DateTime.TryParse(publishedElement.GetString(), out DateTime published) \n ? published \n : DateTime.MinValue;\n \n VersionInfo latestVersion = VersionInfo.FromTag(tagName);\n latestVersion.DownloadUrl = _latestReleaseDownloadUrl;\n \n // Compare with current version\n VersionInfo currentVersion = GetCurrentVersion();\n latestVersion.IsUpdateAvailable = latestVersion.IsNewerThan(currentVersion);\n \n _logService.Log(LogLevel.Info, $\"Current version: {currentVersion.Version}, Latest version: {latestVersion.Version}, Update available: {latestVersion.IsUpdateAvailable}\");\n \n return latestVersion;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking for updates: {ex.Message}\", ex);\n return new VersionInfo { IsUpdateAvailable = false };\n }\n }\n \n public async Task DownloadAndInstallUpdateAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Downloading update...\");\n \n // Create a temporary file to download the installer\n string tempPath = Path.Combine(Path.GetTempPath(), \"Winhance.Installer.exe\");\n \n // Download the installer\n byte[] installerBytes = await _httpClient.GetByteArrayAsync(_latestReleaseDownloadUrl);\n await File.WriteAllBytesAsync(tempPath, installerBytes);\n \n _logService.Log(LogLevel.Info, $\"Update downloaded to {tempPath}, launching installer...\");\n \n // Launch the installer\n Process.Start(new ProcessStartInfo\n {\n FileName = tempPath,\n UseShellExecute = true\n });\n \n _logService.Log(LogLevel.Info, \"Installer launched successfully\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error downloading or installing update: {ex.Message}\", ex);\n throw;\n }\n }\n \n private VersionInfo CreateDefaultVersion()\n {\n // Create a default version based on the current date\n DateTime now = DateTime.Now;\n string versionTag = $\"v{now.Year - 2000:D2}.{now.Month:D2}.{now.Day:D2}\";\n \n return new VersionInfo\n {\n Version = versionTag,\n ReleaseDate = now\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToThemeIconConverter.cs", "using System;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Media.Imaging;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean value (IsDarkTheme) to the appropriate themed icon path\n /// \n public class BooleanToThemeIconConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n bool isDarkTheme = false;\n\n // Handle different input types for theme\n if (value is bool boolValue)\n {\n isDarkTheme = boolValue;\n Debug.WriteLine($\"BooleanToThemeIconConverter: isDarkTheme = {isDarkTheme} (from bool)\");\n }\n else if (value is string stringValue)\n {\n isDarkTheme = stringValue.Equals(\"Dark\", StringComparison.OrdinalIgnoreCase);\n Debug.WriteLine($\"BooleanToThemeIconConverter: isDarkTheme = {isDarkTheme} (from string '{stringValue}')\");\n }\n else\n {\n Debug.WriteLine($\"BooleanToThemeIconConverter: value is {(value == null ? \"null\" : value.GetType().Name)}\");\n }\n\n // Parameter should be in format \"darkIconPath|lightIconPath\"\n if (parameter is string paramString)\n {\n string[] iconPaths = paramString.Split('|');\n if (iconPaths.Length >= 2)\n {\n string darkIconPath = iconPaths[0];\n string lightIconPath = iconPaths[1];\n\n string selectedPath = isDarkTheme ? darkIconPath : lightIconPath;\n Debug.WriteLine($\"BooleanToThemeIconConverter: Selected path = {selectedPath}\");\n\n // If the target type is BitmapImage, create and return it\n if (targetType == typeof(BitmapImage))\n {\n return new BitmapImage(new Uri(selectedPath, UriKind.Relative));\n }\n\n // Otherwise return the path string\n return selectedPath;\n }\n }\n\n // Default fallback icon path\n Debug.WriteLine(\"BooleanToThemeIconConverter: Using fallback icon path\");\n return \"/Resources/AppIcons/winhance-rocket.ico\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // This converter doesn't support converting back\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/TaskbarCustomizations.cs", "using Microsoft.Win32;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Enums;\nusing System;\nusing System.IO;\nusing System.Diagnostics;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Core.Features.Customize.Models;\n\npublic static class TaskbarCustomizations\n{\n /// \n /// Special handling for News and Interests (Widgets) toggle.\n /// This method temporarily disables the UCPD service before applying the settings.\n /// \n /// The registry service.\n /// The log service.\n /// The linked registry settings to apply.\n /// Whether to enable or disable the settings.\n /// True if the settings were applied successfully; otherwise, false.\n public static async Task ApplyNewsAndInterestsSettingsAsync(\n IRegistryService registryService,\n ILogService logService,\n LinkedRegistrySettings linkedSettings,\n bool enable)\n {\n // Path to the UCPD service Start value\n const string ucpdServiceKeyPath = @\"HKLM\\SYSTEM\\CurrentControlSet\\Services\\UCPD\";\n const string startValueName = \"Start\";\n \n // Get the current value of the UCPD service Start key\n object? originalStartValue = registryService.GetValue(ucpdServiceKeyPath, startValueName);\n \n try\n {\n // Set the UCPD service Start value to 4 (disabled)\n logService.LogInformation($\"Temporarily disabling UCPD service by setting {ucpdServiceKeyPath}\\\\{startValueName} to 4\");\n bool setResult = registryService.SetValue(ucpdServiceKeyPath, startValueName, 4, RegistryValueKind.DWord);\n \n if (!setResult)\n {\n logService.LogError(\"Failed to set UCPD service Start value to 4\");\n return false;\n }\n \n // Apply the News and Interests (Widgets) settings\n logService.LogInformation($\"Applying linked setting: News and Interests (Widgets) with {linkedSettings.Settings.Count} registry entries\");\n bool result = await registryService.ApplyLinkedSettingsAsync(linkedSettings, enable);\n \n if (!result)\n {\n logService.LogError(\"Failed to apply linked settings for News and Interests (Widgets)\");\n return false;\n }\n \n return true;\n }\n finally\n {\n // Restore the original UCPD service Start value\n if (originalStartValue != null)\n {\n logService.LogInformation($\"Restoring UCPD service Start value to {originalStartValue}\");\n registryService.SetValue(ucpdServiceKeyPath, startValueName, originalStartValue, RegistryValueKind.DWord);\n }\n }\n }\n /// \n /// Cleans the taskbar by unpinning all items except File Explorer.\n /// \n /// The system services.\n /// The log service.\n public static async Task CleanTaskbar(ISystemServices systemServices, ILogService logService)\n {\n try\n {\n logService.LogInformation(\"Task started: Cleaning taskbar...\");\n logService.LogInformation(\"Cleaning taskbar started\");\n \n // Delete taskband registry key using Registry API\n using (var key = Registry.CurrentUser.OpenSubKey(@\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\", true))\n {\n if (key != null)\n {\n key.DeleteSubKeyTree(\"Taskband\", false);\n }\n }\n \n // Create the Taskband key and set values directly\n using (var taskbandKey = Registry.CurrentUser.CreateSubKey(\n @\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Taskband\", true))\n {\n if (taskbandKey != null)\n {\n // Convert the hex string to a byte array\n // This is the same data that was in the .reg file\n byte[] favoritesData = new byte[] {\n 0x00, 0xaa, 0x01, 0x00, 0x00, 0x3a, 0x00, 0x1f, 0x80, 0xc8, 0x27, 0x34, 0x1f, 0x10, 0x5c, 0x10,\n 0x42, 0xaa, 0x03, 0x2e, 0xe4, 0x52, 0x87, 0xd6, 0x68, 0x26, 0x00, 0x01, 0x00, 0x26, 0x00, 0xef,\n 0xbe, 0x10, 0x00, 0x00, 0x00, 0xf4, 0x7e, 0x76, 0xfa, 0xde, 0x9d, 0xda, 0x01, 0x40, 0x61, 0x5d,\n 0x09, 0xdf, 0x9d, 0xda, 0x01, 0x19, 0xb8, 0x5f, 0x09, 0xdf, 0x9d, 0xda, 0x01, 0x14, 0x00, 0x56,\n 0x00, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x58, 0xa9, 0x26, 0x10, 0x00, 0x54, 0x61, 0x73,\n 0x6b, 0x42, 0x61, 0x72, 0x00, 0x40, 0x00, 0x09, 0x00, 0x04, 0x00, 0xef, 0xbe, 0xa4, 0x58, 0xa9,\n 0x26, 0xa4, 0x58, 0xa9, 0x26, 0x2e, 0x00, 0x00, 0x00, 0xde, 0x9c, 0x01, 0x00, 0x00, 0x00, 0x02,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c,\n 0xf4, 0x85, 0x00, 0x54, 0x00, 0x61, 0x00, 0x73, 0x00, 0x6b, 0x00, 0x42, 0x00, 0x61, 0x00, 0x72,\n 0x00, 0x00, 0x00, 0x16, 0x00, 0x18, 0x01, 0x32, 0x00, 0x8a, 0x04, 0x00, 0x00, 0xa4, 0x58, 0xb6,\n 0x26, 0x20, 0x00, 0x46, 0x49, 0x4c, 0x45, 0x45, 0x58, 0x7e, 0x31, 0x2e, 0x4c, 0x4e, 0x4b, 0x00,\n 0x00, 0x54, 0x00, 0x09, 0x00, 0x04, 0x00, 0xef, 0xbe, 0xa4, 0x58, 0xb6, 0x26, 0xa4, 0x58, 0xb6,\n 0x26, 0x2e, 0x00, 0x00, 0x00, 0xb7, 0xa8, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x5a, 0x1e, 0x01, 0x46,\n 0x00, 0x69, 0x00, 0x6c, 0x00, 0x65, 0x00, 0x20, 0x00, 0x45, 0x00, 0x78, 0x00, 0x70, 0x00, 0x6c,\n 0x00, 0x6f, 0x00, 0x72, 0x00, 0x65, 0x00, 0x72, 0x00, 0x2e, 0x00, 0x6c, 0x00, 0x6e, 0x00, 0x6b,\n 0x00, 0x00, 0x00, 0x1c, 0x00, 0x22, 0x00, 0x00, 0x00, 0x1e, 0x00, 0xef, 0xbe, 0x02, 0x00, 0x55,\n 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x50, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x6e, 0x00, 0x65,\n 0x00, 0x64, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x12, 0x00, 0x00, 0x00, 0x2b, 0x00, 0xef, 0xbe, 0x19,\n 0xb8, 0x5f, 0x09, 0xdf, 0x9d, 0xda, 0x01, 0x1c, 0x00, 0x74, 0x00, 0x00, 0x00, 0x1d, 0x00, 0xef,\n 0xbe, 0x02, 0x00, 0x7b, 0x00, 0x46, 0x00, 0x33, 0x00, 0x38, 0x00, 0x42, 0x00, 0x46, 0x00, 0x34,\n 0x00, 0x30, 0x00, 0x34, 0x00, 0x2d, 0x00, 0x31, 0x00, 0x44, 0x00, 0x34, 0x00, 0x33, 0x00, 0x2d,\n 0x00, 0x34, 0x00, 0x32, 0x00, 0x46, 0x00, 0x32, 0x00, 0x2d, 0x00, 0x39, 0x00, 0x33, 0x00, 0x30,\n 0x00, 0x35, 0x00, 0x2d, 0x00, 0x36, 0x00, 0x37, 0x00, 0x44, 0x00, 0x45, 0x00, 0x30, 0x00, 0x42,\n 0x00, 0x32, 0x00, 0x38, 0x00, 0x46, 0x00, 0x43, 0x00, 0x32, 0x00, 0x33, 0x00, 0x7d, 0x00, 0x5c,\n 0x00, 0x65, 0x00, 0x78, 0x00, 0x70, 0x00, 0x6c, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x65, 0x00, 0x72,\n 0x00, 0x2e, 0x00, 0x65, 0x00, 0x78, 0x00, 0x65, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0xff\n };\n \n // Set the binary value directly\n taskbandKey.SetValue(\"Favorites\", favoritesData, RegistryValueKind.Binary);\n }\n }\n \n // Wait for registry changes to take effect before refreshing Windows GUI\n logService.LogInformation(\"Registry changes applied, waiting for changes to take effect...\");\n await Task.Delay(2000);\n \n // Use the improved RefreshWindowsGUI method to restart Explorer and apply changes\n // This will ensure Explorer is restarted properly with retry logic and fallback\n var result = await systemServices.RefreshWindowsGUI(true);\n if (!result)\n {\n throw new Exception(\"Failed to refresh Windows GUI after cleaning taskbar\");\n }\n }\n catch (Exception ex)\n {\n throw new Exception($\"Error cleaning taskbar: {ex.Message}\", ex);\n }\n }\n\n public static CustomizationGroup GetTaskbarCustomizations()\n {\n return new CustomizationGroup\n {\n Name = \"Taskbar\",\n Category = CustomizationCategory.Taskbar,\n Settings = new List\n {\n new CustomizationSetting\n {\n Id = \"taskbar-chat-icon\",\n Name = \"Windows Chat Icon\",\n Description = \"Controls Windows Chat icon visibility and menu behavior in taskbar\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Icons\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\Windows Chat\",\n Name = \"ChatIcon\",\n RecommendedValue = 3, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, Chat icon is shown (0 = show)\n DisabledValue = 3, // When toggle is OFF, Chat icon is hidden (3 = hide)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls Windows Chat icon visibility in taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n },\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"TaskbarMn\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, taskbar menu is enabled\n DisabledValue = 0, // When toggle is OFF, taskbar menu is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls taskbar menu behavior for chat\",\n IsPrimary = false,\n AbsenceMeansEnabled = false\n }\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All\n },\n new CustomizationSetting\n {\n Id = \"taskbar-meet-now-group\",\n Name = \"Meet Now Button\",\n Description = \"Controls Meet Now button visibility in taskbar\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Icons\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\Explorer\",\n Name = \"HideSCAMeetNow\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, Meet Now button is shown\n DisabledValue = 1, // When toggle is OFF, Meet Now button is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Meet Now button visibility in taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n },\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\Explorer\",\n Name = \"HideSCAMeetNow\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, Meet Now button is shown (user level)\n DisabledValue = 1, // When toggle is OFF, Meet Now button is hidden (user level)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Meet Now button visibility (user level)\",\n IsPrimary = false,\n AbsenceMeansEnabled = true\n }\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All\n },\n new CustomizationSetting\n {\n Id = \"taskbar-search-box\",\n Name = \"Search in Taskbar\",\n Description = \"Controls search box visibility in taskbar\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Icons\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Search\",\n Name = \"SearchboxTaskbarMode\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 2, // When toggle is ON, search box is shown (2 = show search box)\n DisabledValue = 0, // When toggle is OFF, search box is hidden (0 = hide search box)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls search box visibility in taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new CustomizationSetting\n {\n Id = \"taskbar-copilot\",\n Name = \"Copilot Button\",\n Description = \"Controls Copilot button visibility in taskbar\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Icons\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowCopilotButton\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Copilot button is shown\n DisabledValue = 0, // When toggle is OFF, Copilot button is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls Copilot button visibility in taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new CustomizationSetting\n {\n Id = \"taskbar-left-align\",\n Name = \"Left Aligned Taskbar\",\n Description = \"Controls taskbar icons alignment\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Behavior\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"TaskbarAl\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, taskbar icons are left-aligned\n DisabledValue = 1, // When toggle is OFF, taskbar icons are center-aligned\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls taskbar icons alignment\",\n IsPrimary = true,\n AbsenceMeansEnabled = false\n }\n }\n },\n new CustomizationSetting\n {\n Id = \"taskbar-system-tray-icons\",\n Name = \"Show Hidden System Tray Icons (W10 Only)\",\n Description = \"Controls whether system tray icons are shown in the taskbar or hidden in the chevron menu\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"System Tray\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\",\n Name = \"EnableAutoTray\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls whether system tray icons are shown in the taskbar or hidden in the chevron menu\",\n IsPrimary = true,\n AbsenceMeansEnabled = false\n }\n }\n },\n new CustomizationSetting\n {\n Id = \"taskbar-task-view\",\n Name = \"Task View Button\",\n Description = \"Controls Task View button visibility in taskbar\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Icons\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowTaskViewButton\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Task View button is shown\n DisabledValue = 0, // When toggle is OFF, Task View button is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Task View button visibility in taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n }\n }\n };\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/InstallationStatusService.cs", "using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.SoftwareApps.Exceptions;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n public class InstallationStatusService : IInstallationStatusService\n {\n private readonly IPackageManager _packageManager;\n private readonly ConcurrentDictionary _statusCache = new();\n private readonly ILogService _logService;\n\n public InstallationStatusService(IPackageManager packageManager, ILogService logService)\n {\n _packageManager = packageManager;\n _logService = logService;\n }\n\n public Task SetInstallStatusAsync(string appId, InstallStatus status)\n {\n try\n {\n _logService.LogInformation($\"Setting install status for {appId} to {status}\");\n bool isInstalled = status == InstallStatus.Success;\n _statusCache.AddOrUpdate(appId, isInstalled, (k, v) => isInstalled);\n _logService.LogInformation($\"Successfully set status for {appId}\");\n return Task.FromResult(true);\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to set install status for {appId}\", ex);\n return Task.FromResult(false);\n }\n }\n\n public async Task GetInstallStatusAsync(string appId)\n {\n try\n {\n if (_statusCache.TryGetValue(appId, out var cachedStatus))\n {\n _logService.LogInformation($\"Retrieved cached status for {appId}\");\n return cachedStatus ? InstallStatus.Success : InstallStatus.Failed;\n }\n\n _logService.LogInformation($\"Querying package manager for {appId}\");\n var isInstalled = await _packageManager.IsAppInstalledAsync(appId);\n _statusCache.TryAdd(appId, isInstalled);\n \n _logService.LogInformation($\"Install status for {appId}: {isInstalled}\");\n return isInstalled ? InstallStatus.Success : InstallStatus.Failed;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to get install status for {appId}\", ex);\n return InstallStatus.Failed;\n }\n }\n\n public async Task RefreshStatusAsync(IEnumerable appIds)\n {\n var result = new RefreshResult();\n var errors = new Dictionary();\n\n try\n {\n _logService.LogInformation(\"Refreshing installation status for batch of apps\");\n \n foreach (var appId in appIds.Distinct())\n {\n try\n {\n var isInstalled = await _packageManager.IsAppInstalledAsync(appId);\n _statusCache.AddOrUpdate(appId, isInstalled, (k, v) => isInstalled);\n result.SuccessCount++;\n }\n catch (Exception ex)\n {\n errors[appId] = ex.Message;\n result.FailedCount++;\n _logService.LogError($\"Failed to refresh status for {appId}\", ex);\n }\n }\n \n result.Errors = errors;\n _logService.LogSuccess(\"Successfully refreshed installation status\");\n return result;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to refresh installation status\", ex);\n throw new InstallationStatusException(\"Failed to refresh installation status\", ex);\n }\n }\n\n public async Task RefreshInstallationStatusAsync(\n IEnumerable items,\n CancellationToken cancellationToken = default)\n {\n try\n {\n _logService.LogInformation(\"Refreshing installation status for batch of items\");\n \n var packageIds = items.Select(i => i.PackageId).Distinct();\n var statuses = await GetBatchInstallStatusAsync(packageIds, cancellationToken);\n \n foreach (var item in items)\n {\n cancellationToken.ThrowIfCancellationRequested();\n \n if (statuses.TryGetValue(item.PackageId, out var isInstalled))\n {\n _statusCache.TryAdd(item.PackageId, isInstalled);\n }\n }\n \n _logService.LogSuccess(\"Successfully refreshed installation status\");\n }\n catch (OperationCanceledException)\n {\n _logService.LogWarning(\"Installation status refresh was cancelled\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to refresh installation status\", ex);\n throw new InstallationStatusException(\"Failed to refresh installation status\", ex);\n }\n }\n\n public async Task GetItemInstallStatusAsync(\n IInstallableItem item,\n CancellationToken cancellationToken = default)\n {\n try\n {\n if (_statusCache.TryGetValue(item.PackageId, out var cachedStatus))\n {\n _logService.LogInformation($\"Retrieved cached status for {item.PackageId}\");\n return cachedStatus;\n }\n\n _logService.LogInformation($\"Querying package manager for {item.PackageId}\");\n var isInstalled = await _packageManager.IsAppInstalledAsync(item.PackageId, cancellationToken);\n _statusCache.TryAdd(item.PackageId, isInstalled);\n \n _logService.LogInformation($\"Install status for {item.PackageId}: {isInstalled}\");\n return isInstalled;\n }\n catch (OperationCanceledException)\n {\n _logService.LogWarning($\"Install status check for {item.PackageId} was cancelled\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to get install status for {item.PackageId}\", ex);\n throw new InstallationStatusException($\"Failed to get install status for {item.PackageId}\", ex);\n }\n }\n\n public async Task> GetBatchInstallStatusAsync(\n IEnumerable packageIds,\n CancellationToken cancellationToken = default)\n {\n try\n {\n var distinctIds = packageIds.Distinct().ToList();\n var results = new Dictionary();\n _logService.LogInformation($\"Getting batch install status for {distinctIds.Count} packages\");\n\n foreach (var id in distinctIds)\n {\n cancellationToken.ThrowIfCancellationRequested();\n \n if (_statusCache.TryGetValue(id, out var cachedStatus))\n {\n results[id] = cachedStatus;\n _logService.LogInformation($\"Using cached status for {id}\");\n }\n else\n {\n var isInstalled = await _packageManager.IsAppInstalledAsync(id, cancellationToken);\n _statusCache.TryAdd(id, isInstalled);\n results[id] = isInstalled;\n _logService.LogInformation($\"Retrieved fresh status for {id}: {isInstalled}\");\n }\n }\n\n _logService.LogSuccess(\"Completed batch install status check\");\n return results;\n }\n catch (OperationCanceledException)\n {\n _logService.LogWarning(\"Batch install status check was cancelled\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to get batch install status\", ex);\n throw new InstallationStatusException(\"Failed to get batch install status\", ex);\n }\n }\n\n public void ClearStatusCache()\n {\n try\n {\n _logService.LogInformation(\"Clearing installation status cache\");\n _statusCache.Clear();\n _logService.LogSuccess(\"Successfully cleared installation status cache\");\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to clear installation status cache\", ex);\n throw new InstallationStatusException(\"Failed to clear installation status cache\", ex);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/Methods/RegistryVerificationMethod.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Verification;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods\n{\n /// \n /// Verifies if a package is installed by checking the Windows Registry.\n /// This checks both 64-bit and 32-bit registry views.\n /// \n public class RegistryVerificationMethod : VerificationMethodBase\n {\n private const string UninstallKeyPath =\n @\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\";\n private const string UninstallKeyPathWow6432Node =\n @\"SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n public RegistryVerificationMethod()\n : base(\"Registry\", priority: 10) { }\n\n /// \n protected override async Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken = default\n )\n {\n return await Task.Run(\n () =>\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n // Check 64-bit registry view\n using (\n var baseKey = RegistryKey.OpenBaseKey(\n RegistryHive.LocalMachine,\n RegistryView.Registry64\n )\n )\n using (var uninstallKey = baseKey.OpenSubKey(UninstallKeyPath, writable: false))\n {\n var result = CheckRegistryKey(uninstallKey, packageId, null);\n if (result.IsVerified)\n {\n return result;\n }\n }\n\n // Check 32-bit registry view\n using (\n var baseKey = RegistryKey.OpenBaseKey(\n RegistryHive.LocalMachine,\n RegistryView.Registry32\n )\n )\n using (\n var uninstallKey = baseKey.OpenSubKey(\n UninstallKeyPathWow6432Node,\n writable: false\n )\n )\n {\n return CheckRegistryKey(uninstallKey, packageId, null);\n }\n },\n cancellationToken\n );\n }\n\n /// \n /// Checks a registry key for the presence of a package.\n /// \n /// The registry key to check.\n /// The package ID to look for.\n /// The version to check for, or null to check for any version.\n /// A indicating whether the package was found.\n private static VerificationResult CheckRegistryKey(\n RegistryKey uninstallKey,\n string packageId,\n string version\n )\n {\n if (uninstallKey == null)\n {\n return VerificationResult.Failure(\"Registry key not found\");\n }\n\n foreach (var subKeyName in uninstallKey.GetSubKeyNames())\n {\n using (var subKey = uninstallKey.OpenSubKey(subKeyName))\n {\n var displayName = subKey?.GetValue(\"DisplayName\") as string;\n if (string.IsNullOrEmpty(displayName))\n {\n continue;\n }\n\n // Check if the display name matches the package ID (case insensitive)\n if (displayName.IndexOf(packageId, StringComparison.OrdinalIgnoreCase) >= 0)\n {\n // If a version is specified, check if it matches\n if (version != null)\n {\n var displayVersion = subKey.GetValue(\"DisplayVersion\") as string;\n if (\n !string.Equals(\n displayVersion,\n version,\n StringComparison.OrdinalIgnoreCase\n )\n )\n {\n continue;\n }\n }\n\n var installLocation = subKey.GetValue(\"InstallLocation\") as string;\n var uninstallString = subKey.GetValue(\"UninstallString\") as string;\n var foundVersion = subKey.GetValue(\"DisplayVersion\") as string;\n\n return VerificationResult.Success(foundVersion);\n }\n }\n }\n\n return VerificationResult.Failure($\"Package '{packageId}' not found in registry\");\n }\n\n /// \n protected override async Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(version))\n {\n throw new ArgumentException(\n \"Version cannot be null or whitespace.\",\n nameof(version)\n );\n }\n\n return await VerifyPresenceAsync(packageId, cancellationToken).ConfigureAwait(false);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceValueOperations.cs", "using Microsoft.Win32;\nusing System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Registry service implementation for value operations.\n /// \n public partial class RegistryService\n {\n /// \n /// Sets a value in the registry.\n /// \n /// The registry key path.\n /// The name of the value to set.\n /// The value to set.\n /// The type of the value.\n /// True if the operation succeeded; otherwise, false.\n public bool SetValue(string keyPath, string valueName, object value, RegistryValueKind valueKind)\n {\n try\n {\n if (!CheckWindowsPlatform())\n return false;\n\n _logService.Log(LogLevel.Info, $\"Setting registry value: {keyPath}\\\\{valueName}\");\n\n // First ensure the key exists with full access rights\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return false;\n }\n\n string subKeyPath = string.Join('\\\\', pathParts.Skip(1));\n\n // Create the key with direct Registry API and security settings\n // This will also attempt to take ownership if needed\n RegistryKey? targetKey = EnsureKeyWithFullAccess(rootKey, subKeyPath);\n\n if (targetKey == null)\n {\n _logService.Log(LogLevel.Warning, $\"Could not open or create registry key: {keyPath}\");\n \n // Try using PowerShell as a fallback for policy keys\n if (keyPath.Contains(\"Policies\", StringComparison.OrdinalIgnoreCase))\n {\n _logService.Log(LogLevel.Info, $\"Attempting to set policy registry value using PowerShell: {keyPath}\\\\{valueName}\");\n return SetValueUsingPowerShell(keyPath, valueName, value, valueKind);\n }\n \n return false;\n }\n\n using (targetKey)\n {\n try\n {\n targetKey.SetValue(valueName, value, valueKind);\n\n // Clear the cache for this value\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueCache)\n {\n if (_valueCache.ContainsKey(fullValuePath))\n {\n _valueCache.Remove(fullValuePath);\n }\n }\n\n _logService.Log(LogLevel.Success, $\"Successfully set registry value: {keyPath}\\\\{valueName}\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Failed to set registry value even after taking ownership: {ex.Message}\");\n\n // Try using PowerShell as a fallback\n return SetValueUsingPowerShell(keyPath, valueName, value, valueKind);\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting registry value {keyPath}\\\\{valueName}: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Gets a value from the registry.\n /// \n /// The registry key path.\n /// The name of the value to get.\n /// The value from the registry, or null if it doesn't exist.\n public object? GetValue(string keyPath, string valueName)\n {\n try\n {\n if (!CheckWindowsPlatform())\n return null;\n\n // Check the cache first\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueCache)\n {\n if (_valueCache.TryGetValue(fullValuePath, out object? cachedValue))\n {\n return cachedValue;\n }\n }\n\n // Open the key for reading\n using (RegistryKey? key = OpenRegistryKey(keyPath, false))\n {\n if (key == null)\n {\n _logService.Log(LogLevel.Debug, $\"Registry key does not exist: {keyPath}\");\n \n // Cache the null result\n lock (_valueCache)\n {\n _valueCache[fullValuePath] = null;\n }\n \n return null;\n }\n\n // Get the value\n object? value = key.GetValue(valueName);\n \n // Cache the result\n lock (_valueCache)\n {\n _valueCache[fullValuePath] = value;\n }\n \n return value;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting registry value {keyPath}\\\\{valueName}: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Deletes a value from the registry.\n /// \n /// The registry key path.\n /// The name of the value to delete.\n /// True if the operation succeeded; otherwise, false.\n public bool DeleteValue(string keyPath, string valueName)\n {\n try\n {\n if (!CheckWindowsPlatform())\n return false;\n\n _logService.Log(LogLevel.Info, $\"Deleting registry value: {keyPath}\\\\{valueName}\");\n\n // Open the key for writing\n using (RegistryKey? key = OpenRegistryKey(keyPath, true))\n {\n if (key == null)\n {\n _logService.Log(LogLevel.Warning, $\"Registry key does not exist: {keyPath}\");\n return false;\n }\n\n // Delete the value\n key.DeleteValue(valueName, false);\n \n // Clear the cache for this value\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueCache)\n {\n if (_valueCache.ContainsKey(fullValuePath))\n {\n _valueCache.Remove(fullValuePath);\n }\n }\n \n // Also clear the value exists cache\n lock (_valueExistsCache)\n {\n if (_valueExistsCache.ContainsKey(fullValuePath))\n {\n _valueExistsCache.Remove(fullValuePath);\n }\n }\n\n _logService.Log(LogLevel.Success, $\"Successfully deleted registry value: {keyPath}\\\\{valueName}\");\n return true;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error deleting registry value {keyPath}\\\\{valueName}: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Deletes a value from the registry using hive and subkey.\n /// \n /// The registry hive.\n /// The registry subkey.\n /// The name of the value to delete.\n /// True if the operation succeeded; otherwise, false.\n public async Task DeleteValue(RegistryHive hive, string subKey, string valueName)\n {\n string keyPath = $\"{RegistryExtensions.GetRegistryHiveString(hive)}\\\\{subKey}\";\n return DeleteValue(keyPath, valueName);\n }\n\n /// \n /// Checks if a registry value exists.\n /// \n /// The registry key path.\n /// The name of the value to check.\n /// True if the value exists; otherwise, false.\n public bool ValueExists(string keyPath, string valueName)\n {\n try\n {\n if (!CheckWindowsPlatform())\n return false;\n\n // Check the cache first\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueExistsCache)\n {\n if (_valueExistsCache.TryGetValue(fullValuePath, out bool exists))\n {\n return exists;\n }\n }\n\n // Open the key for reading\n using (RegistryKey? key = OpenRegistryKey(keyPath, false))\n {\n if (key == null)\n {\n // Cache the result\n lock (_valueExistsCache)\n {\n _valueExistsCache[fullValuePath] = false;\n }\n \n return false;\n }\n\n // Check if the value exists\n string[] valueNames = key.GetValueNames();\n bool exists = valueNames.Contains(valueName, StringComparer.OrdinalIgnoreCase);\n \n // Cache the result\n lock (_valueExistsCache)\n {\n _valueExistsCache[fullValuePath] = exists;\n }\n \n return exists;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking if registry value exists {keyPath}\\\\{valueName}: {ex.Message}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Views/ExternalAppsView.xaml.cs", "using System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Views\n{\n public partial class ExternalAppsView : UserControl\n {\n public ExternalAppsView()\n {\n InitializeComponent();\n Loaded += ExternalAppsView_Loaded;\n }\n\n private void ExternalAppsView_Loaded(object sender, RoutedEventArgs e)\n {\n // Find all category header borders and attach click handlers\n foreach (var border in FindVisualChildren(this))\n {\n if (border?.Tag != null && border.Tag is string)\n {\n // Add click handler to toggle category expansion\n border.MouseLeftButtonDown += CategoryHeader_MouseLeftButtonDown;\n }\n }\n }\n\n private void CategoryHeader_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n try\n {\n if (sender is Border border && border.DataContext is ExternalAppsCategoryViewModel category)\n {\n // Toggle the IsExpanded property\n category.IsExpanded = !category.IsExpanded;\n e.Handled = true;\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Error handling category click: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n }\n }\n\n // Helper method to find visual children of a specific type\n private System.Collections.Generic.IEnumerable FindVisualChildren(DependencyObject parent) where T : DependencyObject\n {\n int childrenCount = VisualTreeHelper.GetChildrenCount(parent);\n for (int i = 0; i < childrenCount; i++)\n {\n DependencyObject child = VisualTreeHelper.GetChild(parent, i);\n \n if (child is T childOfType)\n yield return childOfType;\n \n foreach (T childOfChild in FindVisualChildren(child))\n yield return childOfChild;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppVerificationService.cs", "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that handles verification of application installations.\n/// \npublic class AppVerificationService : IAppVerificationService\n{\n private readonly ILogService _logService;\n private readonly ISystemServices _systemServices;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The system services.\n public AppVerificationService(\n ILogService logService,\n ISystemServices systemServices)\n {\n _logService = logService;\n _systemServices = systemServices;\n }\n\n /// \n public async Task VerifyAppInstallationAsync(string packageName)\n {\n try\n {\n // Create PowerShell instance\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n\n // For Microsoft Store apps (package IDs that are alphanumeric with no dots)\n if (packageName.All(char.IsLetterOrDigit) && !packageName.Contains('.'))\n {\n // Use Get-AppxPackage to check if the Microsoft Store app is installed\n // Ensure we're using Windows PowerShell for Appx commands\n using var appxPowerShell = PowerShellFactory.CreateForAppxCommands(_logService, _systemServices);\n appxPowerShell.AddScript(\n $\"Get-AppxPackage | Where-Object {{ $_.PackageFullName -like '*{packageName}*' }}\"\n );\n var result = await appxPowerShell.InvokeAsync();\n\n if (result.Count > 0)\n {\n return true;\n }\n }\n\n // For all other apps, use winget list to check if installed\n powerShell.Commands.Clear();\n powerShell.AddScript(\n $@\"\n try {{\n # Ensure we're using Windows PowerShell for Winget operations\n $result = winget list --id '{packageName}' --exact\n $isInstalled = $result -match '{packageName}'\n Write-Output $isInstalled\n }} catch {{\n Write-Output $false\n }}\n \"\n );\n\n var results = await powerShell.InvokeAsync();\n\n // Check if the result indicates the app is installed\n if (results.Count > 0)\n {\n // Extract boolean value from result\n var resultValue = results[0]?.ToString()?.ToLowerInvariant();\n if (resultValue == \"true\")\n {\n return true;\n }\n }\n\n // If we're here, try one more verification with a different approach\n powerShell.Commands.Clear();\n powerShell.AddScript(\n $@\"\n try {{\n # Use where.exe to check if the app is in PATH (for CLI tools)\n $whereResult = where.exe {packageName} 2>&1\n if ($whereResult -notmatch 'not found') {{\n Write-Output 'true'\n return\n }}\n\n # Check common installation directories\n $commonPaths = @(\n [System.Environment]::GetFolderPath('ProgramFiles'),\n [System.Environment]::GetFolderPath('ProgramFilesX86'),\n [System.Environment]::GetFolderPath('LocalApplicationData')\n )\n\n foreach ($basePath in $commonPaths) {{\n if (Test-Path -Path \"\"$basePath\\$packageName\"\" -PathType Container) {{\n Write-Output 'true'\n return\n }}\n }}\n\n Write-Output 'false'\n }} catch {{\n Write-Output 'false'\n }}\n \"\n );\n\n results = await powerShell.InvokeAsync();\n\n // Check if the result indicates the app is installed\n if (results.Count > 0)\n {\n var resultValue = results[0]?.ToString()?.ToLowerInvariant();\n return resultValue == \"true\";\n }\n\n return false;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error verifying app installation: {ex.Message}\", ex);\n // If any error occurs during verification, assume the app is not installed\n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScriptContentModifier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\n/// \n/// Implementation of IScriptContentModifier that provides methods for modifying script content.\n/// \npublic class ScriptContentModifier : IScriptContentModifier\n{\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public ScriptContentModifier(ILogService logService)\n {\n _logService = logService;\n }\n\n /// \n public string RemoveCapabilityFromScript(string scriptContent, string capabilityName)\n {\n // Find the capabilities array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$capabilities = @(\");\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $capabilities array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the capabilities array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find end of $capabilities array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the capabilities in the array\n var capabilities = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var capability = trimmedLine.Trim('\\'', '\"', ' ', ',');\n capabilities.Add(capability);\n }\n }\n\n // Check if the capability is in the array\n bool removed =\n capabilities.RemoveAll(c =>\n c.Equals(capabilityName, StringComparison.OrdinalIgnoreCase)\n ) > 0;\n\n if (!removed)\n {\n // Capability not found in the array\n return scriptContent;\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$capabilities = @(\");\n\n // Add capabilities without trailing comma on the last item\n for (int i = 0; i < capabilities.Count; i++)\n {\n string capability = capabilities[i];\n if (i < capabilities.Count - 1)\n {\n newArrayContent.AppendLine($\" '{capability}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{capability}'\");\n }\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n\n /// \n public string RemovePackageFromScript(string scriptContent, string packageName)\n {\n // Find the packages array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$packages = @(\");\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the packages array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find end of $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the packages in the array\n var packages = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var package = trimmedLine.Trim('\\'', '\"', ' ', ',');\n packages.Add(package);\n }\n }\n\n // Check if the package is in the array\n bool removed =\n packages.RemoveAll(p => p.Equals(packageName, StringComparison.OrdinalIgnoreCase)) > 0;\n\n if (!removed)\n {\n // Package not found in the array\n return scriptContent;\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$packages = @(\");\n\n // Add packages without trailing comma on the last item\n for (int i = 0; i < packages.Count; i++)\n {\n string package = packages[i];\n if (i < packages.Count - 1)\n {\n newArrayContent.AppendLine($\" '{package}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{package}'\");\n }\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n\n /// \n public string RemoveOptionalFeatureFromScript(string scriptContent, string featureName)\n {\n // Check if the optional features section exists\n int sectionStartIndex = scriptContent.IndexOf(\"# Disable Optional Features\");\n if (sectionStartIndex == -1)\n {\n // Optional features section doesn't exist, so nothing to remove\n return scriptContent;\n }\n\n // Find the optional features array\n int arrayStartIndex = scriptContent.IndexOf(\"$optionalFeatures = @(\", sectionStartIndex);\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $optionalFeatures array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the optional features array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\n \"Could not find end of $optionalFeatures array in BloatRemoval.ps1\"\n );\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the optional features in the array\n var optionalFeatures = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var feature = trimmedLine.Trim('\\'', '\"', ' ', ',');\n optionalFeatures.Add(feature);\n }\n }\n\n // Check if the feature is in the array\n bool removed =\n optionalFeatures.RemoveAll(f =>\n f.Equals(featureName, StringComparison.OrdinalIgnoreCase)\n ) > 0;\n\n if (!removed)\n {\n // Feature not found in the array\n return scriptContent;\n }\n\n // If the array is now empty, remove the entire optional features section\n if (optionalFeatures.Count == 0)\n {\n // Find the end of the optional features section\n int sectionEndIndex = scriptContent.IndexOf(\n \"foreach ($feature in $optionalFeatures) {\",\n arrayEndIndex\n );\n if (sectionEndIndex != -1)\n {\n sectionEndIndex = scriptContent.IndexOf(\"}\", sectionEndIndex);\n if (sectionEndIndex != -1)\n {\n sectionEndIndex = scriptContent.IndexOf('\\n', sectionEndIndex);\n if (sectionEndIndex != -1)\n {\n // Remove the entire section\n return scriptContent.Substring(0, sectionStartIndex)\n + scriptContent.Substring(sectionEndIndex + 1);\n }\n }\n }\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$optionalFeatures = @(\");\n\n // Add features without trailing comma on the last item\n for (int i = 0; i < optionalFeatures.Count; i++)\n {\n string feature = optionalFeatures[i];\n if (i < optionalFeatures.Count - 1)\n {\n newArrayContent.AppendLine($\" '{feature}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{feature}'\");\n }\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n\n /// \n public string RemoveAppRegistrySettingsFromScript(string scriptContent, string appName)\n {\n // Find the registry settings section\n int registrySection = scriptContent.IndexOf(\"# Registry settings\");\n if (registrySection == -1)\n {\n return scriptContent;\n }\n\n // Generate possible section headers for this app\n var possibleSectionHeaders = new List\n {\n $\"# Registry settings for {appName}\",\n $\"# Registry settings for Microsoft.{appName}\",\n };\n\n // Add variations without \"Microsoft.\" prefix if it already has it\n if (appName.StartsWith(\"Microsoft.\", StringComparison.OrdinalIgnoreCase))\n {\n string nameWithoutPrefix = appName.Substring(\"Microsoft.\".Length);\n possibleSectionHeaders.Add($\"# Registry settings for {nameWithoutPrefix}\");\n }\n\n // Add common variations\n possibleSectionHeaders.Add($\"# Registry settings for {appName}_8wekyb3d8bbwe\");\n\n // For Copilot specifically, add known variations\n if (appName.Contains(\"Copilot\", StringComparison.OrdinalIgnoreCase))\n {\n possibleSectionHeaders.Add(\"# Registry settings for Copilot\");\n possibleSectionHeaders.Add(\"# Registry settings for Microsoft.Copilot\");\n possibleSectionHeaders.Add(\"# Registry settings for Windows.Copilot\");\n }\n\n // For Xbox/GamingApp specifically, add known variations\n if (\n appName.Contains(\"Xbox\", StringComparison.OrdinalIgnoreCase)\n || appName.Equals(\"Microsoft.GamingApp\", StringComparison.OrdinalIgnoreCase)\n )\n {\n possibleSectionHeaders.Add(\"# Registry settings for Xbox\");\n possibleSectionHeaders.Add(\"# Registry settings for Microsoft.Xbox\");\n possibleSectionHeaders.Add(\"# Registry settings for GamingApp\");\n }\n\n // Find the earliest matching section header\n int appSection = -1;\n string matchedHeader = null;\n\n foreach (var header in possibleSectionHeaders)\n {\n int index = scriptContent.IndexOf(header, registrySection);\n if (index != -1 && (appSection == -1 || index < appSection))\n {\n appSection = index;\n matchedHeader = header;\n }\n }\n\n if (appSection == -1)\n {\n _logService.LogInformation($\"No registry settings found for {appName} in the script\");\n return scriptContent;\n }\n\n _logService.LogInformation(\n $\"Found registry settings for {appName} with header: {matchedHeader}\"\n );\n\n // Find the end of the app section (next section or end of file)\n int nextSection = scriptContent.IndexOf(\n \"# Registry settings for\",\n appSection + matchedHeader.Length\n );\n if (nextSection == -1)\n {\n // Look for the next major section\n nextSection = scriptContent.IndexOf(\"# Prevent apps from reinstalling\", appSection);\n if (nextSection == -1)\n {\n // If no next section, just return the original content\n _logService.LogWarning(\n $\"Could not find end of registry settings section for {appName}\"\n );\n return scriptContent;\n }\n }\n\n // Remove the app registry settings section\n _logService.LogInformation($\"Removing registry settings for {appName} from script\");\n return scriptContent.Substring(0, appSection) + scriptContent.Substring(nextSection);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/CustomDialog.xaml.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n public partial class CustomDialog : Window\n {\n\n public CustomDialog()\n {\n InitializeComponent();\n DataContext = this;\n }\n\n private void PrimaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = true;\n Close();\n }\n\n private void SecondaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = false;\n Close();\n }\n\n private void TertiaryButton_Click(object sender, RoutedEventArgs e)\n {\n // Explicitly set DialogResult to null for Cancel\n DialogResult = null;\n\n Close();\n }\n\n public static CustomDialog CreateConfirmationDialog(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = new CustomDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"QuestionIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.MessageContent.Text = message;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"Yes\";\n dialog.SecondaryButton.Content = \"No\";\n\n return dialog;\n }\n\n public static CustomDialog CreateConfirmationDialog(\n string title,\n string headerText,\n IEnumerable items,\n string footerText\n )\n {\n string message = items != null ? string.Join(Environment.NewLine, items) : string.Empty;\n return CreateConfirmationDialog(title, headerText, message, footerText);\n }\n\n public static CustomDialog CreateInformationDialog(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = new CustomDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"InfoIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.MessageContent.Text = message;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"OK\";\n dialog.SecondaryButton.Visibility = Visibility.Collapsed;\n\n return dialog;\n }\n\n public static CustomDialog CreateInformationDialog(\n string title,\n string headerText,\n IEnumerable items,\n string footerText,\n bool useMultiColumnLayout = false\n )\n {\n string message = items != null ? string.Join(Environment.NewLine, items) : string.Empty;\n return CreateInformationDialog(title, headerText, message, footerText);\n }\n\n public static bool? ShowConfirmation(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = CreateConfirmationDialog(title, headerText, message, footerText);\n return dialog.ShowDialog();\n }\n\n public static bool? ShowConfirmation(\n string title,\n string headerText,\n IEnumerable items,\n string footerText\n )\n {\n var dialog = CreateConfirmationDialog(title, headerText, items, footerText);\n return dialog.ShowDialog();\n }\n\n public static void ShowInformation(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = CreateInformationDialog(title, headerText, message, footerText);\n dialog.ShowDialog();\n }\n\n public static void ShowInformation(\n string title,\n string headerText,\n IEnumerable items,\n string footerText\n )\n {\n var dialog = CreateInformationDialog(title, headerText, items, footerText);\n dialog.ShowDialog();\n }\n\n public static CustomDialog CreateYesNoCancelDialog(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = new CustomDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"QuestionIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.MessageContent.Text = message;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"Yes\";\n dialog.SecondaryButton.Content = \"No\";\n dialog.TertiaryButton.Content = \"Cancel\";\n\n // Ensure the Cancel button is visible and properly styled\n dialog.TertiaryButton.Visibility = Visibility.Visible;\n dialog.TertiaryButton.IsCancel = true;\n\n return dialog;\n }\n\n public static CustomDialog CreateYesNoCancelDialog(\n string title,\n string headerText,\n IEnumerable items,\n string footerText\n )\n {\n string message = items != null ? string.Join(Environment.NewLine, items) : string.Empty;\n return CreateYesNoCancelDialog(title, headerText, message, footerText);\n }\n\n public static bool? ShowYesNoCancel(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = CreateYesNoCancelDialog(title, headerText, message, footerText);\n\n // Add event handler for the Closing event to ensure DialogResult is set correctly\n dialog.Closing += (sender, e) =>\n {\n // If DialogResult is not explicitly set (e.g., if the dialog is closed by clicking outside or pressing Escape),\n // set it to null to indicate Cancel\n if (dialog.DialogResult == null) { }\n };\n\n // Add event handler for the KeyDown event to handle Escape key\n dialog.KeyDown += (sender, e) =>\n {\n if (e.Key == System.Windows.Input.Key.Escape)\n {\n dialog.DialogResult = null;\n dialog.Close();\n }\n };\n\n // Show the dialog and get the result\n var result = dialog.ShowDialog();\n\n return result;\n }\n\n public static bool? ShowYesNoCancel(\n string title,\n string headerText,\n IEnumerable items,\n string footerText\n )\n {\n var dialog = CreateYesNoCancelDialog(title, headerText, items, footerText);\n\n // Add event handler for the Closing event to ensure DialogResult is set correctly\n dialog.Closing += (sender, e) =>\n {\n // If DialogResult is not explicitly set (e.g., if the dialog is closed by clicking outside or pressing Escape),\n // set it to null to indicate Cancel\n if (dialog.DialogResult == null) { }\n };\n\n // Add event handler for the KeyDown event to handle Escape key\n dialog.KeyDown += (sender, e) =>\n {\n if (e.Key == System.Windows.Input.Key.Escape)\n {\n dialog.DialogResult = null;\n dialog.Close();\n }\n };\n\n // Show the dialog and get the result\n var result = dialog.ShowDialog();\n\n return result;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/CustomAppInstallationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Enums;\nusing Winhance.Core.Features.SoftwareApps.Exceptions;\nusing Winhance.Core.Features.SoftwareApps.Helpers;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that handles custom application installations.\n/// \npublic class CustomAppInstallationService : ICustomAppInstallationService\n{\n private readonly ILogService _logService;\n private readonly IOneDriveInstallationService _oneDriveInstallationService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The OneDrive installation service.\n public CustomAppInstallationService(\n ILogService logService,\n IOneDriveInstallationService oneDriveInstallationService)\n {\n _logService = logService;\n _oneDriveInstallationService = oneDriveInstallationService;\n }\n\n /// \n public async Task InstallCustomAppAsync(\n AppInfo appInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n try\n {\n // Handle different custom app installations based on package name\n switch (appInfo.PackageName.ToLowerInvariant())\n {\n case \"onedrive\":\n return await _oneDriveInstallationService.InstallOneDriveAsync(progress, cancellationToken);\n\n // Add other custom app installation cases here\n // case \"some-app\":\n // return await InstallSomeAppAsync(progress, cancellationToken);\n\n default:\n throw new NotSupportedException(\n $\"Custom installation for '{appInfo.PackageName}' is not supported.\"\n );\n }\n }\n catch (Exception ex)\n {\n var errorType = InstallationErrorHelper.DetermineErrorType(ex.Message);\n var errorMessage = InstallationErrorHelper.GetUserFriendlyErrorMessage(errorType);\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Error in custom installation for {appInfo.Name}: {errorMessage}\",\n DetailedMessage = $\"Exception during custom installation: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"ErrorType\", errorType.ToString() },\n { \"PackageName\", appInfo.PackageName },\n { \"AppName\", appInfo.Name },\n { \"IsCustomInstall\", \"True\" },\n { \"OriginalError\", ex.Message }\n }\n }\n );\n\n return false;\n }\n }\n\n /// \n public async Task CheckInternetConnectionAsync()\n {\n try\n {\n // Try to reach a reliable site to check for internet connectivity\n using var client = new HttpClient();\n client.Timeout = TimeSpan.FromSeconds(5);\n var response = await client.GetAsync(\"https://www.google.com\");\n return response.IsSuccessStatusCode;\n }\n catch\n {\n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceKeyOperations.cs", "using Microsoft.Win32;\nusing System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Registry service implementation for key operations.\n /// \n public partial class RegistryService\n {\n /// \n /// Opens a registry key with the specified access rights.\n /// \n /// The full path to the registry key.\n /// Whether to open the key with write access.\n /// The opened registry key, or null if it could not be opened.\n private RegistryKey? OpenRegistryKey(string keyPath, bool writable)\n {\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return null;\n }\n\n string subPath = string.Join('\\\\', pathParts.Skip(1));\n\n if (writable)\n {\n // If we need write access, try to ensure the key exists with proper access rights\n return EnsureKeyWithFullAccess(rootKey, subPath);\n }\n else\n {\n // For read-only access, just try to open the key normally\n return rootKey.OpenSubKey(subPath, false);\n }\n }\n\n /// \n /// Creates a registry key if it doesn't exist.\n /// \n /// The full path to the registry key.\n /// True if the key exists or was created successfully; otherwise, false.\n public bool CreateKeyIfNotExists(string keyPath)\n {\n if (!CheckWindowsPlatform())\n return false;\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Creating registry key if it doesn't exist: {keyPath}\");\n\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return false;\n }\n\n string subKeyPath = string.Join('\\\\', pathParts.Skip(1));\n\n // Create the key with direct Registry API and security settings\n RegistryKey? targetKey = EnsureKeyWithFullAccess(rootKey, subKeyPath);\n\n if (targetKey == null)\n {\n _logService.Log(LogLevel.Warning, $\"Could not create registry key: {keyPath}\");\n return false;\n }\n\n targetKey.Close();\n \n // Update the cache to indicate that this key now exists\n lock (_keyExistsCache)\n {\n _keyExistsCache[keyPath] = true;\n }\n \n _logService.Log(LogLevel.Success, $\"Successfully created or verified registry key: {keyPath}\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating registry key {keyPath}: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Deletes a registry key.\n /// \n /// The full path to the registry key.\n /// True if the key was deleted successfully; otherwise, false.\n public bool DeleteKey(string keyPath)\n {\n if (!CheckWindowsPlatform())\n return false;\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Deleting registry key: {keyPath}\");\n\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return false;\n }\n\n string subKeyPath = string.Join('\\\\', pathParts.Skip(1));\n string parentPath = string.Join('\\\\', subKeyPath.Split('\\\\').Take(subKeyPath.Split('\\\\').Length - 1));\n string keyName = subKeyPath.Split('\\\\').Last();\n\n // Open the parent key with write access\n using (RegistryKey? parentKey = rootKey.OpenSubKey(parentPath, true))\n {\n if (parentKey == null)\n {\n _logService.Log(LogLevel.Warning, $\"Parent key does not exist: {pathParts[0]}\\\\{parentPath}\");\n return false;\n }\n\n // Delete the key\n parentKey.DeleteSubKey(keyName, false);\n \n // Clear the cache for this key\n lock (_keyExistsCache)\n {\n var keysToRemove = _keyExistsCache.Keys\n .Where(k => k.StartsWith(keyPath, StringComparison.OrdinalIgnoreCase))\n .ToList();\n \n foreach (var key in keysToRemove)\n {\n _keyExistsCache.Remove(key);\n }\n }\n\n _logService.Log(LogLevel.Success, $\"Successfully deleted registry key: {keyPath}\");\n return true;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error deleting registry key {keyPath}: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Checks if a registry key exists.\n /// \n /// The full path to the registry key.\n /// True if the key exists; otherwise, false.\n public bool KeyExists(string keyPath)\n {\n if (!CheckWindowsPlatform())\n return false;\n\n try\n {\n // Check the cache first\n lock (_keyExistsCache)\n {\n if (_keyExistsCache.TryGetValue(keyPath, out bool exists))\n {\n return exists;\n }\n }\n\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return false;\n }\n\n string subKeyPath = string.Join('\\\\', pathParts.Skip(1));\n\n // Try to open the key\n using (RegistryKey? key = rootKey.OpenSubKey(subKeyPath))\n {\n bool exists = key != null;\n \n // Cache the result\n lock (_keyExistsCache)\n {\n _keyExistsCache[keyPath] = exists;\n }\n \n return exists;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking if registry key exists {keyPath}: {ex.Message}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/ConfigurationUIService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for handling UI-related operations for configuration management.\n /// \n public class ConfigurationUIService\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public ConfigurationUIService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Shows the unified configuration dialog to let the user select which sections to include.\n /// \n /// The unified configuration file.\n /// Whether this is a save dialog (true) or an import dialog (false).\n /// A dictionary of section names and their selection state.\n public async Task> ShowUnifiedConfigurationDialogAsync(UnifiedConfigurationFile config, bool isSaveDialog)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Showing unified configuration dialog (isSaveDialog: {isSaveDialog})\");\n \n // Create a dictionary of sections with their availability and item counts\n var sectionInfo = new Dictionary\n {\n { \"WindowsApps\", (true, config.WindowsApps.Items.Count > 0, config.WindowsApps.Items.Count) },\n { \"ExternalApps\", (true, config.ExternalApps.Items.Count > 0, config.ExternalApps.Items.Count) },\n { \"Customize\", (true, config.Customize.Items.Count > 0, config.Customize.Items.Count) },\n { \"Optimize\", (true, config.Optimize.Items.Count > 0, config.Optimize.Items.Count) }\n };\n \n // Create and show the dialog\n var dialog = new UnifiedConfigurationDialog(\n isSaveDialog ? \"Save Configuration\" : \"Select Configuration Sections\",\n isSaveDialog ? \"Select which sections you want to save to the unified configuration.\" : \"Select which sections you want to import from the unified configuration.\",\n sectionInfo,\n isSaveDialog);\n \n dialog.Owner = Application.Current.MainWindow;\n bool? dialogResult = dialog.ShowDialog();\n \n if (dialogResult != true)\n {\n _logService.Log(LogLevel.Info, \"User canceled unified configuration dialog\");\n return new Dictionary();\n }\n \n // Get the selected sections from the dialog\n var result = dialog.GetResult();\n \n _logService.Log(LogLevel.Info, $\"Selected sections: {string.Join(\", \", result.Where(kvp => kvp.Value).Select(kvp => kvp.Key))}\");\n \n return result;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error showing unified configuration dialog: {ex.Message}\");\n return new Dictionary();\n }\n }\n\n /// \n /// Shows a success message for configuration operations.\n /// \n /// The title of the message.\n /// The message to show.\n /// The sections that were affected.\n /// Additional information to show.\n public void ShowSuccessMessage(string title, string message, List sections, string additionalInfo)\n {\n CustomDialog.ShowInformation(title, message, sections, additionalInfo);\n }\n\n /// \n /// Shows an error message for configuration operations.\n /// \n /// The title of the message.\n /// The message to show.\n public void ShowErrorMessage(string title, string message)\n {\n MessageBox.Show(message, title, MessageBoxButton.OK, MessageBoxImage.Error);\n }\n\n /// \n /// Shows a confirmation dialog for configuration operations.\n /// \n /// The title of the dialog.\n /// The message to show.\n /// True if the user confirmed, false otherwise.\n public bool ShowConfirmationDialog(string title, string message)\n {\n var result = MessageBox.Show(message, title, MessageBoxButton.YesNo, MessageBoxImage.Question);\n return result == MessageBoxResult.Yes;\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceTestMethods.cs", "using Microsoft.Win32;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n public partial class RegistryService\n {\n public async Task TestValue(string keyPath, string valueName, object expectedValue, RegistryValueKind valueKind)\n {\n var result = new RegistryTestResult\n {\n KeyPath = keyPath,\n ValueName = valueName,\n ExpectedValue = expectedValue,\n Category = \"Registry Test\"\n };\n\n try\n {\n if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n result.IsSuccess = false;\n result.Message = \"Registry operations are only supported on Windows\";\n return result;\n }\n\n _logService.LogInformation($\"Testing registry value: {keyPath}\\\\{valueName}\");\n\n // Check if the key exists\n var keyExists = KeyExists(keyPath); // Removed await\n if (!keyExists)\n {\n result.IsSuccess = false;\n result.Message = $\"Registry key not found: {keyPath}\";\n return result;\n }\n\n // Check if the value exists\n var valueExists = ValueExists(keyPath, valueName); // Removed await\n if (!valueExists)\n {\n result.IsSuccess = false;\n result.Message = $\"Registry value not found: {keyPath}\\\\{valueName}\";\n return result;\n }\n\n // Get the actual value\n var actualValue = GetValue(keyPath, valueName); // Removed await\n result.ActualValue = actualValue;\n\n // Check if the value kind matches\n // var actualValueKind = await GetValueKind(keyPath, valueName); // Method doesn't exist\n // if (actualValueKind != valueKind)\n // {\n // result.IsSuccess = false;\n // result.Message = $\"Value kind mismatch. Expected: {valueKind}, Actual: {actualValueKind}\";\n // return result;\n // }\n\n // Compare the values\n if (expectedValue is int expectedInt && actualValue is int actualInt)\n {\n result.IsSuccess = expectedInt == actualInt;\n }\n else if (expectedValue is string expectedString && actualValue is string actualString)\n {\n result.IsSuccess = string.Equals(expectedString, actualString, StringComparison.OrdinalIgnoreCase);\n }\n else if (expectedValue is byte[] expectedBytes && actualValue is byte[] actualBytes)\n {\n result.IsSuccess = expectedBytes.SequenceEqual(actualBytes);\n }\n else\n {\n // For other types, use Equals\n result.IsSuccess = expectedValue?.Equals(actualValue) ?? (actualValue == null);\n }\n\n if (!result.IsSuccess)\n {\n result.Message = $\"Value mismatch. Expected: {expectedValue}, Actual: {actualValue}\";\n }\n else\n {\n result.Message = \"Value matches expected value\";\n }\n\n return result;\n }\n catch (Exception ex)\n {\n result.IsSuccess = false;\n result.Message = $\"Error testing registry value: {ex.Message}\";\n _logService.LogError($\"Error testing registry value {keyPath}\\\\{valueName}\", ex);\n return result;\n }\n }\n\n public async Task> TestMultipleValues(IEnumerable settings)\n {\n var results = new List();\n\n try\n {\n if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n _logService.LogError(\"Registry operations are only supported on Windows\");\n return results;\n }\n\n _logService.LogInformation(\"Testing multiple registry values\");\n\n foreach (var setting in settings)\n {\n var keyPath = $\"{setting.Hive}\\\\{setting.SubKey}\";\n // Use EnabledValue if available, otherwise fall back to RecommendedValue for backward compatibility\n object valueToTest = setting.EnabledValue ?? setting.RecommendedValue;\n var result = await TestValue(keyPath, setting.Name, valueToTest, setting.ValueType);\n result.Category = setting.Category;\n result.Description = setting.Description;\n results.Add(result);\n }\n\n var passCount = results.Count(r => r.IsSuccess);\n _logService.LogInformation($\"Registry test results: {passCount}/{results.Count} passed\");\n\n return results;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error testing multiple registry values: {ex.Message}\", ex);\n return results;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ExternalAppsConfigurationApplier.cs", "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for applying configuration to the ExternalApps section.\n /// \n public class ExternalAppsConfigurationApplier : ISectionConfigurationApplier\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n private readonly IViewModelRefresher _viewModelRefresher;\n private readonly IConfigurationPropertyUpdater _propertyUpdater;\n\n /// \n /// Gets the section name that this applier handles.\n /// \n public string SectionName => \"ExternalApps\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n /// The view model refresher.\n /// The property updater.\n public ExternalAppsConfigurationApplier(\n IServiceProvider serviceProvider,\n ILogService logService,\n IViewModelRefresher viewModelRefresher,\n IConfigurationPropertyUpdater propertyUpdater)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _viewModelRefresher = viewModelRefresher ?? throw new ArgumentNullException(nameof(viewModelRefresher));\n _propertyUpdater = propertyUpdater ?? throw new ArgumentNullException(nameof(propertyUpdater));\n }\n\n /// \n /// Applies the configuration to the ExternalApps section.\n /// \n /// The configuration file to apply.\n /// True if any items were updated, false otherwise.\n public async Task ApplyConfigAsync(ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Applying configuration to ExternalAppsViewModel\");\n \n var viewModel = _serviceProvider.GetService();\n if (viewModel == null)\n {\n _logService.Log(LogLevel.Warning, \"ExternalAppsViewModel not available\");\n return false;\n }\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, \"ExternalAppsViewModel not initialized, initializing now\");\n await viewModel.LoadItemsAsync();\n }\n \n // Apply the configuration directly to the view model's items\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Items, configFile);\n \n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in ExternalAppsViewModel\");\n \n // Refresh the UI\n await _viewModelRefresher.RefreshViewModelAsync(viewModel);\n \n return updatedCount > 0;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying ExternalApps configuration: {ex.Message}\");\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/WindowsAppsConfigurationApplier.cs", "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for applying configuration to the WindowsApps section.\n /// \n public class WindowsAppsConfigurationApplier : ISectionConfigurationApplier\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n private readonly IViewModelRefresher _viewModelRefresher;\n private readonly IConfigurationPropertyUpdater _propertyUpdater;\n\n /// \n /// Gets the section name that this applier handles.\n /// \n public string SectionName => \"WindowsApps\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n /// The view model refresher.\n /// The property updater.\n public WindowsAppsConfigurationApplier(\n IServiceProvider serviceProvider,\n ILogService logService,\n IViewModelRefresher viewModelRefresher,\n IConfigurationPropertyUpdater propertyUpdater)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _viewModelRefresher = viewModelRefresher ?? throw new ArgumentNullException(nameof(viewModelRefresher));\n _propertyUpdater = propertyUpdater ?? throw new ArgumentNullException(nameof(propertyUpdater));\n }\n\n /// \n /// Applies the configuration to the WindowsApps section.\n /// \n /// The configuration file to apply.\n /// True if any items were updated, false otherwise.\n public async Task ApplyConfigAsync(ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Applying configuration to WindowsAppsViewModel\");\n \n var viewModel = _serviceProvider.GetService();\n if (viewModel == null)\n {\n _logService.Log(LogLevel.Warning, \"WindowsAppsViewModel not available\");\n return false;\n }\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, \"WindowsAppsViewModel not initialized, initializing now\");\n await viewModel.LoadItemsAsync();\n }\n \n // Apply the configuration directly to the view model's items\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Items, configFile);\n \n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in WindowsAppsViewModel\");\n \n // Refresh the UI\n await _viewModelRefresher.RefreshViewModelAsync(viewModel);\n \n return updatedCount > 0;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying WindowsApps configuration: {ex.Message}\");\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/SearchableViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// Base view model class that provides search functionality.\n /// \n /// The type of items to search, must implement ISearchable.\n public abstract partial class SearchableViewModel : AppListViewModel where T : class, ISearchable\n {\n private readonly ISearchService _searchService;\n\n // Backing field for the search text\n private string _searchText = string.Empty;\n\n /// \n /// Gets or sets the search text.\n /// \n public virtual string SearchText\n {\n get => _searchText;\n set\n {\n if (SetProperty(ref _searchText, value))\n {\n IsSearchActive = !string.IsNullOrWhiteSpace(value);\n ApplySearch();\n }\n }\n }\n\n /// \n /// Gets a value indicating whether search is active.\n /// \n [ObservableProperty]\n private bool _isSearchActive;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The search service.\n /// The package manager.\n protected SearchableViewModel(\n ITaskProgressService progressService,\n ISearchService searchService,\n IPackageManager? packageManager = null) \n : base(progressService, packageManager)\n {\n _searchService = searchService ?? throw new ArgumentNullException(nameof(searchService));\n }\n\n /// \n /// Applies the current search text to filter items.\n /// \n protected abstract void ApplySearch();\n\n /// \n /// Filters a collection of items based on the current search text.\n /// \n /// The collection of items to filter.\n /// A filtered collection of items that match the search text.\n protected IEnumerable FilterItems(IEnumerable items)\n {\n Console.WriteLine($\"SearchableViewModel.FilterItems: Filtering {items.Count()} items with search text '{SearchText}'\");\n \n // Log items before filtering\n foreach (var item in items)\n {\n var itemName = item.GetType().GetProperty(\"Name\")?.GetValue(item)?.ToString();\n var itemGroupName = item.GetType().GetProperty(\"GroupName\")?.GetValue(item)?.ToString();\n \n if (itemName?.Contains(\"Web Search\") == true || itemGroupName?.Contains(\"Search\") == true)\n {\n Console.WriteLine($\"SearchableViewModel.FilterItems: Found item before filtering - Name: '{itemName}', GroupName: '{itemGroupName}'\");\n }\n }\n \n var result = _searchService.FilterItems(items, SearchText);\n \n // Log filtered results\n Console.WriteLine($\"SearchableViewModel.FilterItems: Filtered result count: {result.Count()}\");\n \n return result;\n }\n\n /// \n /// Asynchronously filters a collection of items based on the current search text.\n /// \n /// The collection of items to filter.\n /// A task that represents the asynchronous operation. The task result contains a filtered collection of items that match the search text.\n protected Task> FilterItemsAsync(IEnumerable items)\n {\n return _searchService.FilterItemsAsync(items, SearchText);\n }\n\n /// \n /// Clears the search text.\n /// \n protected void ClearSearch()\n {\n SearchText = string.Empty;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/OneDriveInstallationService.cs", "using System;\nusing System.IO;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that handles OneDrive installation.\n/// \npublic class OneDriveInstallationService : IOneDriveInstallationService, IDisposable\n{\n private readonly ILogService _logService;\n private readonly HttpClient _httpClient;\n private readonly string _tempDir = Path.Combine(Path.GetTempPath(), \"WinhanceInstaller\");\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public OneDriveInstallationService(ILogService logService)\n {\n _logService = logService;\n _httpClient = new HttpClient();\n Directory.CreateDirectory(_tempDir);\n }\n\n /// \n public async Task InstallOneDriveAsync(\n IProgress? progress,\n CancellationToken cancellationToken)\n {\n try\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Starting OneDrive installation...\",\n DetailedMessage = \"Downloading OneDrive installer from Microsoft\"\n });\n\n // Download OneDrive from the specific URL\n string downloadUrl = \"https://go.microsoft.com/fwlink/p/?LinkID=2182910\";\n string installerPath = Path.Combine(_tempDir, \"OneDriveSetup.exe\");\n\n using (var client = new HttpClient())\n {\n var response = await client.GetAsync(downloadUrl, cancellationToken);\n if (!response.IsSuccessStatusCode)\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Failed to download OneDrive installer\",\n DetailedMessage = $\"HTTP error: {response.StatusCode}\",\n LogLevel = LogLevel.Error\n });\n return false;\n }\n\n using (var fileStream = new FileStream(installerPath, FileMode.Create, FileAccess.Write, FileShare.None))\n {\n await response.Content.CopyToAsync(fileStream, cancellationToken);\n }\n }\n\n progress?.Report(new TaskProgressDetail\n {\n Progress = 50,\n StatusText = \"Installing OneDrive...\",\n DetailedMessage = \"Running OneDrive installer\"\n });\n\n // Run the installer\n using (var process = new System.Diagnostics.Process())\n {\n process.StartInfo.FileName = installerPath;\n process.StartInfo.Arguments = \"/silent\";\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.RedirectStandardError = true;\n process.StartInfo.CreateNoWindow = true;\n\n process.Start();\n await Task.Run(() => process.WaitForExit(), cancellationToken);\n\n bool success = process.ExitCode == 0;\n\n progress?.Report(new TaskProgressDetail\n {\n Progress = 100,\n StatusText = success ? \"OneDrive installed successfully\" : \"OneDrive installation failed\",\n DetailedMessage = $\"Installer exited with code: {process.ExitCode}\",\n LogLevel = success ? LogLevel.Success : LogLevel.Error\n });\n\n return success;\n }\n }\n catch (Exception ex)\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Error installing OneDrive\",\n DetailedMessage = $\"Exception: {ex.Message}\",\n LogLevel = LogLevel.Error\n });\n return false;\n }\n }\n\n /// \n /// Disposes the resources used by the service.\n /// \n public void Dispose()\n {\n _httpClient.Dispose();\n GC.SuppressFinalize(this);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Utilities/FileLogger.cs", "using System;\nusing System.IO;\nusing System.Threading;\n\nnamespace Winhance.WPF.Features.Common.Utilities\n{\n /// \n /// Utility class for direct file logging, used for diagnostic purposes.\n /// \n public static class FileLogger\n {\n private static readonly object _lockObject = new object();\n private const string LOG_FOLDER = \"DiagnosticLogs\";\n \n // Logging is disabled as CloseButtonDiagnostics.txt is no longer used\n private static readonly bool _loggingEnabled = false;\n\n /// \n /// Logs a message to the diagnostic log file.\n /// \n /// The source of the log message (e.g., class name)\n /// The message to log\n public static void Log(string source, string message)\n {\n // Early return if logging is disabled\n if (!_loggingEnabled)\n return;\n \n try\n {\n string logPath = GetLogFilePath();\n string timestamp = DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss.fff\");\n string threadId = Thread.CurrentThread.ManagedThreadId.ToString();\n string logMessage = $\"[{timestamp}] [Thread:{threadId}] [{source}] {message}\";\n\n lock (_lockObject)\n {\n // Ensure directory exists\n Directory.CreateDirectory(Path.GetDirectoryName(logPath));\n File.AppendAllText(logPath, logMessage + Environment.NewLine);\n }\n }\n catch\n {\n // Ignore errors in logging to avoid affecting the application\n }\n }\n\n /// \n /// Gets the full path to the log file.\n /// \n /// The full path to the log file\n public static string GetLogFilePath()\n {\n string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n string winhancePath = Path.Combine(appDataPath, \"Winhance\");\n string logFolderPath = Path.Combine(winhancePath, LOG_FOLDER);\n // Using a placeholder filename since logging is disabled\n return Path.Combine(logFolderPath, \"diagnostics.log\");\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/FeatureScriptModifier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Implementation of IFeatureScriptModifier that provides methods for modifying feature-related script content.\n /// \n public class FeatureScriptModifier : IFeatureScriptModifier\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public FeatureScriptModifier(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string RemoveOptionalFeatureFromScript(string scriptContent, string featureName)\n {\n // Check if the optional features section exists\n int sectionStartIndex = scriptContent.IndexOf(\"# Disable Optional Features\");\n if (sectionStartIndex == -1)\n {\n // Optional features section doesn't exist, so nothing to remove\n return scriptContent;\n }\n\n // Find the optional features array\n int arrayStartIndex = scriptContent.IndexOf(\"$optionalFeatures = @(\", sectionStartIndex);\n if (arrayStartIndex == -1)\n {\n Console.WriteLine(\"Could not find $optionalFeatures array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the optional features array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n Console.WriteLine(\"Could not find end of $optionalFeatures array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the optional features in the array\n var optionalFeatures = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var feature = trimmedLine.Trim('\\'', '\"', ' ', ',');\n optionalFeatures.Add(feature);\n }\n }\n\n // Check if the feature is in the array\n bool removed =\n optionalFeatures.RemoveAll(f =>\n f.Equals(featureName, StringComparison.OrdinalIgnoreCase)\n ) > 0;\n\n if (!removed)\n {\n // Feature not found in the array\n return scriptContent;\n }\n\n // If the array is now empty, remove the entire optional features section\n if (optionalFeatures.Count == 0)\n {\n // Find the end of the optional features section\n int sectionEndIndex = scriptContent.IndexOf(\n \"foreach ($feature in $optionalFeatures) {\",\n arrayEndIndex\n );\n if (sectionEndIndex != -1)\n {\n sectionEndIndex = scriptContent.IndexOf(\"}\", sectionEndIndex);\n if (sectionEndIndex != -1)\n {\n sectionEndIndex = scriptContent.IndexOf('\\n', sectionEndIndex);\n if (sectionEndIndex != -1)\n {\n // Remove the entire section\n return scriptContent.Substring(0, sectionStartIndex)\n + scriptContent.Substring(sectionEndIndex + 1);\n }\n }\n }\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$optionalFeatures = @(\");\n\n foreach (var feature in optionalFeatures)\n {\n newArrayContent.AppendLine($\" '{feature}'\");\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Customize/Services/WallpaperService.cs", "using System;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.Customize.Models;\n\nnamespace Winhance.Infrastructure.Features.Customize.Services\n{\n /// \n /// Service for wallpaper operations.\n /// \n public class WallpaperService : IWallpaperService\n {\n private readonly ILogService _logService;\n\n // P/Invoke constants\n private const int SPI_SETDESKWALLPAPER = 0x0014;\n private const int SPIF_UPDATEINIFILE = 0x01;\n private const int SPIF_SENDCHANGE = 0x02;\n\n [DllImport(\"user32.dll\", SetLastError = true, CharSet = CharSet.Auto)]\n private static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public WallpaperService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string GetDefaultWallpaperPath(bool isWindows11, bool isDarkMode)\n {\n return WindowsThemeSettings.Wallpaper.GetDefaultWallpaperPath(isWindows11, isDarkMode);\n }\n\n /// \n public async Task SetDefaultWallpaperAsync(bool isWindows11, bool isDarkMode)\n {\n string wallpaperPath = GetDefaultWallpaperPath(isWindows11, isDarkMode);\n return await SetWallpaperAsync(wallpaperPath);\n }\n\n /// \n public async Task SetWallpaperAsync(string wallpaperPath)\n {\n try\n {\n bool success = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, wallpaperPath,\n SPIF_UPDATEINIFILE | SPIF_SENDCHANGE) != 0;\n\n if (success)\n {\n _logService.Log(LogLevel.Info, $\"Wallpaper set to {wallpaperPath}\");\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to set wallpaper: {Marshal.GetLastWin32Error()}\");\n }\n\n await Task.CompletedTask; // To keep the async signature\n return success;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting wallpaper: {ex.Message}\");\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/TaskProgressControl.xaml.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Markup;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.WPF.Features.Common.Models;\n\n[assembly: XmlnsDefinition(\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\", \"Winhance.WPF.Features.Common.Controls\")]\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// Interaction logic for TaskProgressControl.xaml\n /// \n public partial class TaskProgressControl : UserControl\n {\n #region Dependency Properties\n\n /// \n /// Gets or sets the progress value (0-100).\n /// \n public double Progress\n {\n get { return (double)GetValue(ProgressProperty); }\n set { SetValue(ProgressProperty, value); }\n }\n\n /// \n /// Identifies the Progress dependency property.\n /// \n public static readonly DependencyProperty ProgressProperty =\n DependencyProperty.Register(nameof(Progress), typeof(double), typeof(TaskProgressControl), \n new PropertyMetadata(0.0, OnProgressChanged));\n\n /// \n /// Gets or sets the status text.\n /// \n public string StatusText\n {\n get { return (string)GetValue(StatusTextProperty); }\n set { SetValue(StatusTextProperty, value); }\n }\n\n /// \n /// Identifies the StatusText dependency property.\n /// \n public static readonly DependencyProperty StatusTextProperty =\n DependencyProperty.Register(nameof(StatusText), typeof(string), typeof(TaskProgressControl), \n new PropertyMetadata(string.Empty));\n\n /// \n /// Gets or sets whether the progress is indeterminate.\n /// \n public bool IsIndeterminate\n {\n get { return (bool)GetValue(IsIndeterminateProperty); }\n set { SetValue(IsIndeterminateProperty, value); }\n }\n\n /// \n /// Identifies the IsIndeterminate dependency property.\n /// \n public static readonly DependencyProperty IsIndeterminateProperty =\n DependencyProperty.Register(nameof(IsIndeterminate), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets whether the control is visible.\n /// \n public new bool IsVisible\n {\n get { return (bool)GetValue(IsVisibleProperty); }\n set { SetValue(IsVisibleProperty, value); }\n }\n\n /// \n /// Identifies the IsVisible dependency property.\n /// \n public new static readonly DependencyProperty IsVisibleProperty =\n DependencyProperty.Register(nameof(IsVisible), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets the progress text (e.g., \"50%\").\n /// \n public string ProgressText\n {\n get { return (string)GetValue(ProgressTextProperty); }\n private set { SetValue(ProgressTextProperty, value); }\n }\n\n /// \n /// Identifies the ProgressText dependency property.\n /// \n public static readonly DependencyProperty ProgressTextProperty =\n DependencyProperty.Register(nameof(ProgressText), typeof(string), typeof(TaskProgressControl), \n new PropertyMetadata(string.Empty));\n\n /// \n /// Gets or sets whether the details are expanded.\n /// \n public bool AreDetailsExpanded\n {\n get { return (bool)GetValue(AreDetailsExpandedProperty); }\n set { SetValue(AreDetailsExpandedProperty, value); }\n }\n\n /// \n /// Identifies the AreDetailsExpanded dependency property.\n /// \n public static readonly DependencyProperty AreDetailsExpandedProperty =\n DependencyProperty.Register(nameof(AreDetailsExpanded), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets whether there are log messages.\n /// \n public bool HasLogMessages\n {\n get { return (bool)GetValue(HasLogMessagesProperty); }\n private set { SetValue(HasLogMessagesProperty, value); }\n }\n\n /// \n /// Identifies the HasLogMessages dependency property.\n /// \n public static readonly DependencyProperty HasLogMessagesProperty =\n DependencyProperty.Register(nameof(HasLogMessages), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets the log messages.\n /// \n public ObservableCollection LogMessages\n {\n get { return (ObservableCollection)GetValue(LogMessagesProperty); }\n private set { SetValue(LogMessagesProperty, value); }\n }\n\n /// \n /// Identifies the LogMessages dependency property.\n /// \n public static readonly DependencyProperty LogMessagesProperty =\n DependencyProperty.Register(nameof(LogMessages), typeof(ObservableCollection), \n typeof(TaskProgressControl), new PropertyMetadata(null));\n\n /// \n /// Gets or sets whether the operation can be cancelled.\n /// \n public bool CanCancel\n {\n get { return (bool)GetValue(CanCancelProperty); }\n set { SetValue(CanCancelProperty, value); }\n }\n\n /// \n /// Identifies the CanCancel dependency property.\n /// \n public static readonly DependencyProperty CanCancelProperty =\n DependencyProperty.Register(nameof(CanCancel), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets whether a task is running.\n /// \n public bool IsTaskRunning\n {\n get { return (bool)GetValue(IsTaskRunningProperty); }\n set { SetValue(IsTaskRunningProperty, value); }\n }\n\n /// \n /// Identifies the IsTaskRunning dependency property.\n /// \n public static readonly DependencyProperty IsTaskRunningProperty =\n DependencyProperty.Register(nameof(IsTaskRunning), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets the command to execute when the cancel button is clicked.\n /// \n public ICommand CancelCommand\n {\n get { return (ICommand)GetValue(CancelCommandProperty); }\n set { SetValue(CancelCommandProperty, value); }\n }\n\n /// \n /// Identifies the CancelCommand dependency property.\n /// \n public static readonly DependencyProperty CancelCommandProperty =\n DependencyProperty.Register(nameof(CancelCommand), typeof(ICommand), typeof(TaskProgressControl), \n new PropertyMetadata(null));\n\n #endregion\n\n /// \n /// Initializes a new instance of the class.\n /// \n public TaskProgressControl()\n {\n LogMessages = new ObservableCollection();\n InitializeComponent();\n UpdateProgressText();\n }\n\n private static void OnProgressChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is TaskProgressControl control)\n {\n control.UpdateProgressText();\n }\n }\n\n private void UpdateProgressText()\n {\n if (IsIndeterminate)\n {\n ProgressText = string.Empty;\n }\n else\n {\n ProgressText = $\"{Progress:F0}%\";\n }\n }\n\n /// \n /// Adds a log message to the control.\n /// \n /// The message content.\n /// The log level.\n public void AddLogMessage(string message, LogLevel level)\n {\n if (string.IsNullOrEmpty(message)) return;\n\n Application.Current.Dispatcher.Invoke(() =>\n {\n LogMessages.Add(new LogMessageViewModel\n {\n Message = message,\n Level = level,\n Timestamp = DateTime.Now\n });\n\n HasLogMessages = LogMessages.Count > 0;\n\n // Auto-expand details on error or warning\n if (level == LogLevel.Error || level == LogLevel.Warning)\n {\n AreDetailsExpanded = true;\n }\n });\n }\n\n /// \n /// Clears all log messages.\n /// \n public void ClearLogMessages()\n {\n Application.Current.Dispatcher.Invoke(() =>\n {\n LogMessages.Clear();\n HasLogMessages = false;\n });\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Views/SoftwareAppsView.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing MaterialDesignThemes.Wpf;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Views\n{\n /// \n /// Interaction logic for SoftwareAppsView.xaml\n /// \n public partial class SoftwareAppsView : UserControl\n {\n public SoftwareAppsView()\n {\n InitializeComponent();\n Loaded += SoftwareAppsView_Loaded;\n\n // Set up the expandable sections\n WindowsAppsContent.Visibility = Visibility.Collapsed;\n ExternalAppsContent.Visibility = Visibility.Collapsed;\n\n // Add click handlers\n WindowsAppsHeaderBorder.MouseDown += WindowsAppsHeader_MouseDown;\n ExternalAppsHeaderBorder.MouseDown += ExternalAppsHeader_MouseDown;\n }\n\n private async void SoftwareAppsView_Loaded(object sender, RoutedEventArgs e)\n {\n if (DataContext is SoftwareAppsViewModel viewModel)\n {\n try\n {\n // Initialize the view model\n await viewModel.InitializeCommand.ExecuteAsync(null);\n \n // Expand the first section by default after initialization is complete\n WindowsAppsContent.Visibility = Visibility.Visible;\n WindowsAppsHeaderIcon.Kind = PackIconKind.ChevronUp; // Up arrow\n }\n catch (System.Exception ex)\n {\n MessageBox.Show($\"Error initializing Software Apps view: {ex.Message}\",\n \"Initialization Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error);\n }\n }\n }\n\n private void WindowsAppsHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n ToggleSection(WindowsAppsContent, WindowsAppsHeaderIcon);\n }\n\n private void ExternalAppsHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n ToggleSection(ExternalAppsContent, ExternalAppsHeaderIcon);\n }\n\n private void ToggleSection(UIElement content, PackIcon icon)\n {\n if (content.Visibility == Visibility.Collapsed)\n {\n content.Visibility = Visibility.Visible;\n icon.Kind = PackIconKind.ChevronUp; // Up arrow (section expanded)\n }\n else\n {\n content.Visibility = Visibility.Collapsed;\n icon.Kind = PackIconKind.ChevronDown; // Down arrow (section collapsed)\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Services/DependencyManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Services\n{\n /// \n /// Manages dependencies between settings, ensuring that dependent settings are properly handled\n /// when their required settings change state.\n /// \n public class DependencyManager : IDependencyManager\n {\n private readonly ILogService _logService;\n \n public DependencyManager(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n \n /// \n /// Handles the enabling of a setting by automatically enabling any required settings.\n /// \n /// The ID of the setting that is being enabled.\n /// All available settings that might be required by the enabled setting.\n /// True if all required settings were enabled successfully; otherwise, false.\n public bool HandleSettingEnabled(string settingId, IEnumerable allSettings)\n {\n if (string.IsNullOrEmpty(settingId))\n {\n _logService.Log(LogLevel.Warning, \"Cannot handle dependencies for null or empty setting ID\");\n return false;\n }\n \n var setting = allSettings.FirstOrDefault(s => s.Id == settingId);\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, $\"Setting with ID '{settingId}' not found\");\n return false;\n }\n \n if (setting.Dependencies == null || !setting.Dependencies.Any())\n {\n return true; // No dependencies, so nothing to enable\n }\n \n // Get unsatisfied dependencies\n var unsatisfiedDependencies = GetUnsatisfiedDependencies(settingId, allSettings);\n \n // Enable all dependencies\n return EnableDependencies(unsatisfiedDependencies);\n }\n \n /// \n /// Gets a list of unsatisfied dependencies for a setting.\n /// \n /// The ID of the setting to check.\n /// All available settings that might be dependencies.\n /// A list of settings that are required by the specified setting but are not enabled.\n public List GetUnsatisfiedDependencies(string settingId, IEnumerable allSettings)\n {\n var unsatisfiedDependencies = new List();\n \n if (string.IsNullOrEmpty(settingId))\n {\n _logService.Log(LogLevel.Warning, \"Cannot get dependencies for null or empty setting ID\");\n return unsatisfiedDependencies;\n }\n \n var setting = allSettings.FirstOrDefault(s => s.Id == settingId);\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, $\"Setting with ID '{settingId}' not found\");\n return unsatisfiedDependencies;\n }\n \n if (setting.Dependencies == null || !setting.Dependencies.Any())\n {\n return unsatisfiedDependencies; // No dependencies\n }\n \n // Find all settings that this setting depends on\n foreach (var dependency in setting.Dependencies)\n {\n if (dependency.DependencyType == SettingDependencyType.RequiresEnabled)\n {\n var requiredSetting = allSettings.FirstOrDefault(s => s.Id == dependency.RequiredSettingId);\n if (requiredSetting != null && !requiredSetting.IsSelected)\n {\n unsatisfiedDependencies.Add(requiredSetting);\n }\n }\n }\n \n return unsatisfiedDependencies;\n }\n \n /// \n /// Enables all dependencies in the provided list.\n /// \n /// The dependencies to enable.\n /// True if all dependencies were enabled successfully; otherwise, false.\n public bool EnableDependencies(IEnumerable dependencies)\n {\n bool allSucceeded = true;\n \n foreach (var dependency in dependencies)\n {\n _logService.Log(LogLevel.Info, $\"Automatically enabling dependency: {dependency.Name}\");\n \n // Enable the dependency\n dependency.IsUpdatingFromCode = true;\n try\n {\n dependency.IsSelected = true;\n }\n finally\n {\n dependency.IsUpdatingFromCode = false;\n }\n \n // Apply the setting\n dependency.ApplySettingCommand?.Execute(null);\n \n // Check if the setting was successfully enabled\n if (!dependency.IsSelected)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to enable required setting '{dependency.Name}'\");\n allSucceeded = false;\n }\n }\n \n return allSucceeded;\n }\n \n /// \n /// Determines if a setting can be enabled based on its dependencies.\n /// \n /// The ID of the setting to check.\n /// All available settings that might be dependencies.\n /// True if the setting can be enabled; otherwise, false.\n public bool CanEnableSetting(string settingId, IEnumerable allSettings)\n {\n if (string.IsNullOrEmpty(settingId))\n {\n _logService.Log(LogLevel.Warning, \"Cannot check dependencies for null or empty setting ID\");\n return false;\n }\n \n var setting = allSettings.FirstOrDefault(s => s.Id == settingId);\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, $\"Setting with ID '{settingId}' not found\");\n return false;\n }\n \n if (setting.Dependencies == null || !setting.Dependencies.Any())\n {\n return true; // No dependencies, so it can be enabled\n }\n \n foreach (var dependency in setting.Dependencies)\n {\n if (dependency.DependencyType == SettingDependencyType.RequiresEnabled)\n {\n var requiredSetting = allSettings.FirstOrDefault(s => s.Id == dependency.RequiredSettingId);\n if (requiredSetting != null && !requiredSetting.IsSelected)\n {\n _logService.Log(LogLevel.Warning, $\"Cannot enable '{setting.Name}' because '{requiredSetting.Name}' is disabled\");\n return false;\n }\n }\n else if (dependency.DependencyType == SettingDependencyType.RequiresDisabled)\n {\n var requiredSetting = allSettings.FirstOrDefault(s => s.Id == dependency.RequiredSettingId);\n if (requiredSetting != null && requiredSetting.IsSelected)\n {\n _logService.Log(LogLevel.Warning, $\"Cannot enable '{setting.Name}' because '{requiredSetting.Name}' is enabled\");\n return false;\n }\n }\n }\n \n return true;\n }\n \n /// \n /// Handles the disabling of a setting by automatically disabling any dependent settings.\n /// \n /// The ID of the setting that was disabled.\n /// All available settings that might depend on the disabled setting.\n public void HandleSettingDisabled(string settingId, IEnumerable allSettings)\n {\n if (string.IsNullOrEmpty(settingId))\n {\n _logService.Log(LogLevel.Warning, \"Cannot handle dependencies for null or empty setting ID\");\n return;\n }\n \n // Find all settings that depend on this setting\n var dependentSettings = allSettings.Where(s => \n s.Dependencies != null && \n s.Dependencies.Any(d => d.RequiredSettingId == settingId && \n d.DependencyType == SettingDependencyType.RequiresEnabled));\n \n foreach (var dependentSetting in dependentSettings)\n {\n if (dependentSetting.IsSelected)\n {\n _logService.Log(LogLevel.Info, $\"Automatically disabling '{dependentSetting.Name}' as '{settingId}' was disabled\");\n \n // Disable the dependent setting\n dependentSetting.IsUpdatingFromCode = true;\n try\n {\n dependentSetting.IsSelected = false;\n }\n finally\n {\n dependentSetting.IsUpdatingFromCode = false;\n }\n \n // Apply the change\n dependentSetting.ApplySettingCommand?.Execute(null);\n \n // Recursively handle any settings that depend on this one\n HandleSettingDisabled(dependentSetting.Id, allSettings);\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/JsonParameterSerializer.cs", "using System;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Text;\nusing System.Text.Json;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n public class JsonParameterSerializer : IParameterSerializer\n {\n private readonly JsonSerializerOptions _options = new()\n {\n PropertyNameCaseInsensitive = true,\n WriteIndented = false\n };\n\n public int MaxParameterSize { get; set; } = 1024 * 1024; // 1MB default\n public bool UseCompression { get; set; } = true;\n\n public string Serialize(object parameter)\n {\n if (parameter == null) return null;\n \n var json = JsonSerializer.Serialize(parameter, _options);\n \n if (UseCompression && json.Length > 1024) // Compress if over 1KB\n {\n var bytes = Encoding.UTF8.GetBytes(json);\n using var output = new MemoryStream();\n using (var gzip = new GZipStream(output, CompressionMode.Compress))\n {\n gzip.Write(bytes, 0, bytes.Length);\n }\n return Convert.ToBase64String(output.ToArray());\n }\n \n return json;\n }\n\n // Corrected signature to match IParameterSerializer\n public object Deserialize(Type targetType, string value)\n {\n if (string.IsNullOrWhiteSpace(value)) return null;\n\n try\n {\n if (IsCompressed(value)) // Use 'value' parameter\n {\n var bytes = Convert.FromBase64String(value); // Use 'value' parameter\n using var input = new MemoryStream(bytes);\n using var output = new MemoryStream();\n using (var gzip = new GZipStream(input, CompressionMode.Decompress))\n {\n gzip.CopyTo(output);\n }\n var json = Encoding.UTF8.GetString(output.ToArray());\n return JsonSerializer.Deserialize(json, targetType, _options);\n }\n\n return JsonSerializer.Deserialize(value, targetType, _options); // Use 'value' parameter\n }\n catch (JsonException ex)\n {\n throw new InvalidOperationException(\"Failed to deserialize parameter\", ex);\n }\n catch (Exception ex) when (ex is FormatException || ex is InvalidDataException)\n {\n throw new InvalidOperationException(\"Invalid compressed parameter format\", ex);\n }\n }\n\n public T Deserialize(string serialized)\n {\n if (string.IsNullOrWhiteSpace(serialized)) return default;\n\n try\n {\n if (IsCompressed(serialized))\n {\n var bytes = Convert.FromBase64String(serialized);\n using var input = new MemoryStream(bytes);\n using var output = new MemoryStream();\n using (var gzip = new GZipStream(input, CompressionMode.Decompress))\n {\n gzip.CopyTo(output);\n }\n var json = Encoding.UTF8.GetString(output.ToArray());\n return JsonSerializer.Deserialize(json, _options);\n }\n \n return JsonSerializer.Deserialize(serialized, _options);\n }\n catch (JsonException ex)\n {\n throw new InvalidOperationException($\"Failed to deserialize parameter to type {typeof(T).Name}\", ex);\n }\n catch (Exception ex) when (ex is FormatException || ex is InvalidDataException)\n {\n throw new InvalidOperationException(\"Invalid compressed parameter format\", ex);\n }\n }\n\n private bool IsCompressed(string input)\n {\n if (string.IsNullOrEmpty(input)) return false;\n try\n {\n // Simple check - compressed data is base64 and starts with H4sI (GZip magic number)\n return input.Length > 4 && \n input.StartsWith(\"H4sI\") && \n input.Length % 4 == 0;\n }\n catch\n {\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/RegistryScriptModifier.cs", "using System;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Implementation of IRegistryScriptModifier that provides methods for modifying registry-related script content.\n /// \n public class RegistryScriptModifier : IRegistryScriptModifier\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public RegistryScriptModifier(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string RemoveAppRegistrySettingsFromScript(string scriptContent, string appName)\n {\n // Find the registry settings section\n int registrySection = scriptContent.IndexOf(\"# Registry settings\");\n if (registrySection == -1)\n {\n return scriptContent;\n }\n\n // Generate possible section headers for this app\n var possibleSectionHeaders = new List\n {\n $\"# Registry settings for {appName}\",\n $\"# Registry settings for Microsoft.{appName}\",\n };\n\n // Add variations without \"Microsoft.\" prefix if it already has it\n if (appName.StartsWith(\"Microsoft.\", StringComparison.OrdinalIgnoreCase))\n {\n string nameWithoutPrefix = appName.Substring(\"Microsoft.\".Length);\n possibleSectionHeaders.Add($\"# Registry settings for {nameWithoutPrefix}\");\n }\n\n // Add common variations\n possibleSectionHeaders.Add($\"# Registry settings for {appName}_8wekyb3d8bbwe\");\n\n // For Copilot specifically, add known variations\n if (appName.Contains(\"Copilot\", StringComparison.OrdinalIgnoreCase))\n {\n possibleSectionHeaders.Add(\"# Registry settings for Copilot\");\n possibleSectionHeaders.Add(\"# Registry settings for Microsoft.Copilot\");\n possibleSectionHeaders.Add(\"# Registry settings for Windows.Copilot\");\n }\n\n // For Xbox/GamingApp specifically, add known variations\n if (\n appName.Contains(\"Xbox\", StringComparison.OrdinalIgnoreCase)\n || appName.Equals(\"Microsoft.GamingApp\", StringComparison.OrdinalIgnoreCase)\n )\n {\n possibleSectionHeaders.Add(\"# Registry settings for Xbox\");\n possibleSectionHeaders.Add(\"# Registry settings for Microsoft.Xbox\");\n possibleSectionHeaders.Add(\"# Registry settings for GamingApp\");\n }\n\n // Find the earliest matching section header\n int appSection = -1;\n string matchedHeader = null;\n\n foreach (var header in possibleSectionHeaders)\n {\n int index = scriptContent.IndexOf(header, registrySection);\n if (index != -1 && (appSection == -1 || index < appSection))\n {\n appSection = index;\n matchedHeader = header;\n }\n }\n\n if (appSection == -1)\n {\n Console.WriteLine($\"No registry settings found for {appName} in the script\");\n return scriptContent;\n }\n\n Console.WriteLine($\"Found registry settings for {appName} with header: {matchedHeader}\");\n\n // Find the end of the app section (next section or end of file)\n int nextSection = scriptContent.IndexOf(\n \"# Registry settings for\",\n appSection + matchedHeader.Length\n );\n if (nextSection == -1)\n {\n // Look for the next major section\n nextSection = scriptContent.IndexOf(\"# Prevent apps from reinstalling\", appSection);\n if (nextSection == -1)\n {\n // If no next section, just return the original content\n Console.WriteLine($\"Could not find end of registry settings section for {appName}\");\n return scriptContent;\n }\n }\n\n // Remove the app registry settings section\n Console.WriteLine($\"Removing registry settings for {appName} from script\");\n return scriptContent.Substring(0, appSection) + scriptContent.Substring(nextSection);\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/ViewNameToBackgroundConverter.cs", "using System;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing System.Windows.Threading;\nusing Winhance.WPF.Features.Common.Resources.Theme;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class ViewNameToBackgroundConverter : IValueConverter, INotifyPropertyChanged\n {\n private static ViewNameToBackgroundConverter? _instance;\n \n public static ViewNameToBackgroundConverter Instance \n {\n get \n {\n if (_instance == null)\n {\n _instance = new ViewNameToBackgroundConverter();\n }\n return _instance;\n }\n }\n \n public event PropertyChangedEventHandler? PropertyChanged;\n \n // This method will be called when the theme changes\n public void NotifyThemeChanged()\n {\n // Force a refresh of all bindings that use this converter\n Application.Current.Dispatcher.Invoke(() =>\n {\n // Notify all properties to force binding refresh\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(string.Empty));\n \n // Also notify specific properties to ensure all binding scenarios are covered\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(\"ThemeChanged\"));\n \n // Force WPF to update all bindings\n if (Application.Current.MainWindow != null)\n {\n Application.Current.MainWindow.UpdateLayout();\n }\n }, DispatcherPriority.Render);\n }\n \n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n try\n {\n var currentViewName = value as string;\n var buttonViewName = parameter as string;\n \n if (string.Equals(currentViewName, buttonViewName, StringComparison.OrdinalIgnoreCase))\n {\n // Return the main content background color for selected buttons\n var brush = Application.Current.Resources[\"MainContainerBorderBrush\"] as SolidColorBrush;\n return brush?.Color ?? Colors.Transparent;\n }\n \n // Return the default navigation button background color\n var defaultBrush = Application.Current.Resources[\"NavigationButtonBackground\"] as SolidColorBrush;\n return defaultBrush?.Color ?? Colors.Transparent;\n }\n catch\n {\n var defaultBrush = Application.Current.Resources[\"NavigationButtonBackground\"] as SolidColorBrush;\n return defaultBrush?.Color ?? Colors.Transparent;\n }\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/ResponsiveScrollViewer.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// A custom ScrollViewer that handles mouse wheel events regardless of cursor position\n /// and provides enhanced scrolling speed\n /// \n public class ResponsiveScrollViewer : ScrollViewer\n {\n #region Dependency Properties\n\n /// \n /// Dependency property for ScrollSpeedMultiplier\n /// \n public static readonly DependencyProperty ScrollSpeedMultiplierProperty =\n DependencyProperty.RegisterAttached(\n \"ScrollSpeedMultiplier\",\n typeof(double),\n typeof(ResponsiveScrollViewer),\n new PropertyMetadata(10.0));\n\n /// \n /// Gets the scroll speed multiplier for a ScrollViewer\n /// \n public static double GetScrollSpeedMultiplier(DependencyObject obj)\n {\n return (double)obj.GetValue(ScrollSpeedMultiplierProperty);\n }\n\n /// \n /// Sets the scroll speed multiplier for a ScrollViewer\n /// \n public static void SetScrollSpeedMultiplier(DependencyObject obj, double value)\n {\n obj.SetValue(ScrollSpeedMultiplierProperty, value);\n }\n\n #endregion\n\n /// \n /// Static constructor to register event handlers for all ScrollViewers\n /// \n static ResponsiveScrollViewer()\n {\n // Register class handler for the PreviewMouseWheel event\n EventManager.RegisterClassHandler(\n typeof(ScrollViewer),\n UIElement.PreviewMouseWheelEvent,\n new MouseWheelEventHandler(OnPreviewMouseWheel),\n true);\n }\n\n /// \n /// Constructor\n /// \n public ResponsiveScrollViewer()\n {\n // No need to register for the event here anymore as we're using a class handler\n }\n\n /// \n /// Handles the PreviewMouseWheel event for all ScrollViewers\n /// \n private static void OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)\n {\n if (sender is ScrollViewer scrollViewer)\n {\n // Get the current vertical offset\n double currentOffset = scrollViewer.VerticalOffset;\n\n // Get the scroll speed multiplier (use default value if not set)\n double speedMultiplier = GetScrollSpeedMultiplier(scrollViewer);\n\n // Calculate the scroll amount based on the mouse wheel delta and speed multiplier\n double scrollAmount = (SystemParameters.WheelScrollLines * speedMultiplier);\n\n if (e.Delta < 0)\n {\n // Scroll down when the mouse wheel is rotated down\n scrollViewer.ScrollToVerticalOffset(currentOffset + scrollAmount);\n }\n else\n {\n // Scroll up when the mouse wheel is rotated up\n scrollViewer.ScrollToVerticalOffset(currentOffset - scrollAmount);\n }\n\n // Mark the event as handled to prevent it from bubbling up\n e.Handled = true;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/UpdateNotificationViewModel.cs", "using System;\nusing System.Threading.Tasks;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n public partial class UpdateNotificationViewModel : ObservableObject\n {\n private readonly IVersionService _versionService;\n private readonly ILogService _logService;\n private readonly IDialogService _dialogService;\n \n [ObservableProperty]\n private string _currentVersion = string.Empty;\n \n [ObservableProperty]\n private string _latestVersion = string.Empty;\n \n [ObservableProperty]\n private bool _isUpdateAvailable;\n \n [ObservableProperty]\n private bool _isDownloading;\n \n [ObservableProperty]\n private string _statusMessage = string.Empty;\n \n public UpdateNotificationViewModel(\n IVersionService versionService,\n ILogService logService,\n IDialogService dialogService)\n {\n _versionService = versionService;\n _logService = logService;\n _dialogService = dialogService;\n \n VersionInfo currentVersion = _versionService.GetCurrentVersion();\n CurrentVersion = currentVersion.Version;\n }\n \n [RelayCommand]\n private async Task CheckForUpdateAsync()\n {\n try\n {\n StatusMessage = \"Checking for updates...\";\n \n VersionInfo latestVersion = await _versionService.CheckForUpdateAsync();\n LatestVersion = latestVersion.Version;\n IsUpdateAvailable = latestVersion.IsUpdateAvailable;\n \n StatusMessage = IsUpdateAvailable \n ? $\"Update available: {LatestVersion}\" \n : \"You have the latest version.\";\n \n return;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking for updates: {ex.Message}\", ex);\n StatusMessage = \"Error checking for updates.\";\n }\n }\n \n [RelayCommand]\n private async Task DownloadAndInstallUpdateAsync()\n {\n if (!IsUpdateAvailable)\n return;\n \n try\n {\n IsDownloading = true;\n StatusMessage = \"Downloading update...\";\n \n await _versionService.DownloadAndInstallUpdateAsync();\n \n StatusMessage = \"Update downloaded. Installing...\";\n \n // Notify the user that the application will close\n await _dialogService.ShowInformationAsync(\n \"The installer has been launched. The application will now close.\",\n \"Update\");\n \n // Close the application\n System.Windows.Application.Current.Shutdown();\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error downloading update: {ex.Message}\", ex);\n StatusMessage = \"Error downloading update.\";\n IsDownloading = false;\n }\n }\n \n [RelayCommand]\n private void RemindLater()\n {\n // Just close the dialog, will check again next time\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Theme/FontLoader.cs", "using System;\nusing System.IO;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Theme\n{\n public static class FontLoader\n {\n [DllImport(\"gdi32.dll\")]\n private static extern int AddFontResource(string lpFilename);\n\n [DllImport(\"gdi32.dll\")]\n private static extern int RemoveFontResource(string lpFilename);\n\n private static string? _tempFontPath;\n\n public static bool LoadFont(string resourcePath)\n {\n try\n {\n // Extract the font to a temporary file\n var fontUri = new Uri(resourcePath);\n var streamResourceInfo = Application.GetResourceStream(fontUri);\n\n if (streamResourceInfo == null)\n {\n return false;\n }\n\n // Create a temporary file for the font\n _tempFontPath = Path.Combine(\n Path.GetTempPath(),\n $\"MaterialSymbols_{Guid.NewGuid()}.ttf\"\n );\n\n using (var fileStream = File.Create(_tempFontPath))\n using (var resourceStream = streamResourceInfo.Stream)\n {\n resourceStream.CopyTo(fileStream);\n }\n\n // Load the font using the Win32 API\n int result = AddFontResource(_tempFontPath);\n\n // Force a redraw of all text elements\n foreach (Window window in Application.Current.Windows)\n {\n window.InvalidateVisual();\n }\n\n return result > 0;\n }\n catch (Exception)\n {\n return false;\n }\n }\n\n public static void UnloadFont()\n {\n if (!string.IsNullOrEmpty(_tempFontPath) && File.Exists(_tempFontPath))\n {\n RemoveFontResource(_tempFontPath);\n try\n {\n File.Delete(_tempFontPath);\n }\n catch\n {\n // Ignore errors when deleting the temporary file\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToThemeConverter.cs", "using System;\nusing System.Globalization;\nusing System.Linq;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean value to a theme string (\"Dark\" or \"Light\") or theme-specific colors\n /// \n public class BooleanToThemeConverter : IValueConverter, IMultiValueConverter\n {\n // Default track colors\n private static readonly Color DarkTrackColor = Color.FromRgb(68, 68, 68);\n private static readonly Color LightTrackColor = Color.FromRgb(204, 204, 204);\n \n // Checked track colors\n private static readonly Color DarkCheckedTrackColor = Color.FromRgb(85, 85, 85);\n private static readonly Color LightCheckedTrackColor = Color.FromRgb(66, 66, 66);\n \n // Knob colors\n private static readonly Color DefaultKnobColor = Color.FromRgb(255, 255, 255); // White for unchecked\n private static readonly Color DarkCheckedKnobColor = Color.FromRgb(255, 222, 0); // Yellow for dark theme checked\n private static readonly Color LightCheckedKnobColor = Color.FromRgb(66, 66, 66); // Gray for light theme checked\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n bool isDarkTheme = false;\n bool isChecked = false;\n \n // Handle different input types for theme\n if (value is bool boolValue)\n {\n isDarkTheme = boolValue;\n }\n else if (value is string stringValue)\n {\n isDarkTheme = stringValue.Equals(\"Dark\", StringComparison.OrdinalIgnoreCase);\n }\n \n // Extract checked state from parameter if provided\n if (parameter is string paramString)\n {\n string[] parts = paramString.Split(':');\n string elementType = parts[0];\n \n // Check if we have checked state information\n if (parts.Length > 1)\n {\n isChecked = parts[1].Equals(\"Checked\", StringComparison.OrdinalIgnoreCase);\n }\n \n if (targetType == typeof(Brush) || targetType == typeof(SolidColorBrush))\n {\n if (elementType.Equals(\"Track\", StringComparison.OrdinalIgnoreCase))\n {\n if (isChecked)\n {\n return new SolidColorBrush(isDarkTheme ? DarkCheckedTrackColor : LightCheckedTrackColor);\n }\n else\n {\n return new SolidColorBrush(isDarkTheme ? DarkTrackColor : LightTrackColor);\n }\n }\n else if (elementType.Equals(\"Knob\", StringComparison.OrdinalIgnoreCase))\n {\n if (isChecked)\n {\n // Use the hardcoded colors for better reliability\n return new SolidColorBrush(isDarkTheme ? DarkCheckedKnobColor : LightCheckedKnobColor);\n }\n else\n {\n // Use white for unchecked knobs in both themes\n return new SolidColorBrush(DefaultKnobColor);\n }\n }\n }\n }\n \n // Default behavior - return theme string\n return isDarkTheme ? \"Dark\" : \"Light\";\n }\n \n // Implementation for IMultiValueConverter\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length < 2)\n return Binding.DoNothing;\n \n bool isDarkTheme = false;\n bool isChecked = false;\n \n // First value is the theme\n if (values[0] is bool themeBool)\n {\n isDarkTheme = themeBool;\n }\n else if (values[0] is string themeString)\n {\n isDarkTheme = themeString.Equals(\"Dark\", StringComparison.OrdinalIgnoreCase);\n }\n \n // Second value is the checked state\n if (values[1] is bool checkedBool)\n {\n isChecked = checkedBool;\n }\n \n // Determine which element we're styling based on parameter\n string elementType = parameter as string ?? \"Track\";\n \n if (targetType == typeof(Brush) || targetType == typeof(SolidColorBrush))\n {\n if (elementType.Equals(\"Track\", StringComparison.OrdinalIgnoreCase))\n {\n if (isChecked)\n {\n return new SolidColorBrush(isDarkTheme ? DarkCheckedTrackColor : LightCheckedTrackColor);\n }\n else\n {\n return new SolidColorBrush(isDarkTheme ? DarkTrackColor : LightTrackColor);\n }\n }\n else if (elementType.Equals(\"Knob\", StringComparison.OrdinalIgnoreCase))\n {\n if (isChecked)\n {\n // Use the hardcoded colors for better reliability\n return new SolidColorBrush(isDarkTheme ? DarkCheckedKnobColor : LightCheckedKnobColor);\n }\n else\n {\n // Use white for unchecked knobs in both themes\n return new SolidColorBrush(DefaultKnobColor);\n }\n }\n }\n \n return Binding.DoNothing;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is string themeString)\n {\n return themeString.Equals(\"Dark\", StringComparison.OrdinalIgnoreCase);\n }\n \n return false; // Default to Light theme (false) if value is not a string\n }\n \n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n // We don't need to implement this for our use case\n return targetTypes.Select(t => Binding.DoNothing).ToArray();\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/ExplorerCustomizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Enums;\n\nnamespace Winhance.Core.Features.Customize.Models;\n\npublic static class ExplorerCustomizations\n{\n public static CustomizationGroup GetExplorerCustomizations()\n {\n return new CustomizationGroup\n {\n Name = \"Explorer\",\n Category = CustomizationCategory.Explorer,\n Settings = new List\n {\n new CustomizationSetting\n {\n Id = \"explorer-3d-objects\",\n Name = \"3D Objects\",\n Description = \"Controls 3D Objects folder visibility in This PC\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\MyComputer\\\\NameSpace\",\n Name = \"{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}\",\n RecommendedValue = null,\n EnabledValue = null, // When toggle is ON, 3D Objects folder is shown (key exists)\n DisabledValue = null, // When toggle is OFF, 3D Objects folder is hidden (key removed)\n ValueType = RegistryValueKind.None,\n DefaultValue = null,\n Description = \"Controls 3D Objects folder visibility in This PC\",\n ActionType = RegistryActionType.Remove,\n },\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\MyComputer\\\\NameSpace\\\\WOW64\",\n Name = \"{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}\",\n RecommendedValue = null,\n EnabledValue = null, // When toggle is ON, 3D Objects folder is shown (key exists)\n DisabledValue = null, // When toggle is OFF, 3D Objects folder is hidden (key removed)\n ValueType = RegistryValueKind.None,\n DefaultValue = null,\n Description =\n \"Controls 3D Objects folder visibility in This PC (WOW64)\",\n ActionType = RegistryActionType.Remove,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new CustomizationSetting\n {\n Id = \"explorer-home-folder\",\n Name = \"Home Folder in Navigation Pane\",\n Description = \"Controls Home Folder visibility in Navigation Pane\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Desktop\\\\NameSpace\",\n Name = \"{f874310e-b6b7-47dc-bc84-b9e6b38f5903}\",\n RecommendedValue = null,\n EnabledValue = null, // When toggle is ON, Home Folder is shown (key exists)\n DisabledValue = null, // When toggle is OFF, Home Folder is hidden (key removed)\n ValueType = RegistryValueKind.None,\n DefaultValue = null,\n Description = \"Controls Home Folder visibility in Navigation Pane\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n ActionType = RegistryActionType.Remove,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-launch-to\",\n Name = \"Launch to This PC\",\n Description = \"Controls where File Explorer opens by default\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"LaunchTo\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, File Explorer opens to 'This PC'\n DisabledValue = 2, // When toggle is OFF, File Explorer opens to 'Quick access'\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls where File Explorer opens by default\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-show-file-ext\",\n Name = \"Show File Extensions\",\n Description = \"Controls visibility of file name extensions\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"HideFileExt\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, file extensions are shown\n DisabledValue = 1, // When toggle is OFF, file extensions are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls visibility of file name extensions\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-show-hidden-files\",\n Name = \"Show Hidden Files, Folders & Drives\",\n Description = \"Controls visibility of hidden files and folders\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"Hidden\",\n RecommendedValue = 1,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls visibility of hidden files, folders and drives\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-hide-protected-files\",\n Name = \"Hide Protected Operating System Files\",\n Description = \"Controls visibility of protected operating system files\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowSuperHidden\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls visibility of protected operating system files\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-folder-tips\",\n Name = \"Folder Tips\",\n Description = \"Controls file size information in folder tips\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"FolderContentsInfoTip\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, folder tips are enabled\n DisabledValue = 0, // When toggle is OFF, folder tips are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls file size information in folder tips\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-popup-descriptions\",\n Name = \"Pop-up Descriptions\",\n Description = \"Controls pop-up descriptions for folder and desktop items\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowInfoTip\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, pop-up descriptions are shown\n DisabledValue = 0, // When toggle is OFF, pop-up descriptions are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description =\n \"Controls pop-up descriptions for folder and desktop items\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-preview-handlers\",\n Name = \"Preview Handlers\",\n Description = \"Controls preview handlers in preview pane\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowPreviewHandlers\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, preview handlers are enabled\n DisabledValue = 0, // When toggle is OFF, preview handlers are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls preview handlers in preview pane\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-status-bar\",\n Name = \"Status Bar\",\n Description = \"Controls status bar visibility in File Explorer\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowStatusBar\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, status bar is shown\n DisabledValue = 0, // When toggle is OFF, status bar is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls status bar visibility in File Explorer\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-show-thumbnails\",\n Name = \"Show Thumbnails\",\n Description = \"Controls whether to show thumbnails or icons\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"IconsOnly\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, thumbnails are shown\n DisabledValue = 1, // When toggle is OFF, icons are shown\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls whether to show thumbnails or icons\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-translucent-selection\",\n Name = \"Translucent Selection\",\n Description = \"Controls translucent selection rectangle\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ListviewAlphaSelect\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, translucent selection is enabled\n DisabledValue = 0, // When toggle is OFF, translucent selection is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls translucent selection rectangle\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-drop-shadows\",\n Name = \"Drop Shadows\",\n Description = \"Controls drop shadows for icon labels\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ListviewShadow\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, drop shadows are enabled\n DisabledValue = 0, // When toggle is OFF, drop shadows are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls drop shadows for icon labels\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-full-path\",\n Name = \"Full Path in Title Bar\",\n Description = \"Controls full path display in the title bar\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\CabinetState\",\n Name = \"FullPath\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, full path is shown\n DisabledValue = 0, // When toggle is OFF, full path is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls full path display in the title bar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-font-smoothing\",\n Name = \"Font Smoothing\",\n Description = \"Controls smooth edges of screen fonts\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"FontSmoothing\",\n RecommendedValue = \"2\",\n EnabledValue = \"2\", // When toggle is ON, font smoothing is enabled\n DisabledValue = \"0\", // When toggle is OFF, font smoothing is disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = \"0\", // Default value when registry key exists but no value is set\n Description = \"Controls smooth edges of screen fonts\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-dpi-scaling\",\n Name = \"DPI Scaling (100%)\",\n Description = \"Controls DPI scaling setting\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"LogPixels\",\n RecommendedValue = 96,\n EnabledValue = 96, // When toggle is ON, DPI scaling is set to 100%\n DisabledValue = 120, // When toggle is OFF, DPI scaling is set to 125%\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 120, // Default value when registry key exists but no value is set\n Description = \"Controls DPI scaling setting\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-per-process-dpi\",\n Name = \"Per-Process DPI\",\n Description = \"Controls per-process system DPI\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"EnablePerProcessSystemDPI\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, per-process DPI is enabled\n DisabledValue = 0, // When toggle is OFF, per-process DPI is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls per-process system DPI\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-lock-screen\",\n Name = \"Lock Screen\",\n Description = \"Controls lock screen visibility\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\Personalization\",\n Name = \"NoLockScreen\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls lock screen visibility\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-gallery\",\n Name = \"Gallery in Navigation Pane\",\n Description = \"Controls gallery visibility in navigation pane\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Desktop\\\\NameSpace\",\n Name = \"{e88865ea-0e1c-4e20-9aa6-edcd0212c87c}\",\n RecommendedValue = null,\n EnabledValue = null, // When toggle is ON, gallery is shown (key exists)\n DisabledValue = null, // When toggle is OFF, gallery is hidden (key removed)\n ValueType = RegistryValueKind.None,\n DefaultValue = null,\n Description = \"Controls gallery visibility in navigation pane\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n ActionType = RegistryActionType.Remove,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-context-menu\",\n Name = \"Classic Context Menu\",\n Description = \"Controls context menu style (classic or modern)\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Classes\\\\CLSID\\\\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\\\\InprocServer32\",\n Name = \"\",\n RecommendedValue = \"\",\n EnabledValue = null, // When toggle is ON, classic context menu is used (value is deleted)\n DisabledValue = \"\", // When toggle is OFF, modern context menu is used (empty value is set)\n ValueType = RegistryValueKind.String,\n DefaultValue = \"\", // Default value when registry key exists but no value is set\n Description = \"Controls context menu style (classic or modern)\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/WindowsThemeSettings.cs", "using Microsoft.Win32;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Enums;\nusing Winhance.Core.Features.Customize.Interfaces;\n\nnamespace Winhance.Core.Features.Customize.Models\n{\n /// \n /// Model for Windows theme settings.\n /// \n public class WindowsThemeSettings\n {\n // Registry paths and keys\n public static class Registry\n {\n public const string ThemesPersonalizeSubKey = @\"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\";\n public const string AppsUseLightThemeName = \"AppsUseLightTheme\";\n public const string SystemUsesLightThemeName = \"SystemUsesLightTheme\";\n }\n\n // Wallpaper paths\n public static class Wallpaper\n {\n // Windows 11 wallpaper paths\n public const string Windows11BasePath = @\"C:\\Windows\\Web\\Wallpaper\\Windows\";\n public const string Windows11LightWallpaper = \"img0.jpg\";\n public const string Windows11DarkWallpaper = \"img19.jpg\";\n\n // Windows 10 wallpaper path\n public const string Windows10Wallpaper = @\"C:\\Windows\\Web\\4K\\Wallpaper\\Windows\\img0_3840x2160.jpg\";\n\n public static string GetDefaultWallpaperPath(bool isWindows11, bool isDarkMode)\n {\n if (isWindows11)\n {\n return System.IO.Path.Combine(\n Windows11BasePath, \n isDarkMode ? Windows11DarkWallpaper : Windows11LightWallpaper);\n }\n \n return Windows10Wallpaper;\n }\n }\n\n private readonly IThemeService _themeService;\n private bool _isDarkMode;\n private bool _changeWallpaper;\n\n /// \n /// Gets or sets a value indicating whether dark mode is enabled.\n /// \n public bool IsDarkMode\n {\n get => _isDarkMode;\n set => _isDarkMode = value;\n }\n\n /// \n /// Gets or sets a value indicating whether to change the wallpaper when changing the theme.\n /// \n public bool ChangeWallpaper\n {\n get => _changeWallpaper;\n set => _changeWallpaper = value;\n }\n\n /// \n /// Gets the current theme name.\n /// \n public string ThemeName => IsDarkMode ? \"Dark Mode\" : \"Light Mode\";\n\n /// \n /// Gets the available theme options.\n /// \n public List ThemeOptions { get; } = new List { \"Light Mode\", \"Dark Mode\" };\n\n /// \n /// Initializes a new instance of the class.\n /// \n public WindowsThemeSettings()\n {\n // Default constructor for serialization\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The theme service.\n public WindowsThemeSettings(IThemeService themeService)\n {\n _themeService = themeService;\n _isDarkMode = themeService?.IsDarkModeEnabled() ?? false;\n }\n\n /// \n /// Loads the current theme settings from the system.\n /// \n public void LoadCurrentSettings()\n {\n if (_themeService != null)\n {\n _isDarkMode = _themeService.IsDarkModeEnabled();\n }\n }\n\n /// \n /// Applies the current theme settings to the system.\n /// \n /// True if the operation succeeded; otherwise, false.\n public bool ApplyTheme()\n {\n return _themeService?.SetThemeMode(_isDarkMode) ?? false;\n }\n\n /// \n /// Applies the current theme settings to the system asynchronously.\n /// \n /// A task representing the asynchronous operation.\n public async Task ApplyThemeAsync()\n {\n if (_themeService == null)\n return false;\n\n return await _themeService.ApplyThemeAsync(_isDarkMode, _changeWallpaper);\n }\n\n /// \n /// Creates registry settings for Windows theme.\n /// \n /// A list of registry settings.\n public static List CreateRegistrySettings()\n {\n return new List\n {\n new RegistrySetting\n {\n Category = \"WindowsTheme\",\n Hive = RegistryHive.CurrentUser,\n SubKey = Registry.ThemesPersonalizeSubKey,\n Name = Registry.AppsUseLightThemeName,\n EnabledValue = 0, // Dark mode\n DisabledValue = 1, // Light mode\n ValueType = RegistryValueKind.DWord,\n Description = \"Windows Apps Theme Mode\",\n // For backward compatibility\n RecommendedValue = 0,\n DefaultValue = 1\n },\n new RegistrySetting\n {\n Category = \"WindowsTheme\",\n Hive = RegistryHive.CurrentUser,\n SubKey = Registry.ThemesPersonalizeSubKey,\n Name = Registry.SystemUsesLightThemeName,\n EnabledValue = 0, // Dark mode\n DisabledValue = 1, // Light mode\n ValueType = RegistryValueKind.DWord,\n Description = \"Windows System Theme Mode\",\n // For backward compatibility\n RecommendedValue = 0,\n DefaultValue = 1\n }\n };\n }\n\n /// \n /// Creates a customization setting for Windows theme.\n /// \n /// A customization setting.\n public static CustomizationSetting CreateCustomizationSetting()\n {\n var setting = new CustomizationSetting\n {\n Id = \"WindowsTheme\",\n Name = \"Windows Theme\",\n Description = \"Toggle between light and dark theme for Windows\",\n GroupName = \"Windows Theme\",\n Category = CustomizationCategory.Theme,\n ControlType = ControlType.ComboBox,\n RegistrySettings = CreateRegistrySettings()\n };\n\n return setting;\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Extensions/WinGetProgressExtensions.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Extensions\n{\n /// \n /// Extension methods for specific to WinGet operations.\n /// \n public static class WinGetProgressExtensions\n {\n /// \n /// Tracks the progress of a WinGet installation operation.\n /// \n /// The progress service.\n /// The asynchronous operation to track.\n /// The display name of the application.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the result.\n public static async Task TrackWinGetInstallationAsync(\n this ITaskProgressService progressService,\n Func, Task> operation,\n string displayName,\n CancellationToken cancellationToken = default\n )\n {\n if (progressService == null)\n throw new ArgumentNullException(nameof(progressService));\n if (operation == null)\n throw new ArgumentNullException(nameof(operation));\n\n var progress = new Progress(p =>\n {\n progressService.UpdateDetailedProgress(\n new TaskProgressDetail\n {\n Progress = p.Percentage,\n StatusText = $\"Installing {displayName}: {p.Status}\",\n IsIndeterminate = p.IsIndeterminate,\n }\n );\n });\n\n try\n {\n return await operation(progress).ConfigureAwait(false);\n }\n catch (Exception ex)\n {\n progressService.UpdateProgress(0, $\"Failed to install {displayName}: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Tracks the progress of a WinGet upgrade operation.\n /// \n /// The progress service.\n /// The asynchronous operation to track.\n /// The display name of the application.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the result.\n public static async Task TrackWinGetUpgradeAsync(\n this ITaskProgressService progressService,\n Func, Task> operation,\n string displayName,\n CancellationToken cancellationToken = default\n )\n {\n if (progressService == null)\n throw new ArgumentNullException(nameof(progressService));\n if (operation == null)\n throw new ArgumentNullException(nameof(operation));\n\n var progress = new Progress(p =>\n {\n progressService.UpdateDetailedProgress(\n new TaskProgressDetail\n {\n Progress = p.Percentage,\n StatusText = $\"Upgrading {displayName}: {p.Status}\",\n IsIndeterminate = p.IsIndeterminate,\n }\n );\n });\n\n try\n {\n return await operation(progress).ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n progressService.UpdateProgress(0, $\"Upgrade of {displayName} was cancelled\");\n return new UpgradeResult\n {\n Success = false,\n Message = $\"Upgrade of {displayName} was cancelled by user\",\n PackageId = displayName\n };\n }\n catch (Exception ex)\n {\n progressService.UpdateProgress(0, $\"Failed to upgrade {displayName}: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Tracks the progress of a WinGet uninstallation operation.\n /// \n /// The progress service.\n /// The asynchronous operation to track.\n /// The display name of the application.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the result.\n public static async Task TrackWinGetUninstallationAsync(\n this ITaskProgressService progressService,\n Func, Task> operation,\n string displayName,\n CancellationToken cancellationToken = default\n )\n {\n if (progressService == null)\n throw new ArgumentNullException(nameof(progressService));\n if (operation == null)\n throw new ArgumentNullException(nameof(operation));\n\n var progress = new Progress(p =>\n {\n progressService.UpdateDetailedProgress(\n new TaskProgressDetail\n {\n Progress = p.Percentage,\n StatusText = $\"Uninstalling {displayName}: {p.Status}\",\n IsIndeterminate = p.IsIndeterminate,\n }\n );\n });\n\n try\n {\n return await operation(progress).ConfigureAwait(false);\n }\n catch (Exception ex)\n {\n progressService.UpdateProgress(0, $\"Failed to uninstall {displayName}: {ex.Message}\");\n throw;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/GamingandPerformanceOptimizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class GamingandPerformanceOptimizations\n{\n public static OptimizationGroup GetGamingandPerformanceOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Gaming and Performance\",\n Category = OptimizationCategory.GamingandPerformance,\n Settings = new List\n {\n new OptimizationSetting\n {\n Id = \"gaming-xbox-game-dvr\",\n Name = \"Xbox Game DVR\",\n Description = \"Controls Xbox Game DVR functionality\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Game Recording\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"System\\\\GameConfigStore\",\n Name = \"GameDVR_Enabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Game DVR is enabled\n DisabledValue = 0, // When toggle is OFF, Game DVR is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Game Bar and Game DVR functionality\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\GameConfigStore\",\n Name = \"AllowGameDVR\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Xbox Game DVR is enabled\n DisabledValue = 0, // When toggle is OFF, Xbox Game DVR is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Xbox GameDVR functionality\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"gaming-game-bar-controller\",\n Name = \"Game Bar Controller Access\",\n Description = \"Allow your controller to open Game Bar\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Game Bar\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\GameBar\",\n Name = \"UseNexusForGameBarEnabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, controller access is enabled\n DisabledValue = 0, // When toggle is OFF, controller access is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Xbox Game Bar access via game controller\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-game-mode\",\n Name = \"Game Mode\",\n Description = \"Controls Game Mode for optimized gaming performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Game Mode\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\GameBar\",\n Name = \"AutoGameModeEnabled\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Game Mode is enabled\n DisabledValue = 0, // When toggle is OFF, Game Mode is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Game Mode for optimized gaming performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-directx-optimizations\",\n Name = \"DirectX Optimizations\",\n Description = \"Changes DirectX settings for optimal gaming performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"DirectX\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\DirectX\\\\UserGpuPreferences\",\n Name = \"DirectXUserGlobalSettings\",\n RecommendedValue = \"SwapEffectUpgradeEnable=1;VRROptimizeEnable=0;\", // For backward compatibility\n EnabledValue = \"SwapEffectUpgradeEnable=1;VRROptimizeEnable=0;\", // When toggle is ON, optimizations are enabled\n DisabledValue = \"\", // When toggle is OFF, use default settings\n ValueType = RegistryValueKind.String,\n DefaultValue = \"SwapEffectUpgradeEnable=1;VRROptimizeEnable=0;\", // Default value when registry key exists but no value is set\n Description =\n \"Controls DirectX settings for optimal gaming performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-nvidia-sharpening\",\n Name = \"Old Nvidia Sharpening\",\n Description = \"Controls Nvidia sharpening for image quality\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Nvidia\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"Software\\\\NVIDIA Corporation\\\\Global\\\\FTS\",\n Name = \"EnableGR535\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, old Nvidia sharpening is enabled (0 = enabled for this setting)\n DisabledValue = 1, // When toggle is OFF, old Nvidia sharpening is disabled (1 = disabled for this setting)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Nvidia sharpening for image quality\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-high-precision-event-timer\",\n Name = \"High Precision Event Timer\",\n Description = \"Controls the High Precision Event Timer (HPET) for improved system performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CommandSettings = new List\n {\n new CommandSetting\n {\n Id = \"hpet-platform-clock\",\n Category = \"Gaming\",\n Description = \"Controls the platform clock setting for HPET\",\n EnabledCommand = \"bcdedit /set useplatformclock true\",\n DisabledCommand = \"bcdedit /deletevalue useplatformclock\",\n RequiresElevation = true,\n IsPrimary = true\n },\n new CommandSetting\n {\n Id = \"hpet-dynamic-tick\",\n Category = \"Gaming\",\n Description = \"Controls the dynamic tick setting for HPET\",\n EnabledCommand = \"bcdedit /set disabledynamictick no\",\n DisabledCommand = \"bcdedit /set disabledynamictick yes\",\n RequiresElevation = true,\n IsPrimary = false\n }\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"gaming-system-responsiveness\",\n Name = \"System Responsiveness for Games\",\n Description = \"Controls system responsiveness for multimedia applications\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Multimedia\\\\SystemProfile\",\n Name = \"SystemResponsiveness\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, system responsiveness is optimized for games (0 = prioritize foreground)\n DisabledValue = 10, // When toggle is OFF, system responsiveness is balanced (10 = default Windows value)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 10, // Default value when registry key exists but no value is set\n Description =\n \"Controls system responsiveness for multimedia applications\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-network-throttling\",\n Name = \"Network Throttling for Gaming\",\n Description = \"Controls network throttling for optimal gaming performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Multimedia\\\\SystemProfile\",\n Name = \"NetworkThrottlingIndex\",\n RecommendedValue = 10, // For backward compatibility\n EnabledValue = 10, // When toggle is ON, network throttling is disabled (10 = disabled)\n DisabledValue = 5, // When toggle is OFF, network throttling is enabled (default Windows value)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 5, // Default value when registry key exists but no value is set\n Description =\n \"Controls network throttling for optimal gaming performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-gpu-priority\",\n Name = \"GPU Priority for Gaming\",\n Description = \"Controls GPU priority for gaming performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Multimedia\\\\SystemProfile\\\\Tasks\\\\Games\",\n Name = \"GPU Priority\",\n RecommendedValue = 8, // For backward compatibility\n EnabledValue = 8, // When toggle is ON, GPU priority is high (8 = high priority)\n DisabledValue = 2, // When toggle is OFF, GPU priority is normal (default Windows value)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls GPU priority for gaming performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-cpu-priority\",\n Name = \"CPU Priority for Gaming\",\n Description = \"Controls CPU priority for gaming performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Multimedia\\\\SystemProfile\\\\Tasks\\\\Games\",\n Name = \"Priority\",\n RecommendedValue = 6, // For backward compatibility\n EnabledValue = 6, // When toggle is ON, CPU priority is high (6 = high priority)\n DisabledValue = 2, // When toggle is OFF, CPU priority is normal (default Windows value)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls CPU priority for gaming performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-scheduling-category\",\n Name = \"High Scheduling Category for Gaming\",\n Description = \"Controls scheduling category for games\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Multimedia\\\\SystemProfile\\\\Tasks\\\\Games\",\n Name = \"Scheduling Category\",\n RecommendedValue = \"High\", // For backward compatibility\n EnabledValue = \"High\", // When toggle is ON, scheduling category is high\n DisabledValue = \"Medium\", // When toggle is OFF, scheduling category is medium (default Windows value)\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Medium\", // Default value when registry key exists but no value is set\n Description = \"Controls scheduling category for games\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-gpu-scheduling\",\n Name = \"Hardware-Accelerated GPU Scheduling\",\n Description = \"Controls hardware-accelerated GPU scheduling\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"System\\\\CurrentControlSet\\\\Control\\\\GraphicsDrivers\",\n Name = \"HwSchMode\",\n RecommendedValue = 2, // For backward compatibility\n EnabledValue = 2, // When toggle is ON, hardware-accelerated GPU scheduling is enabled\n DisabledValue = 1, // When toggle is OFF, hardware-accelerated GPU scheduling is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls hardware-accelerated GPU scheduling\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-win32-priority\",\n Name = \"Win32 Priority Separation\",\n Description = \"Controls Win32 priority separation for program performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"System\\\\CurrentControlSet\\\\Control\\\\PriorityControl\",\n Name = \"Win32PrioritySeparation\",\n RecommendedValue = 38, // For backward compatibility\n EnabledValue = 38, // When toggle is ON, priority is set for best performance of programs\n DisabledValue = 2, // When toggle is OFF, priority is set to default Windows value\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description =\n \"Controls Win32 priority separation for program performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-storage-sense\",\n Name = \"Storage Sense\",\n Description = \"Controls Storage Sense functionality\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\StorageSense\",\n Name = \"AllowStorageSenseGlobal\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Storage Sense is enabled\n DisabledValue = 0, // When toggle is OFF, Storage Sense is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Storage Sense functionality\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-animations\",\n Name = \"UI Animations\",\n Description = \"Controls UI animations for improved performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Visual Effects\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\\\\WindowMetrics\",\n Name = \"MinAnimate\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, animations are enabled\n DisabledValue = 0, // When toggle is OFF, animations are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls UI animations for improved performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-autostart-delay\",\n Name = \"Startup Delay for Apps\",\n Description = \"Controls startup delay for applications\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Startup\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Serialize\",\n Name = \"StartupDelayInMSec\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 10000, // When toggle is ON, startup delay is enabled (10 seconds)\n DisabledValue = 0, // When toggle is OFF, startup delay is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls startup delay for applications\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-background-services\",\n Name = \"Optimize Background Services\",\n Description = \"Controls background services for better performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Services\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\",\n Name = \"ServicesPipeTimeout\",\n RecommendedValue = 60000, // For backward compatibility\n EnabledValue = 30000, // When toggle is ON, services timeout is reduced (30 seconds)\n DisabledValue = 60000, // When toggle is OFF, services timeout is default (60 seconds)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 60000, // Default value when registry key exists but no value is set\n Description = \"Controls background services for better performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-desktop-composition\",\n Name = \"Desktop Composition Effects\",\n Description = \"Controls desktop composition effects\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Visual Effects\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\DWM\",\n Name = \"CompositionPolicy\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, desktop composition is enabled\n DisabledValue = 0, // When toggle is OFF, desktop composition is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls desktop composition effects\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-fast-startup\",\n Name = \"Fast Startup\",\n Description = \"Controls fast startup feature\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Startup\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Power\",\n Name = \"HiberbootEnabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, fast startup is enabled\n DisabledValue = 0, // When toggle is OFF, fast startup is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls fast startup feature\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-explorer-search\",\n Name = \"Optimize File Explorer Search\",\n Description = \"Controls file explorer search indexing\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Search\\\\Preferences\",\n Name = \"WholeFileSystem\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, search includes whole file system\n DisabledValue = 0, // When toggle is OFF, search is limited to indexed locations\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls file explorer search indexing\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-menu-animations\",\n Name = \"Menu Animations\",\n Description = \"Controls menu animations\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Visual Effects\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"MenuShowDelay\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 400, // When toggle is ON, menu animations are enabled (default delay)\n DisabledValue = 0, // When toggle is OFF, menu animations are disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = 400, // Default value when registry key exists but no value is set\n Description = \"Controls menu animations\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-prefetch\",\n Name = \"Prefetch Feature\",\n Description = \"Controls Windows prefetch feature\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Memory Management\\\\PrefetchParameters\",\n Name = \"EnablePrefetcher\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 3, // When toggle is ON, prefetch is enabled (3 = both application and boot prefetching)\n DisabledValue = 0, // When toggle is OFF, prefetch is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls Windows prefetch feature\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-remote-assistance\",\n Name = \"Remote Assistance\",\n Description = \"Controls remote assistance feature\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Services\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Remote Assistance\",\n Name = \"fAllowToGetHelp\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, remote assistance is enabled\n DisabledValue = 0, // When toggle is OFF, remote assistance is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls remote assistance feature\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-superfetch\",\n Name = \"Superfetch Service\",\n Description = \"Controls superfetch/SysMain service\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Memory Management\\\\PrefetchParameters\",\n Name = \"EnableSuperfetch\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 3, // When toggle is ON, superfetch is enabled (3 = full functionality)\n DisabledValue = 0, // When toggle is OFF, superfetch is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls superfetch/SysMain service\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-visual-effects\",\n Name = \"Optimize Visual Effects\",\n Description = \"Controls visual effects for best performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Visual Effects\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\VisualEffects\",\n Name = \"VisualFXSetting\",\n RecommendedValue = 2, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, visual effects are set to \"best appearance\" (1)\n DisabledValue = 2, // When toggle is OFF, visual effects are set to \"best performance\" (2)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls visual effects for best performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-mouse-precision\",\n Name = \"Enhanced Pointer Precision\",\n Description = \"Controls enhanced pointer precision (mouse acceleration)\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Mouse Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"MouseSpeed\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, enhanced pointer precision is enabled\n DisabledValue = 0, // When toggle is OFF, enhanced pointer precision is disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Controls enhanced pointer precision (mouse acceleration)\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-mouse-threshold1\",\n Name = \"Mouse Acceleration Threshold 1\",\n Description = \"Controls mouse acceleration threshold 1\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Mouse Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"MouseThreshold1\",\n RecommendedValue = 0,\n EnabledValue = 6, // When toggle is ON, mouse threshold 1 is enabled (default value)\n DisabledValue = 0, // When toggle is OFF, mouse threshold 1 is disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls mouse acceleration threshold 1\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-mouse-threshold2\",\n Name = \"Mouse Acceleration Threshold 2\",\n Description = \"Controls mouse acceleration threshold 2\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Mouse Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"MouseThreshold2\",\n RecommendedValue = 0,\n EnabledValue = 10, // When toggle is ON, mouse threshold 2 is enabled (default value)\n DisabledValue = 0, // When toggle is OFF, mouse threshold 2 is disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls mouse acceleration threshold 2\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-set-mouse-sensitivity\",\n Name = \"Set Mouse Sensitivity\",\n Description = \"Sets mouse sensitivity to 10\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"MouseSensitivity\",\n RecommendedValue = 10,\n EnabledValue = 10,\n DisabledValue = \"\", // Sets to default\n ValueType = RegistryValueKind.String,\n DefaultValue = \"\", // Default value when registry key exists but no value is set\n Description = \"Sets mouse sensitivity to 10\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-set-smooth-mouse-x-curve\",\n Name = \"Set Smooth Mouse X Curve\",\n Description = \"Sets SmoothMouseXCurve\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"SmoothMouseXCurve\",\n RecommendedValue = new byte[]\n {\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xC0,\n 0xCC,\n 0x0C,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x80,\n 0x99,\n 0x19,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x40,\n 0x66,\n 0x26,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x33,\n 0x33,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n },\n ValueType = RegistryValueKind.Binary,\n DefaultValue = new byte[]\n {\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xC0,\n 0xCC,\n 0x0C,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x80,\n 0x99,\n 0x19,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x40,\n 0x66,\n 0x26,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x33,\n 0x33,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n },\n Description = \"Sets SmoothMouseXCurve\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-set-smooth-mouse-y-curve\",\n Name = \"Set Smooth Mouse Y Curve\",\n Description = \"Sets SmoothMouseYCurve\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"SmoothMouseYCurve\",\n RecommendedValue = new byte[]\n {\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x38,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x70,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xA8,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xE0,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n },\n ValueType = RegistryValueKind.Binary,\n DefaultValue = new byte[]\n {\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x38,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x70,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xA8,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xE0,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n },\n Description = \"Sets SmoothMouseYCurve\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-animations\",\n Name = \"System Animations\",\n Description = \"Controls animations and visual effects\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"UserPreferencesMask\",\n RecommendedValue = new byte[]\n {\n 0x90,\n 0x12,\n 0x03,\n 0x80,\n 0x10,\n 0x00,\n 0x00,\n 0x00,\n },\n EnabledValue = new byte[]\n {\n 0x9E,\n 0x3E,\n 0x07,\n 0x80,\n 0x12,\n 0x00,\n 0x00,\n 0x00,\n }, // When toggle is ON, animations are enabled\n DisabledValue = new byte[]\n {\n 0x90,\n 0x12,\n 0x03,\n 0x80,\n 0x10,\n 0x00,\n 0x00,\n 0x00,\n }, // When toggle is OFF, animations are disabled\n ValueType = RegistryValueKind.Binary,\n DefaultValue = new byte[]\n {\n 0x90,\n 0x12,\n 0x03,\n 0x80,\n 0x10,\n 0x00,\n 0x00,\n 0x00,\n },\n Description = \"Controls animations and visual effects\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-menu-show-delay\",\n Name = \"Menu Show Delay\",\n Description = \"Controls menu show delay\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"MenuShowDelay\",\n RecommendedValue = 0,\n EnabledValue = 400, // When toggle is ON, menu show delay is enabled (default value)\n DisabledValue = 0, // When toggle is OFF, menu show delay is disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = 400, // Default value when registry key exists but no value is set\n Description = \"Controls menu show delay\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-set-visual-effects\",\n Name = \"Set Visual Effects\",\n Description = \"Sets appearance options to custom\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\VisualEffects\",\n Name = \"VisualFXSetting\",\n RecommendedValue = 3,\n EnabledValue = 3,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Sets appearance options to custom\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-taskbar-animations\",\n Name = \"Taskbar Animations\",\n Description = \"Controls taskbar animations\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"TaskbarAnimations\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, taskbar animations are enabled\n DisabledValue = 0, // When toggle is OFF, taskbar animations are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls taskbar animations\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"background-apps\",\n Name = \"Let Apps Run in Background\",\n Description = \"Controls whether apps can run in the background\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Background Apps\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\AppPrivacy\",\n Name = \"LetAppsRunInBackground\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, background apps are enabled\n DisabledValue = 0, // When toggle is OFF, background apps are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls whether apps can run in the background\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-alt-tab-filter\",\n Name = \"Alt+Tab Filter\",\n Description = \"Sets Alt+Tab to show open windows only\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"MultiTaskingAltTabFilter\",\n RecommendedValue = 3,\n EnabledValue = 3,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Sets Alt+Tab to show open windows only\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Behaviors/ResponsiveLayoutBehavior.cs", "using System.Windows;\nusing System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Common.Behaviors\n{\n /// \n /// Provides attached properties and behaviors for responsive layouts\n /// \n public static class ResponsiveLayoutBehavior\n {\n #region ItemWidth Attached Property\n\n /// \n /// Gets the ItemWidth value\n /// \n public static double GetItemWidth(DependencyObject obj)\n {\n return (double)obj.GetValue(ItemWidthProperty);\n }\n\n /// \n /// Sets the ItemWidth value\n /// \n public static void SetItemWidth(DependencyObject obj, double value)\n {\n obj.SetValue(ItemWidthProperty, value);\n }\n\n /// \n /// ItemWidth Attached Dependency Property\n /// \n public static readonly DependencyProperty ItemWidthProperty =\n DependencyProperty.RegisterAttached(\n \"ItemWidth\",\n typeof(double),\n typeof(ResponsiveLayoutBehavior),\n new PropertyMetadata(200.0, OnItemWidthChanged));\n\n /// \n /// Called when ItemWidth is changed\n /// \n private static void OnItemWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is FrameworkElement element)\n {\n element.Width = (double)e.NewValue;\n }\n }\n\n #endregion\n\n #region MinItemWidth Attached Property\n\n /// \n /// Gets the MinItemWidth value\n /// \n public static double GetMinItemWidth(DependencyObject obj)\n {\n return (double)obj.GetValue(MinItemWidthProperty);\n }\n\n /// \n /// Sets the MinItemWidth value\n /// \n public static void SetMinItemWidth(DependencyObject obj, double value)\n {\n obj.SetValue(MinItemWidthProperty, value);\n }\n\n /// \n /// MinItemWidth Attached Dependency Property\n /// \n public static readonly DependencyProperty MinItemWidthProperty =\n DependencyProperty.RegisterAttached(\n \"MinItemWidth\",\n typeof(double),\n typeof(ResponsiveLayoutBehavior),\n new PropertyMetadata(150.0, OnMinItemWidthChanged));\n\n /// \n /// Called when MinItemWidth is changed\n /// \n private static void OnMinItemWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is FrameworkElement element)\n {\n element.MinWidth = (double)e.NewValue;\n }\n }\n\n #endregion\n\n #region WrapPanelMaxWidth Attached Property\n\n /// \n /// Gets the WrapPanelMaxWidth value\n /// \n public static double GetWrapPanelMaxWidth(DependencyObject obj)\n {\n return (double)obj.GetValue(WrapPanelMaxWidthProperty);\n }\n\n /// \n /// Sets the WrapPanelMaxWidth value\n /// \n public static void SetWrapPanelMaxWidth(DependencyObject obj, double value)\n {\n obj.SetValue(WrapPanelMaxWidthProperty, value);\n }\n\n /// \n /// WrapPanelMaxWidth Attached Dependency Property\n /// \n public static readonly DependencyProperty WrapPanelMaxWidthProperty =\n DependencyProperty.RegisterAttached(\n \"WrapPanelMaxWidth\",\n typeof(double),\n typeof(ResponsiveLayoutBehavior),\n new PropertyMetadata(1000.0));\n\n #endregion\n\n #region MaxItemWidth Attached Property\n\n /// \n /// Gets the MaxItemWidth value\n /// \n public static double GetMaxItemWidth(DependencyObject obj)\n {\n return (double)obj.GetValue(MaxItemWidthProperty);\n }\n\n /// \n /// Sets the MaxItemWidth value\n /// \n public static void SetMaxItemWidth(DependencyObject obj, double value)\n {\n obj.SetValue(MaxItemWidthProperty, value);\n }\n\n /// \n /// MaxItemWidth Attached Dependency Property\n /// \n public static readonly DependencyProperty MaxItemWidthProperty =\n DependencyProperty.RegisterAttached(\n \"MaxItemWidth\",\n typeof(double),\n typeof(ResponsiveLayoutBehavior),\n new PropertyMetadata(400.0, OnMaxItemWidthChanged));\n\n /// \n /// Called when MaxItemWidth is changed\n /// \n private static void OnMaxItemWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is FrameworkElement element)\n {\n element.MaxWidth = (double)e.NewValue;\n }\n }\n\n #endregion\n\n #region UseWrapPanel Attached Property\n\n /// \n /// Gets the UseWrapPanel value\n /// \n public static bool GetUseWrapPanel(DependencyObject obj)\n {\n return (bool)obj.GetValue(UseWrapPanelProperty);\n }\n\n /// \n /// Sets the UseWrapPanel value\n /// \n public static void SetUseWrapPanel(DependencyObject obj, bool value)\n {\n obj.SetValue(UseWrapPanelProperty, value);\n }\n\n /// \n /// UseWrapPanel Attached Dependency Property\n /// \n public static readonly DependencyProperty UseWrapPanelProperty =\n DependencyProperty.RegisterAttached(\n \"UseWrapPanel\",\n typeof(bool),\n typeof(ResponsiveLayoutBehavior),\n new PropertyMetadata(false, OnUseWrapPanelChanged));\n\n /// \n /// Called when UseWrapPanel is changed\n /// \n private static void OnUseWrapPanelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is ItemsControl itemsControl && (bool)e.NewValue)\n {\n // Get the WrapPanelMaxWidth value or use the default\n double maxWidth = GetWrapPanelMaxWidth(itemsControl);\n\n // Create a WrapPanel for the ItemsPanel\n var wrapPanel = new WrapPanel\n {\n Orientation = Orientation.Horizontal,\n MaxWidth = maxWidth,\n HorizontalAlignment = HorizontalAlignment.Left\n };\n \n // Add resources to the WrapPanel\n var wrapPanelStyle = new Style(typeof(ContentPresenter));\n wrapPanelStyle.Setters.Add(new Setter(FrameworkElement.MarginProperty, new Thickness(0, 5, 10, 5)));\n wrapPanel.Resources.Add(typeof(ContentPresenter), wrapPanelStyle);\n\n // Set the ItemsPanel template\n var template = new ItemsPanelTemplate();\n template.VisualTree = new FrameworkElementFactory(typeof(WrapPanel));\n template.VisualTree.SetValue(WrapPanel.OrientationProperty, Orientation.Horizontal);\n template.VisualTree.SetValue(WrapPanel.MaxWidthProperty, maxWidth);\n template.VisualTree.SetValue(WrapPanel.HorizontalAlignmentProperty, HorizontalAlignment.Left);\n \n // Add resources to the template\n var resourceDictionary = new ResourceDictionary();\n var contentPresenterStyle = new Style(typeof(ContentPresenter));\n contentPresenterStyle.Setters.Add(new Setter(FrameworkElement.MarginProperty, new Thickness(0, 5, 10, 5)));\n resourceDictionary.Add(typeof(ContentPresenter), contentPresenterStyle);\n template.Resources = resourceDictionary;\n \n // Set item spacing through the ItemContainerStyle\n var style = new Style(typeof(ContentPresenter));\n style.Setters.Add(new Setter(FrameworkElement.MarginProperty, new Thickness(0, 5, 10, 5)));\n style.Setters.Add(new Setter(FrameworkElement.WidthProperty, 250.0));\n style.Setters.Add(new Setter(FrameworkElement.MinWidthProperty, 250.0));\n style.Setters.Add(new Setter(FrameworkElement.MaxWidthProperty, 250.0));\n \n if (itemsControl.ItemContainerStyle == null)\n {\n itemsControl.ItemContainerStyle = style;\n }\n\n itemsControl.ItemsPanel = template;\n }\n }\n\n #endregion\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/SpecialAppHandler.cs", "using System;\nusing System.IO;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a handler for special applications that require custom removal processes.\n/// \npublic class SpecialAppHandler\n{\n /// \n /// Gets or sets the unique identifier for the special handler type.\n /// \n public string HandlerType { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the display name of the application.\n /// \n public string DisplayName { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the description of the application.\n /// \n public string Description { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the script content for removing the application.\n /// \n public string RemovalScriptContent { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the name of the scheduled task to create for preventing reinstallation.\n /// \n public string ScheduledTaskName { get; init; } = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether the application is currently installed.\n /// \n public bool IsInstalled { get; set; }\n\n /// \n /// Gets the path where the removal script will be saved.\n /// \n public string ScriptPath => Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n \"Winhance\",\n \"Scripts\",\n $\"{HandlerType}Removal.ps1\");\n\n /// \n /// Gets a collection of predefined special app handlers.\n /// \n /// A collection of special app handlers.\n public static SpecialAppHandler[] GetPredefinedHandlers()\n {\n return new[]\n {\n new SpecialAppHandler\n {\n HandlerType = \"Edge\",\n DisplayName = \"Microsoft Edge\",\n Description = \"Microsoft's web browser (requires special removal process)\",\n RemovalScriptContent = GetEdgeRemovalScript(),\n ScheduledTaskName = \"Winhance\\\\EdgeRemoval\"\n },\n new SpecialAppHandler\n {\n HandlerType = \"OneDrive\",\n DisplayName = \"OneDrive\",\n Description = \"Microsoft's cloud storage service (requires special removal process)\",\n RemovalScriptContent = GetOneDriveRemovalScript(),\n ScheduledTaskName = \"Winhance\\\\OneDriveRemoval\"\n },\n new SpecialAppHandler\n {\n HandlerType = \"OneNote\",\n DisplayName = \"Microsoft OneNote\",\n Description = \"Microsoft's note-taking application (requires special removal process)\",\n RemovalScriptContent = GetOneNoteRemovalScript(),\n ScheduledTaskName = \"Winhance\\\\OneNoteRemoval\"\n },\n };\n }\n\n private static string GetEdgeRemovalScript()\n {\n return @\"\n# EdgeRemoval.ps1\n# Standalone script to remove Microsoft Edge\n# Source: Winhance (https://github.com/memstechtips/Winhance)\n\n# stop edge running\n$stop = \"\"MicrosoftEdgeUpdate\"\", \"\"OneDrive\"\", \"\"WidgetService\"\", \"\"Widgets\"\", \"\"msedge\"\", \"\"msedgewebview2\"\"\n$stop | ForEach-Object { Stop-Process -Name $_ -Force -ErrorAction SilentlyContinue }\n# uninstall copilot\nGet-AppxPackage -allusers *Microsoft.Windows.Ai.Copilot.Provider* | Remove-AppxPackage\n# disable edge updates regedit\nreg add \"\"HKLM\\SOFTWARE\\Microsoft\\EdgeUpdate\"\" /v \"\"DoNotUpdateToEdgeWithChromium\"\" /t REG_DWORD /d \"\"1\"\" /f | Out-Null\n# allow edge uninstall regedit\nreg add \"\"HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\EdgeUpdateDev\"\" /v \"\"AllowUninstall\"\" /t REG_SZ /f | Out-Null\n# new folder to uninstall edge\nNew-Item -Path \"\"$env:SystemRoot\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\"\" -ItemType Directory -ErrorAction SilentlyContinue | Out-Null\n# new file to uninstall edge\nNew-Item -Path \"\"$env:SystemRoot\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\"\" -ItemType File -Name \"\"MicrosoftEdge.exe\"\" -ErrorAction SilentlyContinue | Out-Null\n# find edge uninstall string\n$regview = [Microsoft.Win32.RegistryView]::Registry32\n$microsoft = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $regview).\nOpenSubKey(\"\"SOFTWARE\\Microsoft\"\", $true)\n$uninstallregkey = $microsoft.OpenSubKey(\"\"Windows\\CurrentVersion\\Uninstall\\Microsoft Edge\"\")\ntry {\n $uninstallstring = $uninstallregkey.GetValue(\"\"UninstallString\"\") + \"\" --force-uninstall\"\"\n}\ncatch {\n}\n# uninstall edge\nStart-Process cmd.exe \"\"/c $uninstallstring\"\" -WindowStyle Hidden -Wait\n# remove folder file\nRemove-Item -Recurse -Force \"\"$env:SystemRoot\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\"\" -ErrorAction SilentlyContinue | Out-Null\n# find edgeupdate.exe\n$edgeupdate = @(); \"\"LocalApplicationData\"\", \"\"ProgramFilesX86\"\", \"\"ProgramFiles\"\" | ForEach-Object {\n $folder = [Environment]::GetFolderPath($_)\n $edgeupdate += Get-ChildItem \"\"$folder\\Microsoft\\EdgeUpdate\\*.*.*.*\\MicrosoftEdgeUpdate.exe\"\" -rec -ea 0\n}\n# find edgeupdate & allow uninstall regedit\n$global:REG = \"\"HKCU:\\SOFTWARE\"\", \"\"HKLM:\\SOFTWARE\"\", \"\"HKCU:\\SOFTWARE\\Policies\"\", \"\"HKLM:\\SOFTWARE\\Policies\"\", \"\"HKCU:\\SOFTWARE\\WOW6432Node\"\", \"\"HKLM:\\SOFTWARE\\WOW6432Node\"\", \"\"HKCU:\\SOFTWARE\\WOW6432Node\\Policies\"\", \"\"HKLM:\\SOFTWARE\\WOW6432Node\\Policies\"\"\nforeach ($location in $REG) { Remove-Item \"\"$location\\Microsoft\\EdgeUpdate\"\" -recurse -force -ErrorAction SilentlyContinue }\n# uninstall edgeupdate\nforeach ($path in $edgeupdate) {\n if (Test-Path $path) { Start-Process -Wait $path -Args \"\"/unregsvc\"\" | Out-Null }\n do { Start-Sleep 3 } while ((Get-Process -Name \"\"setup\"\", \"\"MicrosoftEdge*\"\" -ErrorAction SilentlyContinue).Path -like \"\"*\\Microsoft\\Edge*\"\")\n if (Test-Path $path) { Start-Process -Wait $path -Args \"\"/uninstall\"\" | Out-Null }\n do { Start-Sleep 3 } while ((Get-Process -Name \"\"setup\"\", \"\"MicrosoftEdge*\"\" -ErrorAction SilentlyContinue).Path -like \"\"*\\Microsoft\\Edge*\"\")\n}\n# remove edgewebview regedit\ncmd /c \"\"reg delete `\"\"HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Microsoft EdgeWebView`\"\" /f >nul 2>&1\"\"\ncmd /c \"\"reg delete `\"\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Microsoft EdgeWebView`\"\" /f >nul 2>&1\"\"\n# remove folders edge edgecore edgeupdate edgewebview temp\nRemove-Item -Recurse -Force \"\"$env:SystemDrive\\Program Files (x86)\\Microsoft\"\" -ErrorAction SilentlyContinue | Out-Null\n# remove edge shortcuts\nRemove-Item -Recurse -Force \"\"$env:SystemDrive\\Windows\\System32\\config\\systemprofile\\AppData\\Roaming\\Microsoft\\Internet Explorer\\Quick Launch\\Microsoft Edge.lnk\"\" -ErrorAction SilentlyContinue | Out-Null\nRemove-Item -Recurse -Force \"\"$env:ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Edge.lnk\"\" -ErrorAction SilentlyContinue | Out-Null\n\n$fileSystemProfiles = Get-ChildItem -Path \"\"C:\\Users\"\" -Directory | Where-Object { \n $_.Name -notin @('Public', 'Default', 'Default User', 'All Users') -and \n (Test-Path -Path \"\"$($_.FullName)\\NTUSER.DAT\"\")\n}\n\n# Loop through each user profile and clean up Edge shortcuts\nforeach ($profile in $fileSystemProfiles) {\n $userProfilePath = $profile.FullName\n \n # Define user-specific paths to clean\n $edgeShortcutPaths = @(\n \"\"$userProfilePath\\AppData\\Roaming\\Microsoft\\Internet Explorer\\Quick Launch\\Microsoft Edge.lnk\"\",\n \"\"$userProfilePath\\Desktop\\Microsoft Edge.lnk\"\",\n \"\"$userProfilePath\\AppData\\Roaming\\Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar\\Microsoft Edge.lnk\"\",\n \"\"$userProfilePath\\AppData\\Roaming\\Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar\\Tombstones\\Microsoft Edge.lnk\"\",\n \"\"$userProfilePath\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Edge.lnk\"\"\n )\n\n # Remove Edge shortcuts for each user\n foreach ($path in $edgeShortcutPaths) {\n if (Test-Path -Path $path -PathType Leaf) {\n Remove-Item -Path $path -Force -ErrorAction SilentlyContinue\n }\n }\n}\n\n# Clean up common locations\n$commonShortcutPaths = @(\n \"\"$env:PUBLIC\\Desktop\\Microsoft Edge.lnk\"\",\n \"\"$env:ALLUSERSPROFILE\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Edge.lnk\"\",\n \"\"C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Edge.lnk\"\"\n)\n\nforeach ($path in $commonShortcutPaths) {\n if (Test-Path -Path $path -PathType Leaf) {\n Remove-Item -Path $path -Force -ErrorAction SilentlyContinue\n }\n}\n\n# Removes Edge in Task Manager Startup Apps for All Users\n# Get all user profiles on the system\n$userProfiles = Get-CimInstance -ClassName Win32_UserProfile | \nWhere-Object { -not $_.Special -and $_.SID -notmatch 'S-1-5-18|S-1-5-19|S-1-5-20' }\n\nforeach ($profile in $userProfiles) {\n $sid = $profile.SID\n $hiveLoaded = $false\n\n if (-not (Test-Path \"\"Registry::HKEY_USERS\\$sid\"\")) {\n $userRegPath = Join-Path $profile.LocalPath \"\"NTUSER.DAT\"\"\n if (Test-Path $userRegPath) {\n reg load \"\"HKU\\$sid\"\" $userRegPath | Out-Null\n $hiveLoaded = $true\n Start-Sleep -Seconds 2\n }\n }\n\n $runKeyPath = \"\"Registry::HKEY_USERS\\$sid\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\"\"\n\n if (Test-Path $runKeyPath) {\n $properties = Get-ItemProperty -Path $runKeyPath\n $edgeEntries = $properties.PSObject.Properties | \n Where-Object { $_.Name -like 'MicrosoftEdgeAutoLaunch*' }\n\n foreach ($entry in $edgeEntries) {\n Remove-ItemProperty -Path $runKeyPath -Name $entry.Name -Force\n }\n }\n\n if ($hiveLoaded) {\n [gc]::Collect()\n Start-Sleep -Seconds 2\n reg unload \"\"HKU\\$sid\"\" | Out-Null\n }\n}\n\";\n }\n\n private static string GetOneNoteRemovalScript()\n {\n return @\"# OneNoteRemoval.ps1\n# Standalone script to remove Microsoft OneNote\n# Source: Winhance (https://github.com/memstechtips/Winhance)\n\ntry {\n # Stop OneNote processes\n $processesToStop = @(\"\"OneNote\"\", \"\"ONENOTE\"\", \"\"ONENOTEM\"\")\n foreach ($processName in $processesToStop) { \n Get-Process -Name $processName -ErrorAction SilentlyContinue | \n Stop-Process -Force -ErrorAction SilentlyContinue\n }\n Start-Sleep -Seconds 1\n}\ncatch {\n # Continue if process stopping fails\n}\n\n# Remove OneNote AppX package (Windows 10 version)\nGet-AppxPackage -AllUsers *OneNote* | Remove-AppxPackage\n\n# Check and execute uninstall strings from registry (Windows 11 version)\n$registryPaths = @(\n \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneNote*\"\",\n \"\"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneNote*\"\",\n \"\"HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneNote*\"\"\n)\n\nforeach ($regPathPattern in $registryPaths) {\n try {\n $regPaths = Get-ChildItem -Path $regPathPattern -ErrorAction SilentlyContinue\n foreach ($regPath in $regPaths) {\n $uninstallString = (Get-ItemProperty -Path $regPath.PSPath -ErrorAction SilentlyContinue).UninstallString\n if ($uninstallString) {\n if ($uninstallString -match '^\\\"\"([^\\\"\"]+)\\\"\"(.*)$') {\n $exePath = $matches[1]\n $args = $matches[2].Trim()\n Start-Process -FilePath $exePath -ArgumentList $args -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n else {\n Start-Process -FilePath $uninstallString -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n }\n }\n }\n catch {\n # Continue if registry operation fails\n continue\n }\n}\n\n# Try to uninstall using the Office setup\n$officeUninstallPaths = @(\n \"\"$env:ProgramFiles\\Microsoft Office\\Office16\\setup.exe\"\",\n \"\"$env:ProgramFiles\\Microsoft Office\\root\\Office16\\setup.exe\"\",\n \"\"$env:ProgramFiles(x86)\\Microsoft Office\\Office16\\setup.exe\"\",\n \"\"$env:ProgramFiles(x86)\\Microsoft Office\\root\\Office16\\setup.exe\"\"\n)\n\nforeach ($path in $officeUninstallPaths) {\n try {\n if (Test-Path $path) {\n Start-Process -FilePath $path -ArgumentList \"\"/uninstall OneNote /config OneNoteRemoval.xml\"\" -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if uninstall fails\n continue\n }\n}\n\n# Remove OneNote scheduled tasks\ntry {\n Get-ScheduledTask -ErrorAction SilentlyContinue | \n Where-Object { $_.TaskName -match 'OneNote' -and $_.TaskName -ne 'OneNoteRemoval' } | \n ForEach-Object { \n Unregister-ScheduledTask -TaskName $_.TaskName -Confirm:$false -ErrorAction SilentlyContinue \n }\n}\ncatch {\n # Continue if task removal fails\n}\n\n# Remove OneNote from startup\ntry {\n Remove-ItemProperty -Path \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\"\" -Name \"\"OneNote*\"\" -ErrorAction SilentlyContinue\n}\ncatch {\n # Continue if registry operations fail\n}\n\n# Files to remove (single items)\n$filesToRemove = @(\n \"\"$env:ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\OneNote.lnk\"\",\n \"\"$env:PUBLIC\\Desktop\\OneNote.lnk\"\"\n)\n\n# Remove single files\nforeach ($file in $filesToRemove) {\n try {\n if (Test-Path $file) {\n Remove-Item $file -Force -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if file removal fails\n continue\n }\n}\n\n# Folders that need special handling\n$foldersToRemove = @(\n \"\"$env:ProgramFiles\\Microsoft\\OneNote\"\",\n \"\"$env:ProgramFiles(x86)\\Microsoft\\OneNote\"\",\n \"\"$env:LOCALAPPDATA\\Microsoft\\OneNote\"\"\n)\n\n# Remove folders\nforeach ($folder in $foldersToRemove) {\n try {\n if (Test-Path $folder) {\n Remove-Item -Path $folder -Force -Recurse -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if folder removal fails\n continue\n }\n}\n\n# Clean up per-user OneNote shortcuts\n$userProfiles = Get-ChildItem -Path \"\"C:\\Users\"\" -Directory | Where-Object { \n $_.Name -notin @('Public', 'Default', 'Default User', 'All Users') -and \n (Test-Path -Path \"\"$($_.FullName)\\NTUSER.DAT\"\")\n}\n\nforeach ($profile in $userProfiles) {\n $userProfilePath = $profile.FullName\n \n # Define user-specific paths to clean\n $oneNoteShortcutPaths = @(\n \"\"$userProfilePath\\Desktop\\OneNote.lnk\"\",\n \"\"$userProfilePath\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\OneNote.lnk\"\"\n )\n\n # Remove OneNote shortcuts for each user\n foreach ($path in $oneNoteShortcutPaths) {\n if (Test-Path -Path $path -PathType Leaf) {\n Remove-Item -Path $path -Force -ErrorAction SilentlyContinue\n }\n }\n}\n\";\n }\n\n private static string GetOneDriveRemovalScript()\n {\n return @\"\n# OneDriveRemoval.ps1\n# Standalone script to remove Microsoft OneDrive\n# Source: Winhance (https://github.com/memstechtips/Winhance)\n\ntry {\n # Stop OneDrive processes\n $processesToStop = @(\"\"OneDrive\"\", \"\"FileCoAuth\"\", \"\"FileSyncHelper\"\")\n foreach ($processName in $processesToStop) { \n Get-Process -Name $processName -ErrorAction SilentlyContinue | \n Stop-Process -Force -ErrorAction SilentlyContinue\n }\n Start-Sleep -Seconds 1\n}\ncatch {\n # Continue if process stopping fails\n}\n\n# Check and execute uninstall strings from registry\n$registryPaths = @(\n \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneDriveSetup.exe\"\",\n \"\"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneDriveSetup.exe\"\"\n)\n\nforeach ($regPath in $registryPaths) {\n try {\n if (Test-Path $regPath) {\n $uninstallString = (Get-ItemProperty -Path $regPath -ErrorAction Stop).UninstallString\n if ($uninstallString) {\n if ($uninstallString -match '^\"\"([^\"\"]+)\"\"(.*)$') {\n $exePath = $matches[1]\n $args = $matches[2].Trim()\n Start-Process -FilePath $exePath -ArgumentList $args -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n else {\n Start-Process -FilePath $uninstallString -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n }\n }\n }\n catch {\n # Continue if registry operation fails\n continue\n }\n}\n\ntry {\n # Remove OneDrive AppX package\n Get-AppxPackage -Name \"\"*OneDrive*\"\" -ErrorAction SilentlyContinue | \n Remove-AppxPackage -ErrorAction SilentlyContinue\n}\ncatch {\n # Continue if AppX removal fails\n}\n\n# Uninstall OneDrive using setup files\n$oneDrivePaths = @(\n \"\"$env:SystemRoot\\SysWOW64\\OneDriveSetup.exe\"\",\n \"\"$env:SystemRoot\\System32\\OneDriveSetup.exe\"\",\n \"\"$env:LOCALAPPDATA\\Microsoft\\OneDrive\\OneDrive.exe\"\"\n)\n\nforeach ($path in $oneDrivePaths) {\n try {\n if (Test-Path $path) {\n Start-Process -FilePath $path -ArgumentList \"\"/uninstall\"\" -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if uninstall fails\n continue\n }\n}\n\ntry {\n # Remove OneDrive scheduled tasks\n Get-ScheduledTask -ErrorAction SilentlyContinue | \n Where-Object { $_.TaskName -match 'OneDrive' -and $_.TaskName -ne 'OneDriveRemoval' } | \n ForEach-Object { \n Unregister-ScheduledTask -TaskName $_.TaskName -Confirm:$false -ErrorAction SilentlyContinue \n }\n}\ncatch {\n # Continue if task removal fails\n}\n\ntry {\n # Configure registry settings\n $regPath = \"\"HKLM:\\SOFTWARE\\Policies\\Microsoft\\OneDrive\"\"\n if (-not (Test-Path $regPath)) {\n New-Item -Path $regPath -Force -ErrorAction SilentlyContinue | Out-Null\n }\n Set-ItemProperty -Path $regPath -Name \"\"KFMBlockOptIn\"\" -Value 1 -Type DWord -Force -ErrorAction SilentlyContinue\n \n # Remove OneDrive from startup\n Remove-ItemProperty -Path \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\"\" -Name \"\"OneDriveSetup\"\" -ErrorAction SilentlyContinue\n \n # Remove OneDrive from Navigation Pane\n Remove-Item -Path \"\"Registry::HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Desktop\\NameSpace\\{018D5C66-4533-4307-9B53-224DE2ED1FE6}\"\" -Recurse -Force -ErrorAction SilentlyContinue\n}\ncatch {\n # Continue if registry operations fail\n}\n\n# Function to handle robust folder removal\nfunction Remove-OneDriveFolder {\n param ([string]$folderPath)\n \n if (-not (Test-Path $folderPath)) {\n return\n }\n \n try {\n # Stop OneDrive processes if they're running\n Get-Process -Name \"\"OneDrive\"\" -ErrorAction SilentlyContinue | \n Stop-Process -Force -ErrorAction SilentlyContinue\n \n # Take ownership and grant permissions\n $null = Start-Process \"\"takeown.exe\"\" -ArgumentList \"\"/F `\"\"$folderPath`\"\" /R /A /D Y\"\" -Wait -NoNewWindow -PassThru -ErrorAction SilentlyContinue\n $null = Start-Process \"\"icacls.exe\"\" -ArgumentList \"\"`\"\"$folderPath`\"\" /grant administrators:F /T\"\" -Wait -NoNewWindow -PassThru -ErrorAction SilentlyContinue\n \n # Try direct removal\n Remove-Item -Path $folderPath -Force -Recurse -ErrorAction SilentlyContinue\n }\n catch {\n try {\n # If direct removal fails, create and execute a cleanup batch file\n $batchPath = \"\"$env:TEMP\\RemoveOneDrive_$(Get-Random).bat\"\"\n $batchContent = @\"\"\n@echo off\ntimeout /t 2 /nobreak > nul\ntakeown /F \"\"$folderPath\"\" /R /A /D Y\nicacls \"\"$folderPath\"\" /grant administrators:F /T\nrd /s /q \"\"$folderPath\"\"\ndel /F /Q \"\"%~f0\"\"\n\"\"@\n Set-Content -Path $batchPath -Value $batchContent -Force -ErrorAction SilentlyContinue\n Start-Process \"\"cmd.exe\"\" -ArgumentList \"\"/c $batchPath\"\" -WindowStyle Hidden -ErrorAction SilentlyContinue\n }\n catch {\n # Continue if batch file cleanup fails\n }\n }\n}\n\n# Files to remove (single items)\n$filesToRemove = @(\n \"\"$env:ALLUSERSPROFILE\\Users\\Default\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\OneDrive.lnk\"\",\n \"\"$env:ALLUSERSPROFILE\\Users\\Default\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\OneDrive.exe\"\",\n \"\"$env:PUBLIC\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\OneDrive.lnk\"\",\n \"\"$env:PUBLIC\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\OneDrive.exe\"\",\n \"\"$env:SystemRoot\\System32\\OneDriveSetup.exe\"\",\n \"\"$env:SystemRoot\\SysWOW64\\OneDriveSetup.exe\"\",\n \"\"$env:LOCALAPPDATA\\Microsoft\\OneDrive\\OneDrive.exe\"\",\n \"\"$env:ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\OneDrive.lnk\"\"\n)\n\n# Remove single files\nforeach ($file in $filesToRemove) {\n try {\n if (Test-Path $file) {\n Remove-Item $file -Force -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if file removal fails\n continue\n }\n}\n\n# Folders that need special handling\n$foldersToRemove = @(\n \"\"$env:ProgramFiles\\Microsoft\\OneDrive\"\",\n \"\"$env:ProgramFiles\\Microsoft OneDrive\"\",\n \"\"$env:LOCALAPPDATA\\Microsoft\\OneDrive\"\"\n)\n\n# Remove folders with robust method\nforeach ($folder in $foldersToRemove) {\n try {\n Remove-OneDriveFolder -folderPath $folder\n }\n catch {\n # Continue if folder removal fails\n continue\n }\n}\n\n# Additional cleanup for stubborn setup files\n$setupFiles = @(\n \"\"$env:SystemRoot\\System32\\OneDriveSetup.exe\"\",\n \"\"$env:SystemRoot\\SysWOW64\\OneDriveSetup.exe\"\"\n)\n\nforeach ($file in $setupFiles) {\n if (Test-Path $file) {\n try {\n # Take ownership and grant full permissions\n $null = Start-Process \"\"takeown.exe\"\" -ArgumentList \"\"/F `\"\"$file`\"\"\"\" -Wait -NoNewWindow -PassThru -ErrorAction SilentlyContinue\n $null = Start-Process \"\"icacls.exe\"\" -ArgumentList \"\"`\"\"$file`\"\" /grant administrators:F\"\" -Wait -NoNewWindow -PassThru -ErrorAction SilentlyContinue\n \n # Attempt direct removal\n Remove-Item -Path $file -Force -ErrorAction SilentlyContinue\n \n # If file still exists, schedule it for deletion on next reboot\n if (Test-Path $file) {\n $pendingRename = \"\"$file.pending\"\"\n Move-Item -Path $file -Destination $pendingRename -Force -ErrorAction SilentlyContinue\n Start-Process \"\"cmd.exe\"\" -ArgumentList \"\"/c del /F /Q `\"\"$pendingRename`\"\"\"\" -WindowStyle Hidden -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if cleanup fails\n continue\n }\n }\n}\n\";\n }\n\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/LoadingWindowViewModel.cs", "using System;\nusing System.ComponentModel;\nusing System.Runtime.CompilerServices;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n public class LoadingWindowViewModel : INotifyPropertyChanged\n {\n private readonly ITaskProgressService _progressService;\n\n // INotifyPropertyChanged implementation\n public event PropertyChangedEventHandler? PropertyChanged;\n\n protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n protected bool SetProperty(ref T field, T value, [CallerMemberName] string? propertyName = null)\n {\n if (Equals(field, value)) return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n\n // Progress properties\n private double _progress;\n public double Progress\n {\n get => _progress;\n set => SetProperty(ref _progress, value);\n }\n\n private string _progressText = string.Empty;\n public string ProgressText\n {\n get => _progressText;\n set => SetProperty(ref _progressText, value);\n }\n\n private bool _isIndeterminate = true;\n public bool IsIndeterminate\n {\n get => _isIndeterminate;\n set => SetProperty(ref _isIndeterminate, value);\n }\n\n private bool _showProgressText;\n public bool ShowProgressText\n {\n get => _showProgressText;\n set => SetProperty(ref _showProgressText, value);\n }\n\n // Additional properties for more detailed loading information\n private string _statusMessage = \"Initializing...\";\n public string StatusMessage\n {\n get => _statusMessage;\n set => SetProperty(ref _statusMessage, value);\n }\n\n private string _detailMessage = \"Please wait while the application loads...\";\n public string DetailMessage\n {\n get => _detailMessage;\n set => SetProperty(ref _detailMessage, value);\n }\n\n public LoadingWindowViewModel(ITaskProgressService progressService)\n {\n _progressService = progressService ?? throw new ArgumentNullException(nameof(progressService));\n \n // Subscribe to progress events\n _progressService.ProgressUpdated += ProgressService_ProgressUpdated;\n }\n\n private void ProgressService_ProgressUpdated(object? sender, TaskProgressDetail detail)\n {\n // Update UI properties based on progress events\n IsIndeterminate = detail.IsIndeterminate;\n Progress = detail.Progress ?? 0;\n \n // Update progress text with percentage and status\n ProgressText = detail.IsIndeterminate ? string.Empty : $\"{detail.Progress:F0}% - {detail.StatusText}\";\n ShowProgressText = !detail.IsIndeterminate && _progressService.IsTaskRunning;\n \n // Update status message with the current operation\n if (!string.IsNullOrEmpty(detail.StatusText))\n {\n StatusMessage = detail.StatusText;\n \n // Update detail message based on the current operation\n if (detail.StatusText.Contains(\"Loading installable apps\"))\n {\n DetailMessage = \"Discovering available applications...\";\n }\n else if (detail.StatusText.Contains(\"Loading removable apps\"))\n {\n DetailMessage = \"Identifying Windows applications...\";\n }\n else if (detail.StatusText.Contains(\"Checking installation status\"))\n {\n DetailMessage = \"Verifying which applications are installed...\";\n }\n else if (detail.StatusText.Contains(\"Organizing apps\"))\n {\n DetailMessage = \"Sorting applications for display...\";\n }\n else\n {\n DetailMessage = \"Please wait while the application loads...\";\n }\n }\n }\n\n public void Cleanup()\n {\n // Unsubscribe from events to prevent memory leaks\n _progressService.ProgressUpdated -= ProgressService_ProgressUpdated;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/ConfigurationItem.cs", "using System;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents an item in a configuration file.\n /// \n public class ConfigurationItem\n {\n /// \n /// Gets or sets the name of the item.\n /// \n public string Name { get; set; }\n\n /// \n /// Gets or sets the package name of the item.\n /// \n public string PackageName { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the item is selected.\n /// \n public bool IsSelected { get; set; }\n \n /// \n /// Gets or sets the type of control used for this item.\n /// \n public ControlType ControlType { get; set; } = ControlType.BinaryToggle;\n \n /// \n /// Gets or sets the selected value for ComboBox controls.\n /// This is used when ControlType is ComboBox.\n /// \n public string SelectedValue { get; set; }\n \n /// \n /// Gets or sets additional properties for the item.\n /// This can be used to store custom properties like wallpaper change preference.\n /// \n public Dictionary CustomProperties { get; set; } = new Dictionary();\n \n /// \n /// Ensures that SelectedValue is set for ComboBox controls based on SliderValue and available options.\n /// \n public void EnsureSelectedValueIsSet()\n {\n // Only process ComboBox controls with null SelectedValue\n if (ControlType == ControlType.ComboBox && string.IsNullOrEmpty(SelectedValue))\n {\n // For Power Plan\n if (Name?.Contains(\"Power Plan\") == true ||\n (CustomProperties.TryGetValue(\"Id\", out var id) && id?.ToString() == \"PowerPlanComboBox\"))\n {\n // Try to get the value from PowerPlanOptions if available\n if (CustomProperties.TryGetValue(\"PowerPlanOptions\", out var options) &&\n options is List powerPlanOptions &&\n powerPlanOptions.Count > 0 &&\n CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int index = Convert.ToInt32(sliderValue);\n if (index >= 0 && index < powerPlanOptions.Count)\n {\n SelectedValue = powerPlanOptions[index];\n }\n }\n // If PowerPlanOptions is not available, use default values\n else if (CustomProperties.TryGetValue(\"SliderValue\", out var sv))\n {\n int index = Convert.ToInt32(sv);\n string[] defaultOptions = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n if (index >= 0 && index < defaultOptions.Length)\n {\n SelectedValue = defaultOptions[index];\n }\n }\n \n // If we still don't have a SelectedValue, add PowerPlanOptions\n if (string.IsNullOrEmpty(SelectedValue) && CustomProperties.TryGetValue(\"SliderValue\", out var sv2))\n {\n int index = Convert.ToInt32(sv2);\n string[] defaultOptions = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n if (index >= 0 && index < defaultOptions.Length)\n {\n SelectedValue = defaultOptions[index];\n CustomProperties[\"PowerPlanOptions\"] = new List(defaultOptions);\n }\n }\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/PrivacyOptimizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class PrivacyOptimizations\n{\n public static OptimizationGroup GetPrivacyOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Privacy\",\n Category = OptimizationCategory.Privacy,\n Settings = new List\n {\n // Activity History\n new OptimizationSetting\n {\n Id = \"privacy-activity-history\",\n Name = \"Activity History\",\n Description = \"Controls activity history tracking\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Activity History\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\System\",\n Name = \"PublishUserActivities\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, Activity History is enabled\n DisabledValue = 0, // When toggle is OFF, Activity History is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls activity history tracking\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Personalized Ads (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-advertising-id\",\n Name = \"Personalized Ads\",\n Description = \"Controls personalized ads using advertising ID\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Advertising\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\AdvertisingInfo\",\n Name = \"Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, advertising ID is enabled\n DisabledValue = 0, // When toggle is OFF, advertising ID is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls advertising ID for personalized ads\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\AdvertisingInfo\",\n Name = \"DisabledByGroupPolicy\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, advertising is NOT disabled by policy\n DisabledValue = 1, // When toggle is OFF, advertising is disabled by policy\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls advertising ID for personalized ads\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Language List Access\n new OptimizationSetting\n {\n Id = \"privacy-language-list\",\n Name = \"Allow Websites Access to Language List\",\n Description =\n \"Let websites show me locally relevant content by accessing my language list\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"General\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\International\\\\User Profile\",\n Name = \"HttpAcceptLanguageOptOut\",\n RecommendedValue = 0,\n EnabledValue = 0, // When toggle is ON, language list access is enabled\n DisabledValue = 1, // When toggle is OFF, language list access is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls language list access for websites\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // App Launch Tracking\n new OptimizationSetting\n {\n Id = \"privacy-app-launch-tracking\",\n Name = \"App Launch Tracking\",\n Description =\n \"Let Windows improve Start and search results by tracking app launches\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"General\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"Start_TrackProgs\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, app launch tracking is enabled\n DisabledValue = 0, // When toggle is OFF, app launch tracking is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description =\n \"Controls app launch tracking for improved Start and search results\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Show Suggested Content in Settings (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-settings-content\",\n Name = \"Show Suggested Content in Settings\",\n Description = \"Controls suggested content in the Settings app\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Settings App\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ContentDeliveryManager\",\n Name = \"SubscribedContent-338393Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, suggested content is enabled\n DisabledValue = 0, // When toggle is OFF, suggested content is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls suggested content in the Settings app\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ContentDeliveryManager\",\n Name = \"SubscribedContent-353694Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, suggested content is enabled\n DisabledValue = 0, // When toggle is OFF, suggested content is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls suggested content in the Settings app\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ContentDeliveryManager\",\n Name = \"SubscribedContent-353696Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, suggested content is enabled\n DisabledValue = 0, // When toggle is OFF, suggested content is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls suggested content in the Settings app\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Settings App Notifications\n new OptimizationSetting\n {\n Id = \"privacy-settings-notifications\",\n Name = \"Settings App Notifications\",\n Description =\n \"Controls notifications in the Settings app and immersive control panel\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Settings App\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\SystemSettings\\\\AccountNotifications\",\n Name = \"EnableAccountNotifications\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, account notifications are enabled\n DisabledValue = 0, // When toggle is OFF, account notifications are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description =\n \"Controls notifications in the Settings app and immersive control panel\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Online Speech Recognition (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-speech-recognition\",\n Name = \"Online Speech Recognition\",\n Description = \"Controls online speech recognition\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Speech\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Speech_OneCore\\\\Settings\\\\OnlineSpeechPrivacy\",\n Name = \"HasAccepted\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, online speech recognition is enabled\n DisabledValue = 0, // When toggle is OFF, online speech recognition is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls online speech recognition\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\InputPersonalization\",\n Name = \"AllowInputPersonalization\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, input personalization is allowed\n DisabledValue = 0, // When toggle is OFF, input personalization is not allowed\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls input personalization for speech recognition\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Custom Inking and Typing Dictionary (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-inking-typing-dictionary\",\n Name = \"Custom Inking and Typing Dictionary\",\n Description =\n \"Controls custom inking and typing dictionary (turning off will clear all words in your custom dictionary)\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Inking and Typing\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CPSS\\\\Store\\\\InkingAndTypingPersonalization\",\n Name = \"Value\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, custom dictionary is enabled\n DisabledValue = 0, // When toggle is OFF, custom dictionary is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls custom inking and typing dictionary\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Personalization\\\\Settings\",\n Name = \"AcceptedPrivacyPolicy\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, privacy policy is accepted\n DisabledValue = 0, // When toggle is OFF, privacy policy is not accepted\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls custom inking and typing dictionary\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\InputPersonalization\",\n Name = \"RestrictImplicitTextCollection\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, text collection is not restricted\n DisabledValue = 1, // When toggle is OFF, text collection is restricted\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls custom inking and typing dictionary\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\InputPersonalization\\\\TrainedDataStore\",\n Name = \"HarvestContacts\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, contacts harvesting is enabled\n DisabledValue = 0, // When toggle is OFF, contacts harvesting is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls custom inking and typing dictionary\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Send Diagnostic Data (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-diagnostics\",\n Name = \"Send Diagnostic Data\",\n Description = \"Controls diagnostic data collection level\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Diagnostics & Feedback\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Diagnostics\\\\DiagTrack\",\n Name = \"ShowedToastAtLevel\",\n RecommendedValue = 1,\n EnabledValue = 3, // When toggle is ON, full diagnostic data is enabled\n DisabledValue = 1, // When toggle is OFF, basic diagnostic data is enabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls diagnostic data collection level\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\DataCollection\",\n Name = \"AllowTelemetry\",\n RecommendedValue = 1,\n EnabledValue = 3, // When toggle is ON, full telemetry is allowed\n DisabledValue = 1, // When toggle is OFF, basic telemetry is allowed\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls telemetry data collection\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\DataCollection\",\n Name = \"MaxTelemetryAllowed\",\n RecommendedValue = 1,\n EnabledValue = 3, // When toggle is ON, full telemetry is allowed\n DisabledValue = 1, // When toggle is OFF, basic telemetry is allowed\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls telemetry data collection\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\DataCollection\",\n Name = \"AllowTelemetry\",\n RecommendedValue = 1,\n EnabledValue = 3, // When toggle is ON, telemetry is allowed by policy\n DisabledValue = 0, // When toggle is OFF, telemetry is not allowed by policy\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls telemetry data collection\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Improve Inking and Typing (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-improve-inking-typing\",\n Name = \"Improve Inking and Typing\",\n Description = \"Controls inking and typing data collection\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Diagnostics & Feedback\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n Dependencies = new List\n {\n new SettingDependency\n {\n DependencyType = SettingDependencyType.RequiresEnabled,\n DependentSettingId = \"privacy-improve-inking-typing\",\n RequiredSettingId = \"privacy-diagnostics\",\n },\n },\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Input\\\\TIPC\",\n Name = \"Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, inking and typing improvement is enabled\n DisabledValue = 0, // When toggle is OFF, inking and typing improvement is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls inking and typing data collection\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CPSS\\\\Store\\\\ImproveInkingAndTyping\",\n Name = \"Value\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, linguistic data collection is allowed\n DisabledValue = 0, // When toggle is OFF, linguistic data collection is not allowed\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls inking and typing data collection\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Tailored Experiences (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-tailored-experiences\",\n Name = \"Tailored Experiences\",\n Description = \"Controls personalized experiences with diagnostic data\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Diagnostics & Feedback\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Privacy\",\n Name = \"TailoredExperiencesWithDiagnosticDataEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, tailored experiences are enabled\n DisabledValue = 0, // When toggle is OFF, tailored experiences are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls personalized experiences with diagnostic data\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Policies\\\\Microsoft\\\\Windows\\\\CloudContent\",\n Name = \"DisableTailoredExperiencesWithDiagnosticData\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, tailored experiences are not disabled by policy\n DisabledValue = 1, // When toggle is OFF, tailored experiences are disabled by policy\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls personalized experiences with diagnostic data\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Location Services (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-location-services\",\n Name = \"Location Services\",\n Description = \"Controls location services\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"App Permissions\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\location\",\n Name = \"Value\",\n RecommendedValue = \"Deny\",\n EnabledValue = \"Allow\", // When toggle is ON, location services are allowed\n DisabledValue = \"Deny\", // When toggle is OFF, location services are denied\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Allow\", // Default value when registry key exists but no value is set\n Description = \"Controls location services\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\LocationAndSensors\",\n Name = \"DisableLocation\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, location is not disabled by policy\n DisabledValue = 1, // When toggle is OFF, location is disabled by policy\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls location services\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Camera Access\n new OptimizationSetting\n {\n Id = \"privacy-camera-access\",\n Name = \"Camera Access\",\n Description = \"Controls camera access\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"App Permissions\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\webcam\",\n Name = \"Value\",\n RecommendedValue = \"Deny\",\n EnabledValue = \"Allow\", // When toggle is ON, camera access is allowed\n DisabledValue = \"Deny\", // When toggle is OFF, camera access is denied\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Allow\", // Default value when registry key exists but no value is set\n Description = \"Controls camera access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Microphone Access\n new OptimizationSetting\n {\n Id = \"privacy-microphone-access\",\n Name = \"Microphone Access\",\n Description = \"Controls microphone access\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"App Permissions\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\microphone\",\n Name = \"Value\",\n RecommendedValue = \"Deny\",\n EnabledValue = \"Allow\", // When toggle is ON, microphone access is allowed\n DisabledValue = \"Deny\", // When toggle is OFF, microphone access is denied\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Allow\", // Default value when registry key exists but no value is set\n Description = \"Controls microphone access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Account Info Access\n new OptimizationSetting\n {\n Id = \"privacy-account-info-access\",\n Name = \"Account Info Access\",\n Description = \"Controls account information access\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"App Permissions\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\userAccountInformation\",\n Name = \"Value\",\n RecommendedValue = \"Deny\",\n EnabledValue = \"Allow\", // When toggle is ON, account info access is allowed\n DisabledValue = \"Deny\", // When toggle is OFF, account info access is denied\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Allow\", // Default value when registry key exists but no value is set\n Description = \"Controls account information access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // App Diagnostic Access\n new OptimizationSetting\n {\n Id = \"privacy-app-diagnostic-access\",\n Name = \"App Diagnostic Access\",\n Description = \"Controls app diagnostic access\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"App Permissions\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\appDiagnostics\",\n Name = \"Value\",\n RecommendedValue = \"Deny\",\n EnabledValue = \"Allow\", // When toggle is ON, app diagnostic access is allowed\n DisabledValue = \"Deny\", // When toggle is OFF, app diagnostic access is denied\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Allow\", // Default value when registry key exists but no value is set\n Description = \"Controls app diagnostic access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Cloud Content Search for Microsoft Account\n new OptimizationSetting\n {\n Id = \"privacy-search-msa-cloud\",\n Name = \"Cloud Content Search (Microsoft Account)\",\n Description = \"Controls cloud content search for Microsoft account\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Search\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\SearchSettings\",\n Name = \"IsMSACloudSearchEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, cloud search is enabled\n DisabledValue = 0, // When toggle is OFF, cloud search is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls cloud content search for Microsoft account\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Cloud Content Search for Work or School Account\n new OptimizationSetting\n {\n Id = \"privacy-search-aad-cloud\",\n Name = \"Cloud Content Search (Work/School Acc)\",\n Description = \"Controls cloud content search for work or school account\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Search\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\SearchSettings\",\n Name = \"IsAADCloudSearchEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, cloud search is enabled\n DisabledValue = 0, // When toggle is OFF, cloud search is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description =\n \"Controls cloud content search for work or school account\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Web Search\n new OptimizationSetting\n {\n Id = \"privacy-web-search\",\n Name = \"Web Search\",\n Description = \"Controls web search in Start menu and taskbar\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Search\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Search\",\n Name = \"BingSearchEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, web search is enabled\n DisabledValue = 0, // When toggle is OFF, web search is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls web search in Start menu and taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/CapabilityScriptModifier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Implementation of ICapabilityScriptModifier that provides methods for modifying capability-related script content.\n /// \n public class CapabilityScriptModifier : ICapabilityScriptModifier\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public CapabilityScriptModifier(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string RemoveCapabilityFromScript(string scriptContent, string capabilityName)\n {\n // Find the capabilities array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$capabilities = @(\");\n if (arrayStartIndex == -1)\n {\n Console.WriteLine(\"Could not find $capabilities array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the capabilities array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n Console.WriteLine(\"Could not find end of $capabilities array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the capabilities in the array\n var capabilities = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var capability = trimmedLine.Trim('\\'', '\"', ' ', ',');\n capabilities.Add(capability);\n }\n }\n\n // Check if the capability is in the array\n bool removed =\n capabilities.RemoveAll(c =>\n c.Equals(capabilityName, StringComparison.OrdinalIgnoreCase)\n ) > 0;\n\n if (!removed)\n {\n // Capability not found in the array\n return scriptContent;\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$capabilities = @(\");\n\n foreach (var capability in capabilities)\n {\n newArrayContent.AppendLine($\" '{capability}'\");\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/PackageScriptModifier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Implementation of IPackageScriptModifier that provides methods for modifying package-related script content.\n /// \n public class PackageScriptModifier : IPackageScriptModifier\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public PackageScriptModifier(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string RemovePackageFromScript(string scriptContent, string packageName)\n {\n // Find the packages array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$packages = @(\");\n if (arrayStartIndex == -1)\n {\n Console.WriteLine(\"Could not find $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the packages array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n Console.WriteLine(\"Could not find end of $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the packages in the array\n var packages = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var package = trimmedLine.Trim('\\'', '\"', ' ', ',');\n packages.Add(package);\n }\n }\n\n // Check if the package is in the array\n bool removed =\n packages.RemoveAll(p => p.Equals(packageName, StringComparison.OrdinalIgnoreCase)) > 0;\n\n if (!removed)\n {\n // Package not found in the array\n return scriptContent;\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$packages = @(\");\n\n foreach (var package in packages)\n {\n newArrayContent.AppendLine($\" '{package}'\");\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/SearchService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service for handling search operations across different types of items.\n /// \n public class SearchService : ISearchService\n {\n /// \n /// Filters a collection of items based on a search term.\n /// \n /// The type of items to filter.\n /// The collection of items to filter.\n /// The search term to filter by.\n /// A filtered collection of items that match the search term.\n public IEnumerable FilterItems(IEnumerable items, string searchTerm) where T : ISearchable\n {\n // Add console logging for debugging\n Console.WriteLine($\"SearchService.FilterItems: Filtering with search term '{searchTerm}'\");\n \n if (string.IsNullOrWhiteSpace(searchTerm))\n {\n Console.WriteLine($\"SearchService.FilterItems: Search term is empty, returning all {items.Count()} items\");\n return items;\n }\n\n // Just trim the search term, but don't convert to lowercase\n // We'll handle case insensitivity in the MatchesSearch method\n searchTerm = searchTerm.Trim();\n Console.WriteLine($\"SearchService.FilterItems: Normalized search term '{searchTerm}'\");\n Console.WriteLine($\"SearchService.FilterItems: Starting search with term '{searchTerm}'\");\n \n // Log items before filtering\n int totalItems = items.Count();\n Console.WriteLine($\"SearchService.FilterItems: Total items before filtering: {totalItems}\");\n \n // Apply filtering and log results\n var filteredItems = items.Where(item => {\n bool matches = item.MatchesSearch(searchTerm);\n \n // Log details for all items to help diagnose search issues\n var itemName = item.GetType().GetProperty(\"Name\")?.GetValue(item)?.ToString();\n var itemGroupName = item.GetType().GetProperty(\"GroupName\")?.GetValue(item)?.ToString();\n \n // Log all items for better debugging\n Console.WriteLine($\"SearchService.FilterItems: Checking item '{itemName}' (Group: '{itemGroupName}') - matches: {matches}\");\n \n return matches;\n }).ToList();\n \n Console.WriteLine($\"SearchService.FilterItems: Found {filteredItems.Count} matching items out of {totalItems}\");\n \n return filteredItems;\n }\n\n /// \n /// Asynchronously filters a collection of items based on a search term.\n /// \n /// The type of items to filter.\n /// The collection of items to filter.\n /// The search term to filter by.\n /// A task that represents the asynchronous operation. The task result contains a filtered collection of items that match the search term.\n public Task> FilterItemsAsync(IEnumerable items, string searchTerm) where T : ISearchable\n {\n return Task.FromResult(FilterItems(items, searchTerm));\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppServiceAdapter.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Adapter class that implements IAppService by delegating to AppDiscoveryService\n /// and other services for the additional functionality required by IAppService.\n /// \n public class AppServiceAdapter : IAppService\n {\n private readonly AppDiscoveryService _appDiscoveryService;\n private readonly ILogService _logService;\n private Dictionary _installStatusCache = new Dictionary();\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The app discovery service to delegate to.\n /// The logging service.\n public AppServiceAdapter(AppDiscoveryService appDiscoveryService, ILogService logService)\n {\n _appDiscoveryService = appDiscoveryService ?? throw new ArgumentNullException(nameof(appDiscoveryService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public async Task> GetInstallableAppsAsync()\n {\n return await _appDiscoveryService.GetInstallableAppsAsync();\n }\n\n /// \n public async Task> GetStandardAppsAsync()\n {\n return await _appDiscoveryService.GetStandardAppsAsync();\n }\n\n /// \n public async Task> GetCapabilitiesAsync()\n {\n return await _appDiscoveryService.GetCapabilitiesAsync();\n }\n\n /// \n public async Task> GetOptionalFeaturesAsync()\n {\n return await _appDiscoveryService.GetOptionalFeaturesAsync();\n }\n\n /// \n public async Task IsAppInstalledAsync(string packageName, CancellationToken cancellationToken = default)\n {\n // Implement using the concrete AppDiscoveryService\n return await _appDiscoveryService.IsAppInstalledAsync(packageName, cancellationToken);\n }\n\n /// \n public async Task IsEdgeInstalledAsync()\n {\n return await _appDiscoveryService.IsEdgeInstalledAsync();\n }\n\n /// \n public async Task IsOneDriveInstalledAsync()\n {\n return await _appDiscoveryService.IsOneDriveInstalledAsync();\n }\n\n /// \n public async Task GetItemInstallStatusAsync(IInstallableItem item)\n {\n if (item == null)\n return false;\n\n return await IsAppInstalledAsync(item.PackageId);\n }\n\n /// \n public async Task> GetBatchInstallStatusAsync(IEnumerable packageIds)\n {\n var result = new Dictionary();\n \n // Check for special apps first\n foreach (var packageId in packageIds)\n {\n // Special handling for Edge and OneDrive\n if (packageId.Equals(\"Microsoft Edge\", StringComparison.OrdinalIgnoreCase) ||\n packageId.Equals(\"msedge\", StringComparison.OrdinalIgnoreCase) ||\n packageId.Equals(\"Edge\", StringComparison.OrdinalIgnoreCase))\n {\n result[packageId] = await _appDiscoveryService.IsEdgeInstalledAsync();\n }\n else if (packageId.Equals(\"OneDrive\", StringComparison.OrdinalIgnoreCase))\n {\n result[packageId] = await _appDiscoveryService.IsOneDriveInstalledAsync();\n }\n }\n \n // Get the remaining package IDs that aren't special apps\n var remainingPackageIds = packageIds.Where(id =>\n !result.ContainsKey(id) &&\n !id.Equals(\"Microsoft Edge\", StringComparison.OrdinalIgnoreCase) &&\n !id.Equals(\"msedge\", StringComparison.OrdinalIgnoreCase) &&\n !id.Equals(\"Edge\", StringComparison.OrdinalIgnoreCase) &&\n !id.Equals(\"OneDrive\", StringComparison.OrdinalIgnoreCase));\n \n // Use the concrete AppDiscoveryService's batch method for the remaining packages\n var batchResults = await _appDiscoveryService.GetInstallationStatusBatchAsync(remainingPackageIds);\n \n // Merge the results\n foreach (var pair in batchResults)\n {\n result[pair.Key] = pair.Value;\n }\n \n return result;\n }\n\n /// \n public async Task GetInstallStatusAsync(string appId)\n {\n if (string.IsNullOrEmpty(appId))\n return InstallStatus.Failed;\n\n // Check cache first\n if (_installStatusCache.TryGetValue(appId, out var cachedStatus))\n {\n return cachedStatus;\n }\n\n // Check if the app is installed\n bool isInstalled = await IsAppInstalledAsync(appId);\n var status = isInstalled ? InstallStatus.Success : InstallStatus.NotFound;\n\n // Cache the result\n _installStatusCache[appId] = status;\n\n return status;\n }\n\n /// \n public async Task RefreshInstallationStatusAsync(IEnumerable items)\n {\n // Clear the cache for the specified items\n foreach (var item in items)\n {\n if (_installStatusCache.ContainsKey(item.PackageId))\n {\n _installStatusCache.Remove(item.PackageId);\n }\n }\n\n // Refresh the status for each item\n foreach (var item in items)\n {\n await GetInstallStatusAsync(item.PackageId);\n }\n }\n\n /// \n public async Task SetInstallStatusAsync(string appId, InstallStatus status)\n {\n if (string.IsNullOrEmpty(appId))\n return false;\n\n // Update the cache\n _installStatusCache[appId] = status;\n return true;\n }\n\n /// \n public void ClearStatusCache()\n {\n _installStatusCache.Clear();\n\n // Clear the app discovery service's cache\n _appDiscoveryService.ClearInstallationStatusCache();\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/MessengerService.cs", "using System;\nusing System.Collections.Generic;\nusing CommunityToolkit.Mvvm.Messaging;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Implementation of IMessengerService that uses CommunityToolkit.Mvvm.Messenger\n /// \n public class MessengerService : IMessengerService\n {\n private readonly IMessenger _messenger;\n private readonly Dictionary> _recipientTokens;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public MessengerService()\n {\n _messenger = WeakReferenceMessenger.Default;\n _recipientTokens = new Dictionary>();\n }\n\n /// \n /// Initializes a new instance of the class with a specific messenger.\n /// \n /// The messenger to use.\n public MessengerService(IMessenger messenger)\n {\n _messenger = messenger ?? throw new ArgumentNullException(nameof(messenger));\n _recipientTokens = new Dictionary>();\n }\n\n /// \n void IMessengerService.Send(TMessage message)\n {\n // Only MessageBase objects can be sent with the messenger\n if (message is MessageBase msgBase)\n {\n _messenger.Send(msgBase);\n }\n }\n\n /// \n void IMessengerService.Register(object recipient, Action action)\n {\n // Only reference types can be registered with the messenger\n if (typeof(TMessage).IsClass && typeof(TMessage).IsAssignableTo(typeof(MessageBase)))\n {\n // We need to use dynamic here to handle the generic type constraints\n dynamic typedRecipient = recipient;\n dynamic typedAction = action;\n RegisterInternal(typedRecipient, typedAction);\n }\n }\n\n private void RegisterInternal(object recipient, Action action) \n where TMessage : MessageBase\n {\n // Register the recipient with the messenger\n _messenger.Register(recipient, (r, m) => action(m));\n \n // Create a token that will unregister the recipient when disposed\n var token = new RegistrationToken(() => _messenger.Unregister(recipient));\n\n // Keep track of the token for later cleanup\n if (!_recipientTokens.TryGetValue(recipient, out var tokens))\n {\n tokens = new List();\n _recipientTokens[recipient] = tokens;\n }\n\n tokens.Add(token);\n }\n\n /// \n /// A token that unregisters a recipient when disposed\n /// \n private class RegistrationToken : IDisposable\n {\n private readonly Action _unregisterAction;\n private bool _isDisposed;\n\n public RegistrationToken(Action unregisterAction)\n {\n _unregisterAction = unregisterAction;\n }\n\n public void Dispose()\n {\n if (!_isDisposed)\n {\n _unregisterAction();\n _isDisposed = true;\n }\n }\n }\n\n /// \n void IMessengerService.Unregister(object recipient)\n {\n if (_recipientTokens.TryGetValue(recipient, out var tokens))\n {\n foreach (var token in tokens)\n {\n token.Dispose();\n }\n\n _recipientTokens.Remove(recipient);\n }\n\n _messenger.UnregisterAll(recipient);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/PowerOptimizations.cs", "using System;\nusing System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\n/// \n/// Represents a PowerCfg command setting.\n/// \npublic class PowerCfgSetting\n{\n /// \n /// Gets or sets the command to execute.\n /// \n public string Command { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description of the command.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the value to use when the setting is enabled.\n /// \n public string EnabledValue { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the value to use when the setting is disabled.\n /// \n public string DisabledValue { get; set; } = string.Empty;\n}\n\npublic static class PowerOptimizations\n{\n /// \n /// Gets all power optimizations as an OptimizationGroup.\n /// \n /// An OptimizationGroup containing all power settings.\n public static OptimizationGroup GetPowerOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Power\",\n Category = OptimizationCategory.Power,\n Settings = new List\n {\n // Hibernate Settings\n new OptimizationSetting\n {\n Id = \"power-hibernate-enabled\",\n Name = \"Hibernate\",\n Description = \"Controls whether hibernate is enabled\",\n Category = OptimizationCategory.Power,\n GroupName = \"Power Management\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Power\",\n Name = \"HibernateEnabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, hibernate is enabled\n DisabledValue = 0, // When toggle is OFF, hibernate is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls whether hibernate is enabled\",\n IsPrimary = true, // Mark as primary for linked settings\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Power\",\n Name = \"HibernateEnabledDefault\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, hibernate is enabled\n DisabledValue = 0, // When toggle is OFF, hibernate is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls whether hibernate is enabled by default\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.Primary,\n },\n // Video Settings\n new OptimizationSetting\n {\n Id = \"power-video-quality\",\n Name = \"High Video Quality on Battery\",\n Description = \"Controls video quality when running on battery power\",\n Category = OptimizationCategory.Power,\n GroupName = \"Display & Graphics\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\VideoSettings\",\n Name = \"VideoQualityOnBattery\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 1, // High quality (from Recommended)\n DisabledValue = 0, // Lower quality (from Default)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls video quality when running on battery power\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n // Performance Settings\n new OptimizationSetting\n {\n Id = \"power-fast-boot\",\n Name = \"Fast Boot\",\n Description = \"Controls whether fast boot (hybrid boot) is enabled\",\n Category = OptimizationCategory.Power,\n GroupName = \"Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Power\",\n Name = \"HiberbootEnabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // Enable fast boot\n DisabledValue = 0, // Disable fast boot\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls whether fast boot (hybrid boot) is enabled\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Sleep Settings\n new OptimizationSetting\n {\n Id = \"power-sleep-settings\",\n Name = \"Sleep & Hibernate\",\n Description =\n \"When enabled, prevents your computer from going to sleep or hibernating\",\n Category = OptimizationCategory.Power,\n GroupName = \"Sleep & Hibernate\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command = \"powercfg /hibernate off\",\n Description = \"Disable hibernate\",\n EnabledValue = \"/hibernate off\",\n DisabledValue = \"/hibernate on\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n Description = \"Set sleep timeout (AC) to never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n DisabledValue =\n \"/setactive 381b4222-f694-41f0-9685-ff5bb260df2e\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n Description = \"Set sleep timeout (DC) to never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n DisabledValue =\n \"/setactive 381b4222-f694-41f0-9685-ff5bb260df2e\",\n },\n }\n },\n },\n },\n // Display Settings\n new OptimizationSetting\n {\n Id = \"power-display-settings\",\n Name = \"Display Always On\",\n Description =\n \"When enabled, prevents your display from turning off and sets maximum brightness\",\n Category = OptimizationCategory.Power,\n GroupName = \"Display & Graphics\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\",\n Description = \"Set display timeout (AC) to never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000258\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\",\n Description = \"Set display timeout (DC) to never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000258\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 aded5e82-b909-4619-9949-f5d71dac0bcb 0x00000064\",\n Description = \"Set display brightness (AC) to 100%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 aded5e82-b909-4619-9949-f5d71dac0bcb 0x00000064\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 aded5e82-b909-4619-9949-f5d71dac0bcb 0x00000032\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\",\n Description = \"Disable adaptive brightness (AC)\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\",\n Description = \"Disable adaptive brightness (DC)\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 001\",\n },\n }\n },\n },\n },\n // Processor Settings\n new OptimizationSetting\n {\n Id = \"power-processor-settings\",\n Name = \"CPU Performance\",\n Description =\n \"When enabled, sets processor to run at 100% power with active cooling\",\n Category = OptimizationCategory.Power,\n GroupName = \"Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 893dee8e-2bef-41e0-89c6-b55d0929964c 0x00000064\",\n Description = \"Set processor minimum state (AC) to 100%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 893dee8e-2bef-41e0-89c6-b55d0929964c 0x00000064\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 893dee8e-2bef-41e0-89c6-b55d0929964c 0x00000005\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 bc5038f7-23e0-4960-96da-33abaf5935ec 0x00000064\",\n Description = \"Set processor maximum state (AC) to 100%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 bc5038f7-23e0-4960-96da-33abaf5935ec 0x00000064\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 bc5038f7-23e0-4960-96da-33abaf5935ec 0x00000064\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 94d3a615-a899-4ac5-ae2b-e4d8f634367f 001\",\n Description = \"Set cooling policy (AC) to active\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 94d3a615-a899-4ac5-ae2b-e4d8f634367f 001\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 94d3a615-a899-4ac5-ae2b-e4d8f634367f 000\",\n },\n }\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"power-cpu-unpark\",\n Name = \"CPU Core Unparking\",\n Description = \"Controls CPU core parking for better performance\",\n Category = OptimizationCategory.Power,\n GroupName = \"Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SYSTEM\\\\ControlSet001\\\\Control\\\\Power\\\\PowerSettings\\\\54533251-82be-4824-96c1-47b60b740d00\\\\0cc5b647-c1df-4637-891a-dec35c318583\",\n Name = \"ValueMax\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // Unpark CPU cores (from Recommended)\n DisabledValue = 1, // Allow CPU core parking (from Default)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls CPU core parking for better performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"power-throttling\",\n Name = \"Power Throttling\",\n Description = \"Controls power throttling for better performance\",\n Category = OptimizationCategory.Power,\n GroupName = \"Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Power\\\\PowerThrottling\",\n Name = \"PowerThrottlingOff\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 0, // Enable power throttling\n DisabledValue = 1, // Disable power throttling\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls power throttling for better performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Storage Settings\n new OptimizationSetting\n {\n Id = \"power-hard-disk-settings\",\n Name = \"Hard Disks Always On\",\n Description =\n \"When enabled, prevents hard disks from turning off to improve performance\",\n Category = OptimizationCategory.Power,\n GroupName = \"Storage\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\",\n Description = \"Set hard disk timeout (AC) to never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000258\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\",\n Description = \"Set hard disk timeout (DC) to never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000258\",\n },\n }\n },\n },\n },\n // Desktop & Display Settings\n new OptimizationSetting\n {\n Id = \"power-desktop-slideshow-settings\",\n Name = \"Desktop Slideshow\",\n Description =\n \"When enabled, allows desktop background slideshow to run even on battery power\",\n Category = OptimizationCategory.Power,\n GroupName = \"Desktop & Display\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 000\",\n Description =\n \"Desktop slideshow (AC) - Value 0 means Available\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 000\",\n Description =\n \"Desktop slideshow (DC) - Value 0 means Available\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 001\",\n },\n }\n },\n },\n },\n // Network Settings\n new OptimizationSetting\n {\n Id = \"power-wireless-adapter-settings\",\n Name = \"Wi-Fi Performance\",\n Description = \"When enabled, sets wireless adapter to maximum performance mode\",\n Category = OptimizationCategory.Power,\n GroupName = \"Network\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\",\n Description =\n \"Wireless adapter power saving mode (AC) - Maximum performance\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\",\n Description =\n \"Wireless adapter power saving mode (DC) - Maximum performance\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 001\",\n },\n }\n },\n },\n },\n // Sleep & Hibernate Settings\n new OptimizationSetting\n {\n Id = \"power-sleep-hibernate-settings\",\n Name = \"All Sleep Features\",\n Description =\n \"When enabled, disables sleep, hybrid sleep, hibernate, and wake timers\",\n Category = OptimizationCategory.Power,\n GroupName = \"Sleep & Hibernate\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n Description = \"Sleep timeout (AC) - Never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000384\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n Description = \"Sleep timeout (DC) - Never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000384\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\",\n Description = \"Hybrid sleep (AC) - Off\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\",\n Description = \"Hybrid sleep (DC) - Off\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\",\n Description = \"Hibernate timeout (AC) - Never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000384\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\",\n Description = \"Hibernate timeout (DC) - Never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000384\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\",\n Description = \"Wake timers (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\",\n Description = \"Wake timers (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 001\",\n },\n }\n },\n },\n },\n // USB Settings\n new OptimizationSetting\n {\n Id = \"power-usb-settings\",\n Name = \"USB Devices Always On\",\n Description =\n \"When enabled, prevents USB devices from being powered down to save energy\",\n Category = OptimizationCategory.Power,\n GroupName = \"USB\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\",\n Description = \"USB hub timeout (AC) - Never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000258\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\",\n Description = \"USB hub timeout (DC) - Never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000258\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\",\n Description = \"USB selective suspend (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\",\n Description = \"USB selective suspend (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\",\n Description = \"USB 3.0 link power management (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\",\n Description = \"USB 3.0 link power management (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 001\",\n },\n }\n },\n },\n },\n // Power Button Settings\n new OptimizationSetting\n {\n Id = \"power-button-settings\",\n Name = \"Power Button Shutdown\",\n Description =\n \"When enabled, sets power button to immediately shut down your computer\",\n Category = OptimizationCategory.Power,\n GroupName = \"Power Buttons\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\",\n Description = \"Power button action (AC) - Shut down\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\",\n Description = \"Power button action (DC) - Shut down\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 000\",\n },\n }\n },\n },\n },\n // PCI Express Settings\n new OptimizationSetting\n {\n Id = \"power-pci-express-settings\",\n Name = \"PCI Express Performance\",\n Description =\n \"When enabled, disables power saving features for PCI Express devices\",\n Category = OptimizationCategory.Power,\n GroupName = \"PCI Express\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\",\n Description = \"PCI Express power management (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\",\n Description = \"PCI Express power management (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 001\",\n },\n }\n },\n },\n },\n // Video Playback Settings\n new OptimizationSetting\n {\n Id = \"power-video-playback-settings\",\n Name = \"Video Playback Quality\",\n Description =\n \"When enabled, ensures maximum video quality even when on battery power\",\n Category = OptimizationCategory.Power,\n GroupName = \"Video Playback\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\",\n Description =\n \"Video playback quality (AC) - Optimized for performance\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\",\n Description =\n \"Video playback quality (DC) - Optimized for performance\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\",\n Description =\n \"Video quality reduction on battery (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\",\n Description =\n \"Video quality reduction on battery (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 001\",\n },\n }\n },\n },\n },\n // Graphics Settings\n new OptimizationSetting\n {\n Id = \"power-graphics-settings\",\n Name = \"GPU Performance\",\n Description = \"When enabled, sets graphics cards to run at maximum performance\",\n Category = OptimizationCategory.Power,\n GroupName = \"Graphics\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\",\n Description = \"Intel graphics power (AC) - Maximum performance\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\",\n Description = \"Intel graphics power (DC) - Maximum performance\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\",\n Description = \"AMD power slider (AC) - Maximum performance\",\n EnabledValue =\n \"/setacvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\",\n DisabledValue =\n \"/setacvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\",\n Description = \"AMD power slider (DC) - Maximum performance\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\",\n Description = \"ATI PowerPlay (AC) - Enabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\",\n DisabledValue =\n \"/setacvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\",\n Description = \"ATI PowerPlay (DC) - Enabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\",\n Description = \"Switchable graphics (AC) - Maximum performance\",\n EnabledValue =\n \"/setacvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\",\n DisabledValue =\n \"/setacvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\",\n Description = \"Switchable graphics (DC) - Maximum performance\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 000\",\n },\n }\n },\n },\n },\n // Battery Settings\n new OptimizationSetting\n {\n Id = \"power-battery-settings\",\n Name = \"Battery Notifications\",\n Description =\n \"When enabled, turns off low battery and critical battery notifications\",\n Category = OptimizationCategory.Power,\n GroupName = \"Battery\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\",\n Description = \"Critical battery notification (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\",\n Description = \"Critical battery notification (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\",\n Description = \"Critical battery action (AC) - Do nothing\",\n EnabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\",\n Description = \"Critical battery action (DC) - Do nothing\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\",\n Description = \"Low battery level (AC) - 0%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x0000000A\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\",\n Description = \"Low battery level (DC) - 0%\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x0000000A\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\",\n Description = \"Low battery notification (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\",\n Description = \"Low battery notification (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 001\",\n },\n }\n },\n },\n },\n // Battery Saver Settings\n new OptimizationSetting\n {\n Id = \"power-battery-saver-settings\",\n Name = \"Battery Saver\",\n Description =\n \"When enabled, prevents battery saver from activating at any battery level\",\n Category = OptimizationCategory.Power,\n GroupName = \"Battery Saver\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\",\n Description = \"Battery saver brightness (AC) - 100%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\",\n DisabledValue =\n \"/setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000032\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\",\n Description = \"Battery saver brightness (DC) - 100%\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000032\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\",\n Description = \"Battery saver threshold (AC) - 0%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000032\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\",\n Description = \"Battery saver threshold (DC) - 0%\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000032\",\n },\n }\n },\n },\n },\n },\n };\n }\n\n /// \n /// Contains all the powercfg commands for the Ultimate Performance Power Plan.\n /// \n public static class UltimatePerformancePowerPlan\n {\n public static readonly Dictionary PowerCfgCommands = new()\n {\n // Create and set the Ultimate Performance power plan\n {\n \"CreateUltimatePlan\",\n \"/duplicatescheme e9a42b02-d5df-448d-aa00-03f14749eb61 99999999-9999-9999-9999-999999999999\"\n },\n { \"SetActivePlan\", \"/SETACTIVE 99999999-9999-9999-9999-999999999999\" },\n // Hard disk settings\n {\n \"HardDiskTimeout_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\"\n },\n {\n \"HardDiskTimeout_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\"\n },\n // Desktop background slideshow\n {\n \"DesktopSlideshow_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 001\"\n },\n {\n \"DesktopSlideshow_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 001\"\n },\n // Wireless adapter settings\n {\n \"WirelessAdapter_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\"\n },\n {\n \"WirelessAdapter_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\"\n },\n // Sleep settings\n {\n \"SleepTimeout_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\"\n },\n {\n \"SleepTimeout_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\"\n },\n {\n \"HybridSleep_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\"\n },\n {\n \"HybridSleep_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\"\n },\n {\n \"HibernateTimeout_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\"\n },\n {\n \"HibernateTimeout_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\"\n },\n {\n \"WakeTimers_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\"\n },\n {\n \"WakeTimers_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\"\n },\n // USB settings\n {\n \"UsbHubTimeout_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\"\n },\n {\n \"UsbHubTimeout_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\"\n },\n {\n \"UsbSelectiveSuspend_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\"\n },\n {\n \"UsbSelectiveSuspend_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\"\n },\n {\n \"Usb3LinkPower_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\"\n },\n {\n \"Usb3LinkPower_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\"\n },\n // Power button action\n {\n \"PowerButtonAction_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\"\n },\n {\n \"PowerButtonAction_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\"\n },\n // PCI Express\n {\n \"PciExpressPower_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\"\n },\n {\n \"PciExpressPower_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\"\n },\n // Processor settings\n {\n \"ProcessorMinState_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 893dee8e-2bef-41e0-89c6-b55d0929964c 0x00000064\"\n },\n {\n \"ProcessorMinState_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 893dee8e-2bef-41e0-89c6-b55d0929964c 0x00000064\"\n },\n {\n \"CoolingPolicy_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 94d3a615-a899-4ac5-ae2b-e4d8f634367f 001\"\n },\n {\n \"CoolingPolicy_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 94d3a615-a899-4ac5-ae2b-e4d8f634367f 001\"\n },\n {\n \"ProcessorMaxState_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 bc5038f7-23e0-4960-96da-33abaf5935ec 0x00000064\"\n },\n {\n \"ProcessorMaxState_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 bc5038f7-23e0-4960-96da-33abaf5935ec 0x00000064\"\n },\n // Display settings\n {\n \"DisplayTimeout_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\"\n },\n {\n \"DisplayTimeout_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\"\n },\n {\n \"DisplayBrightness_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 aded5e82-b909-4619-9949-f5d71dac0bcb 0x00000064\"\n },\n {\n \"DisplayBrightness_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 aded5e82-b909-4619-9949-f5d71dac0bcb 0x00000064\"\n },\n {\n \"DimmedBrightness_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 f1fbfde2-a960-4165-9f88-50667911ce96 0x00000064\"\n },\n {\n \"DimmedBrightness_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 f1fbfde2-a960-4165-9f88-50667911ce96 0x00000064\"\n },\n {\n \"AdaptiveBrightness_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\"\n },\n {\n \"AdaptiveBrightness_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\"\n },\n // Video playback settings\n {\n \"VideoPlaybackQuality_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\"\n },\n {\n \"VideoPlaybackQuality_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\"\n },\n {\n \"VideoPlaybackQualityOnBattery_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\"\n },\n {\n \"VideoPlaybackQualityOnBattery_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\"\n },\n // Graphics settings\n {\n \"IntelGraphicsPower_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\"\n },\n {\n \"IntelGraphicsPower_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\"\n },\n {\n \"AmdPowerSlider_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\"\n },\n {\n \"AmdPowerSlider_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\"\n },\n {\n \"AtiPowerPlay_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\"\n },\n {\n \"AtiPowerPlay_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\"\n },\n {\n \"SwitchableGraphics_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\"\n },\n {\n \"SwitchableGraphics_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\"\n },\n // Battery settings\n {\n \"CriticalBatteryNotification_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\"\n },\n {\n \"CriticalBatteryNotification_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\"\n },\n {\n \"CriticalBatteryAction_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\"\n },\n {\n \"CriticalBatteryAction_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\"\n },\n {\n \"LowBatteryLevel_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\"\n },\n {\n \"LowBatteryLevel_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\"\n },\n {\n \"CriticalBatteryLevel_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 9a66d8d7-4ff7-4ef9-b5a2-5a326ca2a469 0x00000000\"\n },\n {\n \"CriticalBatteryLevel_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 9a66d8d7-4ff7-4ef9-b5a2-5a326ca2a469 0x00000000\"\n },\n {\n \"LowBatteryNotification_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\"\n },\n {\n \"LowBatteryNotification_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\"\n },\n {\n \"LowBatteryAction_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f d8742dcb-3e6a-4b3c-b3fe-374623cdcf06 000\"\n },\n {\n \"LowBatteryAction_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f d8742dcb-3e6a-4b3c-b3fe-374623cdcf06 000\"\n },\n {\n \"ReserveBatteryLevel_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f f3c5027d-cd16-4930-aa6b-90db844a8f00 0x00000000\"\n },\n {\n \"ReserveBatteryLevel_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f f3c5027d-cd16-4930-aa6b-90db844a8f00 0x00000000\"\n },\n // Battery Saver settings\n {\n \"BatterySaverBrightness_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\"\n },\n {\n \"BatterySaverBrightness_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\"\n },\n {\n \"BatterySaverThreshold_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\"\n },\n {\n \"BatterySaverThreshold_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\"\n },\n };\n }\n\n /// \n /// Provides access to all available power plans.\n /// \n public static class PowerPlans\n {\n /// \n /// The Balanced power plan.\n /// \n public static readonly PowerPlan Balanced = new PowerPlan\n {\n Name = \"Balanced\",\n Guid = \"381b4222-f694-41f0-9685-ff5bb260df2e\",\n Description =\n \"Automatically balances performance with energy consumption on capable hardware.\",\n };\n\n /// \n /// The High Performance power plan.\n /// \n public static readonly PowerPlan HighPerformance = new PowerPlan\n {\n Name = \"High Performance\",\n Guid = \"8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c\",\n Description = \"Favors performance, but may use more energy.\",\n };\n\n /// \n /// The Ultimate Performance power plan.\n /// \n public static readonly PowerPlan UltimatePerformance = new PowerPlan\n {\n Name = \"Ultimate Performance\",\n // This GUID is a placeholder and will be updated at runtime by PowerPlanService\n Guid = \"e9a42b02-d5df-448d-aa00-03f14749eb61\",\n Description = \"Provides ultimate performance on Windows.\",\n };\n\n /// \n /// Gets a list of all available power plans.\n /// \n /// A list of all power plans.\n public static List GetAllPowerPlans()\n {\n return new List { Balanced, HighPerformance, UltimatePerformance };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Models/WindowsApp.cs", "using System;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing System.Linq;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Models\n{\n /// \n /// Represents the type of Windows app.\n /// \n public enum WindowsAppType\n {\n /// \n /// Standard Windows application.\n /// \n StandardApp,\n\n /// \n /// Windows capability.\n /// \n Capability,\n\n /// \n /// Windows optional feature.\n /// \n OptionalFeature,\n }\n\n /// \n /// Represents a Windows built-in application that can be installed or removed.\n /// This includes system components, default Windows apps, and capabilities.\n /// \n public partial class WindowsApp : ObservableObject, IInstallableItem, ISearchable\n {\n public string PackageId => PackageID;\n public string DisplayName => Name;\n public InstallItemType ItemType => AppType switch\n {\n WindowsAppType.Capability => InstallItemType.Capability,\n WindowsAppType.OptionalFeature => InstallItemType.Feature,\n _ => InstallItemType.WindowsApp\n };\n public bool RequiresRestart { get; set; }\n\n // List of package names that cannot be reinstalled via winget/Microsoft Store\n private static readonly string[] NonReinstallablePackages = new string[]\n {\n \"Microsoft.MicrosoftOfficeHub\",\n \"Microsoft.MSPaint\",\n \"Microsoft.Getstarted\",\n };\n\n [ObservableProperty]\n private string _name = string.Empty;\n\n [ObservableProperty]\n private string _description = string.Empty;\n\n [ObservableProperty]\n private string _packageName = string.Empty;\n\n [ObservableProperty]\n private string _packageID = string.Empty;\n\n [ObservableProperty]\n private string _category = string.Empty;\n\n [ObservableProperty]\n private bool _isInstalled;\n\n [ObservableProperty]\n private bool _isSelected;\n\n [ObservableProperty]\n private bool _isSpecialHandler;\n\n [ObservableProperty]\n private string _specialHandlerType = string.Empty;\n\n [ObservableProperty]\n private string[]? _subPackages;\n\n [ObservableProperty]\n private AppRegistrySetting[]? _registrySettings;\n\n [ObservableProperty]\n private bool _isSystemProtected;\n\n [ObservableProperty]\n private bool _isNotReinstallable;\n\n /// \n /// Gets or sets a value indicating whether the item can be reinstalled or reenabled after removal.\n /// \n [ObservableProperty]\n private bool _canBeReinstalled = true;\n\n /// \n /// Gets or sets the type of Windows app.\n /// \n [ObservableProperty]\n private WindowsAppType _appType = WindowsAppType.StandardApp;\n\n /// \n /// Determines if the app should show its description.\n /// \n public bool HasDescription => !string.IsNullOrEmpty(Description);\n\n /// \n /// Gets a value indicating whether this app is a Windows capability.\n /// \n public bool IsCapability => AppType == WindowsAppType.Capability;\n\n /// \n /// Gets a value indicating whether this app is a Windows optional feature.\n /// \n public bool IsOptionalFeature => AppType == WindowsAppType.OptionalFeature;\n\n /// \n /// Creates a WindowsApp instance from an AppInfo model.\n /// \n /// The AppInfo model containing the app's data.\n /// A new WindowsApp instance.\n public static WindowsApp FromAppInfo(AppInfo appInfo)\n {\n // Map AppType to WindowsAppType\n WindowsAppType appType;\n switch (appInfo.Type)\n {\n case Winhance.Core.Features.SoftwareApps.Models.AppType.Capability:\n appType = WindowsAppType.Capability;\n break;\n case Winhance.Core.Features.SoftwareApps.Models.AppType.OptionalFeature:\n appType = WindowsAppType.OptionalFeature;\n break;\n case Winhance.Core.Features.SoftwareApps.Models.AppType.StandardApp:\n default:\n appType = WindowsAppType.StandardApp;\n break;\n }\n\n var app = new WindowsApp\n {\n Name = appInfo.Name,\n Description = appInfo.Description,\n PackageName = appInfo.PackageName,\n PackageID = appInfo.PackageID,\n Category = appInfo.Category,\n IsInstalled = appInfo.IsInstalled,\n IsSpecialHandler = appInfo.RequiresSpecialHandling,\n SpecialHandlerType = appInfo.SpecialHandlerType ?? string.Empty,\n SubPackages = appInfo.SubPackages,\n RegistrySettings = appInfo.RegistrySettings,\n IsSystemProtected = appInfo.IsSystemProtected,\n IsSelected = true,\n CanBeReinstalled = appInfo.CanBeReinstalled,\n AppType = appType,\n };\n\n // Check if this app is in the list of non-reinstallable packages\n app.IsNotReinstallable = Array.Exists(\n NonReinstallablePackages,\n p => p.Equals(appInfo.PackageName, StringComparison.OrdinalIgnoreCase)\n );\n\n return app;\n }\n\n /// \n /// Creates a WindowsApp instance from a CapabilityInfo model.\n /// \n /// The CapabilityInfo model containing the capability's data.\n /// A new WindowsApp instance.\n public static WindowsApp FromCapabilityInfo(CapabilityInfo capabilityInfo)\n {\n var app = new WindowsApp\n {\n Name = capabilityInfo.Name,\n Description = capabilityInfo.Description,\n PackageName = capabilityInfo.PackageName,\n PackageID = capabilityInfo.PackageName, // Ensure PackageID is set for capabilities\n Category = capabilityInfo.Category,\n IsInstalled = capabilityInfo.IsInstalled,\n RegistrySettings = capabilityInfo.RegistrySettings,\n IsSystemProtected = capabilityInfo.IsSystemProtected,\n CanBeReinstalled = capabilityInfo.CanBeReenabled,\n IsSelected = true,\n AppType = WindowsAppType.Capability,\n };\n\n return app;\n }\n\n /// \n /// Creates a WindowsApp instance from a FeatureInfo model.\n /// \n /// The FeatureInfo model containing the feature's data.\n /// A new WindowsApp instance.\n public static WindowsApp FromFeatureInfo(FeatureInfo featureInfo)\n {\n var app = new WindowsApp\n {\n Name = featureInfo.Name,\n Description = featureInfo.Description,\n PackageName = featureInfo.PackageName,\n PackageID = featureInfo.PackageName, // Ensure PackageID is set for features\n Category = featureInfo.Category,\n IsInstalled = featureInfo.IsInstalled,\n RegistrySettings = featureInfo.RegistrySettings,\n IsSystemProtected = featureInfo.IsSystemProtected,\n CanBeReinstalled = featureInfo.CanBeReenabled,\n IsSelected = true,\n AppType = WindowsAppType.OptionalFeature,\n };\n\n return app;\n }\n\n /// \n /// Converts this WindowsApp to an AppInfo object.\n /// \n /// An AppInfo object with data from this WindowsApp.\n public AppInfo ToAppInfo()\n {\n // Map WindowsAppType to AppType\n Winhance.Core.Features.SoftwareApps.Models.AppType appType;\n switch (AppType)\n {\n case WindowsAppType.Capability:\n appType = Winhance.Core.Features.SoftwareApps.Models.AppType.Capability;\n break;\n case WindowsAppType.OptionalFeature:\n appType = Winhance.Core.Features.SoftwareApps.Models.AppType.OptionalFeature;\n break;\n case WindowsAppType.StandardApp:\n default:\n appType = Winhance.Core.Features.SoftwareApps.Models.AppType.StandardApp;\n break;\n }\n\n return new AppInfo\n {\n Name = Name,\n Description = Description,\n PackageName = PackageName,\n PackageID = PackageID,\n Category = Category,\n IsInstalled = IsInstalled,\n RequiresSpecialHandling = IsSpecialHandler,\n SpecialHandlerType = SpecialHandlerType,\n SubPackages = SubPackages,\n RegistrySettings = RegistrySettings,\n IsSystemProtected = IsSystemProtected,\n CanBeReinstalled = CanBeReinstalled,\n Type = appType,\n Version = string.Empty // Default to empty string for version\n };\n }\n \n /// \n /// Converts this WindowsApp to a CapabilityInfo object.\n /// \n /// A CapabilityInfo object with data from this WindowsApp.\n public CapabilityInfo ToCapabilityInfo()\n {\n if (AppType != WindowsAppType.Capability)\n {\n throw new InvalidOperationException(\"Cannot convert non-capability WindowsApp to CapabilityInfo\");\n }\n \n return new CapabilityInfo\n {\n Name = Name,\n Description = Description,\n PackageName = PackageName,\n Category = Category,\n IsInstalled = IsInstalled,\n RegistrySettings = RegistrySettings,\n IsSystemProtected = IsSystemProtected,\n CanBeReenabled = CanBeReinstalled\n };\n }\n \n /// \n /// Converts this WindowsApp to a FeatureInfo object.\n /// \n /// A FeatureInfo object with data from this WindowsApp.\n public FeatureInfo ToFeatureInfo()\n {\n if (AppType != WindowsAppType.OptionalFeature)\n {\n throw new InvalidOperationException(\"Cannot convert non-feature WindowsApp to FeatureInfo\");\n }\n \n return new FeatureInfo\n {\n Name = Name,\n Description = Description,\n PackageName = PackageName,\n Category = Category,\n IsInstalled = IsInstalled,\n RegistrySettings = RegistrySettings,\n IsSystemProtected = IsSystemProtected,\n CanBeReenabled = CanBeReinstalled\n };\n }\n\n /// \n /// Determines if the app matches the given search term.\n /// \n /// The search term to match against.\n /// True if the app matches the search term, false otherwise.\n public bool MatchesSearch(string searchTerm)\n {\n if (string.IsNullOrWhiteSpace(searchTerm))\n {\n return true;\n }\n\n searchTerm = searchTerm.ToLowerInvariant();\n \n // Check if the search term matches any of the searchable properties\n return Name.ToLowerInvariant().Contains(searchTerm) ||\n (!string.IsNullOrEmpty(Description) && Description.ToLowerInvariant().Contains(searchTerm)) ||\n (!string.IsNullOrEmpty(PackageName) && PackageName.ToLowerInvariant().Contains(searchTerm)) ||\n (!string.IsNullOrEmpty(Category) && Category.ToLowerInvariant().Contains(searchTerm));\n }\n\n /// \n /// Gets the searchable properties of the app.\n /// \n /// An array of property names that should be searched.\n public string[] GetSearchableProperties()\n {\n return new[] { nameof(Name), nameof(Description), nameof(PackageName), nameof(Category) };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Services/LoggingService.cs", "using Microsoft.Extensions.Hosting;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System;\n\nnamespace Winhance.Core.Features.Common.Services\n{\n public class LoggingService : ILogService, IHostedService, IDisposable\n {\n private readonly ILogService _logService;\n \n public event EventHandler? LogMessageGenerated;\n\n public LoggingService(ILogService logService)\n {\n _logService = logService;\n \n // Subscribe to the inner log service events and forward them\n _logService.LogMessageGenerated += (sender, args) => \n {\n LogMessageGenerated?.Invoke(this, args);\n };\n }\n\n public void StartLog()\n {\n _logService.StartLog();\n }\n\n public void StopLog()\n {\n _logService.StopLog();\n }\n\n public Task StartAsync(CancellationToken cancellationToken)\n {\n _logService.StartLog();\n return Task.CompletedTask;\n }\n\n public Task StopAsync(CancellationToken cancellationToken)\n {\n _logService.StopLog();\n return Task.CompletedTask;\n }\n\n public void LogInformation(string message)\n {\n _logService.LogInformation(message);\n }\n\n public void LogWarning(string message)\n {\n _logService.LogWarning(message);\n }\n\n public void LogError(string message, Exception? exception)\n {\n _logService.LogError(message, exception);\n }\n\n public void LogSuccess(string message)\n {\n _logService.LogSuccess(message);\n }\n\n public void Log(LogLevel level, string message, Exception? exception = null)\n {\n _logService.Log(level, message, exception);\n }\n \n // Removed the incorrectly ordered Log method to fix the parameter order error\n // This was causing CS1503 errors with parameter type mismatches\n\n public string GetLogPath()\n {\n return _logService.GetLogPath();\n }\n\n public void Dispose()\n {\n if (_logService is IDisposable disposable)\n {\n disposable.Dispose();\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/SoundOptimizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class SoundOptimizations\n{\n public static OptimizationGroup GetSoundOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Sound\",\n Category = OptimizationCategory.Sound,\n Settings = new List\n {\n new OptimizationSetting\n {\n Id = \"sound-startup\",\n Name = \"Startup Sound During Boot\",\n Description = \"Controls the startup sound during boot and for the user\",\n Category = OptimizationCategory.Sound,\n GroupName = \"System Sounds\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Authentication\\\\LogonUI\\\\BootAnimation\",\n Name = \"DisableStartupSound\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, startup sound is enabled\n DisabledValue = 1, // When toggle is OFF, startup sound is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls the startup sound during boot\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\EditionOverrides\",\n Name = \"UserSetting_DisableStartupSound\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, user startup sound is enabled\n DisabledValue = 1, // When toggle is OFF, user startup sound is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls the startup sound for the user\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"sound-communication-ducking\",\n Name = \"Sound Ducking Preference\",\n Description = \"Controls sound behavior by reducing the volume of other sounds\",\n Category = OptimizationCategory.Sound,\n GroupName = \"System Sounds\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Multimedia\\\\Audio\",\n Name = \"UserDuckingPreference\",\n RecommendedValue = 3, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, sound ducking is enabled (1 = reduce other sounds by 80%)\n DisabledValue = 3, // When toggle is OFF, sound ducking is disabled (3 = do nothing)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls sound communications behavior\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"sound-voice-activation\",\n Name = \"Voice Activation for Apps\",\n Description = \"Controls voice activation for all apps\",\n Category = OptimizationCategory.Sound,\n GroupName = \"System Sounds\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\SpeechOneCore\\\\Settings\",\n Name = \"AgentActivationEnabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, voice activation is enabled\n DisabledValue = 0, // When toggle is OFF, voice activation is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls voice activation for all apps\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"sound-voice-activation-last-used\",\n Name = \"Last Used Voice Activation Setting\",\n Description = \"Controls the last used voice activation setting\",\n Category = OptimizationCategory.Sound,\n GroupName = \"System Sounds\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\SpeechOneCore\\\\Settings\",\n Name = \"AgentActivationLastUsed\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, last used voice activation is enabled\n DisabledValue = 0, // When toggle is OFF, last used voice activation is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls the last used voice activation setting\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"sound-effects-enhancements\",\n Name = \"Sound Effects and Enhancements\",\n Description = \"Controls audio enhancements for playback devices\",\n Category = OptimizationCategory.Sound,\n GroupName = \"Audio Enhancements\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Multimedia\\\\Audio\\\\DeviceFx\",\n Name = \"EnableDeviceEffects\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, audio enhancements are enabled\n DisabledValue = 0, // When toggle is OFF, audio enhancements are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls audio enhancements for playback devices\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"sound-spatial-audio\",\n Name = \"Spatial Sound Settings\",\n Description = \"Controls Windows Sonic and spatial sound features\",\n Category = OptimizationCategory.Sound,\n GroupName = \"Audio Enhancements\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Audio\",\n Name = \"EnableSpatialSound\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, spatial sound is enabled\n DisabledValue = 0, // When toggle is OFF, spatial sound is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Windows Sonic and spatial sound features\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/UI/Services/NotificationService.cs", "using System;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.UI.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.UI.Services\n{\n /// \n /// Implementation of the notification service that shows toast notifications.\n /// \n public class NotificationService : INotificationService\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public NotificationService(ILogService logService)\n {\n _logService = logService;\n }\n\n /// \n public void ShowToast(string title, string message, ToastType type)\n {\n // Log the notification\n switch (type)\n {\n case ToastType.Information:\n _logService.LogInformation($\"Toast Notification - {title}: {message}\");\n break;\n case ToastType.Success:\n _logService.LogSuccess($\"Toast Notification - {title}: {message}\");\n break;\n case ToastType.Warning:\n _logService.LogWarning($\"Toast Notification - {title}: {message}\");\n break;\n case ToastType.Error:\n _logService.LogError($\"Toast Notification - {title}: {message}\");\n break;\n default:\n _logService.LogInformation($\"Toast Notification - {title}: {message}\");\n break;\n }\n\n // In a real implementation, this would show a toast notification in the UI\n // For now, we're just logging the notification\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/VerificationMethodBase.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification\n{\n /// \n /// Base class for verification methods that provides common functionality.\n /// \n public abstract class VerificationMethodBase : IVerificationMethod\n {\n /// \n /// Initializes a new instance of the class.\n /// \n /// The name of the verification method.\n /// The priority of the verification method. Lower numbers indicate higher priority.\n protected VerificationMethodBase(string name, int priority)\n {\n if (string.IsNullOrWhiteSpace(name))\n throw new ArgumentException(\n \"Verification method name cannot be null or whitespace.\",\n nameof(name)\n );\n\n Name = name;\n Priority = priority;\n }\n\n /// \n public string Name { get; }\n\n /// \n public int Priority { get; }\n\n /// \n public async Task VerifyAsync(\n string packageId,\n string version = null,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n try\n {\n if (version == null)\n {\n return await VerifyPresenceAsync(packageId, cancellationToken)\n .ConfigureAwait(false);\n }\n\n return await VerifyVersionAsync(packageId, version, cancellationToken)\n .ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n return new VerificationResult\n {\n IsVerified = false,\n Message = $\"Error during verification using {Name}: {ex.Message}\",\n MethodUsed = Name,\n };\n }\n }\n\n /// \n /// Verifies if a package is present (without version check).\n /// \n /// The ID of the package to verify.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the verification result.\n protected abstract Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken\n );\n\n /// \n /// Verifies if a package is present with the specified version.\n /// \n /// The ID of the package to verify.\n /// The expected version of the package.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the verification result.\n protected abstract Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken\n );\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Extensions/SettingViewModelExtensions.cs", "using System;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Extensions\n{\n /// \n /// Extension methods for setting view models.\n /// \n public static class SettingViewModelExtensions\n {\n /// \n /// Safely converts an ApplicationSettingViewModel to an ApplicationSettingViewModel if possible.\n /// \n /// The setting to convert.\n /// The setting as an ApplicationSettingViewModel, or null if conversion is not possible.\n public static ApplicationSettingViewModel? AsApplicationSettingViewModel(this ApplicationSettingViewModel setting)\n {\n return setting;\n }\n \n /// \n /// Creates a new ApplicationSettingViewModel with properties copied from an ApplicationSettingViewModel.\n /// \n /// The setting to convert.\n /// The registry service.\n /// The dialog service.\n /// The log service.\n /// The dependency manager.\n /// The view model locator.\n /// The settings registry.\n /// A new ApplicationSettingViewModel with properties copied from the input setting.\n public static ApplicationSettingViewModel ToApplicationSettingViewModel(\n this ApplicationSettingViewModel setting,\n IRegistryService registryService,\n IDialogService? dialogService,\n ILogService logService,\n IDependencyManager? dependencyManager = null,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n {\n if (setting is ApplicationSettingViewModel applicationSetting)\n {\n return applicationSetting;\n }\n \n var result = new ApplicationSettingViewModel(\n registryService, \n dialogService, \n logService, \n dependencyManager)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsGroupHeader = setting.IsGroupHeader,\n IsGroupedSetting = setting.IsGroupedSetting,\n ControlType = setting.ControlType,\n SliderSteps = setting.SliderSteps,\n SliderValue = setting.SliderValue,\n Status = setting.Status,\n CurrentValue = setting.CurrentValue,\n StatusMessage = setting.StatusMessage,\n RegistrySetting = setting.RegistrySetting,\n LinkedRegistrySettings = setting.LinkedRegistrySettings,\n Dependencies = setting.Dependencies\n };\n \n // Copy child settings if any\n foreach (var child in setting.ChildSettings)\n {\n result.ChildSettings.Add(child.ToApplicationSettingViewModel(\n registryService, \n dialogService, \n logService, \n dependencyManager, \n viewModelLocator, \n settingsRegistry));\n }\n \n return result;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/WindowStateToCommandConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Input;\n\nnamespace Winhance.WPF.Converters\n{\n public class WindowStateToCommandConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is WindowState windowState)\n {\n return windowState == WindowState.Maximized\n ? SystemCommands.RestoreWindowCommand\n : SystemCommands.MaximizeWindowCommand;\n }\n \n return SystemCommands.MaximizeWindowCommand;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/WindowsAppCatalog.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a catalog of Windows built-in applications that can be removed.\n/// \npublic class WindowsAppCatalog\n{\n /// \n /// Gets or sets the collection of removable Windows applications.\n /// \n public IReadOnlyList WindowsApps { get; init; } = new List();\n\n /// \n /// Creates a default Windows app catalog with predefined removable apps.\n /// \n /// A new WindowsAppCatalog instance with default apps.\n public static WindowsAppCatalog CreateDefault()\n {\n return new WindowsAppCatalog { WindowsApps = CreateDefaultWindowsApps() };\n }\n\n private static List CreateDefaultWindowsApps()\n {\n return new List\n {\n // 3D/Mixed Reality\n new AppInfo\n {\n Name = \"3D Viewer\",\n Description = \"View 3D models and animations\",\n PackageName = \"Microsoft.Microsoft3DViewer\",\n PackageID = \"9NBLGGH42THS\",\n Category = \"3D/Mixed Reality\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Mixed Reality Portal\",\n Description = \"Portal for Windows Mixed Reality experiences\",\n PackageName = \"Microsoft.MixedReality.Portal\",\n PackageID = \"9NG1H8B3ZC7M\",\n Category = \"3D/Mixed Reality\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Bing/Search\n new AppInfo\n {\n Name = \"Bing Search\",\n Description = \"Bing search integration for Windows\",\n PackageName = \"Microsoft.BingSearch\",\n PackageID = \"9NZBF4GT040C\",\n Category = \"Bing\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Microsoft News\",\n Description = \"Microsoft News app\",\n PackageName = \"Microsoft.BingNews\",\n PackageID = \"9WZDNCRFHVFW\",\n Category = \"Bing\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"MSN Weather\",\n Description = \"Weather forecasts and information\",\n PackageName = \"Microsoft.BingWeather\",\n PackageID = \"9WZDNCRFJ3Q2\",\n Category = \"Bing/Search\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Camera/Media\n new AppInfo\n {\n Name = \"Camera\",\n Description = \"Windows Camera app\",\n PackageName = \"Microsoft.WindowsCamera\",\n PackageID = \"9WZDNCRFJBBG\",\n Category = \"Camera/Media\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Clipchamp\",\n Description = \"Video editor app\",\n PackageName = \"Clipchamp.Clipchamp\",\n PackageID = \"9P1J8S7CCWWT\",\n Category = \"Camera/Media\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // System Utilities\n new AppInfo\n {\n Name = \"Alarms & Clock\",\n Description = \"Clock, alarms, timer, and stopwatch app\",\n PackageName = \"Microsoft.WindowsAlarms\",\n PackageID = \"9WZDNCRFJ3PR\",\n Category = \"System Utilities\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Cortana\",\n Description = \"Microsoft's virtual assistant\",\n PackageName = \"Microsoft.549981C3F5F10\",\n PackageID = \"9NFFX4SZZ23L\",\n Category = \"System Utilities\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Get Help\",\n Description = \"Microsoft support app\",\n PackageName = \"Microsoft.GetHelp\",\n PackageID = \"9PKDZBMV1H3T\",\n Category = \"System Utilities\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Calculator\",\n Description = \"Calculator app with standard, scientific, and programmer modes\",\n PackageName = \"Microsoft.WindowsCalculator\",\n PackageID = \"9WZDNCRFHVN5\",\n Category = \"System Utilities\",\n IsSystemProtected = true,\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Development\n new AppInfo\n {\n Name = \"Dev Home\",\n Description = \"Development environment for Windows\",\n PackageName = \"Microsoft.Windows.DevHome\",\n PackageID = \"9WZDNCRFHVN5\",\n Category = \"Development\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Communication & Family\n new AppInfo\n {\n Name = \"Microsoft Family Safety\",\n Description = \"Family safety and screen time management\",\n PackageName = \"MicrosoftCorporationII.MicrosoftFamily\",\n PackageID = \"9PDJDJS743XF\",\n Category = \"Communication\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Mail and Calendar\",\n Description = \"Microsoft Mail and Calendar apps\",\n PackageName = \"microsoft.windowscommunicationsapps\",\n PackageID = \"9WZDNCRFHVQM\",\n Category = \"Communication\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Skype\",\n Description = \"Video calling and messaging app\",\n PackageName = \"Microsoft.SkypeApp\",\n PackageID = \"9WZDNCRFJ364\",\n Category = \"Communication\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Microsoft Teams\",\n Description = \"Team collaboration and communication app\",\n PackageName = \"MSTeams\",\n PackageID = \"XP8BT8DW290MPQ\",\n Category = \"Communication\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // System Tools\n new AppInfo\n {\n Name = \"Feedback Hub\",\n Description = \"App for sending feedback to Microsoft\",\n PackageName = \"Microsoft.WindowsFeedbackHub\",\n PackageID = \"9NBLGGH4R32N\",\n Category = \"System Tools\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Maps\",\n Description = \"Microsoft Maps app\",\n PackageName = \"Microsoft.WindowsMaps\",\n PackageID = \"9WZDNCRDTBVB\",\n Category = \"System Tools\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Terminal\",\n Description = \"Modern terminal application for Windows\",\n PackageName = \"Microsoft.WindowsTerminal\",\n PackageID = \"9N0DX20HK701\",\n Category = \"System Tools\",\n IsSystemProtected = true,\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Office & Productivity\n new AppInfo\n {\n Name = \"Office Hub\",\n Description = \"Microsoft Office app hub\",\n PackageName = \"Microsoft.MicrosoftOfficeHub\",\n Category = \"Office\",\n CanBeReinstalled = false,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"OneNote\",\n Description = \"Microsoft note-taking app\",\n PackageName = \"Microsoft.Office.OneNote\",\n PackageID = \"XPFFZHVGQWWLHB\",\n Category = \"Office\",\n CanBeReinstalled = true,\n RequiresSpecialHandling = true,\n SpecialHandlerType = \"OneNote\",\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Outlook for Windows\",\n Description = \"Reimagined Outlook app for Windows\",\n PackageName = \"Microsoft.OutlookForWindows\",\n PackageID = \"9NRX63209R7B\",\n Category = \"Office\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Graphics & Images\n new AppInfo\n {\n Name = \"Paint 3D\",\n Description = \"3D modeling and editing app\",\n PackageName = \"Microsoft.MSPaint\",\n Category = \"Graphics\",\n CanBeReinstalled = false,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Paint\",\n Description = \"Traditional image editing app\",\n PackageName = \"Microsoft.Paint\",\n PackageID = \"9PCFS5B6T72H\",\n Category = \"Graphics\",\n IsSystemProtected = true,\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Photos\",\n Description = \"Photo viewing and editing app\",\n PackageName = \"Microsoft.Windows.Photos\",\n PackageID = \"9WZDNCRFJBH4\",\n Category = \"Graphics\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Snipping Tool\",\n Description = \"Screen capture and annotation tool\",\n PackageName = \"Microsoft.ScreenSketch\",\n PackageID = \"9MZ95KL8MR0L\",\n Category = \"Graphics\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Social & People\n new AppInfo\n {\n Name = \"People\",\n Description = \"Contact management app\",\n PackageName = \"Microsoft.People\",\n PackageID = \"9NBLGGH10PG8\",\n Category = \"Social\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Automation\n new AppInfo\n {\n Name = \"Power Automate\",\n Description = \"Desktop automation tool\",\n PackageName = \"Microsoft.PowerAutomateDesktop\",\n PackageID = \"9NFTCH6J7FHV\",\n Category = \"Automation\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Support Tools\n new AppInfo\n {\n Name = \"Quick Assist\",\n Description = \"Remote assistance tool\",\n PackageName = \"MicrosoftCorporationII.QuickAssist\",\n PackageID = \"9P7BP5VNWKX5\",\n Category = \"Support\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Games & Entertainment\n new AppInfo\n {\n Name = \"Solitaire Collection\",\n Description = \"Microsoft Solitaire Collection games\",\n PackageName = \"Microsoft.MicrosoftSolitaireCollection\",\n PackageID = \"9WZDNCRFHWD2\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Xbox\",\n Description = \"Xbox App for Windows\",\n PackageName = \"Microsoft.GamingApp\", // New Xbox Package Name (Windows 11)\n PackageID = \"9MV0B5HZVK9Z\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n SubPackages = new string[]\n {\n \"Microsoft.XboxApp\", // Microsoft.XboxApp is deprecated but still on Windows 10 22H2 ISO's\n },\n RegistrySettings = new AppRegistrySetting[]\n {\n new AppRegistrySetting\n {\n Path = @\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\GameDVR\",\n Name = \"AppCaptureEnabled\",\n Value = 0,\n ValueKind = Microsoft.Win32.RegistryValueKind.DWord,\n Description =\n \"Disables the Get an app to open this 'ms-gamingoverlay' popup\",\n },\n },\n },\n new AppInfo\n {\n Name = \"Xbox Identity Provider\",\n Description =\n \"Authentication service for Xbox Live and related Microsoft gaming services\",\n PackageName = \"Microsoft.XboxIdentityProvider\",\n PackageID = \"9WZDNCRD1HKW\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Xbox Game Bar Plugin\",\n Description =\n \"Extension component for Xbox Game Bar providing additional functionality\",\n PackageName = \"Microsoft.XboxGameOverlay\",\n PackageID = \"9NBLGGH537C2\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Xbox Live In-Game Experience\",\n Description = \"Core component for Xbox Live services within games\",\n PackageName = \"Microsoft.Xbox.TCUI\",\n PackageID = \"9NKNC0LD5NN6\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Xbox Game Bar\",\n Description =\n \"Gaming overlay with screen capture, performance monitoring, and social features\",\n PackageName = \"Microsoft.XboxGamingOverlay\",\n PackageID = \"9NZKPSTSNW4P\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Windows Store\n new AppInfo\n {\n Name = \"Microsoft Store\",\n Description = \"App store for Windows\",\n PackageName = \"Microsoft.WindowsStore\",\n PackageID = \"9WZDNCRFJBMP\",\n Category = \"Store\",\n IsSystemProtected = true,\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Media Players\n new AppInfo\n {\n Name = \"Media Player\",\n Description = \"Music player app\",\n PackageName = \"Microsoft.ZuneMusic\",\n PackageID = \"9WZDNCRFJ3PT\",\n Category = \"Media\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Movies & TV\",\n Description = \"Video player app\",\n PackageName = \"Microsoft.ZuneVideo\",\n PackageID = \"9WZDNCRFJ3P2\",\n Category = \"Media\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Sound Recorder\",\n Description = \"Audio recording app\",\n PackageName = \"Microsoft.WindowsSoundRecorder\",\n PackageID = \"9WZDNCRFHWKN\",\n Category = \"Media\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Productivity Tools\n new AppInfo\n {\n Name = \"Sticky Notes\",\n Description = \"Note-taking app\",\n PackageName = \"Microsoft.MicrosoftStickyNotes\",\n PackageID = \"9NBLGGH4QGHW\",\n Category = \"Productivity\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Tips\",\n Description = \"Windows tutorial app\",\n PackageName = \"Microsoft.Getstarted\",\n Category = \"Productivity\",\n CanBeReinstalled = false,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"To Do\",\n Description = \"Task management app\",\n PackageName = \"Microsoft.Todos\",\n PackageID = \"9NBLGGH5R558\",\n Category = \"Productivity\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Notepad\",\n Description = \"Text editing app\",\n PackageName = \"Microsoft.WindowsNotepad\",\n PackageID = \"9MSMLRH6LZF3\",\n Category = \"Productivity\",\n IsSystemProtected = true,\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Phone Integration\n new AppInfo\n {\n Name = \"Phone Link\",\n Description = \"Connect your Android or iOS device to Windows\",\n PackageName = \"Microsoft.YourPhone\",\n PackageID = \"9NMPJ99VJBWV\",\n Category = \"Phone\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // AI & Copilot\n new AppInfo\n {\n Name = \"Copilot\",\n Description =\n \"AI assistant for Windows, includes Copilot provider and Store components\",\n PackageName = \"Microsoft.Copilot\",\n PackageID = \"9NHT9RB2F4HD\",\n Category = \"AI\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n SubPackages = new string[]\n {\n \"Microsoft.Windows.Ai.Copilot.Provider\",\n \"Microsoft.Copilot_8wekyb3d8bbwe\",\n },\n RegistrySettings = new AppRegistrySetting[]\n {\n new AppRegistrySetting\n {\n Path = @\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced\",\n Name = \"ShowCopilotButton\",\n Value = 0,\n ValueKind = Microsoft.Win32.RegistryValueKind.DWord,\n Description = \"Hide Copilot button from taskbar\",\n },\n new AppRegistrySetting\n {\n Path = @\"HKLM\\Software\\Policies\\Microsoft\\Windows\\CloudContent\",\n Name = \"TurnOffWindowsCopilot\",\n Value = 1,\n ValueKind = Microsoft.Win32.RegistryValueKind.DWord,\n Description = \"Disable Windows Copilot system-wide\",\n },\n },\n },\n // Special Items that require special handling\n new AppInfo\n {\n Name = \"Microsoft Edge\",\n Description = \"Microsoft's web browser (requires special removal process)\",\n PackageName = \"Edge\",\n PackageID = \"XPFFTQ037JWMHS\",\n Category = \"Browsers\",\n CanBeReinstalled = true,\n RequiresSpecialHandling = true,\n SpecialHandlerType = \"Edge\",\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"OneDrive\",\n Description =\n \"Microsoft's cloud storage service (requires special removal process)\",\n PackageName = \"OneDrive\",\n PackageID = \"Microsoft.OneDrive\",\n Category = \"System\",\n CanBeReinstalled = true,\n RequiresSpecialHandling = true,\n SpecialHandlerType = \"OneDrive\",\n Type = AppType.StandardApp,\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Extensions/RegistrySettingExtensions.cs", "using Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Extensions\n{\n /// \n /// Extension methods for RegistrySetting.\n /// \n public static class RegistrySettingExtensions\n {\n /// \n /// Determines if the registry setting is for HttpAcceptLanguageOptOut.\n /// \n /// The registry setting to check.\n /// True if the setting is for HttpAcceptLanguageOptOut; otherwise, false.\n public static bool IsHttpAcceptLanguageOptOut(this RegistrySetting setting)\n {\n if (setting == null)\n return false;\n\n return setting.SubKey == \"Control Panel\\\\International\\\\User Profile\" &&\n setting.Name == \"HttpAcceptLanguageOptOut\";\n }\n\n /// \n /// Determines if the registry setting requires special handling.\n /// \n /// The registry setting to check.\n /// True if the setting requires special handling; otherwise, false.\n public static bool RequiresSpecialHandling(this RegistrySetting setting)\n {\n if (setting == null)\n return false;\n\n // Currently, only HttpAcceptLanguageOptOut requires special handling\n return IsHttpAcceptLanguageOptOut(setting);\n }\n\n /// \n /// Applies special handling for the registry setting.\n /// \n /// The registry setting to apply special handling for.\n /// The registry service to use.\n /// Whether the setting is being enabled or disabled.\n /// True if the special handling was applied successfully; otherwise, false.\n public static bool ApplySpecialHandling(this RegistrySetting setting, IRegistryService registryService, bool isEnabled)\n {\n if (setting == null || registryService == null)\n return false;\n\n if (IsHttpAcceptLanguageOptOut(setting) && isEnabled && setting.EnabledValue != null &&\n ((setting.EnabledValue is int intValue && intValue == 0) ||\n (setting.EnabledValue is string strValue && strValue == \"0\")))\n {\n // When enabling language list access, Windows deletes the key entirely\n string hiveString = GetRegistryHiveString(setting.Hive);\n return registryService.DeleteValue(\n $\"{hiveString}\\\\{setting.SubKey}\",\n setting.Name);\n }\n\n // No special handling needed or applicable\n return false;\n }\n\n /// \n /// Converts a RegistryHive enum to its string representation (HKCU, HKLM, etc.)\n /// \n /// The registry hive.\n /// The string representation of the registry hive.\n private static string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => throw new System.ArgumentException($\"Unsupported registry hive: {hive}\")\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/UpdateOptimizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class UpdateOptimizations\n{\n public static OptimizationGroup GetUpdateOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Windows Updates\",\n Category = OptimizationCategory.Updates,\n Settings = new List\n {\n new OptimizationSetting\n {\n Id = \"updates-auto-update\",\n Name = \"Automatic Windows Updates\",\n Description = \"Controls automatic Windows updates behavior\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Windows Update Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\\\\AU\",\n Name = \"NoAutoUpdate\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, automatic updates are enabled\n DisabledValue = 1, // When toggle is OFF, automatic updates are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls automatic Windows updates\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\\\\AU\",\n Name = \"AUOptions\",\n RecommendedValue = 2,\n EnabledValue = 4, // When toggle is ON, auto download and schedule install (4)\n DisabledValue = 2, // When toggle is OFF, notify before download (2)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls automatic update behavior\",\n },\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\\\\AU\",\n Name = \"AutoInstallMinorUpdates\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, minor updates are installed automatically\n DisabledValue = 0, // When toggle is OFF, minor updates are not installed automatically\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls automatic installation of minor updates\",\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"updates-defer-feature-updates\",\n Name = \"Delay Feature Updates for 365 Days\",\n Description = \"Delays major Windows feature updates for 365 days\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Windows Update Policies\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"DeferFeatureUpdates\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, feature updates are deferred\n DisabledValue = 0, // When toggle is OFF, feature updates are not deferred\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Enables deferral of feature updates\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"DeferFeatureUpdatesPeriodInDays\",\n RecommendedValue = 365,\n EnabledValue = 365, // When toggle is ON, feature updates are deferred for 365 days\n DisabledValue = 0, // When toggle is OFF, feature updates are not deferred\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Sets the deferral period for feature updates to 365 days\",\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"updates-defer-quality-updates\",\n Name = \"Delay Security Updates for 7 Days\",\n Description = \"Delays Windows security and quality updates for 7 days\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Windows Update Policies\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"DeferQualityUpdates\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, quality updates are deferred\n DisabledValue = 0, // When toggle is OFF, quality updates are not deferred\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Enables deferral of security and quality updates\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"DeferQualityUpdatesPeriodInDays\",\n RecommendedValue = 7,\n EnabledValue = 7, // When toggle is ON, quality updates are deferred for 7 days\n DisabledValue = 0, // When toggle is OFF, quality updates are not deferred\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Sets the deferral period for security and quality updates to 7 days\",\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"updates-delivery-optimization\",\n Name = \"Delivery Optimization (LAN)\",\n Description = \"Controls peer-to-peer update distribution\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Delivery Optimization\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\DeliveryOptimization\",\n Name = \"DODownloadMode\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, peer-to-peer update distribution is enabled (LAN only)\n DisabledValue = 0, // When toggle is OFF, peer-to-peer update distribution is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls peer-to-peer update distribution\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-store-auto-download\",\n Name = \"Auto Update Microsoft Store Apps\",\n Description = \"Controls automatic updates for Microsoft Store apps\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Microsoft Store\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\WindowsStore\",\n Name = \"AutoDownload\",\n RecommendedValue = 2,\n EnabledValue = 4, // When toggle is ON, automatic updates for Microsoft Store apps are enabled\n DisabledValue = 2, // When toggle is OFF, automatic updates for Microsoft Store apps are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls automatic updates for Microsoft Store apps\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-app-archiving\",\n Name = \"Automatic Archiving of Unused Apps\",\n Description = \"Controls automatic archiving of unused apps\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Microsoft Store\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\Appx\",\n Name = \"AllowAutomaticAppArchiving\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, automatic archiving of unused apps is enabled\n DisabledValue = 0, // When toggle is OFF, automatic archiving of unused apps is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls automatic archiving of unused apps\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-restart-options\",\n Name = \"Prevent Automatic Restarts\",\n Description =\n \"Prevents automatic restarts after installing updates when users are logged on\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Update Behavior\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\\\\AU\",\n Name = \"NoAutoRebootWithLoggedOnUsers\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, automatic restarts are prevented\n DisabledValue = 1, // When toggle is OFF, automatic restarts are allowed\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls automatic restart behavior after updates\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-driver-controls\",\n Name = \"Do Not Include Drivers with Updates\",\n Description = \"Does not include driver updates with Windows quality updates\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Update Content\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"ExcludeWUDriversInQualityUpdate\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, driver updates are included\n DisabledValue = 1, // When toggle is OFF, driver updates are excluded\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Controls whether driver updates are included in Windows quality updates\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-notification-level\",\n Name = \"Update Notifications\",\n Description = \"Controls the visibility of update notifications\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Update Behavior\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"SetUpdateNotificationLevel\",\n RecommendedValue = 1,\n EnabledValue = 2, // When toggle is ON, show all notifications (2 = default)\n DisabledValue = 1, // When toggle is OFF, show only restart required notifications (1 = reduced)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls the visibility level of update notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-metered-connection\",\n Name = \"Updates on Metered Connections\",\n Description =\n \"Controls whether updates are downloaded over metered connections\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Update Behavior\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\WindowsUpdate\\\\UX\\\\Settings\",\n Name = \"AllowAutoWindowsUpdateDownloadOverMeteredNetwork\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, updates are downloaded over metered connections\n DisabledValue = 0, // When toggle is OFF, updates are not downloaded over metered connections\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Controls update download behavior on metered connections\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/UacOptimizations.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Models.Enums;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class UacOptimizations\n{\n public const string RegistryPath = @\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\";\n public const string ConsentPromptName = \"ConsentPromptBehaviorAdmin\";\n public const string SecureDesktopName = \"PromptOnSecureDesktop\";\n public static readonly RegistryValueKind ValueKind = RegistryValueKind.DWord;\n\n // UAC settings require two registry values working together\n // ConsentPromptBehaviorAdmin controls the behavior type\n // PromptOnSecureDesktop controls whether the desktop is dimmed\n\n // Map from UacLevel enum to ConsentPromptBehaviorAdmin registry values\n public static readonly Dictionary UacLevelToConsentPromptValue = new()\n {\n { UacLevel.NeverNotify, 0 }, // Never notify\n { UacLevel.NotifyNoDesktopDim, 5 }, // Notify without dimming desktop\n { UacLevel.NotifyChangesOnly, 5 }, // Notify only for changes (default)\n { UacLevel.AlwaysNotify, 2 }, // Always notify\n };\n\n // Map from UacLevel enum to PromptOnSecureDesktop registry values\n public static readonly Dictionary UacLevelToSecureDesktopValue = new()\n {\n { UacLevel.NeverNotify, 0 }, // Secure desktop disabled\n { UacLevel.NotifyNoDesktopDim, 0 }, // Secure desktop disabled\n { UacLevel.NotifyChangesOnly, 1 }, // Secure desktop enabled\n { UacLevel.AlwaysNotify, 1 }, // Secure desktop enabled\n };\n\n // User-friendly names for each UAC level\n public static readonly Dictionary UacLevelNames = new()\n {\n { UacLevel.AlwaysNotify, \"Always notify\" },\n { UacLevel.NotifyChangesOnly, \"Notify when apps try to make changes\" },\n { UacLevel.NotifyNoDesktopDim, \"Notify when apps try to make changes (no dim)\" },\n { UacLevel.NeverNotify, \"Never notify\" },\n { UacLevel.Custom, \"Custom UAC Setting\" },\n };\n\n /// \n /// Helper method to get UacLevel from both registry values\n /// \n /// The ConsentPromptBehaviorAdmin registry value\n /// The PromptOnSecureDesktop registry value\n /// Optional UAC settings service to save custom values\n /// The corresponding UacLevel\n public static UacLevel GetUacLevelFromRegistryValues(\n int consentPromptValue,\n int secureDesktopValue,\n IUacSettingsService uacSettingsService = null\n )\n {\n // Check for exact matches of both values\n foreach (var level in UacLevelToConsentPromptValue.Keys)\n {\n if (\n UacLevelToConsentPromptValue[level] == consentPromptValue\n && UacLevelToSecureDesktopValue[level] == secureDesktopValue\n )\n {\n return level;\n }\n }\n\n // If no exact match, determine if it's one of the common non-standard combinations\n if (consentPromptValue == 0)\n {\n return UacLevel.NeverNotify; // ConsentPrompt=0 always means Never Notify\n }\n else if (consentPromptValue == 5)\n {\n // ConsentPrompt=5 with SecureDesktop determines dimming\n return secureDesktopValue == 0\n ? UacLevel.NotifyNoDesktopDim\n : UacLevel.NotifyChangesOnly;\n }\n else if (consentPromptValue == 2)\n {\n return UacLevel.AlwaysNotify; // ConsentPrompt=2 is Always Notify\n }\n\n // If we get here, we have a custom UAC setting\n // Save the custom values if we have a service\n if (uacSettingsService != null)\n {\n // Save asynchronously - fire and forget\n _ = Task.Run(() => uacSettingsService.SaveCustomUacSettingsAsync(consentPromptValue, secureDesktopValue));\n }\n \n return UacLevel.Custom;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/ExplorerOptimizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class ExplorerOptimizations\n{\n public static OptimizationGroup GetExplorerOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Explorer\",\n Category = OptimizationCategory.Explorer,\n Settings = new List\n {\n new OptimizationSetting\n {\n Id = \"explorer-long-paths-enabled\",\n Name = \"Long Paths Enabled\",\n Description = \"Controls support for long file paths (up to 32,767 characters)\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\FileSystem\",\n Name = \"LongPathsEnabled\",\n RecommendedValue = 1,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description =\n \"Controls support for long file paths (up to 32,767 characters)\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-block-aad-workplace-join\",\n Name = \"Block AAD Workplace Join\",\n Description = \"Controls 'Allow my organization to manage my device' pop-up\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\System\",\n Name = \"BlockAADWorkplaceJoin\",\n RecommendedValue = 1,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description =\n \"Controls 'Allow my organization to manage my device' pop-up\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-disable-sync-provider-notifications\",\n Name = \"Sync Provider Notifications\",\n Description = \"Controls sync provider notifications visibility\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowSyncProviderNotifications\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls sync provider notifications visibility\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-tablet-mode\",\n Name = \"Tablet Mode\",\n Description = \"Controls Tablet Mode\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"System Interface\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ImmersiveShell\",\n Name = \"TabletMode\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, tablet mode is enabled\n DisabledValue = 0, // When toggle is OFF, tablet mode is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls Tablet Mode\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-desktop-mode-signin\",\n Name = \"Desktop Mode on Sign-in\",\n Description = \"Controls whether the system goes to desktop mode on sign-in\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"System Interface\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ImmersiveShell\",\n Name = \"SignInMode\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, system goes to desktop mode on sign-in\n DisabledValue = 0, // When toggle is OFF, system uses default behavior\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description =\n \"Controls whether the system goes to desktop mode on sign-in\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-voice-typing\",\n Name = \"Voice Typing Button\",\n Description = \"Controls voice typing microphone button\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"Input Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\InputSettings\",\n Name = \"IsVoiceTypingKeyEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, voice typing is enabled\n DisabledValue = 0, // When toggle is OFF, voice typing is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls voice typing microphone button\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-typing-insights\",\n Name = \"Typing Insights\",\n Description = \"Controls typing insights and suggestions\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"Input Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\InputSettings\",\n Name = \"InsightsEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, typing insights are enabled\n DisabledValue = 0, // When toggle is OFF, typing insights are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls typing insights and suggestions\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-suggested-actions\",\n Name = \"Clipboard Suggested Actions\",\n Description = \"Controls suggested actions for clipboard content\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"System Interface\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\SmartActionPlatform\\\\SmartClipboard\",\n Name = \"Disabled\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, suggested actions are enabled\n DisabledValue = 1, // When toggle is OFF, suggested actions are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls suggested actions for clipboard content\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-windows-manage-printer\",\n Name = \"Default Printer Management\",\n Description = \"Controls Windows managing default printer\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"Printer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Windows\",\n Name = \"LegacyDefaultPrinterMode\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, Windows manages default printer\n DisabledValue = 1, // When toggle is OFF, Windows does not manage default printer\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls Windows managing default printer\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-disable-snap-assist\",\n Name = \"Snap Assist\",\n Description = \"Controls Snap Assist feature\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"SnapAssist\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls Snap Assist feature\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-frequent-folders\",\n Name = \"Frequent Folders in Quick Access\",\n Description = \"Controls display of frequent folders in Quick Access\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\",\n Name = \"ShowFrequent\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, frequent folders are shown\n DisabledValue = 0, // When toggle is OFF, frequent folders are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls display of frequent folders in Quick Access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"compress-desktop-wallpaper\",\n Name = \"Compress Desktop Wallpaper\",\n Description = \"Controls compression of desktop wallpaper\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"Desktop Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"JPEGImportQuality\",\n RecommendedValue = 100,\n EnabledValue = 0,\n DisabledValue = 100,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls compression of desktop wallpaper\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-office-files\",\n Name = \"Office Files in Quick Access\",\n Description = \"Controls display of files from Office.com in Quick Access\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\",\n Name = \"ShowCloudFilesInQuickAccess\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, Office.com files are shown\n DisabledValue = 0, // When toggle is OFF, Office.com files are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description =\n \"Controls display of files from Office.com in Quick Access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Services/SettingsRegistry.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Core.Features.Common.Services\n{\n /// \n /// Registry for settings.\n /// \n public class SettingsRegistry : ISettingsRegistry\n {\n private readonly ILogService _logService;\n private readonly List _settings = new List();\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public SettingsRegistry(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Registers a setting in the registry.\n /// \n /// The setting to register.\n public void RegisterSetting(ISettingItem setting)\n {\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot register null setting\");\n return;\n }\n\n if (string.IsNullOrEmpty(setting.Id))\n {\n _logService.Log(LogLevel.Warning, \"Cannot register setting with null or empty ID\");\n return;\n }\n\n lock (_settings)\n {\n // Check if the setting is already registered\n if (_settings.Any(s => s.Id == setting.Id))\n {\n _logService.Log(LogLevel.Info, $\"Setting with ID '{setting.Id}' is already registered\");\n return;\n }\n\n _settings.Add(setting);\n _logService.Log(LogLevel.Info, $\"Registered setting {setting.Id} in global settings collection\");\n }\n }\n\n /// \n /// Gets a setting by its ID.\n /// \n /// The ID of the setting to get.\n /// The setting if found, otherwise null.\n public ISettingItem? GetSettingById(string id)\n {\n if (string.IsNullOrEmpty(id))\n {\n _logService.Log(LogLevel.Warning, \"Cannot get setting with null or empty ID\");\n return null;\n }\n\n lock (_settings)\n {\n return _settings.FirstOrDefault(s => s.Id == id);\n }\n }\n\n /// \n /// Gets all settings in the registry.\n /// \n /// A list of all settings.\n public List GetAllSettings()\n {\n lock (_settings)\n {\n return new List(_settings);\n }\n }\n\n /// \n /// Gets all settings of a specific type.\n /// \n /// The type of settings to get.\n /// A list of settings of the specified type.\n public List GetSettingsByType() where T : ISettingItem\n {\n lock (_settings)\n {\n return _settings.OfType().Cast().ToList();\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/PowerShellScriptTemplateProvider.cs", "using System;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Provides PowerShell script templates with OS-specific adjustments.\n /// \n public class PowerShellScriptTemplateProvider : IScriptTemplateProvider\n {\n private readonly ISystemServices _systemService;\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The system service.\n /// The logging service.\n public PowerShellScriptTemplateProvider(\n ISystemServices systemService,\n ILogService logService)\n {\n _systemService = systemService ?? throw new ArgumentNullException(nameof(systemService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string GetPackageRemovalTemplate()\n {\n // Windows 10 compatibility: Don't use -AllUsers with Remove-AppxPackage\n return @\"Get-AppxPackage -Name \"\"{0}\"\" | Remove-AppxPackage -ErrorAction SilentlyContinue\nGet-AppxProvisionedPackage -Online | Where-Object {{ $_.DisplayName -eq \"\"{0}\"\" }} | Remove-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue\";\n }\n\n /// \n public string GetCapabilityRemovalTemplate()\n {\n return @\"Get-WindowsCapability -Online | Where-Object {{ $_.Name -like \"\"{0}*\"\" }} | Remove-WindowsCapability -Online\";\n }\n\n /// \n public string GetFeatureRemovalTemplate()\n {\n return @\"Write-Host \"\"Disabling optional feature: {0}\"\" -ForegroundColor Yellow\nDisable-WindowsOptionalFeature -Online -FeatureName \"\"{0}\"\" -NoRestart | Out-Null\";\n }\n\n /// \n public string GetRegistrySettingTemplate(bool isDelete)\n {\n if (isDelete)\n {\n return @\"reg delete \"\"{0}\"\" /v {1} /f | Out-Null\";\n }\n else\n {\n return @\"reg add \"\"{0}\"\" /v {1} /t REG_{2} /d {3} /f | Out-Null\";\n }\n }\n\n /// \n public string GetScriptHeader(string scriptName)\n {\n return $@\"# {scriptName}.ps1\n# This script removes Windows bloatware apps and prevents them from reinstalling\n# Source: Winhance (https://github.com/memstechtips/Winhance)\n# Generated by Winhance on {DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\")}\n\n\";\n }\n\n /// \n public string GetScriptFooter()\n {\n return @\"\n# Prevent apps from reinstalling\nreg add \"\"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\CloudContent\"\" /v DisableWindowsConsumerFeatures /t REG_DWORD /d 1 /f | Out-Null\n\nWrite-Host \"\"=== Script Completed ===\"\" -ForegroundColor Green\n\";\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Services/ModelMapper.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\nnamespace Winhance.Core.Features.Common.Services\n{\n /// \n /// Interface for mapping between different model types.\n /// \n public interface IModelMapper\n {\n /// \n /// Maps a source object to a destination type.\n /// \n /// The source type.\n /// The destination type.\n /// The source object.\n /// The mapped destination object.\n TDestination Map(TSource source) where TDestination : new();\n\n /// \n /// Maps a collection of source objects to a collection of destination objects.\n /// \n /// The source type.\n /// The destination type.\n /// The collection of source objects.\n /// The collection of mapped destination objects.\n IEnumerable MapCollection(IEnumerable source) where TDestination : new();\n }\n\n /// \n /// Service for mapping between different model types.\n /// \n public class ModelMapper : IModelMapper\n {\n /// \n public TDestination Map(TSource source) where TDestination : new()\n {\n if (source == null)\n {\n throw new ArgumentNullException(nameof(source));\n }\n\n var destination = new TDestination();\n MapProperties(source, destination);\n return destination;\n }\n\n /// \n public IEnumerable MapCollection(IEnumerable source) where TDestination : new()\n {\n if (source == null)\n {\n throw new ArgumentNullException(nameof(source));\n }\n\n return source.Select(item => Map(item));\n }\n\n private static void MapProperties(TSource source, TDestination destination)\n {\n var sourceProperties = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);\n var destinationProperties = typeof(TDestination).GetProperties(BindingFlags.Public | BindingFlags.Instance)\n .ToDictionary(p => p.Name, p => p);\n\n foreach (var sourceProperty in sourceProperties)\n {\n if (destinationProperties.TryGetValue(sourceProperty.Name, out var destinationProperty))\n {\n if (destinationProperty.CanWrite && \n (destinationProperty.PropertyType == sourceProperty.PropertyType || \n IsAssignableOrConvertible(sourceProperty.PropertyType, destinationProperty.PropertyType)))\n {\n var value = sourceProperty.GetValue(source);\n \n if (value != null && sourceProperty.PropertyType != destinationProperty.PropertyType)\n {\n value = Convert.ChangeType(value, destinationProperty.PropertyType);\n }\n \n destinationProperty.SetValue(destination, value);\n }\n }\n }\n }\n\n private static bool IsAssignableOrConvertible(Type sourceType, Type destinationType)\n {\n return destinationType.IsAssignableFrom(sourceType) || \n (sourceType.IsPrimitive && destinationType.IsPrimitive) ||\n (sourceType == typeof(string) && destinationType.IsPrimitive) ||\n (destinationType == typeof(string) && sourceType.IsPrimitive);\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/CategoryToIconConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing MaterialDesignThemes.Wpf;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a category name to an appropriate Material Design icon.\n /// \n public class CategoryToIconConverter : IValueConverter\n {\n public static CategoryToIconConverter Instance { get; } = new CategoryToIconConverter();\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is string categoryName)\n {\n // Convert category name to lowercase for case-insensitive comparison\n string category = categoryName.ToLowerInvariant();\n\n // Map category names to appropriate Material Design icons\n return category switch\n {\n // Browser related categories\n var c when c.Contains(\"browser\") => PackIconKind.Web,\n \n // Compression related categories\n var c when c.Contains(\"compression\") => PackIconKind.ZipBox,\n var c when c.Contains(\"zip\") => PackIconKind.ZipBox,\n var c when c.Contains(\"archive\") => PackIconKind.Archive,\n \n // Customization related categories\n var c when c.Contains(\"customization\") => PackIconKind.Palette,\n var c when c.Contains(\"utilities\") => PackIconKind.Tools,\n var c when c.Contains(\"shell\") => PackIconKind.Console,\n \n // Development related categories\n var c when c.Contains(\"development\") => PackIconKind.CodeBraces,\n var c when c.Contains(\"programming\") => PackIconKind.CodeBraces,\n var c when c.Contains(\"code\") => PackIconKind.CodeBraces,\n \n // Document related categories\n var c when c.Contains(\"document\") => PackIconKind.FileDocument,\n var c when c.Contains(\"pdf\") => PackIconKind.File,\n var c when c.Contains(\"office\") => PackIconKind.FileDocument,\n var c when c.Contains(\"viewer\") => PackIconKind.FileDocument,\n \n // Media related categories\n var c when c.Contains(\"media\") => PackIconKind.Play,\n var c when c.Contains(\"video\") => PackIconKind.Video,\n var c when c.Contains(\"audio\") => PackIconKind.Music,\n var c when c.Contains(\"player\") => PackIconKind.Play,\n var c when c.Contains(\"multimedia\") => PackIconKind.Play,\n \n // Communication related categories\n var c when c.Contains(\"communication\") => PackIconKind.Message,\n var c when c.Contains(\"chat\") => PackIconKind.Chat,\n var c when c.Contains(\"email\") => PackIconKind.Email,\n var c when c.Contains(\"messaging\") => PackIconKind.Message,\n var c when c.Contains(\"calendar\") => PackIconKind.Calendar,\n \n // Security related categories\n var c when c.Contains(\"security\") => PackIconKind.Shield,\n var c when c.Contains(\"antivirus\") => PackIconKind.ShieldOutline,\n var c when c.Contains(\"firewall\") => PackIconKind.Fire,\n var c when c.Contains(\"privacy\") => PackIconKind.Lock,\n \n // File & Disk Management\n var c when c.Contains(\"file\") => PackIconKind.Folder,\n var c when c.Contains(\"disk\") => PackIconKind.Database,\n \n // Gaming\n var c when c.Contains(\"gaming\") => PackIconKind.GamepadVariant,\n var c when c.Contains(\"game\") => PackIconKind.GamepadVariant,\n \n // Imaging\n var c when c.Contains(\"imaging\") => PackIconKind.Image,\n var c when c.Contains(\"image\") => PackIconKind.Image,\n \n // Online Storage\n var c when c.Contains(\"storage\") => PackIconKind.Cloud,\n var c when c.Contains(\"cloud\") => PackIconKind.Cloud,\n \n // Remote Access\n var c when c.Contains(\"remote\") => PackIconKind.Remote,\n var c when c.Contains(\"access\") => PackIconKind.Remote,\n \n // Optical Disc Utilities\n var c when c.Contains(\"optical\") => PackIconKind.Album,\n var c when c.Contains(\"disc\") => PackIconKind.Album,\n var c when c.Contains(\"dvd\") => PackIconKind.Album,\n var c when c.Contains(\"cd\") => PackIconKind.Album,\n \n // Default icon for unknown categories\n _ => PackIconKind.Apps\n };\n }\n \n // Default to Apps icon if value is not a string\n return PackIconKind.Apps;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // This converter doesn't support converting back\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/UnifiedConfigurationDialogViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// ViewModel for the UnifiedConfigurationDialog.\n /// \n public class UnifiedConfigurationDialogViewModel : ObservableObject\n {\n private string _title;\n private string _description;\n private bool _isSaveDialog;\n\n /// \n /// Gets or sets the title of the dialog.\n /// \n public string Title\n {\n get => _title;\n set => SetProperty(ref _title, value);\n }\n\n /// \n /// Gets or sets the description of the dialog.\n /// \n public string Description\n {\n get => _description;\n set => SetProperty(ref _description, value);\n }\n\n /// \n /// Gets a value indicating whether this is a save dialog.\n /// \n public bool IsSaveDialog => _isSaveDialog;\n\n /// \n /// Gets the collection of configuration sections.\n /// \n public ObservableCollection Sections { get; } = new ObservableCollection();\n\n /// \n /// Gets or sets the command to confirm the selection.\n /// \n public ICommand OkCommand { get; set; }\n\n /// \n /// Gets or sets the command to cancel the selection.\n /// \n public ICommand CancelCommand { get; set; }\n\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The title of the dialog.\n /// The description of the dialog.\n /// The dictionary of section names, their availability, and item counts.\n /// Whether this is a save dialog (true) or an import dialog (false).\n public UnifiedConfigurationDialogViewModel(\n string title, \n string description, \n Dictionary sections,\n bool isSaveDialog)\n {\n Title = title;\n Description = description;\n _isSaveDialog = isSaveDialog;\n\n // Create section view models\n foreach (var section in sections)\n {\n Sections.Add(new UnifiedConfigurationSectionViewModel\n {\n Name = GetSectionDisplayName(section.Key),\n Description = GetSectionDescription(section.Key),\n IsSelected = section.Value.IsSelected,\n IsAvailable = section.Value.IsAvailable,\n ItemCount = section.Value.ItemCount,\n SectionKey = section.Key\n });\n }\n\n // Commands will be set by the dialog\n OkCommand = null;\n CancelCommand = null;\n }\n\n /// \n /// Gets the result of the dialog as a dictionary of section names and their selection state.\n /// \n /// A dictionary of section names and their selection state.\n public Dictionary GetResult()\n {\n var result = new Dictionary();\n\n foreach (var section in Sections)\n {\n result[section.SectionKey] = section.IsSelected;\n }\n\n return result;\n }\n\n\n private string GetSectionDisplayName(string sectionKey)\n {\n return sectionKey switch\n {\n \"WindowsApps\" => \"Windows Apps\",\n \"ExternalApps\" => \"External Apps\",\n \"Customize\" => \"Customization Settings\",\n \"Optimize\" => \"Optimization Settings\",\n _ => sectionKey\n };\n }\n\n private string GetSectionDescription(string sectionKey)\n {\n return sectionKey switch\n {\n \"WindowsApps\" => \"Settings for Windows built-in applications\",\n \"ExternalApps\" => \"Settings for third-party applications\",\n \"Customize\" => \"Windows UI customization settings\",\n \"Optimize\" => \"Windows optimization settings\",\n _ => string.Empty\n };\n }\n }\n\n /// \n /// ViewModel for a unified configuration section.\n /// \n public class UnifiedConfigurationSectionViewModel : ObservableObject\n {\n private string _name;\n private string _description;\n private bool _isSelected;\n private bool _isAvailable;\n private int _itemCount;\n private string _sectionKey;\n\n /// \n /// Gets or sets the name of the section.\n /// \n public string Name\n {\n get => _name;\n set => SetProperty(ref _name, value);\n }\n\n /// \n /// Gets or sets the description of the section.\n /// \n public string Description\n {\n get => _description;\n set => SetProperty(ref _description, value);\n }\n\n /// \n /// Gets or sets a value indicating whether the section is selected.\n /// \n public bool IsSelected\n {\n get => _isSelected;\n set => SetProperty(ref _isSelected, value);\n }\n\n /// \n /// Gets or sets a value indicating whether the section is available.\n /// \n public bool IsAvailable\n {\n get => _isAvailable;\n set => SetProperty(ref _isAvailable, value);\n }\n\n /// \n /// Gets or sets the number of items in the section.\n /// \n public int ItemCount\n {\n get => _itemCount;\n set => SetProperty(ref _itemCount, value);\n }\n\n /// \n /// Gets or sets the section key.\n /// \n public string SectionKey\n {\n get => _sectionKey;\n set => SetProperty(ref _sectionKey, value);\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/StringToMaximizeIconConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing MaterialDesignThemes.Wpf;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class StringToMaximizeIconConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is string iconName)\n {\n switch (iconName)\n {\n case \"WindowMaximize\":\n return PackIconKind.WindowMaximize;\n case \"WindowRestore\":\n return PackIconKind.WindowRestore;\n default:\n return PackIconKind.WindowMaximize;\n }\n }\n \n return PackIconKind.WindowMaximize;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is PackIconKind kind)\n {\n switch (kind)\n {\n case PackIconKind.WindowMaximize:\n return \"WindowMaximize\";\n case PackIconKind.WindowRestore:\n return \"WindowRestore\";\n default:\n return \"WindowMaximize\";\n }\n }\n \n return \"WindowMaximize\";\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Helpers/InstallationErrorHelper.cs", "using System;\nusing Winhance.Core.Features.SoftwareApps.Enums;\n\nnamespace Winhance.Core.Features.SoftwareApps.Helpers\n{\n /// \n /// Helper class for installation error handling.\n /// \n public static class InstallationErrorHelper\n {\n /// \n /// Gets a user-friendly error message based on the error type.\n /// \n /// The type of installation error.\n /// A user-friendly error message.\n public static string GetUserFriendlyErrorMessage(InstallationErrorType errorType)\n {\n return errorType switch\n {\n InstallationErrorType.NetworkError => \n \"Network connection error. Please check your internet connection and try again.\",\n \n InstallationErrorType.PermissionError => \n \"Permission denied. Please run the application with administrator privileges.\",\n \n InstallationErrorType.PackageNotFoundError => \n \"Package not found. The requested package may not be available in the repositories.\",\n \n InstallationErrorType.WinGetNotInstalledError => \n \"WinGet is not installed and could not be installed automatically.\",\n \n InstallationErrorType.AlreadyInstalledError => \n \"The package is already installed.\",\n \n InstallationErrorType.CancelledByUserError => \n \"The installation was cancelled by the user.\",\n \n InstallationErrorType.SystemStateError => \n \"The system is in a state that prevents installation. Please restart your computer and try again.\",\n \n InstallationErrorType.PackageCorruptedError => \n \"The package is corrupted or invalid. Please try reinstalling or contact the package maintainer.\",\n \n InstallationErrorType.DependencyResolutionError => \n \"The package dependencies could not be resolved. Some required components may be missing.\",\n \n InstallationErrorType.UnknownError or _ => \n \"An unknown error occurred during installation. Please check the logs for more details.\"\n };\n }\n\n /// \n /// Determines the error type based on the exception message.\n /// \n /// The exception message.\n /// The determined error type.\n public static InstallationErrorType DetermineErrorType(string exceptionMessage)\n {\n if (string.IsNullOrEmpty(exceptionMessage))\n return InstallationErrorType.UnknownError;\n\n exceptionMessage = exceptionMessage.ToLowerInvariant();\n\n if (exceptionMessage.Contains(\"network\") || \n exceptionMessage.Contains(\"connection\") || \n exceptionMessage.Contains(\"internet\") ||\n exceptionMessage.Contains(\"timeout\") ||\n exceptionMessage.Contains(\"unreachable\"))\n {\n return InstallationErrorType.NetworkError;\n }\n \n if (exceptionMessage.Contains(\"permission\") || \n exceptionMessage.Contains(\"access\") || \n exceptionMessage.Contains(\"denied\") ||\n exceptionMessage.Contains(\"administrator\") ||\n exceptionMessage.Contains(\"elevation\"))\n {\n return InstallationErrorType.PermissionError;\n }\n \n if (exceptionMessage.Contains(\"not found\") || \n exceptionMessage.Contains(\"no package\") ||\n exceptionMessage.Contains(\"no such package\") ||\n exceptionMessage.Contains(\"could not find\"))\n {\n return InstallationErrorType.PackageNotFoundError;\n }\n \n if (exceptionMessage.Contains(\"winget\") && \n (exceptionMessage.Contains(\"not installed\") || \n exceptionMessage.Contains(\"could not be installed\")))\n {\n return InstallationErrorType.WinGetNotInstalledError;\n }\n \n if (exceptionMessage.Contains(\"already installed\") ||\n exceptionMessage.Contains(\"is installed\"))\n {\n return InstallationErrorType.AlreadyInstalledError;\n }\n \n if (exceptionMessage.Contains(\"cancelled\") || \n exceptionMessage.Contains(\"canceled\") ||\n exceptionMessage.Contains(\"aborted\"))\n {\n return InstallationErrorType.CancelledByUserError;\n }\n \n if (exceptionMessage.Contains(\"system state\") || \n exceptionMessage.Contains(\"restart\") ||\n exceptionMessage.Contains(\"reboot\"))\n {\n return InstallationErrorType.SystemStateError;\n }\n \n if (exceptionMessage.Contains(\"corrupt\") || \n exceptionMessage.Contains(\"invalid\") ||\n exceptionMessage.Contains(\"damaged\"))\n {\n return InstallationErrorType.PackageCorruptedError;\n }\n \n if (exceptionMessage.Contains(\"dependency\") || \n exceptionMessage.Contains(\"dependencies\") ||\n exceptionMessage.Contains(\"requires\"))\n {\n return InstallationErrorType.DependencyResolutionError;\n }\n \n return InstallationErrorType.UnknownError;\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/CapabilitiesViewModel.cs", "using CommunityToolkit.Mvvm.Input;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n public partial class CapabilitiesViewModel : AppListViewModel\n {\n private readonly IAppLoadingService _appLoadingService;\n private readonly IInstallationOrchestrator _installationOrchestrator;\n\n public CapabilitiesViewModel(\n IAppLoadingService appLoadingService,\n IInstallationOrchestrator installationOrchestrator,\n ITaskProgressService taskProgressService,\n IPackageManager packageManager)\n : base(taskProgressService, packageManager)\n {\n _appLoadingService = appLoadingService;\n _installationOrchestrator = installationOrchestrator;\n }\n\n public override async Task LoadItemsAsync()\n {\n var capabilities = await _appLoadingService.LoadCapabilitiesAsync();\n Items.Clear();\n foreach (var item in capabilities)\n {\n Items.Add(item);\n }\n }\n\n public override async Task CheckInstallationStatusAsync()\n {\n await Task.Run(async () =>\n {\n foreach (var item in Items)\n {\n // Use the AppLoadingService to check installation status\n item.IsInstalled = await _appLoadingService.GetItemInstallStatusAsync(item);\n }\n });\n }\n\n [RelayCommand]\n private async Task InstallAsync()\n {\n var selected = Items.Where(item => item.IsSelected).ToList();\n if (!selected.Any())\n {\n return;\n }\n await _installationOrchestrator.InstallBatchAsync(selected);\n }\n\n [RelayCommand]\n private async Task RemoveAsync()\n {\n var selected = Items.Where(item => item.IsSelected).ToList();\n if (!selected.Any())\n {\n return;\n }\n await _installationOrchestrator.RemoveBatchAsync(selected);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Messaging/Messages.cs", "using System;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Messaging\n{\n /// \n /// Base class for all messages that will be sent through the messenger\n /// \n public abstract class MessageBase\n {\n public DateTime Timestamp { get; } = DateTime.Now;\n }\n\n /// \n /// Message sent when a log entry is created\n /// \n public class LogMessage : MessageBase\n {\n public string Message { get; set; }\n public LogLevel Level { get; set; }\n public Exception Exception { get; set; }\n }\n\n /// \n /// Message sent when progress changes\n /// \n public class ProgressMessage : MessageBase\n {\n public double Progress { get; set; }\n public string StatusText { get; set; }\n public bool IsIndeterminate { get; set; }\n public bool IsTaskRunning { get; set; }\n }\n\n /// \n /// Message sent when detailed task progress changes\n /// \n public class TaskProgressMessage : MessageBase\n {\n public string TaskName { get; set; }\n public double Progress { get; set; }\n public string StatusText { get; set; }\n public bool IsIndeterminate { get; set; }\n public bool IsTaskRunning { get; set; }\n public bool CanCancel { get; set; }\n }\n\n /// \n /// Message sent when window state changes\n /// \n public class WindowStateMessage : MessageBase\n {\n public enum WindowStateAction\n {\n Minimize,\n Maximize,\n Restore,\n Close\n }\n\n public WindowStateAction Action { get; set; }\n }\n\n /// \n /// Message sent to update the UI theme\n /// \n public class ThemeChangedMessage : MessageBase\n {\n public bool IsDarkTheme { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/ExternalAppCatalog.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a catalog of external applications that can be installed.\n/// \npublic class ExternalAppCatalog\n{\n /// \n /// Gets or sets the collection of installable external applications.\n /// \n public IReadOnlyList ExternalApps { get; init; } = new List();\n\n /// \n /// Creates a default external app catalog with predefined installable apps.\n /// \n /// A new ExternalAppCatalog instance with default apps.\n public static ExternalAppCatalog CreateDefault()\n {\n return new ExternalAppCatalog { ExternalApps = CreateDefaultExternalApps() };\n }\n\n private static IReadOnlyList CreateDefaultExternalApps()\n {\n return new List\n {\n // Browsers\n new AppInfo\n {\n Name = \"Microsoft Edge WebView\",\n Description = \"WebView2 runtime for Windows applications\",\n PackageName = \"Microsoft.EdgeWebView2Runtime\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Thorium\",\n Description = \"Chromium-based browser with enhanced privacy features\",\n PackageName = \"Alex313031.Thorium\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Thorium AVX2\",\n Description = \"Chromium-based browser with enhanced privacy features\",\n PackageName = \"Alex313031.Thorium.AVX2\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Mercury\",\n Description = \"Compiler optimized, private Firefox fork\",\n PackageName = \"Alex313031.Mercury\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Firefox\",\n Description = \"Popular web browser known for privacy and customization\",\n PackageName = \"Mozilla.Firefox\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Chrome\",\n Description = \"Google's web browser with sync and extension support\",\n PackageName = \"Google.Chrome\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Ungoogled Chromium\",\n Description = \"Chromium-based browser with privacy enhancements\",\n PackageName = \"Eloston.Ungoogled-Chromium\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Brave\",\n Description = \"Privacy-focused browser with built-in ad blocking\",\n PackageName = \"Brave.Brave\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Opera\",\n Description = \"Feature-rich web browser with built-in VPN and ad blocker\",\n PackageName = \"Opera.Opera\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Opera GX\",\n Description = \"Gaming-oriented version of Opera with unique features\",\n PackageName = \"Opera.OperaGX\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Arc Browser\",\n Description = \"Innovative browser with a focus on design and user experience\",\n PackageName = \"TheBrowserCompany.Arc\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Tor Browser\",\n Description = \"Privacy-focused browser that routes traffic through the Tor network\",\n PackageName = \"TorProject.TorBrowser\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Vivaldi\",\n Description = \"Highly customizable browser with a focus on user control\",\n PackageName = \"Vivaldi.Vivaldi\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Waterfox\",\n Description = \"Firefox-based browser with a focus on privacy and customization\",\n PackageName = \"Waterfox.Waterfox\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Zen Browser\",\n Description = \"Privacy-focused browser with built-in ad blocking\",\n PackageName = \"Zen-Team.Zen-Browser\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Mullvad Browser\",\n Description =\n \"Privacy-focused browser designed to minimize tracking and fingerprints\",\n PackageName = \"MullvadVPN.MullvadBrowser\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Pale Moon Browser\",\n Description =\n \"Open Source, Goanna-based web browser focusing on efficiency and customization\",\n PackageName = \"MoonchildProductions.PaleMoon\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Maxthon Browser\",\n Description = \"Privacy focused browser with built-in ad blocking and VPN\",\n PackageName = \"Maxthon.Maxthon\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Floorp\",\n Description = \"Privacy focused browser with strong tracking protection\",\n PackageName = \"Ablaze.Floorp\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"DuckDuckGo\",\n Description = \"Privacy-focused search engine with a browser extension\",\n PackageName = \"DuckDuckGo.DesktopBrowser\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Document Viewers\n new AppInfo\n {\n Name = \"LibreOffice\",\n Description = \"Free and open-source office suite\",\n PackageName = \"TheDocumentFoundation.LibreOffice\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"ONLYOFFICE Desktop Editors\",\n Description = \"100% open-source free alternative to Microsoft Office\",\n PackageName = \"ONLYOFFICE.DesktopEditors\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Foxit Reader\",\n Description = \"Lightweight PDF reader with advanced features\",\n PackageName = \"Foxit.FoxitReader\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"SumatraPDF\",\n Description =\n \"PDF, eBook (epub, mobi), comic book (cbz/cbr), DjVu, XPS, CHM, image viewer for Windows\",\n PackageName = \"SumatraPDF.SumatraPDF\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"OpenOffice\",\n Description =\n \"Discontinued open-source office suite. Active successor projects is LibreOffice\",\n PackageName = \"Apache.OpenOffice\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Adobe Acrobat Reader DC\",\n Description = \"PDF reader and editor\",\n PackageName = \"XPDP273C0XHQH2\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Evernote\",\n Description = \"Note-taking app\",\n PackageName = \"Evernote.Evernote\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Online Storage\n new AppInfo\n {\n Name = \"Google Drive\",\n Description = \"Cloud storage and file synchronization service\",\n PackageName = \"Google.GoogleDrive\",\n Category = \"Online Storage\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Dropbox\",\n Description =\n \"File hosting service that offers cloud storage, file synchronization, personal cloud\",\n PackageName = \"Dropbox.Dropbox\",\n Category = \"Online Storage\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"SugarSync\",\n Description =\n \"Automatically access and share your photos, videos, and files in any folder\",\n PackageName = \"IPVanish.SugarSync\",\n Category = \"Online Storage\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"NextCloud\",\n Description =\n \"Access, share and protect your files, calendars, contacts, communication & more at home and in your organization\",\n PackageName = \"Nextcloud.NextcloudDesktop\",\n Category = \"Online Storage\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Proton Drive\",\n Description = \"Secure cloud storage with end-to-end encryption\",\n PackageName = \"Proton.ProtonDrive\",\n Category = \"Online Storage\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Development Apps\n new AppInfo\n {\n Name = \"Python 3.13\",\n Description = \"Python programming language\",\n PackageName = \"Python.Python.3.13\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Notepad++\",\n Description = \"Free source code editor and Notepad replacement\",\n PackageName = \"Notepad++.Notepad++\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"WinSCP\",\n Description = \"Free SFTP, SCP, Amazon S3, WebDAV, and FTP client\",\n PackageName = \"WinSCP.WinSCP\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"PuTTY\",\n Description = \"Free SSH and telnet client\",\n PackageName = \"PuTTY.PuTTY\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"WinMerge\",\n Description = \"Open source differencing and merging tool\",\n PackageName = \"WinMerge.WinMerge\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Eclipse\",\n Description = \"Java IDE and development platform\",\n PackageName = \"EclipseFoundation.EclipseIDEforJavaDevelopers\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Visual Studio Code\",\n Description = \"Code editor with support for development operations\",\n PackageName = \"Microsoft.VisualStudioCode\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Git\",\n Description = \"Distributed version control system\",\n PackageName = \"Git.Git\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"GitHub Desktop\",\n Description = \"GitHub desktop client\",\n PackageName = \"GitHub.GitHubDesktop\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"AutoHotkey\",\n Description = \"Scripting language for desktop automation\",\n PackageName = \"AutoHotkey.AutoHotkey\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Windsurf\",\n Description = \"AI Code Editor\",\n PackageName = \"Codeium.Windsurf\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Cursor\",\n Description = \"AI Code Editor\",\n PackageName = \"Anysphere.Cursor\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Multimedia (Audio & Video)\n new AppInfo\n {\n Name = \"VLC\",\n Description = \"Open-source multimedia player and framework\",\n PackageName = \"VideoLAN.VLC\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"iTunes\",\n Description = \"Media player and library\",\n PackageName = \"Apple.iTunes\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"AIMP\",\n Description = \"Audio player with support for various formats\",\n PackageName = \"AIMP.AIMP\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"foobar2000\",\n Description = \"Advanced audio player for Windows\",\n PackageName = \"PeterPawlowski.foobar2000\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"MusicBee\",\n Description = \"Music manager and player\",\n PackageName = \"9P4CLT2RJ1RS\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Audacity\",\n Description = \"Audio editor and recorder\",\n PackageName = \"Audacity.Audacity\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"GOM\",\n Description = \"Media player for Windows\",\n PackageName = \"GOMLab.GOMPlayer\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Spotify\",\n Description = \"Music streaming service\",\n PackageName = \"Spotify.Spotify\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"MediaMonkey\",\n Description = \"Media manager and player\",\n PackageName = \"VentisMedia.MediaMonkey.5\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"HandBrake\",\n Description = \"Open-source video transcoder\",\n PackageName = \"HandBrake.HandBrake\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"OBS Studio\",\n Description =\n \"Free and open source software for video recording and live streaming\",\n PackageName = \"OBSProject.OBSStudio\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Streamlabs OBS\",\n Description = \"Streaming software built on OBS with additional features for streamers\",\n PackageName = \"Streamlabs.StreamlabsOBS\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"MPC-BE\",\n Description = \"Media Player Classic - Black Edition\",\n PackageName = \"MPC-BE.MPC-BE\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"K-Lite Codec Pack (Mega)\",\n Description = \"Collection of codecs and related tools\",\n PackageName = \"CodecGuide.K-LiteCodecPack.Mega\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"CapCut\",\n Description = \"Video editor\",\n PackageName = \"ByteDance.CapCut\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"PotPlayer\",\n Description = \"Comprehensive multimedia player for Windows\",\n PackageName = \"Daum.PotPlayer\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Imaging\n new AppInfo\n {\n Name = \"IrfanView\",\n Description = \"Fast and compact image viewer and converter\",\n PackageName = \"IrfanSkiljan.IrfanView\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Krita\",\n Description = \"Digital painting and illustration software\",\n PackageName = \"KDE.Krita\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Blender\",\n Description = \"3D creation suite\",\n PackageName = \"BlenderFoundation.Blender\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Paint.NET\",\n Description = \"Image and photo editing software\",\n PackageName = \"dotPDN.PaintDotNet\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"GIMP\",\n Description = \"GNU Image Manipulation Program\",\n PackageName = \"GIMP.GIMP.3\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"XnViewMP\",\n Description = \"Image viewer, browser and converter\",\n PackageName = \"XnSoft.XnViewMP\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"XnView Classic\",\n Description = \"Image viewer, browser and converter (Classic Version)\",\n PackageName = \"XnSoft.XnView.Classic\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Inkscape\",\n Description = \"Vector graphics editor\",\n PackageName = \"Inkscape.Inkscape\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Greenshot\",\n Description = \"Screenshot tool with annotation features\",\n PackageName = \"Greenshot.Greenshot\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"ShareX\",\n Description = \"Screen capture, file sharing and productivity tool\",\n PackageName = \"ShareX.ShareX\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Flameshot\",\n Description = \"Powerful yet simple to use screenshot software\",\n PackageName = \"Flameshot.Flameshot\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"FastStone\",\n Description = \"Image browser, converter and editor\",\n PackageName = \"FastStone.Viewer\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Compression\n new AppInfo\n {\n Name = \"7-Zip\",\n Description = \"Open-source file archiver with a high compression ratio\",\n PackageName = \"7zip.7zip\",\n Category = \"Compression\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"WinRAR\",\n Description = \"File archiver with a high compression ratio\",\n PackageName = \"RARLab.WinRAR\",\n Category = \"Compression\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"PeaZip\",\n Description =\n \"Free file archiver utility. Open and extract RAR, TAR, ZIP files and more\",\n PackageName = \"Giorgiotani.Peazip\",\n Category = \"Compression\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"NanaZip\",\n Description =\n \"Open source fork of 7-zip intended for the modern Windows experience\",\n PackageName = \"M2Team.NanaZip\",\n Category = \"Compression\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Messaging, Email & Calendar\n new AppInfo\n {\n Name = \"Telegram\",\n Description = \"Instant messaging and voice calling app\",\n PackageName = \"Telegram.TelegramDesktop\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Whatsapp\",\n Description = \"Instant messaging and voice calling app\",\n PackageName = \"9NKSQGP7F2NH\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Zoom\",\n Description = \"Video conferencing and messaging platform\",\n PackageName = \"Zoom.Zoom\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Discord\",\n Description = \"Voice, video and text communication service\",\n PackageName = \"Discord.Discord\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Pidgin\",\n Description = \"Multi-protocol instant messaging client\",\n PackageName = \"Pidgin.Pidgin\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Thunderbird\",\n Description = \"Free email application\",\n PackageName = \"Mozilla.Thunderbird\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"eMClient\",\n Description = \"Email client with calendar, tasks, and chat\",\n PackageName = \"eMClient.eMClient\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Proton Mail\",\n Description = \"Secure email service with end-to-end encryption\",\n PackageName = \"Proton.ProtonMail\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Trillian\",\n Description = \"Instant messaging application\",\n PackageName = \"CeruleanStudios.Trillian\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // File & Disk Management\n new AppInfo\n {\n Name = \"WinDirStat\",\n Description = \"Disk usage statistics viewer and cleanup tool\",\n PackageName = \"WinDirStat.WinDirStat\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"WizTree\",\n Description = \"Disk space analyzer with extremely fast scanning\",\n PackageName = \"AntibodySoftware.WizTree\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"TreeSize Free\",\n Description = \"Disk space manager\",\n PackageName = \"JAMSoftware.TreeSize.Free\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Everything\",\n Description = \"Locate files and folders by name instantly\",\n PackageName = \"voidtools.Everything\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"TeraCopy\",\n Description = \"Copy files faster and more securely\",\n PackageName = \"CodeSector.TeraCopy\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"File Converter\",\n Description = \"Batch file converter for Windows\",\n PackageName = \"AdrienAllard.FileConverter\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Crystal Disk Info\",\n Description = \"Hard drive health monitoring utility\",\n PackageName = \"WsSolInfor.CrystalDiskInfo\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Bulk Rename Utility\",\n Description = \"File renaming software for Windows\",\n PackageName = \"TGRMNSoftware.BulkRenameUtility\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"IObit Unlocker\",\n Description = \"Tool to unlock files that are in use by other processes\",\n PackageName = \"IObit.IObitUnlocker\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Ventoy\",\n Description = \"Open source tool to create bootable USB drive for ISO files\",\n PackageName = \"Ventoy.Ventoy\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Volume2\",\n Description = \"Advanced Windows volume control\",\n PackageName = \"irzyxa.Volume2Portable\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Remote Access\n new AppInfo\n {\n Name = \"RustDesk\",\n Description = \"Fast Open-Source Remote Access and Support Software\",\n PackageName = \"RustDesk.RustDesk\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Input Leap\",\n Description = \"Open-source KVM software for sharing mouse and keyboard between computers\",\n PackageName = \"input-leap.input-leap\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"AnyDesk\",\n Description = \"Remote desktop software for remote access and support\",\n PackageName = \"AnyDesk.AnyDesk\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"TeamViewer 15\",\n Description =\n \"Remote control, desktop sharing, online meetings, web conferencing and file transfer\",\n PackageName = \"TeamViewer.TeamViewer\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"RealVNC Server\",\n Description = \"Remote access software\",\n PackageName = \"RealVNC.VNCServer\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"RealVNC Viewer\",\n Description = \"Remote access software\",\n PackageName = \"RealVNC.VNCViewer\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Chrome Remote Desktop Host\",\n Description = \"Remote access to your computer through Chrome browser\",\n PackageName = \"Google.ChromeRemoteDesktopHost\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Optical Disc Tools\n new AppInfo\n {\n Name = \"CDBurnerXP\",\n Description = \"Application to burn CDs and DVDs\",\n PackageName = \"\",\n Category = \"Optical Disc Tools\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"ImgBurn\",\n Description = \"Lightweight CD / DVD / HD DVD / Blu-ray burning application\",\n PackageName = \"LIGHTNINGUK.ImgBurn\",\n Category = \"Optical Disc Tools\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"AnyBurn\",\n Description = \"Lightweight CD/DVD/Blu-ray burning software\",\n PackageName = \"PowerSoftware.AnyBurn\",\n Category = \"Optical Disc Tools\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Other Utilities\n new AppInfo\n {\n Name = \"Snappy Driver Installer Origin\",\n Description = \"Driver installer and updater\",\n PackageName = \"GlennDelahoy.SnappyDriverInstallerOrigin\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Wise Registry Cleaner\",\n Description = \"Registry cleaning and optimization tool\",\n PackageName = \"XPDLS1XBTXVPP4\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"UniGetUI\",\n Description =\n \"Universal package manager interface supporting WinGet, Chocolatey, and more\",\n PackageName = \"MartiCliment.UniGetUI\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Google Earth\",\n Description = \"3D representation of Earth based on satellite imagery\",\n PackageName = \"Google.GoogleEarthPro\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"NV Access\",\n Description = \"Screen reader for blind and vision impaired users\",\n PackageName = \"NVAccess.NVDA\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Revo Uninstaller\",\n Description = \"Uninstaller with advanced features\",\n PackageName = \"RevoUninstaller.RevoUninstaller\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Bulk Crap Uninstaller\",\n Description = \"Free and open-source program uninstaller with advanced features\",\n PackageName = \"Klocman.BulkCrapUninstaller\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Text Grab\",\n Description = \"Tool for extracting text from images and screenshots\",\n PackageName = \"JosephFinney.Text-Grab\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Glary Utilities\",\n Description = \"All-in-one PC care utility\",\n PackageName = \"Glarysoft.GlaryUtilities\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Buzz\",\n Description = \"AI video & audio transcription tool\",\n PackageName = \"ChidiWilliams.Buzz\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"PowerToys\",\n Description = \"Windows system utilities to maximize productivity\",\n PackageName = \"Microsoft.PowerToys\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Customization Utilities\n new AppInfo\n {\n Name = \"Nilesoft Shell\",\n Description = \"Windows context menu customization tool\",\n PackageName = \"Nilesoft.Shell\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"StartAllBack\",\n Description = \"Windows 11 Start menu and taskbar customization\",\n PackageName = \"StartIsBack.StartAllBack\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Open-Shell\",\n Description = \"Classic style Start Menu for Windows\",\n PackageName = \"Open-Shell.Open-Shell-Menu\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Windhawk\",\n Description = \"Customization platform for Windows\",\n PackageName = \"RamenSoftware.Windhawk\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Lively Wallpaper\",\n Description = \"Free and open-source animated desktop wallpaper application\",\n PackageName = \"rocksdanister.LivelyWallpaper\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Sucrose Wallpaper Engine\",\n Description = \"Free and open-source animated desktop wallpaper application\",\n PackageName = \"Taiizor.SucroseWallpaperEngine\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Rainmeter\",\n Description = \"Desktop customization tool for Windows\",\n PackageName = \"Rainmeter.Rainmeter\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"ExplorerPatcher\",\n Description = \"Utility that enhances the Windows Explorer experience\",\n PackageName = \"valinet.ExplorerPatcher\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Gaming\n new AppInfo\n {\n Name = \"Steam\",\n Description = \"Digital distribution platform for PC gaming\",\n PackageName = \"Valve.Steam\",\n Category = \"Gaming\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Epic Games Launcher\",\n Description = \"Digital distribution platform for PC gaming\",\n PackageName = \"EpicGames.EpicGamesLauncher\",\n Category = \"Gaming\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"EA Desktop App\",\n Description = \"Digital distribution platform for PC gaming\",\n PackageName = \"ElectronicArts.EADesktop\",\n Category = \"Gaming\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Ubisoft Connect\",\n Description = \"Digital distribution platform for PC gaming\",\n PackageName = \"Ubisoft.Connect\",\n Category = \"Gaming\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Battle.net\",\n Description = \"Digital distribution platform for PC gaming\",\n PackageName = \"Blizzard.BattleNet\",\n Category = \"Gaming\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Privacy & Security\n new AppInfo\n {\n Name = \"Malwarebytes\",\n Description = \"Anti-malware software for Windows\",\n PackageName = \"Malwarebytes.Malwarebytes\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Malwarebytes AdwCleaner\",\n Description = \"Adware removal tool for Windows\",\n PackageName = \"Malwarebytes.AdwCleaner\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"SUPERAntiSpyware\",\n Description = \"Anti-spyware software for Windows\",\n PackageName = \"SUPERAntiSpyware.SUPERAntiSpyware\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"ProtonVPN\",\n Description = \"Secure and private VPN service\",\n PackageName = \"Proton.ProtonVPN\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"KeePass 2\",\n Description = \"Free, open source, light-weight password manager\",\n PackageName = \"DominikReichl.KeePass\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Proton Pass\",\n Description = \"Secure password manager with end-to-end encryption\",\n PackageName = \"Proton.ProtonPass\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Bitwarden\",\n Description = \"Open source password manager\",\n PackageName = \"Bitwarden.Bitwarden\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"KeePassXC\",\n Description = \"Cross-platform secure password manager\",\n PackageName = \"KeePassXCTeam.KeePassXC\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Tailscale\",\n Description = \"Zero config VPN for building secure networks\",\n PackageName = \"Tailscale.Tailscale\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/NotificationOptimizations.cs", "using Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class NotificationOptimizations\n{\n public static OptimizationGroup GetNotificationOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Notifications\",\n Category = OptimizationCategory.Notifications,\n Settings = new List\n {\n new OptimizationSetting\n {\n Id = \"notifications-toast\",\n Name = \"Windows Notifications\",\n Description = \"Controls toast notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\PushNotifications\",\n Name = \"ToastEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls toast notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-sound\",\n Name = \"Notification Sounds\",\n Description = \"Controls notification sounds\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\",\n Name = \"NOC_GLOBAL_SETTING_ALLOW_NOTIFICATION_SOUND\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls notification sounds\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-toast-above-lock\",\n Name = \"Notifications On Lock Screen\",\n Description = \"Controls notifications above lock screen\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\",\n Name = \"NOC_GLOBAL_SETTING_ALLOW_TOASTS_ABOVE_LOCK\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls notifications on lock screen\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n },\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\PushNotifications\",\n Name = \"LockScreenToastEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls notifications on lock screen\",\n IsPrimary = false,\n AbsenceMeansEnabled = true\n }\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All\n },\n new OptimizationSetting\n {\n Id = \"notifications-critical-toast-above-lock\",\n Name = \"Show Reminders and VoIP Calls Notifications\",\n Description = \"Controls critical notifications above lock screen\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\",\n Name = \"NOC_GLOBAL_SETTING_ALLOW_CRITICAL_TOASTS_ABOVE_LOCK\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls critical notifications above lock screen\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-security-maintenance\",\n Name = \"Security and Maintenance Notifications\",\n Description = \"Controls security and maintenance notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\\\\Windows.SystemToast.SecurityAndMaintenance\",\n Name = \"Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls security and maintenance notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-capability-access\",\n Name = \"Capability Access Notifications\",\n Description = \"Controls capability access notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\\\\Windows.SystemToast.CapabilityAccess\",\n Name = \"Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls capability access notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-startup-app\",\n Name = \"Startup App Notifications\",\n Description = \"Controls startup app notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\\\\Windows.SystemToast.StartupApp\",\n Name = \"Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls startup app notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-system-setting-engagement\",\n Name = \"System Setting Engagement Notifications\",\n Description = \"Controls system setting engagement notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\UserProfileEngagement\",\n Name = \"ScoobeSystemSettingEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls system setting engagement notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-app-location-request\",\n Name = \"Notify when apps request location\",\n Description = \"Controls wheter notifications are shown for location requests\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"Privacy Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\location\",\n Name = \"ShowGlobalPrompts\",\n RecommendedValue = 1,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls wheter notifications are shown for location requests\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-windows-security\",\n Name = \"Windows Security Notifications\",\n Description = \"Controls whether Windows Security notifications are shown\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"Security Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows Defender Security Center\\\\Notifications\",\n Name = \"DisableNotifications\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls whether Windows Security Center notifications are shown\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n },\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows Defender Security Center\\\\Notifications\",\n Name = \"DisableNotifications\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls whether Windows Defender Security Center notifications are shown\",\n IsPrimary = false,\n AbsenceMeansEnabled = true\n },\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows Defender Security Center\\\\Notifications\",\n Name = \"DisableEnhancedNotifications\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls whether Windows Defender Security Center notifications are shown\",\n IsPrimary = false,\n AbsenceMeansEnabled = true\n }\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All\n },\n new OptimizationSetting\n {\n Id = \"notifications-clock-change\",\n Name = \"Clock Change Notifications\",\n Description = \"Controls clock change notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"DstNotification\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls clock change notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n }\n }\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/OptimizationModels.cs", "using Microsoft.Win32;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Core.Features.Common.Models;\n\n// This class is deprecated. Use Winhance.Core.Features.Optimize.Models.OptimizationSetting instead.\n[System.Obsolete(\"This class is deprecated. Use Winhance.Core.Features.Optimize.Models.OptimizationSetting instead.\")]\npublic record OptimizationSetting\n{\n public required string Id { get; init; } // Unique identifier\n public required string Name { get; init; } // User-friendly name\n public required string Description { get; init; }\n public required OptimizationCategory Category { get; init; }\n public required string GroupName { get; init; } // Sub-group within category\n\n // Single registry setting (for backward compatibility)\n public RegistrySetting? RegistrySetting { get; init; }\n\n // Multiple registry settings (new approach)\n private LinkedRegistrySettings? _linkedRegistrySettings;\n public LinkedRegistrySettings LinkedRegistrySettings\n {\n get\n {\n // If LinkedRegistrySettings is null but RegistrySetting is not, create a new LinkedRegistrySettings with the single RegistrySetting\n if (_linkedRegistrySettings == null && RegistrySetting != null)\n {\n _linkedRegistrySettings = new LinkedRegistrySettings(RegistrySetting);\n }\n return _linkedRegistrySettings ?? new LinkedRegistrySettings();\n }\n init { _linkedRegistrySettings = value; }\n }\n\n // New approach: Use a collection of registry settings directly\n public List RegistrySettings { get; init; } = new List();\n \n // Linked settings configuration\n public LinkedSettingsLogic LinkedSettingsLogic { get; init; } = LinkedSettingsLogic.Any;\n\n // Dependencies between settings\n public List Dependencies { get; init; } = new List();\n\n public ControlType ControlType { get; init; } = ControlType.BinaryToggle; // Default to binary toggle\n public int? SliderSteps { get; init; } // For discrete sliders (null for binary toggles)\n public bool IsEnabled { get; init; } // Current state\n}\n\npublic record OptimizationGroup\n{\n public required string Name { get; init; }\n public required OptimizationCategory Category { get; init; }\n public required IReadOnlyList Settings { get; init; }\n}\n\n/// \n/// Represents a dependency between two settings.\n/// \n/// \n/// For example, \"Improve Inking and Typing\" requires \"Send Diagnostic Data\" to be enabled.\n/// \n/// \n/// new SettingDependency\n/// {\n/// DependencyType = SettingDependencyType.RequiresEnabled,\n/// DependentSettingId = \"privacy-improve-inking-typing-user\",\n/// RequiredSettingId = \"privacy-diagnostics-policy\"\n/// }\n/// \npublic record SettingDependency\n{\n /// \n /// The type of dependency.\n /// \n public SettingDependencyType DependencyType { get; init; }\n\n /// \n /// The ID of the setting that depends on another setting.\n /// \n public required string DependentSettingId { get; init; }\n\n /// \n /// The ID of the setting that is required by the dependent setting.\n /// \n public required string RequiredSettingId { get; init; }\n}\n\n/// \n/// The type of dependency between two settings.\n/// \npublic enum SettingDependencyType\n{\n /// \n /// The dependent setting requires the required setting to be enabled.\n /// \n RequiresEnabled,\n\n /// \n /// The dependent setting requires the required setting to be disabled.\n /// \n RequiresDisabled\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/RegistryValueStatusConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class RegistryValueStatusConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null)\n return DependencyProperty.UnsetValue;\n\n if (value is RegistrySettingStatus status)\n {\n return status switch\n {\n RegistrySettingStatus.NotApplied => \"Not Applied\",\n RegistrySettingStatus.Applied => \"Applied\",\n RegistrySettingStatus.Modified => \"Modified\",\n RegistrySettingStatus.Error => \"Error\",\n RegistrySettingStatus.Unknown => \"Unknown\",\n _ => \"Unknown\"\n };\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n\n public class RegistryValueStatusToColorConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null)\n return DependencyProperty.UnsetValue;\n\n if (value is RegistrySettingStatus status)\n {\n return status switch\n {\n RegistrySettingStatus.NotApplied => new SolidColorBrush(Colors.Gray),\n RegistrySettingStatus.Applied => new SolidColorBrush(Colors.Green),\n RegistrySettingStatus.Modified => new SolidColorBrush(Colors.Orange),\n RegistrySettingStatus.Error => new SolidColorBrush(Colors.Red),\n RegistrySettingStatus.Unknown => new SolidColorBrush(Colors.Gray),\n _ => new SolidColorBrush(Colors.Gray)\n };\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n\n public class RegistryValueStatusToIconConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null)\n return DependencyProperty.UnsetValue;\n\n if (value is RegistrySettingStatus status)\n {\n return status switch\n {\n RegistrySettingStatus.NotApplied => \"⚪\", // Empty circle\n RegistrySettingStatus.Applied => \"✅\", // Green checkmark\n RegistrySettingStatus.Modified => \"⚠️\", // Warning\n RegistrySettingStatus.Error => \"❌\", // Red X\n RegistrySettingStatus.Unknown => \"❓\", // Question mark\n _ => \"❓\"\n };\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/DesignTimeDataService.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.WPF.Features.SoftwareApps.Models;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Implementation of the IDesignTimeDataService interface that provides\n /// realistic sample data for design-time visualization.\n /// \n public class DesignTimeDataService : IDesignTimeDataService\n {\n /// \n /// Gets a collection of sample third-party applications for design-time.\n /// \n /// A collection of ThirdPartyApp instances.\n public IEnumerable GetSampleThirdPartyApps()\n {\n return new List\n {\n new ThirdPartyApp\n {\n Name = \"Visual Studio Code\",\n Description = \"Lightweight code editor with powerful features\",\n PackageName = \"Microsoft.VisualStudioCode\",\n Category = \"Development\",\n IsInstalled = true,\n IsCustomInstall = false\n },\n new ThirdPartyApp\n {\n Name = \"Mozilla Firefox\",\n Description = \"Fast, private and secure web browser\",\n PackageName = \"Mozilla.Firefox\",\n Category = \"Web Browsers\",\n IsInstalled = false,\n IsCustomInstall = false\n },\n new ThirdPartyApp\n {\n Name = \"7-Zip\",\n Description = \"File archiver with high compression ratio\",\n PackageName = \"7zip.7zip\",\n Category = \"Utilities\",\n IsInstalled = true,\n IsCustomInstall = false\n },\n new ThirdPartyApp\n {\n Name = \"Adobe Photoshop\",\n Description = \"Professional image editing software\",\n PackageName = \"Adobe.Photoshop\",\n Category = \"Graphics & Design\",\n IsInstalled = false,\n IsCustomInstall = true\n }\n };\n }\n\n /// \n /// Gets a collection of sample Windows applications for design-time.\n /// \n /// A collection of WindowsApp instances.\n public IEnumerable GetSampleWindowsApps()\n {\n // Create sample AppInfo objects to use with the factory method\n var appInfos = new List\n {\n new AppInfo\n {\n Name = \"Microsoft Store\",\n Description = \"Microsoft's digital distribution platform\",\n PackageName = \"Microsoft.WindowsStore\",\n PackageID = \"9WZDNCRFJBMP\",\n Category = \"System\",\n IsInstalled = true,\n CanBeReinstalled = true,\n IsSystemProtected = false\n },\n new AppInfo\n {\n Name = \"Xbox\",\n Description = \"Xbox console companion app for Windows\",\n PackageName = \"Microsoft.XboxApp\",\n PackageID = \"9MV0B5HZVK9Z\",\n Category = \"Entertainment\",\n IsInstalled = true,\n CanBeReinstalled = true,\n IsSystemProtected = false\n },\n new AppInfo\n {\n Name = \"Microsoft Edge\",\n Description = \"Microsoft's web browser\",\n PackageName = \"Microsoft.MicrosoftEdge\",\n PackageID = \"9NBLGGH4M8RR\",\n Category = \"Web Browsers\",\n IsInstalled = true,\n RequiresSpecialHandling = true,\n SpecialHandlerType = \"Edge\",\n CanBeReinstalled = false,\n IsSystemProtected = true\n },\n new AppInfo\n {\n Name = \"OneDrive\",\n Description = \"Microsoft's cloud storage service\",\n PackageName = \"Microsoft.OneDrive\",\n PackageID = \"9WZDNCRFJ3PL\",\n Category = \"Cloud Storage\",\n IsInstalled = false,\n RequiresSpecialHandling = true,\n SpecialHandlerType = \"OneDrive\",\n CanBeReinstalled = true,\n IsSystemProtected = false\n }\n };\n\n // Use the factory method to create properly configured WindowsApp instances\n var windowsApps = new List();\n foreach (var appInfo in appInfos)\n {\n windowsApps.Add(WindowsApp.FromAppInfo(appInfo));\n }\n\n return windowsApps;\n }\n\n /// \n /// Gets a collection of sample Windows capabilities for design-time.\n /// \n /// A collection of WindowsApp instances configured as capabilities.\n public IEnumerable GetSampleWindowsCapabilities()\n {\n // Create sample CapabilityInfo objects to use with the factory method\n var capabilityInfos = new List\n {\n new CapabilityInfo\n {\n Name = \"Windows Media Player\",\n Description = \"Classic media player for Windows\",\n PackageName = \"Media.WindowsMediaPlayer\",\n Category = \"Media\",\n IsInstalled = true,\n CanBeReenabled = true,\n IsSystemProtected = false\n },\n new CapabilityInfo\n {\n Name = \"Internet Explorer\",\n Description = \"Legacy web browser\",\n PackageName = \"Browser.InternetExplorer\",\n Category = \"Web Browsers\",\n IsInstalled = false,\n CanBeReenabled = true,\n IsSystemProtected = false\n },\n new CapabilityInfo\n {\n Name = \"Windows Hello Face\",\n Description = \"Facial recognition authentication\",\n PackageName = \"Hello.Face\",\n Category = \"Security\",\n IsInstalled = true,\n CanBeReenabled = true,\n IsSystemProtected = true\n }\n };\n\n // Use the factory method to create properly configured WindowsApp instances\n var capabilities = new List();\n foreach (var capabilityInfo in capabilityInfos)\n {\n capabilities.Add(WindowsApp.FromCapabilityInfo(capabilityInfo));\n }\n\n return capabilities;\n }\n\n /// \n /// Gets a collection of sample Windows features for design-time.\n /// \n /// A collection of WindowsApp instances configured as features.\n public IEnumerable GetSampleWindowsFeatures()\n {\n // Create sample FeatureInfo objects to use with the factory method\n var featureInfos = new List\n {\n new FeatureInfo\n {\n Name = \"Windows Subsystem for Linux\",\n Description = \"Run Linux command-line tools on Windows\",\n PackageName = \"Microsoft-Windows-Subsystem-Linux\",\n Category = \"Development\",\n IsInstalled = true,\n CanBeReenabled = true,\n IsSystemProtected = false\n },\n new FeatureInfo\n {\n Name = \"Hyper-V\",\n Description = \"Windows virtualization platform\",\n PackageName = \"Microsoft-Hyper-V-All\",\n Category = \"Virtualization\",\n IsInstalled = false,\n CanBeReenabled = true,\n IsSystemProtected = false\n },\n new FeatureInfo\n {\n Name = \"Windows Sandbox\",\n Description = \"Isolated desktop environment for running applications\",\n PackageName = \"Containers-DisposableClientVM\",\n Category = \"Security\",\n IsInstalled = false,\n CanBeReenabled = true,\n IsSystemProtected = false\n }\n };\n\n // Use the factory method to create properly configured WindowsApp instances\n var features = new List();\n foreach (var featureInfo in featureInfos)\n {\n features.Add(WindowsApp.FromFeatureInfo(featureInfo));\n }\n\n return features;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/SearchBox.xaml.cs", "using System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// Interaction logic for SearchBox.xaml\n /// \n public partial class SearchBox : UserControl\n {\n /// \n /// Dependency property for the SearchText property.\n /// \n public static readonly DependencyProperty SearchTextProperty =\n DependencyProperty.Register(\n nameof(SearchText),\n typeof(string),\n typeof(SearchBox),\n new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSearchTextChanged));\n\n /// \n /// Dependency property for the Placeholder property.\n /// \n public static readonly DependencyProperty PlaceholderProperty =\n DependencyProperty.Register(\n nameof(Placeholder),\n typeof(string),\n typeof(SearchBox),\n new PropertyMetadata(\"Search...\"));\n\n /// \n /// Dependency property for the HasText property.\n /// \n public static readonly DependencyProperty HasTextProperty =\n DependencyProperty.Register(\n nameof(HasText),\n typeof(bool),\n typeof(SearchBox),\n new PropertyMetadata(false));\n\n /// \n /// Initializes a new instance of the class.\n /// \n public SearchBox()\n {\n InitializeComponent();\n }\n\n /// \n /// Gets or sets the search text.\n /// \n public string SearchText\n {\n get => (string)GetValue(SearchTextProperty);\n set => SetValue(SearchTextProperty, value);\n }\n\n /// \n /// Gets or sets the placeholder text.\n /// \n public string Placeholder\n {\n get => (string)GetValue(PlaceholderProperty);\n set => SetValue(PlaceholderProperty, value);\n }\n\n /// \n /// Gets a value indicating whether the search box has text.\n /// \n public bool HasText\n {\n get => (bool)GetValue(HasTextProperty);\n private set => SetValue(HasTextProperty, value);\n }\n\n /// \n /// Called when the search text changes.\n /// \n /// The dependency object.\n /// The event arguments.\n private static void OnSearchTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is SearchBox searchBox)\n {\n searchBox.HasText = !string.IsNullOrEmpty((string)e.NewValue);\n }\n }\n\n /// \n /// Handles the click event of the clear button.\n /// \n /// The sender.\n /// The event arguments.\n private void ClearButton_Click(object sender, RoutedEventArgs e)\n {\n SearchText = string.Empty;\n SearchTextBox.Focus();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/FileSystemService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading.Tasks;\nusing Winhance.Core.Interfaces.Services;\n\nnamespace Winhance.Infrastructure.FileSystem\n{\n /// \n /// Implementation of IFileSystem that wraps the System.IO operations.\n /// \n public class FileSystemService : IFileSystemService\n {\n /// \n /// Determines whether the specified file exists.\n /// \n /// The file to check.\n /// True if the file exists; otherwise, false.\n public bool FileExists(string path)\n {\n return File.Exists(path);\n }\n\n /// \n /// Determines whether the specified directory exists.\n /// \n /// The directory to check.\n /// True if the directory exists; otherwise, false.\n public bool DirectoryExists(string path)\n {\n return Directory.Exists(path);\n }\n\n /// \n /// Creates a directory if it doesn't exist.\n /// \n /// The directory to create.\n /// True if the directory was created or already exists; otherwise, false.\n public bool CreateDirectory(string path)\n {\n try\n {\n if (!Directory.Exists(path))\n {\n Directory.CreateDirectory(path);\n }\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n /// Reads all text from a file.\n /// \n /// The file to read from.\n /// The text read from the file.\n public string ReadAllText(string path)\n {\n return File.ReadAllText(path);\n }\n\n /// \n /// Reads all text from a file asynchronously.\n /// \n /// The file to read from.\n /// A task that represents the asynchronous read operation and wraps the text read from the file.\n public async Task ReadAllTextAsync(string path)\n {\n using var reader = new StreamReader(path);\n return await reader.ReadToEndAsync();\n }\n\n /// \n /// Reads all bytes from a file.\n /// \n /// The file to read from.\n /// The bytes read from the file.\n public byte[] ReadAllBytes(string path)\n {\n return File.ReadAllBytes(path);\n }\n\n /// \n /// Reads all bytes from a file asynchronously.\n /// \n /// The file to read from.\n /// A task that represents the asynchronous read operation and wraps the bytes read from the file.\n public async Task ReadAllBytesAsync(string path)\n {\n return await File.ReadAllBytesAsync(path);\n }\n\n /// \n /// Writes text to a file.\n /// \n /// The file to write to.\n /// The text to write to the file.\n /// True if the text was written successfully; otherwise, false.\n public bool WriteAllText(string path, string contents)\n {\n try\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n File.WriteAllText(path, contents);\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n /// Writes text to a file asynchronously.\n /// \n /// The file to write to.\n /// The text to write to the file.\n /// A task that represents the asynchronous write operation.\n public async Task WriteAllTextAsync(string path, string contents)\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n await File.WriteAllTextAsync(path, contents);\n }\n \n /// \n /// Appends text to a file.\n /// \n /// The file to append to.\n /// The text to append to the file.\n public void AppendAllText(string path, string contents)\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n File.AppendAllText(path, contents);\n }\n \n /// \n /// Appends text to a file asynchronously.\n /// \n /// The file to append to.\n /// The text to append to the file.\n /// A task that represents the asynchronous append operation.\n public async Task AppendAllTextAsync(string path, string contents)\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n await File.AppendAllTextAsync(path, contents);\n }\n\n /// \n /// Writes bytes to a file.\n /// \n /// The file to write to.\n /// The bytes to write to the file.\n public void WriteAllBytes(string path, byte[] bytes)\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n File.WriteAllBytes(path, bytes);\n }\n\n /// \n /// Writes bytes to a file asynchronously.\n /// \n /// The file to write to.\n /// The bytes to write to the file.\n /// A task that represents the asynchronous write operation.\n public async Task WriteAllBytesAsync(string path, byte[] bytes)\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n await File.WriteAllBytesAsync(path, bytes);\n }\n\n /// \n /// Deletes a file.\n /// \n /// The file to delete.\n /// True if the file was deleted or didn't exist; otherwise, false.\n public bool DeleteFile(string path)\n {\n try\n {\n if (File.Exists(path))\n {\n File.Delete(path);\n }\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n /// Deletes a directory.\n /// \n /// The directory to delete.\n /// True to delete subdirectories and files; otherwise, false.\n public void DeleteDirectory(string path, bool recursive)\n {\n if (Directory.Exists(path))\n {\n Directory.Delete(path, recursive);\n }\n }\n\n /// \n /// Gets all files in a directory that match the specified pattern.\n /// \n /// The directory to search.\n /// The search pattern.\n /// Whether to search subdirectories.\n /// A collection of file paths.\n public IEnumerable GetFiles(string path, string pattern, bool recursive)\n {\n return Directory.GetFiles(path, pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);\n }\n\n /// \n /// Gets all directories in a directory that match the specified pattern.\n /// \n /// The directory to search.\n /// The search pattern.\n /// Whether to search subdirectories.\n /// A collection of directory paths.\n public IEnumerable GetDirectories(string path, string pattern, bool recursive)\n {\n return Directory.GetDirectories(path, pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);\n }\n \n /// \n /// Gets the path to a special folder, such as AppData, ProgramFiles, etc.\n /// \n /// The name of the special folder.\n /// The path to the special folder.\n public string GetSpecialFolderPath(string specialFolder)\n {\n if (Enum.TryParse(specialFolder, out var folder))\n {\n return Environment.GetFolderPath(folder);\n }\n return string.Empty;\n }\n \n /// \n /// Combines multiple paths into a single path.\n /// \n /// The paths to combine.\n /// The combined path.\n public string CombinePaths(params string[] paths)\n {\n return Path.Combine(paths);\n }\n \n /// \n /// Gets the current directory of the application.\n /// \n /// The current directory path.\n public string GetCurrentDirectory()\n {\n return Directory.GetCurrentDirectory();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/VersionInfo.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n public class VersionInfo\n {\n public string Version { get; set; } = string.Empty;\n public DateTime ReleaseDate { get; set; }\n public string DownloadUrl { get; set; } = string.Empty;\n public bool IsUpdateAvailable { get; set; }\n \n public static VersionInfo FromTag(string tag)\n {\n // Parse version tag in format v25.05.02\n if (string.IsNullOrEmpty(tag) || !tag.StartsWith(\"v\"))\n return new VersionInfo();\n \n string versionString = tag.Substring(1); // Remove 'v' prefix\n string[] parts = versionString.Split('.');\n \n if (parts.Length != 3)\n return new VersionInfo();\n \n if (!int.TryParse(parts[0], out int year) || \n !int.TryParse(parts[1], out int month) || \n !int.TryParse(parts[2], out int day))\n return new VersionInfo();\n \n // Construct a date from the version components\n DateTime releaseDate;\n try\n {\n releaseDate = new DateTime(2000 + year, month, day);\n }\n catch\n {\n // Invalid date components\n return new VersionInfo();\n }\n \n return new VersionInfo\n {\n Version = tag,\n ReleaseDate = releaseDate\n };\n }\n \n public bool IsNewerThan(VersionInfo other)\n {\n if (other == null)\n return true;\n \n return ReleaseDate > other.ReleaseDate;\n }\n \n public override string ToString()\n {\n return Version;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Models/ExternalApp.cs", "using System;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Models\n{\n public partial class ExternalApp : ObservableObject, ISearchable\n {\n public string Name { get; set; }\n public string Description { get; set; }\n public string PackageName { get; set; }\n public string Version { get; set; } = string.Empty;\n \n [ObservableProperty]\n private bool _isInstalled;\n \n public bool CanBeReinstalled { get; set; }\n \n [ObservableProperty]\n private bool _isSelected;\n \n [ObservableProperty]\n private string _lastOperationError;\n\n public static ExternalApp FromAppInfo(AppInfo appInfo)\n {\n if (appInfo == null)\n throw new ArgumentNullException(nameof(appInfo));\n\n var app = new ExternalApp\n {\n Name = appInfo.Name,\n Description = appInfo.Description,\n PackageName = appInfo.PackageName,\n Version = appInfo.Version,\n CanBeReinstalled = appInfo.CanBeReinstalled,\n Category = appInfo.Category,\n LastOperationError = appInfo.LastOperationError\n };\n \n app.IsInstalled = appInfo.IsInstalled;\n \n return app;\n }\n\n public AppInfo ToAppInfo()\n {\n return new AppInfo\n {\n Name = Name,\n Description = Description,\n PackageName = PackageName,\n Version = Version,\n IsInstalled = IsInstalled,\n CanBeReinstalled = CanBeReinstalled,\n Category = Category,\n LastOperationError = LastOperationError\n };\n }\n\n /// \n /// Gets the category of the app.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Determines if the app matches the given search term.\n /// \n /// The search term to match against.\n /// True if the app matches the search term, false otherwise.\n public bool MatchesSearch(string searchTerm)\n {\n if (string.IsNullOrWhiteSpace(searchTerm))\n {\n return true;\n }\n\n searchTerm = searchTerm.ToLowerInvariant();\n \n // Check if the search term matches any of the searchable properties\n return Name.ToLowerInvariant().Contains(searchTerm) ||\n (!string.IsNullOrEmpty(Description) && Description.ToLowerInvariant().Contains(searchTerm)) ||\n (!string.IsNullOrEmpty(PackageName) && PackageName.ToLowerInvariant().Contains(searchTerm)) ||\n (!string.IsNullOrEmpty(Category) && Category.ToLowerInvariant().Contains(searchTerm));\n }\n\n /// \n /// Gets the searchable properties of the app.\n /// \n /// An array of property names that should be searched.\n public string[] GetSearchableProperties()\n {\n return new[] { nameof(Name), nameof(Description), nameof(PackageName), nameof(Category) };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Resources/MaterialSymbols.cs", "using System.Collections.Generic;\n\nnamespace Winhance.WPF.Features.Common.Resources\n{\n /// \n /// Provides access to Material Symbols icon Unicode values.\n /// \n public static class MaterialSymbols\n {\n private static readonly Dictionary _iconMap = new Dictionary\n {\n // Navigation icons\n { \"RocketLaunch\", \"\\uEB9B\" },\n { \"Rocket\", \"\\uE837\" },\n { \"DeployedCode\", \"\\uE8A7\" },\n { \"DeployedCodeUpdate\", \"\\uE8A8\" },\n { \"CodeBraces\", \"\\uE86F\" },\n { \"Routine\", \"\\uEBB9\" },\n { \"ThemeLightDark\", \"\\uE51C\" },\n { \"Palette\", \"\\uE40A\" },\n { \"Information\", \"\\uE88E\" },\n { \"MicrosoftWindows\", \"\\uE950\" },\n\n // Other common icons\n { \"Apps\", \"\\uE5C3\" },\n { \"Settings\", \"\\uE8B8\" },\n { \"Close\", \"\\uE5CD\" },\n { \"Menu\", \"\\uE5D2\" },\n { \"Search\", \"\\uE8B6\" },\n { \"Add\", \"\\uE145\" },\n { \"Delete\", \"\\uE872\" },\n { \"Edit\", \"\\uE3C9\" },\n { \"Save\", \"\\uE161\" },\n { \"Download\", \"\\uE2C4\" },\n { \"Upload\", \"\\uE2C6\" },\n { \"Refresh\", \"\\uE5D5\" },\n { \"ArrowBack\", \"\\uE5C4\" },\n { \"ArrowForward\", \"\\uE5C8\" },\n { \"ChevronDown\", \"\\uE5CF\" },\n { \"ChevronUp\", \"\\uE5CE\" },\n { \"ChevronLeft\", \"\\uE5CB\" },\n { \"ChevronRight\", \"\\uE5CC\" },\n { \"ExpandMore\", \"\\uE5CF\" },\n { \"ExpandLess\", \"\\uE5CE\" },\n { \"MoreVert\", \"\\uE5D4\" },\n { \"MoreHoriz\", \"\\uE5D3\" },\n { \"Check\", \"\\uE5CA\" },\n { \"Clear\", \"\\uE14C\" },\n { \"Error\", \"\\uE000\" },\n { \"Warning\", \"\\uE002\" },\n { \"Info\", \"\\uE88E\" },\n { \"Help\", \"\\uE887\" },\n { \"HelpOutline\", \"\\uE8FD\" },\n { \"Sync\", \"\\uE627\" },\n { \"SyncDisabled\", \"\\uE628\" },\n { \"SyncProblem\", \"\\uE629\" },\n { \"Visibility\", \"\\uE8F4\" },\n { \"VisibilityOff\", \"\\uE8F5\" },\n { \"Lock\", \"\\uE897\" },\n { \"LockOpen\", \"\\uE898\" },\n { \"Star\", \"\\uE838\" },\n { \"StarBorder\", \"\\uE83A\" },\n { \"Favorite\", \"\\uE87D\" },\n { \"FavoriteBorder\", \"\\uE87E\" },\n { \"ThumbUp\", \"\\uE8DC\" },\n { \"ThumbDown\", \"\\uE8DB\" },\n { \"MicrosoftWindows\", \"\\uE9AA\" }\n };\n\n /// \n /// Gets the Unicode character for the specified icon name.\n /// \n /// The name of the icon.\n /// The Unicode character for the icon, or a question mark if not found.\n public static string GetIcon(string iconName)\n {\n if (_iconMap.TryGetValue(iconName, out string iconChar))\n {\n return iconChar;\n }\n\n return \"?\"; // Return a question mark if the icon is not found\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/LogLevelToColorConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a LogLevel to a color for display in the UI.\n /// \n public class LogLevelToColorConverter : IValueConverter\n {\n /// \n /// Converts a LogLevel to a color.\n /// \n /// The LogLevel value.\n /// The target type.\n /// The converter parameter.\n /// The culture information.\n /// A color brush based on the log level.\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is LogLevel level)\n {\n switch (level)\n {\n case LogLevel.Error:\n return new SolidColorBrush(Colors.Red);\n case LogLevel.Warning:\n return new SolidColorBrush(Colors.Orange);\n case LogLevel.Debug:\n return new SolidColorBrush(Colors.Gray);\n default:\n return new SolidColorBrush(Colors.White);\n }\n }\n return new SolidColorBrush(Colors.White);\n }\n\n /// \n /// Converts a color back to a LogLevel (not implemented).\n /// \n /// The color value.\n /// The target type.\n /// The converter parameter.\n /// The culture information.\n /// Not implemented.\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/StatusToColorConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class StatusToColorConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // Handle RegistrySettingStatus\n if (value is RegistrySettingStatus status)\n {\n return status switch\n {\n RegistrySettingStatus.Applied => new SolidColorBrush(Color.FromRgb(0, 255, 60)), // Electric Green (#00FF3C)\n RegistrySettingStatus.NotApplied => new SolidColorBrush(Color.FromRgb(255, 40, 0)), // Ferrari Red (#FF2800)\n RegistrySettingStatus.Modified => new SolidColorBrush(Colors.Orange),\n RegistrySettingStatus.Error => new SolidColorBrush(Colors.Gray),\n _ => new SolidColorBrush(Colors.Gray)\n };\n }\n \n // Handle boolean for reinstallability status\n if (value is bool canBeReinstalled)\n {\n return canBeReinstalled \n ? new SolidColorBrush(Color.FromRgb(0, 165, 255)) // Blue (#00A5FF)\n : new SolidColorBrush(Color.FromRgb(255, 40, 0)); // Ferrari Red (#FF2800)\n }\n\n return new SolidColorBrush(Colors.Gray);\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceCore.cs", "using Microsoft.Win32;\nusing System;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Core implementation of the registry service.\n /// \n [SupportedOSPlatform(\"windows\")]\n public partial class RegistryService : IRegistryService\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public RegistryService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Checks if the current platform is Windows.\n /// \n /// True if the platform is Windows; otherwise, logs an error and returns false.\n private bool CheckWindowsPlatform()\n {\n if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n return true;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceCompletion.cs", "using Microsoft.Win32;\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Security.AccessControl;\nusing System.Security.Principal;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing LogLevel = Winhance.Core.Features.Common.Enums.LogLevel;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n [SupportedOSPlatform(\"windows\")]\n public partial class RegistryService\n {\n private RegistryKey? GetRootKey(string rootKeyName)\n {\n // Normalize the input by converting to uppercase\n rootKeyName = rootKeyName.ToUpper();\n \n // Check for full names first\n if (rootKeyName == \"HKEY_LOCAL_MACHINE\" || rootKeyName == \"LOCALMACHINE\")\n return Microsoft.Win32.Registry.LocalMachine;\n if (rootKeyName == \"HKEY_CURRENT_USER\" || rootKeyName == \"CURRENTUSER\")\n return Microsoft.Win32.Registry.CurrentUser;\n if (rootKeyName == \"HKEY_CLASSES_ROOT\")\n return Microsoft.Win32.Registry.ClassesRoot;\n if (rootKeyName == \"HKEY_USERS\")\n return Microsoft.Win32.Registry.Users;\n if (rootKeyName == \"HKEY_CURRENT_CONFIG\")\n return Microsoft.Win32.Registry.CurrentConfig;\n \n // Then check for abbreviated names using the extension method's constants\n if (rootKeyName == RegistryExtensions.GetRegistryHiveString(RegistryHive.LocalMachine))\n return Microsoft.Win32.Registry.LocalMachine;\n if (rootKeyName == RegistryExtensions.GetRegistryHiveString(RegistryHive.CurrentUser))\n return Microsoft.Win32.Registry.CurrentUser;\n if (rootKeyName == RegistryExtensions.GetRegistryHiveString(RegistryHive.ClassesRoot))\n return Microsoft.Win32.Registry.ClassesRoot;\n if (rootKeyName == RegistryExtensions.GetRegistryHiveString(RegistryHive.Users))\n return Microsoft.Win32.Registry.Users;\n if (rootKeyName == RegistryExtensions.GetRegistryHiveString(RegistryHive.CurrentConfig))\n return Microsoft.Win32.Registry.CurrentConfig;\n \n // If no match is found, return null\n return null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Verification/VerificationMethodBase.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Verification\n{\n /// \n /// Base class for verification methods that check if a package is installed.\n /// \n public abstract class VerificationMethodBase\n {\n /// \n /// Gets the name of the verification method.\n /// \n public string Name { get; }\n\n /// \n /// Gets the priority of this verification method. Lower values mean higher priority.\n /// \n public int Priority { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The name of the verification method.\n /// The priority of the verification method. Lower values mean higher priority.\n protected VerificationMethodBase(string name, int priority)\n {\n Name = name ?? throw new System.ArgumentNullException(nameof(name));\n Priority = priority;\n }\n\n /// \n /// Verifies if a package is installed.\n /// \n /// The ID of the package to verify.\n /// The version of the package to verify, or null to check for any version.\n /// A cancellation token that can be used to cancel the operation.\n /// A task that represents the asynchronous operation. The task result contains the verification result.\n public async Task VerifyAsync(\n string packageId,\n string version = null,\n CancellationToken cancellationToken = default)\n {\n if (string.IsNullOrWhiteSpace(packageId))\n {\n throw new System.ArgumentException(\"Package ID cannot be null or whitespace.\", nameof(packageId));\n }\n\n return version == null\n ? await VerifyPresenceAsync(packageId, cancellationToken).ConfigureAwait(false)\n : await VerifyVersionAsync(packageId, version, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// When overridden in a derived class, verifies if a package is installed, regardless of version.\n /// \n /// The ID of the package to verify.\n /// A cancellation token that can be used to cancel the operation.\n /// A task that represents the asynchronous operation. The task result contains the verification result.\n protected abstract Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken);\n\n /// \n /// When overridden in a derived class, verifies if a specific version of a package is installed.\n /// \n /// The ID of the package to verify.\n /// The version of the package to verify.\n /// A cancellation token that can be used to cancel the operation.\n /// A task that represents the asynchronous operation. The task result contains the verification result.\n protected abstract Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/MaterialSymbol.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\nusing Winhance.WPF.Features.Common.Resources;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// Interaction logic for MaterialSymbol.xaml\n /// \n public partial class MaterialSymbol : UserControl\n {\n public static readonly DependencyProperty IconProperty = DependencyProperty.Register(\n \"Icon\", typeof(string), typeof(MaterialSymbol), \n new PropertyMetadata(string.Empty, OnIconChanged));\n\n public static readonly DependencyProperty IconTextProperty = DependencyProperty.Register(\n \"IconText\", typeof(string), typeof(MaterialSymbol), \n new PropertyMetadata(string.Empty));\n\n public string Icon\n {\n get { return (string)GetValue(IconProperty); }\n set { SetValue(IconProperty, value); }\n }\n\n public string IconText\n {\n get { return (string)GetValue(IconTextProperty); }\n set { SetValue(IconTextProperty, value); }\n }\n\n public MaterialSymbol()\n {\n InitializeComponent();\n }\n\n private static void OnIconChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is MaterialSymbol control && e.NewValue is string iconName)\n {\n control.IconText = MaterialSymbols.GetIcon(iconName);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/ScriptStatusToColorConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean script status to a color.\n /// \n public class ScriptStatusToColorConverter : IValueConverter\n {\n /// \n /// Converts a boolean value to a color.\n /// \n /// The boolean value indicating if scripts are active.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// A color based on the script status.\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isActive)\n {\n // Return green if scripts are active, gray if not\n return isActive \n ? new SolidColorBrush(Color.FromRgb(0, 200, 83)) // Green for active\n : new SolidColorBrush(Color.FromRgb(150, 150, 150)); // Gray for inactive\n }\n \n return new SolidColorBrush(Colors.Gray);\n }\n \n /// \n /// Converts a color back to a boolean value.\n /// \n /// The color to convert back.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// A boolean value based on the color.\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Helpers/ValidationHelper.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Helpers\n{\n /// \n /// Helper class for common validation operations.\n /// \n public static class ValidationHelper\n {\n /// \n /// Validates that the specified object is not null.\n /// \n /// The object to validate.\n /// The name of the parameter being validated.\n /// Thrown if the value is null.\n public static void NotNull(object value, string paramName)\n {\n if (value == null)\n {\n throw new ArgumentNullException(paramName);\n }\n }\n\n /// \n /// Validates that the specified string is not null or empty.\n /// \n /// The string to validate.\n /// The name of the parameter being validated.\n /// Thrown if the value is null.\n /// Thrown if the value is empty.\n public static void NotNullOrEmpty(string value, string paramName)\n {\n if (value == null)\n {\n throw new ArgumentNullException(paramName);\n }\n\n if (string.IsNullOrEmpty(value))\n {\n throw new ArgumentException(\"Value cannot be empty.\", paramName);\n }\n }\n\n /// \n /// Validates that the specified string is not null, empty, or consists only of white-space characters.\n /// \n /// The string to validate.\n /// The name of the parameter being validated.\n /// Thrown if the value is null.\n /// Thrown if the value is empty or consists only of white-space characters.\n public static void NotNullOrWhiteSpace(string value, string paramName)\n {\n if (value == null)\n {\n throw new ArgumentNullException(paramName);\n }\n\n if (string.IsNullOrWhiteSpace(value))\n {\n throw new ArgumentException(\"Value cannot be empty or consist only of white-space characters.\", paramName);\n }\n }\n\n /// \n /// Validates that the specified value is greater than or equal to the minimum value.\n /// \n /// The value to validate.\n /// The minimum allowed value.\n /// The name of the parameter being validated.\n /// Thrown if the value is less than the minimum value.\n public static void GreaterThanOrEqualTo(int value, int minValue, string paramName)\n {\n if (value < minValue)\n {\n throw new ArgumentOutOfRangeException(paramName, value, $\"Value must be greater than or equal to {minValue}.\");\n }\n }\n\n /// \n /// Validates that the specified value is less than or equal to the maximum value.\n /// \n /// The value to validate.\n /// The maximum allowed value.\n /// The name of the parameter being validated.\n /// Thrown if the value is greater than the maximum value.\n public static void LessThanOrEqualTo(int value, int maxValue, string paramName)\n {\n if (value > maxValue)\n {\n throw new ArgumentOutOfRangeException(paramName, value, $\"Value must be less than or equal to {maxValue}.\");\n }\n }\n\n /// \n /// Validates that the specified value is in the specified range.\n /// \n /// The value to validate.\n /// The minimum allowed value.\n /// The maximum allowed value.\n /// The name of the parameter being validated.\n /// Thrown if the value is outside the specified range.\n public static void InRange(int value, int minValue, int maxValue, string paramName)\n {\n if (value < minValue || value > maxValue)\n {\n throw new ArgumentOutOfRangeException(paramName, value, $\"Value must be between {minValue} and {maxValue}.\");\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/LogMessageEventArgs.cs", "using System;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Event arguments for log message events.\n /// \n public class LogMessageEventArgs : EventArgs\n {\n /// \n /// Gets the message content.\n /// \n public string Message { get; }\n \n /// \n /// Gets the log level.\n /// \n public LogLevel Level { get; }\n \n /// \n /// Gets the timestamp when the message was created.\n /// \n public DateTime Timestamp { get; }\n \n /// \n /// Gets the exception associated with the log message, if any.\n /// \n public Exception? Exception { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The message content.\n /// The log level.\n public LogMessageEventArgs(string message, LogLevel level)\n {\n Message = message ?? throw new ArgumentNullException(nameof(message));\n Level = level;\n Timestamp = DateTime.Now;\n Exception = null;\n }\n \n /// \n /// Initializes a new instance of the class.\n /// \n /// The log level.\n /// The message content.\n /// The exception associated with the message, if any.\n public LogMessageEventArgs(LogLevel level, string message, Exception? exception)\n {\n Message = message ?? throw new ArgumentNullException(nameof(message));\n Level = level;\n Timestamp = DateTime.Now;\n Exception = exception;\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppRemovalServiceAdapter.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Adapter class that adapts IAppRemovalService to IInstallationService<AppInfo>.\n /// This is used to maintain backward compatibility with code that expects the AppRemovalService\n /// property of IPackageManager to return an IInstallationService<AppInfo>.\n /// \n public class AppRemovalServiceAdapter : IInstallationService\n {\n private readonly IAppRemovalService _appRemovalService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The app removal service to adapt.\n public AppRemovalServiceAdapter(IAppRemovalService appRemovalService)\n {\n _appRemovalService = appRemovalService ?? throw new ArgumentNullException(nameof(appRemovalService));\n }\n\n /// \n public Task> InstallAsync(\n AppInfo item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n // This is an adapter for removal service, so \"install\" actually means \"remove\"\n return _appRemovalService.RemoveAppAsync(item, progress, cancellationToken);\n }\n\n /// \n public Task> CanInstallAsync(AppInfo item)\n {\n // Since this is an adapter for removal, we'll always return true\n // The actual validation will happen in the RemoveAppAsync method\n return Task.FromResult(OperationResult.Succeeded(true));\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/RegistryHiveToFullNameConverter.cs", "using Microsoft.Win32;\nusing System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a RegistryHive enum to its full string representation (HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, etc.)\n /// \n public class RegistryHiveToFullNameConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKEY_CLASSES_ROOT\",\n RegistryHive.CurrentUser => \"HKEY_CURRENT_USER\",\n RegistryHive.LocalMachine => \"HKEY_LOCAL_MACHINE\",\n RegistryHive.Users => \"HKEY_USERS\",\n RegistryHive.CurrentConfig => \"HKEY_CURRENT_CONFIG\",\n _ => value.ToString()\n };\n }\n \n return value?.ToString() ?? string.Empty;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/ScriptDetectionService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Implementation of the IScriptDetectionService interface.\n /// \n public class ScriptDetectionService : IScriptDetectionService\n {\n private const string ScriptsDirectory = @\"C:\\Program Files\\Winhance\\Scripts\";\n \n private static readonly Dictionary ScriptDescriptions = new Dictionary(StringComparer.OrdinalIgnoreCase)\n {\n { \"BloatRemoval.ps1\", \"Multiple items removed via BloatRemoval.ps1\" },\n { \"EdgeRemoval.ps1\", \"Microsoft Edge Removed via EdgeRemoval.ps1\" },\n { \"OneDriveRemoval.ps1\", \"OneDrive Removed via OneDriveRemoval.ps1\" }\n };\n \n /// \n public bool AreRemovalScriptsPresent()\n {\n if (!Directory.Exists(ScriptsDirectory))\n {\n return false;\n }\n \n return GetScriptFiles().Any();\n }\n \n /// \n public IEnumerable GetActiveScripts()\n {\n if (!Directory.Exists(ScriptsDirectory))\n {\n return Enumerable.Empty();\n }\n \n var scriptFiles = GetScriptFiles();\n \n return scriptFiles.Select(file => new ScriptInfo\n {\n Name = Path.GetFileName(file),\n Description = GetScriptDescription(Path.GetFileName(file)),\n FilePath = file\n });\n }\n \n private IEnumerable GetScriptFiles()\n {\n if (!Directory.Exists(ScriptsDirectory))\n {\n return Enumerable.Empty();\n }\n \n return Directory.GetFiles(ScriptsDirectory, \"*.ps1\")\n .Where(file => ScriptDescriptions.ContainsKey(Path.GetFileName(file)));\n }\n \n private string GetScriptDescription(string fileName)\n {\n return ScriptDescriptions.TryGetValue(fileName, out var description)\n ? description\n : $\"Unknown script: {fileName}\";\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/TaskProgressEventArgs.cs", "using System;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Event arguments for task progress events.\n /// \n public class TaskProgressEventArgs : EventArgs\n {\n /// \n /// Gets the progress value (0-100), or null if not applicable.\n /// \n public double Progress { get; }\n \n /// \n /// Gets the status text.\n /// \n public string StatusText { get; }\n \n /// \n /// Gets a detailed message about the current operation.\n /// \n public string DetailedMessage { get; }\n \n /// \n /// Gets the log level for the detailed message.\n /// \n public LogLevel LogLevel { get; }\n \n /// \n /// Gets whether the progress is indeterminate.\n /// \n public bool IsIndeterminate { get; }\n \n /// \n /// Gets whether a task is currently running.\n /// \n public bool IsTaskRunning { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The progress value.\n /// The status text.\n /// The detailed message.\n /// The log level.\n /// Whether the progress is indeterminate.\n /// Whether a task is running.\n public TaskProgressEventArgs(double progress, string statusText, string detailedMessage = \"\", LogLevel logLevel = LogLevel.Info, bool isIndeterminate = false, bool isTaskRunning = true)\n {\n Progress = progress;\n StatusText = statusText;\n DetailedMessage = detailedMessage;\n LogLevel = logLevel;\n IsIndeterminate = isIndeterminate;\n IsTaskRunning = isTaskRunning;\n }\n\n /// \n /// Creates a TaskProgressEventArgs instance from a TaskProgressDetail.\n /// \n /// The progress detail.\n /// Whether a task is running.\n /// A new TaskProgressEventArgs instance.\n public static TaskProgressEventArgs FromTaskProgressDetail(TaskProgressDetail detail, bool isTaskRunning = true)\n {\n return new TaskProgressEventArgs(\n detail.Progress ?? 0,\n detail.StatusText ?? string.Empty,\n detail.DetailedMessage ?? string.Empty,\n detail.LogLevel,\n detail.IsIndeterminate,\n isTaskRunning);\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ILogService.cs", "using System;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides logging functionality for the application.\n /// \n public interface ILogService\n {\n /// \n /// Starts logging to a file.\n /// \n void StartLog();\n\n /// \n /// Stops logging to a file.\n /// \n void StopLog();\n\n /// \n /// Logs an informational message.\n /// \n /// The message to log.\n void LogInformation(string message);\n\n /// \n /// Logs a warning message.\n /// \n /// The message to log.\n void LogWarning(string message);\n\n /// \n /// Logs an error message.\n /// \n /// The message to log.\n /// The exception associated with the error, if any.\n void LogError(string message, Exception? exception = null);\n\n /// \n /// Logs a success message.\n /// \n /// The message to log.\n void LogSuccess(string message);\n\n /// \n /// Gets the path to the current log file.\n /// \n /// The path to the log file.\n string GetLogPath();\n\n /// \n /// Logs a message with the specified level.\n /// \n /// The log level.\n /// The message to log.\n /// The exception associated with the message, if any.\n void Log(LogLevel level, string message, Exception? exception = null);\n\n /// \n /// Event raised when a log message is generated.\n /// \n event EventHandler? LogMessageGenerated;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/ApplicationSetting.cs", "using Microsoft.Win32;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Base class for all application settings that can modify registry values.\n /// \n public abstract record ApplicationSetting\n {\n /// \n /// Gets or sets the unique identifier for this setting.\n /// \n public required string Id { get; init; }\n\n /// \n /// Gets or sets the user-friendly name for this setting.\n /// \n public required string Name { get; init; }\n\n /// \n /// Gets or sets the description for this setting.\n /// \n public required string Description { get; init; }\n\n /// \n /// Gets or sets the group name for this setting.\n /// \n public required string GroupName { get; init; }\n\n /// \n /// Gets or sets the collection of registry settings associated with this application setting.\n /// \n public List RegistrySettings { get; init; } = new List();\n\n /// \n /// Gets or sets the collection of command settings associated with this application setting.\n /// \n public List CommandSettings { get; init; } = new List();\n\n /// \n /// Gets or sets the logic to use when determining the status of linked registry settings.\n /// \n public LinkedSettingsLogic LinkedSettingsLogic { get; init; } = LinkedSettingsLogic.Any;\n\n /// \n /// Gets or sets the dependencies between settings.\n /// \n public List Dependencies { get; init; } = new List();\n\n /// \n /// Gets or sets the control type for the UI.\n /// \n public ControlType ControlType { get; init; } = ControlType.BinaryToggle;\n\n /// \n /// Gets or sets the number of steps for a slider control.\n /// \n public int? SliderSteps { get; init; }\n\n /// \n /// Gets or sets a value indicating whether this setting is enabled.\n /// \n public bool IsEnabled { get; init; }\n\n /// \n /// Creates a LinkedRegistrySettings object from the RegistrySettings collection.\n /// \n /// A LinkedRegistrySettings object.\n public LinkedRegistrySettings CreateLinkedRegistrySettings()\n {\n if (RegistrySettings.Count == 0)\n {\n return new LinkedRegistrySettings();\n }\n\n var linkedSettings = new LinkedRegistrySettings\n {\n Category = RegistrySettings[0].Category,\n Description = Description,\n Logic = LinkedSettingsLogic\n };\n\n foreach (var registrySetting in RegistrySettings)\n {\n linkedSettings.AddSetting(registrySetting);\n }\n\n return linkedSettings;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ITaskProgressService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides functionality for tracking task progress.\n /// \n public interface ITaskProgressService\n {\n /// \n /// Gets a value indicating whether a task is currently running.\n /// \n bool IsTaskRunning { get; }\n\n /// \n /// Gets the current progress value (0-100).\n /// \n int CurrentProgress { get; }\n\n /// \n /// Gets the current status text.\n /// \n string CurrentStatusText { get; }\n\n /// \n /// Gets a value indicating whether the current task progress is indeterminate.\n /// \n bool IsIndeterminate { get; }\n\n /// \n /// Gets the cancellation token source for the current task.\n /// \n CancellationTokenSource? CurrentTaskCancellationSource { get; }\n\n /// \n /// Starts a new task.\n /// \n /// The name of the task.\n /// Whether the task progress is indeterminate.\n /// A cancellation token source for the task.\n CancellationTokenSource StartTask(string taskName, bool isIndeterminate = false);\n\n /// \n /// Updates the progress of the current task.\n /// \n /// The progress percentage (0-100).\n /// The status text.\n void UpdateProgress(int progressPercentage, string? statusText = null);\n\n /// \n /// Updates the progress of the current task with detailed information.\n /// \n /// The detailed progress information.\n void UpdateDetailedProgress(TaskProgressDetail detail);\n\n /// \n /// Completes the current task.\n /// \n void CompleteTask();\n\n /// \n /// Adds a log message to the task progress.\n /// \n /// The log message.\n void AddLogMessage(string message);\n\n /// \n /// Cancels the current task.\n /// \n void CancelCurrentTask();\n\n /// \n /// Creates a progress reporter for detailed progress.\n /// \n /// The progress reporter.\n IProgress CreateDetailedProgress();\n\n /// \n /// Creates a progress reporter for PowerShell progress.\n /// \n /// The progress reporter.\n IProgress CreatePowerShellProgress();\n\n /// \n /// Event raised when progress is updated.\n /// \n event EventHandler? ProgressUpdated;\n \n /// \n /// Event raised when progress is updated (legacy compatibility).\n /// \n event EventHandler? ProgressChanged;\n\n /// \n /// Event raised when a log message is added.\n /// \n event EventHandler? LogMessageAdded;\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/StatusToTextConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class StatusToTextConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is RegistrySettingStatus status)\n {\n return status switch\n {\n RegistrySettingStatus.Applied => \"Applied\",\n RegistrySettingStatus.NotApplied => \"Not Applied\",\n RegistrySettingStatus.Modified => \"Modified\",\n RegistrySettingStatus.Error => \"Error\",\n _ => \"Unknown\"\n };\n }\n\n return \"Unknown\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Properties/Settings.Designer.cs", "namespace Winhance.WPF.Properties {\n \n [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator\", \"17.0.0.0\")]\n internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {\n \n private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));\n \n public static Settings Default {\n get {\n return defaultInstance;\n }\n }\n \n [global::System.Configuration.UserScopedSettingAttribute()]\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n [global::System.Configuration.DefaultSettingValueAttribute(\"True\")]\n public bool IsDarkTheme {\n get {\n return ((bool)(this[\"IsDarkTheme\"]));\n }\n set {\n this[\"IsDarkTheme\"] = value;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BoolToArrowConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean value to an arrow character for UI display.\n /// True returns an up arrow, False returns a down arrow.\n /// \n public class BoolToArrowConverter : IValueConverter\n {\n public static BoolToArrowConverter Instance { get; } = new BoolToArrowConverter();\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isExpanded)\n {\n // Up arrow for expanded, down arrow for collapsed\n return isExpanded ? \"\\uE70E\" : \"\\uE70D\";\n }\n \n // Default to down arrow if value is not a boolean\n return \"\\uE70D\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // This converter doesn't support converting back\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/LinkedRegistrySettings.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents a collection of registry settings that should be treated as a single logical setting.\n /// This allows multiple registry keys to be controlled by a single toggle in the UI.\n /// \n public class LinkedRegistrySettings\n {\n /// \n /// Gets or sets the list of registry settings that are linked together.\n /// \n public List Settings { get; set; } = new List();\n\n /// \n /// Gets or sets the category for all linked settings.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description for all linked settings.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the logic to use when determining the status of linked settings.\n /// Default is Any, which means if any setting is applied, the entire setting is considered applied.\n /// \n public LinkedSettingsLogic Logic { get; set; } = LinkedSettingsLogic.Any;\n\n /// \n /// Creates a new instance of the LinkedRegistrySettings class.\n /// \n public LinkedRegistrySettings()\n {\n }\n\n /// \n /// Creates a new instance of the LinkedRegistrySettings class with a single registry setting.\n /// \n /// The registry setting to include.\n public LinkedRegistrySettings(RegistrySetting registrySetting)\n {\n if (registrySetting != null)\n {\n Settings.Add(registrySetting);\n Category = registrySetting.Category;\n Description = registrySetting.Description;\n }\n }\n\n /// \n /// Creates a new instance of the LinkedRegistrySettings class with a specific logic type.\n /// \n /// The logic to use when determining the status of linked settings.\n public LinkedRegistrySettings(LinkedSettingsLogic logic)\n {\n Logic = logic;\n }\n\n /// \n /// Adds a registry setting to the linked collection.\n /// \n /// The registry setting to add.\n public void AddSetting(RegistrySetting registrySetting)\n {\n if (registrySetting != null)\n {\n Settings.Add(registrySetting);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/INavigationService.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for navigating between views in the application.\n /// \n public interface INavigationService\n {\n /// \n /// Navigates to a view.\n /// \n /// The name of the view to navigate to.\n /// True if navigation was successful; otherwise, false.\n bool NavigateTo(string viewName);\n\n /// \n /// Navigates to a view with parameters.\n /// \n /// The name of the view to navigate to.\n /// The navigation parameter.\n /// True if navigation was successful; otherwise, false.\n bool NavigateTo(string viewName, object parameter);\n\n /// \n /// Navigates back to the previous view.\n /// \n /// True if navigation was successful; otherwise, false.\n bool NavigateBack();\n\n /// \n /// Gets the current view name.\n /// \n string CurrentView { get; }\n\n /// \n /// Event raised when navigation occurs.\n /// \n event EventHandler? Navigated;\n\n /// \n /// Event raised before navigation occurs.\n /// \n event EventHandler? Navigating;\n\n /// \n /// Event raised when navigation fails.\n /// \n event EventHandler? NavigationFailed;\n }\n\n /// \n /// Event arguments for navigation events.\n /// \n public class NavigationEventArgs : EventArgs\n {\n /// \n /// Gets the source view name.\n /// \n public string SourceView { get; }\n\n /// \n /// Gets the target view name.\n /// \n public string TargetView { get; }\n\n /// \n /// Gets the navigation route (same as TargetView).\n /// \n public string Route => TargetView;\n\n /// \n /// Gets the view model type associated with the navigation.\n /// \n public Type? ViewModelType => Parameter?.GetType();\n\n /// \n /// Gets the navigation parameter.\n /// \n public object? Parameter { get; }\n\n /// \n /// Gets a value indicating whether the navigation can be canceled.\n /// \n public bool CanCancel { get; }\n\n /// \n /// Gets or sets a value indicating whether the navigation should be canceled.\n /// \n public bool Cancel { get; set; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The source view name.\n /// The target view name.\n /// The navigation parameter.\n /// Whether the navigation can be canceled.\n public NavigationEventArgs(\n string sourceView,\n string targetView,\n object? parameter = null,\n bool canCancel = false\n )\n {\n SourceView = sourceView;\n TargetView = targetView;\n Parameter = parameter;\n CanCancel = canCancel;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IPackageManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Provides package management functionality across the application.\n /// \n public interface IPackageManager\n {\n /// \n /// Gets the logging service.\n /// \n ILogService LogService { get; }\n\n /// \n /// Gets the app discovery service.\n /// \n IAppService AppDiscoveryService { get; }\n\n /// \n /// Gets the app removal service.\n /// \n IInstallationService AppRemovalService { get; }\n\n /// \n /// Gets the special app handler service.\n /// \n ISpecialAppHandlerService SpecialAppHandlerService { get; }\n\n /// \n /// Gets the script generation service.\n /// \n IScriptGenerationService ScriptGenerationService { get; }\n\n /// \n /// Gets the system services.\n /// \n ISystemServices SystemServices { get; }\n\n /// \n /// Gets the notification service.\n /// \n INotificationService NotificationService { get; }\n\n /// \n /// Gets all installable applications.\n /// \n /// A collection of installable applications.\n Task> GetInstallableAppsAsync();\n\n /// \n /// Gets all standard (built-in) applications.\n /// \n /// A collection of standard applications.\n Task> GetStandardAppsAsync();\n\n /// \n /// Gets all available Windows capabilities.\n /// \n /// A collection of Windows capabilities.\n Task> GetCapabilitiesAsync();\n\n /// \n /// Gets all available Windows optional features.\n /// \n /// A collection of Windows optional features.\n Task> GetOptionalFeaturesAsync();\n\n /// \n /// Removes a specific application.\n /// \n /// The package name to remove.\n /// Whether the package is a capability.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task RemoveAppAsync(string packageName, bool isCapability = false);\n\n /// \n /// Checks if an application is installed.\n /// \n /// The package name to check.\n /// The cancellation token.\n /// True if the application is installed; otherwise, false.\n Task IsAppInstalledAsync(string packageName, CancellationToken cancellationToken = default);\n\n /// \n /// Removes Microsoft Edge.\n /// \n /// True if Edge was removed successfully; otherwise, false.\n Task RemoveEdgeAsync();\n\n /// \n /// Removes OneDrive.\n /// \n /// True if OneDrive was removed successfully; otherwise, false.\n Task RemoveOneDriveAsync();\n\n /// \n /// Removes OneNote.\n /// \n /// True if OneNote was removed successfully; otherwise, false.\n Task RemoveOneNoteAsync();\n\n /// \n /// Removes a special application.\n /// \n /// The type of special app handler to use.\n /// True if the application was removed successfully; otherwise, false.\n Task RemoveSpecialAppAsync(string appHandlerType);\n\n /// \n /// Removes multiple applications in a batch operation.\n /// \n /// A list of app information to remove.\n /// A list of results indicating success or failure for each application.\n Task> RemoveAppsInBatchAsync(\n List<(string PackageName, bool IsCapability, string? SpecialHandlerType)> apps);\n\n /// \n /// Registers a removal task.\n /// \n /// The removal script to register.\n /// A task representing the asynchronous operation.\n Task RegisterRemovalTaskAsync(RemovalScript script);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/EnumToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts an enum value to a Visibility value based on whether it matches the parameter.\n /// \n public class EnumToVisibilityConverter : IValueConverter\n {\n /// \n /// Converts an enum value to a Visibility value.\n /// \n /// The enum value to convert.\n /// The type of the binding target property.\n /// The parameter to compare against.\n /// The culture to use in the converter.\n /// \n /// Visibility.Visible if the value matches the parameter; otherwise, Visibility.Collapsed.\n /// \n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null || parameter == null)\n {\n return Visibility.Collapsed;\n }\n\n // Check if the value is equal to the parameter\n bool isEqual = value.Equals(parameter);\n return isEqual ? Visibility.Visible : Visibility.Collapsed;\n }\n\n /// \n /// Converts a Visibility value back to an enum value.\n /// \n /// The Visibility value to convert back.\n /// The type of the binding source property.\n /// The parameter to use in the converter.\n /// The culture to use in the converter.\n /// \n /// The parameter if the value is Visibility.Visible; otherwise, null.\n /// \n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is Visibility visibility && visibility == Visibility.Visible)\n {\n return parameter;\n }\n\n return Binding.DoNothing;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Models/WindowsAppSettingItem.cs", "using System.Collections.Generic;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Models\n{\n /// \n /// Adapter class that wraps a WindowsApp and implements ISettingItem.\n /// \n public class WindowsAppSettingItem : ISettingItem\n {\n private readonly WindowsApp _windowsApp;\n \n public WindowsAppSettingItem(WindowsApp windowsApp)\n {\n _windowsApp = windowsApp;\n \n // Initialize properties required by ISettingItem\n Id = windowsApp.PackageId;\n Name = windowsApp.DisplayName;\n Description = windowsApp.Description;\n IsSelected = windowsApp.IsSelected;\n GroupName = windowsApp.Category;\n IsVisible = true;\n ControlType = ControlType.BinaryToggle;\n Dependencies = new List();\n \n // Create a command that does nothing (placeholder)\n ApplySettingCommand = new RelayCommand(() => { });\n }\n \n // ISettingItem implementation\n public string Id { get; set; }\n public string Name { get; set; }\n public string Description { get; set; }\n public bool IsSelected { get; set; }\n public string GroupName { get; set; }\n public bool IsVisible { get; set; }\n public ControlType ControlType { get; set; }\n public List Dependencies { get; set; }\n public bool IsUpdatingFromCode { get; set; }\n public ICommand ApplySettingCommand { get; }\n \n // Method to convert back to WindowsApp\n public WindowsApp ToWindowsApp()\n {\n // Update the original WindowsApp with any changes\n _windowsApp.IsSelected = IsSelected;\n return _windowsApp;\n }\n \n // Static method to convert a collection of WindowsApps to WindowsAppSettingItems\n public static IEnumerable FromWindowsApps(IEnumerable windowsApps)\n {\n foreach (var app in windowsApps)\n {\n yield return new WindowsAppSettingItem(app);\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/AppInfo.cs", "// This contains the model for standard application information\n\nusing System;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models\n{\n /// \n /// Defines the type of application.\n /// \n public enum AppType\n {\n /// \n /// Standard application.\n /// \n StandardApp,\n\n /// \n /// Windows capability.\n /// \n Capability,\n\n /// \n /// Windows optional feature.\n /// \n OptionalFeature,\n }\n\n /// \n /// Represents information about a standard application.\n /// \n public class AppInfo : IInstallableItem\n {\n string IInstallableItem.PackageId => PackageID;\n string IInstallableItem.DisplayName => Name;\n InstallItemType IInstallableItem.ItemType =>\n Type switch\n {\n AppType.Capability => InstallItemType.Capability,\n AppType.OptionalFeature => InstallItemType.Feature,\n _ => InstallItemType.WindowsApp,\n };\n bool IInstallableItem.RequiresRestart => false;\n\n /// \n /// Gets or sets the name of the application.\n /// \n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description of the application.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the package name of the application.\n /// \n public string PackageName { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the package ID of the application.\n /// \n public string PackageID { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the category of the application.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether the application is installed.\n /// \n public bool IsInstalled { get; set; }\n\n /// \n /// Gets or sets the type of application.\n /// \n public AppType Type { get; set; } = AppType.StandardApp;\n\n /// \n /// Gets or sets a value indicating whether the application requires a custom installation process.\n /// \n public bool IsCustomInstall { get; set; }\n\n /// \n /// Gets or sets the sub-packages associated with this application.\n /// \n public string[]? SubPackages { get; set; }\n\n /// \n /// Gets or sets the registry settings associated with this application.\n /// \n public AppRegistrySetting[]? RegistrySettings { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the application requires special handling.\n /// \n public bool RequiresSpecialHandling { get; set; }\n\n /// \n /// Gets or sets the special handler type for this application.\n /// \n public string? SpecialHandlerType { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the application is protected by the system.\n /// \n public bool IsSystemProtected { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the application can be reinstalled after removal.\n /// \n public bool CanBeReinstalled { get; set; } = true;\n\n /// \n /// Gets or sets the version of the application.\n /// \n public string Version { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the last operation error message, if any.\n /// \n public string? LastOperationError { get; set; }\n }\n\n /// \n /// Represents a registry setting for an application.\n /// \n public class AppRegistrySetting\n {\n /// \n /// Gets or sets the registry path.\n /// \n public string Path { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the registry value name.\n /// \n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the registry value.\n /// \n public object? Value { get; set; }\n\n /// \n /// Gets or sets the registry value kind.\n /// \n public Microsoft.Win32.RegistryValueKind ValueKind { get; set; }\n\n /// \n /// Gets or sets the description of the registry setting.\n /// \n public string? Description { get; set; }\n }\n\n /// \n /// Represents a package removal script.\n /// \n public class PackageRemovalScript\n {\n /// \n /// Gets or sets the name of the script.\n /// \n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the content of the script.\n /// \n public string Content { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the target scheduled task name.\n /// \n public string? TargetScheduledTaskName { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the script should run on startup.\n /// \n public bool RunOnStartup { get; set; }\n }\n\n /// \n /// Defines the types of special app handlers.\n /// \n public enum AppHandlerType\n {\n /// \n /// No special handling required.\n /// \n None,\n\n /// \n /// Microsoft Edge browser.\n /// \n Edge,\n\n /// \n /// Microsoft OneDrive.\n /// \n OneDrive,\n\n /// \n /// Microsoft Copilot.\n /// \n Copilot,\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryExtensions.cs", "using System;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Extension methods for registry operations.\n /// \n public static class RegistryExtensions\n {\n /// \n /// Converts a RegistryHive enum to its string representation (HKCU, HKLM, etc.)\n /// \n /// The registry hive.\n /// The string representation of the registry hive.\n public static string GetRegistryHiveString(this RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => throw new ArgumentException($\"Unsupported registry hive: {hive}\")\n };\n }\n\n /// \n /// Gets the full registry path by combining the hive and subkey.\n /// \n /// The registry hive.\n /// The registry subkey.\n /// The full registry path.\n public static string GetFullRegistryPath(this RegistryHive hive, string subKey)\n {\n return $\"{hive.GetRegistryHiveString()}\\\\{subKey}\";\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Models/ExternalAppSettingItem.cs", "using System.Collections.Generic;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Models\n{\n /// \n /// Adapter class that wraps an ExternalApp and implements ISettingItem.\n /// \n public class ExternalAppSettingItem : ISettingItem\n {\n private readonly ExternalApp _externalApp;\n \n public ExternalAppSettingItem(ExternalApp externalApp)\n {\n _externalApp = externalApp;\n \n // Initialize properties required by ISettingItem\n Id = externalApp.PackageName;\n Name = externalApp.Name;\n Description = externalApp.Description;\n IsSelected = externalApp.IsSelected;\n GroupName = externalApp.Category;\n IsVisible = true;\n ControlType = ControlType.BinaryToggle;\n Dependencies = new List();\n \n // Create a command that does nothing (placeholder)\n ApplySettingCommand = new RelayCommand(() => { });\n }\n \n // ISettingItem implementation\n public string Id { get; set; }\n public string Name { get; set; }\n public string Description { get; set; }\n public bool IsSelected { get; set; }\n public string GroupName { get; set; }\n public bool IsVisible { get; set; }\n public ControlType ControlType { get; set; }\n public List Dependencies { get; set; }\n public bool IsUpdatingFromCode { get; set; }\n public ICommand ApplySettingCommand { get; }\n \n // Method to convert back to ExternalApp\n public ExternalApp ToExternalApp()\n {\n // Update the original ExternalApp with any changes\n _externalApp.IsSelected = IsSelected;\n return _externalApp;\n }\n \n // Static method to convert a collection of ExternalApps to ExternalAppSettingItems\n public static IEnumerable FromExternalApps(IEnumerable externalApps)\n {\n foreach (var app in externalApps)\n {\n yield return new ExternalAppSettingItem(app);\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Models/ThirdPartyApp.cs", "using CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Models\n{\n /// \n /// Represents a third-party application that can be installed through package managers like winget.\n /// These are applications not built into Windows but available for installation.\n /// \n public partial class ThirdPartyApp : ObservableObject\n {\n [ObservableProperty]\n private string _name = string.Empty;\n\n [ObservableProperty]\n private string _description = string.Empty;\n\n [ObservableProperty]\n private string _packageName = string.Empty;\n \n [ObservableProperty]\n private string _category = string.Empty;\n\n [ObservableProperty]\n private bool _isInstalled;\n\n [ObservableProperty]\n private bool _isCustomInstall;\n\n /// \n /// Determines if the app has a description that should be displayed.\n /// \n public bool HasDescription => !string.IsNullOrEmpty(Description);\n\n public static ThirdPartyApp FromAppInfo(AppInfo appInfo)\n {\n return new ThirdPartyApp\n {\n Name = appInfo.Name,\n Description = appInfo.Description,\n PackageName = appInfo.PackageName,\n Category = appInfo.Category,\n IsInstalled = appInfo.IsInstalled,\n IsCustomInstall = appInfo.IsCustomInstall\n };\n }\n\n /// \n /// Converts this ThirdPartyApp to an AppInfo object.\n /// \n /// An AppInfo object representing this ThirdPartyApp.\n public AppInfo ToAppInfo()\n {\n return new AppInfo\n {\n Name = Name,\n Description = Description,\n PackageName = PackageName,\n Category = Category,\n IsInstalled = IsInstalled,\n IsCustomInstall = IsCustomInstall\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/IconNameToSymbolConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing Winhance.WPF.Features.Common.Resources;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts an icon name to a Material Symbols Unicode character.\n /// \n public class IconNameToSymbolConverter : IValueConverter\n {\n public static IconNameToSymbolConverter Instance { get; } = new IconNameToSymbolConverter();\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is string iconName)\n {\n return MaterialSymbols.GetIcon(iconName);\n }\n \n return \"?\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/ScriptStatusToTextConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean script status to a descriptive text.\n /// \n public class ScriptStatusToTextConverter : IValueConverter\n {\n /// \n /// Converts a boolean value to a descriptive text.\n /// \n /// The boolean value indicating if scripts are active.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// A descriptive text based on the script status.\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isActive)\n {\n return isActive \n ? \"Winhance Removing Apps\" \n : \"No Active Removals\";\n }\n \n return \"Unknown Status\";\n }\n \n /// \n /// Converts a descriptive text back to a boolean value.\n /// \n /// The text to convert back.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// A boolean value based on the text.\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/CapabilityCatalog.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a catalog of Windows capabilities that can be enabled or disabled.\n/// \npublic class CapabilityCatalog\n{\n /// \n /// Gets or sets the collection of Windows capabilities.\n /// \n public IReadOnlyList Capabilities { get; init; } = new List();\n\n /// \n /// Creates a default capability catalog with predefined Windows capabilities.\n /// \n /// A new CapabilityCatalog instance with default capabilities.\n public static CapabilityCatalog CreateDefault()\n {\n return new CapabilityCatalog { Capabilities = CreateDefaultCapabilities() };\n }\n\n private static IReadOnlyList CreateDefaultCapabilities()\n {\n return new List\n {\n // Browser capabilities\n new CapabilityInfo\n {\n Name = \"Internet Explorer\",\n Description = \"Legacy web browser\",\n PackageName = \"Browser.InternetExplorer\",\n Category = \"Browser\",\n CanBeReenabled = false,\n },\n // Development capabilities\n new CapabilityInfo\n {\n Name = \"PowerShell ISE\",\n Description = \"PowerShell Integrated Scripting Environment\",\n PackageName = \"Microsoft.Windows.PowerShell.ISE\",\n Category = \"Development\",\n CanBeReenabled = true,\n },\n // System capabilities\n new CapabilityInfo\n {\n Name = \"Quick Assist\",\n Description = \"Remote assistance app\",\n PackageName = \"App.Support.QuickAssist\",\n Category = \"System\",\n CanBeReenabled = false,\n },\n // Utilities capabilities\n new CapabilityInfo\n {\n Name = \"Steps Recorder\",\n Description = \"Screen recording tool\",\n PackageName = \"App.StepsRecorder\",\n Category = \"Utilities\",\n CanBeReenabled = true,\n },\n // Media capabilities\n new CapabilityInfo\n {\n Name = \"Windows Media Player\",\n Description = \"Classic media player\",\n PackageName = \"Media.WindowsMediaPlayer\",\n Category = \"Media\",\n CanBeReenabled = true,\n },\n // Productivity capabilities\n new CapabilityInfo\n {\n Name = \"WordPad\",\n Description = \"Rich text editor\",\n PackageName = \"Microsoft.Windows.WordPad\",\n Category = \"Productivity\",\n CanBeReenabled = false,\n },\n new CapabilityInfo\n {\n Name = \"Paint (Legacy)\",\n Description = \"Classic Paint app\",\n PackageName = \"Microsoft.Windows.MSPaint\",\n Category = \"Graphics\",\n CanBeReenabled = false,\n },\n // OpenSSH capabilities\n new CapabilityInfo\n {\n Name = \"OpenSSH Client\",\n Description = \"Secure Shell client for remote connections\",\n PackageName = \"OpenSSH.Client\",\n Category = \"Networking\",\n IsSystemProtected = false,\n CanBeReenabled = true,\n },\n new CapabilityInfo\n {\n Name = \"OpenSSH Server\",\n Description = \"Secure Shell server for remote connections\",\n PackageName = \"OpenSSH.Server\",\n Category = \"Networking\",\n IsSystemProtected = false,\n CanBeReenabled = true,\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/FeatureCatalog.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a catalog of Windows optional features that can be enabled or disabled.\n/// \npublic class FeatureCatalog\n{\n /// \n /// Gets or sets the collection of Windows optional features.\n /// \n public IReadOnlyList Features { get; init; } = new List();\n\n /// \n /// Creates a default feature catalog with predefined Windows optional features.\n /// \n /// A new FeatureCatalog instance with default features.\n public static FeatureCatalog CreateDefault()\n {\n return new FeatureCatalog { Features = CreateDefaultFeatures() };\n }\n\n private static IReadOnlyList CreateDefaultFeatures()\n {\n return new List\n {\n // Windows Subsystems\n new FeatureInfo\n {\n Name = \"Subsystem for Linux\",\n Description = \"Allows running Linux binary executables natively on Windows\",\n PackageName = \"Microsoft-Windows-Subsystem-Linux\",\n Category = \"Development\",\n RequiresReboot = true,\n CanBeReenabled = true,\n },\n // Virtualization\n new FeatureInfo\n {\n Name = \"Windows Hypervisor Platform\",\n Description = \"Core virtualization platform without Hyper-V management tools\",\n PackageName = \"Microsoft-Hyper-V-Hypervisor\",\n Category = \"Virtualization\",\n RequiresReboot = true,\n CanBeReenabled = true,\n },\n // Hyper-V\n new FeatureInfo\n {\n Name = \"Hyper-V\",\n Description = \"Virtualization platform for running multiple operating systems\",\n PackageName = \"Microsoft-Hyper-V-All\",\n Category = \"Virtualization\",\n RequiresReboot = true,\n CanBeReenabled = true,\n },\n new FeatureInfo\n {\n Name = \"Hyper-V Management Tools\",\n Description = \"Tools for managing Hyper-V virtual machines\",\n PackageName = \"Microsoft-Hyper-V-Tools-All\",\n Category = \"Virtualization\",\n RequiresReboot = false,\n CanBeReenabled = true,\n },\n // .NET Framework\n new FeatureInfo\n {\n Name = \".NET Framework 3.5\",\n Description = \"Legacy .NET Framework for older applications\",\n PackageName = \"NetFx3\",\n Category = \"Development\",\n RequiresReboot = true,\n CanBeReenabled = true,\n },\n // Windows Features\n new FeatureInfo\n {\n Name = \"Windows Sandbox\",\n Description = \"Isolated desktop environment for running applications\",\n PackageName = \"Containers-DisposableClientVM\",\n Category = \"Security\",\n RequiresReboot = true,\n CanBeReenabled = true,\n },\n new FeatureInfo\n {\n Name = \"Recall\",\n Description = \"Windows 11 feature that records user activity\",\n PackageName = \"Recall\",\n Category = \"System\",\n RequiresReboot = false,\n CanBeReenabled = true,\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/OperationResult.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents the result of an operation, including success status, error details, and a result value.\n /// \n /// The type of the result value.\n public class OperationResult\n {\n /// \n /// Gets or sets a value indicating whether the operation was successful.\n /// \n public bool Success { get; set; }\n\n /// \n /// Gets or sets the result value of the operation.\n /// \n public T? Result { get; set; }\n\n /// \n /// Gets or sets the error message if the operation failed.\n /// \n public string? ErrorMessage { get; set; }\n\n /// \n /// Gets or sets the exception that occurred during the operation, if any.\n /// \n public Exception? Exception { get; set; }\n\n /// \n /// Gets or sets additional error details.\n /// \n public Dictionary? ErrorDetails { get; set; }\n\n /// \n /// Creates a successful operation result with the specified result value.\n /// \n /// The result value.\n /// A successful operation result.\n public static OperationResult CreateSuccess(T result)\n {\n return new OperationResult\n {\n Success = true,\n Result = result\n };\n }\n\n /// \n /// Creates a failed operation result with the specified error message.\n /// \n /// The error message.\n /// A failed operation result.\n public static OperationResult CreateFailure(string errorMessage)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = errorMessage\n };\n }\n\n /// \n /// Creates a failed operation result with the specified exception.\n /// \n /// The exception that occurred.\n /// A failed operation result.\n public static OperationResult CreateFailure(Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = exception.Message,\n Exception = exception\n };\n }\n\n /// \n /// Creates a failed operation result with the specified error message and exception.\n /// \n /// The error message.\n /// The exception that occurred.\n /// A failed operation result.\n public static OperationResult CreateFailure(string errorMessage, Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = errorMessage,\n Exception = exception\n };\n }\n\n /// \n /// Checks if the operation was successful.\n /// \n /// True if the operation was successful; otherwise, false.\n public bool Succeeded()\n {\n return Success;\n }\n\n /// \n /// Creates a successful operation result with the specified message.\n /// \n /// The message.\n /// A successful operation result.\n public static OperationResult Succeeded(string message)\n {\n return new OperationResult\n {\n Success = true,\n ErrorMessage = message\n };\n }\n\n /// \n /// Creates a successful operation result with the specified result value.\n /// \n /// The result value.\n /// A successful operation result.\n public static OperationResult Succeeded(T result)\n {\n return new OperationResult\n {\n Success = true,\n Result = result\n };\n }\n\n /// \n /// Checks if the operation failed.\n /// \n /// True if the operation failed; otherwise, false.\n public bool Failed()\n {\n return !Success;\n }\n\n /// \n /// Creates a failed operation result with the specified message.\n /// \n /// The message.\n /// A failed operation result.\n public static OperationResult Failed(string message)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = message\n };\n }\n\n /// \n /// Creates a failed operation result with the specified message and exception.\n /// \n /// The message.\n /// The exception.\n /// A failed operation result.\n public static OperationResult Failed(string message, Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = message,\n Exception = exception\n };\n }\n\n /// \n /// Creates a failed operation result with the specified message and result value.\n /// \n /// The error message.\n /// The result value to set even though the operation failed.\n /// A failed operation result with the specified result value.\n public static OperationResult Failed(string message, T result)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = message,\n Result = result\n };\n }\n }\n\n /// \n /// Represents the result of an operation, including success status and error details.\n /// \n public class OperationResult\n {\n /// \n /// Gets or sets a value indicating whether the operation was successful.\n /// \n public bool Success { get; set; }\n\n /// \n /// Gets or sets the error message if the operation failed.\n /// \n public string? ErrorMessage { get; set; }\n\n /// \n /// Gets or sets the exception that occurred during the operation, if any.\n /// \n public Exception? Exception { get; set; }\n\n /// \n /// Gets or sets additional error details.\n /// \n public Dictionary? ErrorDetails { get; set; }\n\n /// \n /// Creates a successful operation result.\n /// \n /// A successful operation result.\n public static OperationResult CreateSuccess()\n {\n return new OperationResult\n {\n Success = true\n };\n }\n\n /// \n /// Creates a failed operation result with the specified error message.\n /// \n /// The error message.\n /// A failed operation result.\n public static OperationResult CreateFailure(string errorMessage)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = errorMessage\n };\n }\n\n /// \n /// Creates a failed operation result with the specified exception.\n /// \n /// The exception that occurred.\n /// A failed operation result.\n public static OperationResult CreateFailure(Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = exception.Message,\n Exception = exception\n };\n }\n\n /// \n /// Creates a failed operation result with the specified error message and exception.\n /// \n /// The error message.\n /// The exception that occurred.\n /// A failed operation result.\n public static OperationResult CreateFailure(string errorMessage, Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = errorMessage,\n Exception = exception\n };\n }\n\n /// \n /// Checks if the operation was successful.\n /// \n /// True if the operation was successful; otherwise, false.\n public bool Succeeded()\n {\n return Success;\n }\n\n /// \n /// Creates a successful operation result with the specified message.\n /// \n /// The message.\n /// A successful operation result.\n public static OperationResult Succeeded(string message)\n {\n return new OperationResult\n {\n Success = true,\n ErrorMessage = message\n };\n }\n\n /// \n /// Checks if the operation failed.\n /// \n /// True if the operation failed; otherwise, false.\n public bool Failed()\n {\n return !Success;\n }\n\n /// \n /// Creates a failed operation result with the specified message.\n /// \n /// The message.\n /// A failed operation result.\n public static OperationResult Failed(string message)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = message\n };\n }\n\n /// \n /// Creates a failed operation result with the specified message and exception.\n /// \n /// The message.\n /// The exception.\n /// A failed operation result.\n public static OperationResult Failed(string message, Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = message,\n Exception = exception\n };\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Interfaces/IViewModelLocator.cs", "using System.Windows;\n\nnamespace Winhance.WPF.Features.Common.Interfaces\n{\n /// \n /// Interface for locating view models in the application.\n /// \n public interface IViewModelLocator\n {\n /// \n /// Finds a view model of the specified type in the application.\n /// \n /// The type of view model to find.\n /// The view model if found, otherwise null.\n T? FindViewModel() where T : class;\n\n /// \n /// Finds a view model of the specified type in the specified window.\n /// \n /// The type of view model to find.\n /// The window to search in.\n /// The view model if found, otherwise null.\n T? FindViewModelInWindow(Window window) where T : class;\n\n /// \n /// Finds a view model of the specified type in the visual tree starting from the specified element.\n /// \n /// The type of view model to find.\n /// The starting element.\n /// The view model if found, otherwise null.\n T? FindViewModelInVisualTree(DependencyObject element) where T : class;\n\n /// \n /// Finds a view model by its name.\n /// \n /// The name of the view model to find.\n /// The view model if found, otherwise null.\n object? FindViewModelByName(string viewModelName);\n\n /// \n /// Gets a property from a view model.\n /// \n /// The type of the property to get.\n /// The view model to get the property from.\n /// The name of the property to get.\n /// The property value if found, otherwise null.\n T? GetPropertyFromViewModel(object viewModel, string propertyName) where T : class;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/VerificationResult.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents the result of a verification operation.\n /// \n public class VerificationResult\n {\n /// \n /// Gets or sets a value indicating whether the verification was successful.\n /// \n public bool IsVerified { get; set; }\n\n /// \n /// Gets or sets the version that was verified, if applicable.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets an optional message providing additional information about the verification.\n /// \n public string Message { get; set; }\n\n /// \n /// Gets or sets the name of the verification method that was used.\n /// \n public string MethodUsed { get; set; }\n\n /// \n /// Gets or sets additional information about the verification result.\n /// This can be any object containing relevant details.\n /// \n public object AdditionalInfo { get; set; }\n\n /// \n /// Creates a successful verification result.\n /// \n /// The version that was verified.\n /// The name of the verification method that was used.\n /// Additional information about the verification result.\n /// A successful verification result.\n public static VerificationResult Success(string version = null, string methodUsed = null, object additionalInfo = null)\n {\n return new VerificationResult\n {\n IsVerified = true,\n Version = version,\n MethodUsed = methodUsed,\n AdditionalInfo = additionalInfo\n };\n }\n\n /// \n /// Creates a failed verification result.\n /// \n /// An optional message explaining why the verification failed.\n /// The name of the verification method that was used.\n /// Additional information about the verification result.\n /// A failed verification result.\n public static VerificationResult Failure(string message = null, string methodUsed = null, object additionalInfo = null)\n {\n return new VerificationResult\n {\n IsVerified = false,\n Message = message,\n MethodUsed = methodUsed,\n AdditionalInfo = additionalInfo\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToGridSpanConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Converters\n{\n /// \n /// Converts a boolean value to an integer grid span - true returns 4 (full width), false returns 1\n /// \n public class BooleanToGridSpanConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return boolValue ? 4 : 1; // Return 4 for true (header spans full width), 1 for false\n }\n return 1;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Exceptions/InstallationException.cs", "using System;\nusing Winhance.Core.Features.SoftwareApps.Enums;\n\nnamespace Winhance.Core.Features.SoftwareApps.Exceptions\n{\n /// \n /// Exception thrown when there is an error with installation operations.\n /// \n public class InstallationException : Exception\n {\n /// \n /// Gets the type of installation error.\n /// \n public InstallationErrorType ErrorType { get; }\n \n /// \n /// Initializes a new instance of the class.\n /// \n public InstallationException() : base()\n {\n ErrorType = InstallationErrorType.UnknownError;\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message.\n /// \n /// The message that describes the error.\n public InstallationException(string message) : base(message)\n {\n ErrorType = InstallationErrorType.UnknownError;\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message\n /// and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception.\n public InstallationException(string message, Exception innerException) : base(message, innerException)\n {\n ErrorType = InstallationErrorType.UnknownError;\n }\n \n /// \n /// Initializes a new instance of the class with a specified error message,\n /// error type, and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception.\n /// The type of installation error.\n public InstallationException(string message, Exception innerException, InstallationErrorType errorType)\n : base(message, innerException)\n {\n ErrorType = errorType;\n }\n\n /// \n /// Initializes a new instance of the class with a specified item name, error message,\n /// a flag indicating whether the error is critical, and a reference to the inner exception that is the cause of this exception.\n /// \n /// The name of the item that failed to be installed.\n /// The error message.\n /// A flag indicating whether the error is critical.\n /// The exception that is the cause of the current exception.\n public InstallationException(string itemName, string errorMessage, bool isCritical, Exception innerException)\n : base($\"Failed to install {itemName}: {errorMessage}\", innerException)\n {\n ItemName = itemName;\n IsCritical = isCritical;\n ErrorType = InstallationErrorType.UnknownError;\n }\n \n /// \n /// Initializes a new instance of the class with a specified item name, error message,\n /// a flag indicating whether the error is critical, the error type, and a reference to the inner exception that is the cause of this exception.\n /// \n /// The name of the item that failed to be installed.\n /// The error message.\n /// A flag indicating whether the error is critical.\n /// The type of installation error.\n /// The exception that is the cause of the current exception.\n public InstallationException(string itemName, string errorMessage, bool isCritical, InstallationErrorType errorType, Exception innerException)\n : base($\"Failed to install {itemName}: {errorMessage}\", innerException)\n {\n ItemName = itemName;\n IsCritical = isCritical;\n ErrorType = errorType;\n }\n\n /// \n /// Gets the name of the item that failed to be installed.\n /// \n public string? ItemName { get; }\n\n /// \n /// Gets a value indicating whether the error is critical.\n /// \n public bool IsCritical { get; }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IDialogService.cs", "using System.Threading.Tasks;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides functionality for displaying dialog boxes to the user.\n /// \n public interface IDialogService\n {\n /// \n /// Displays a message to the user.\n /// \n /// The message to display.\n /// The title of the dialog box.\n void ShowMessage(string message, string title = \"\");\n\n /// \n /// Displays a confirmation dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// The text for the OK button.\n /// The text for the Cancel button.\n /// True if the user confirmed; otherwise, false.\n Task ShowConfirmationAsync(string message, string title = \"\", string okButtonText = \"OK\", string cancelButtonText = \"Cancel\");\n\n /// \n /// Displays an information dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// The text for the button.\n /// A task representing the asynchronous operation.\n Task ShowInformationAsync(string message, string title = \"Information\", string buttonText = \"OK\");\n\n /// \n /// Displays a warning dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// The text for the button.\n /// A task representing the asynchronous operation.\n Task ShowWarningAsync(string message, string title = \"Warning\", string buttonText = \"OK\");\n\n /// \n /// Displays an error dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// The text for the button.\n /// A task representing the asynchronous operation.\n Task ShowErrorAsync(string message, string title = \"Error\", string buttonText = \"OK\");\n\n /// \n /// Displays an input dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// The default value for the input.\n /// The value entered by the user, or null if the user canceled.\n Task ShowInputAsync(string message, string title = \"\", string defaultValue = \"\");\n\n /// \n /// Displays a Yes/No/Cancel dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// True if the user clicked Yes, false if the user clicked No, null if the user clicked Cancel.\n Task ShowYesNoCancelAsync(string message, string title = \"\");\n\n /// \n /// Displays a unified configuration save dialog.\n /// \n /// The title of the dialog box.\n /// The description of the dialog.\n /// A dictionary of section names, their availability, and item counts.\n /// A dictionary of section names and their final selection state, or null if the user canceled.\n Task> ShowUnifiedConfigurationSaveDialogAsync(string title, string description, Dictionary sections);\n\n /// \n /// Displays a unified configuration import dialog.\n /// \n /// The title of the dialog box.\n /// The description of the dialog.\n /// A dictionary of section names, their availability, and item counts.\n /// A dictionary of section names and their final selection state, or null if the user canceled.\n Task> ShowUnifiedConfigurationImportDialogAsync(string title, string description, Dictionary sections);\n\n /// \n /// Displays a donation dialog.\n /// \n /// The title of the dialog box.\n /// The support message to display.\n /// The footer text.\n /// A task representing the asynchronous operation, with a tuple containing the dialog result (whether the user clicked Yes or No) and whether the \"Don't show again\" checkbox was checked.\n Task<(bool? Result, bool DontShowAgain)> ShowDonationDialogAsync(string title, string supportMessage, string footerText);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/InverseCountToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts an integer count to a Visibility value, with the count inverted.\n /// Returns Visible if the count is 0, otherwise returns Collapsed.\n /// \n public class InverseCountToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is int count)\n {\n return count == 0 ? Visibility.Visible : Visibility.Collapsed;\n }\n \n return Visibility.Visible;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/RemoveActionToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class RemoveActionToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // If the action type is Remove, return Visible, otherwise return Collapsed\n if (value is RegistryActionType actionType)\n {\n return actionType == RegistryActionType.Remove ? Visibility.Visible : Visibility.Collapsed;\n }\n \n return Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Exceptions/InstallationException.cs", "using System;\n\nnamespace Winhance.Core.Models.Exceptions\n{\n public class InstallationException : Exception \n {\n public bool IsRecoverable { get; }\n public string ItemName { get; }\n \n public InstallationException(string itemName, string message, \n bool isRecoverable = false, Exception? inner = null)\n : base(message, inner)\n {\n ItemName = itemName;\n IsRecoverable = isRecoverable;\n }\n }\n\n public class InstallationCancelledException : InstallationException\n {\n public InstallationCancelledException(string itemName)\n : base(itemName, $\"Installation cancelled for {itemName}\", true) { }\n }\n\n public class DependencyInstallationException : InstallationException\n {\n public string DependencyName { get; }\n\n public DependencyInstallationException(string itemName, string dependencyName)\n : base(itemName, $\"Dependency {dependencyName} failed to install for {itemName}\", true)\n {\n DependencyName = dependencyName;\n }\n }\n\n public class ItemOperationException : InstallationException\n {\n public ItemOperationException(string itemName, string operation, string message, \n bool isRecoverable = false, Exception? inner = null)\n : base(itemName, $\"{operation} failed for {itemName}: {message}\", isRecoverable, inner) { }\n }\n\n public class RemovalException : ItemOperationException\n {\n public RemovalException(string itemName, string message, \n bool isRecoverable = false, Exception? inner = null)\n : base(itemName, \"removal\", message, isRecoverable, inner) { }\n }\n\n public class BatchOperationException : InstallationException\n {\n public int FailedCount { get; }\n public string OperationType { get; }\n\n public BatchOperationException(string operationType, int failedCount, int totalCount)\n : base(\"multiple items\", \n $\"{operationType} failed for {failedCount} of {totalCount} items\", \n true)\n {\n OperationType = operationType;\n FailedCount = failedCount;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BoolToChevronConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing MaterialDesignThemes.Wpf;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class BoolToChevronConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isExpanded)\n {\n return isExpanded ? PackIconKind.ChevronUp : PackIconKind.ChevronDown;\n }\n \n return PackIconKind.ChevronDown;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is PackIconKind kind)\n {\n return kind == PackIconKind.ChevronUp;\n }\n \n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/AppListViewModel.cs", "using System.Collections.ObjectModel;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.SoftwareApps.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n public abstract partial class AppListViewModel : BaseViewModel where T : class\n {\n protected readonly IPackageManager? _packageManager;\n protected readonly ITaskProgressService _progressService;\n \n [ObservableProperty]\n private bool _isLoading;\n\n public ObservableCollection Items { get; } = new();\n\n protected AppListViewModel(ITaskProgressService progressService, IPackageManager? packageManager) \n : base(progressService)\n {\n _packageManager = packageManager;\n _progressService = progressService;\n }\n\n public abstract Task LoadItemsAsync();\n public abstract Task CheckInstallationStatusAsync();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppInstallationCoordinatorService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Coordinates the installation of applications, handling connectivity monitoring,\n /// user notifications, and installation state management.\n /// \n public interface IAppInstallationCoordinatorService\n {\n /// \n /// Installs an application with connectivity monitoring and proper cancellation handling.\n /// \n /// The application information.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the installation operation with the result.\n Task InstallAppAsync(\n AppInfo appInfo,\n IProgress progress,\n CancellationToken cancellationToken = default);\n \n /// \n /// Event that is raised when the installation status changes.\n /// \n event EventHandler InstallationStatusChanged;\n }\n \n /// \n /// Result of an installation coordination operation.\n /// \n public class InstallationCoordinationResult\n {\n /// \n /// Gets or sets a value indicating whether the installation was successful.\n /// \n public bool Success { get; set; }\n \n /// \n /// Gets or sets the error message if the installation failed.\n /// \n public string ErrorMessage { get; set; }\n \n /// \n /// Gets or sets a value indicating whether the installation was cancelled by the user.\n /// \n public bool WasCancelled { get; set; }\n \n /// \n /// Gets or sets a value indicating whether the installation failed due to connectivity issues.\n /// \n public bool WasConnectivityIssue { get; set; }\n \n /// \n /// Gets or sets the application information.\n /// \n public AppInfo AppInfo { get; set; }\n }\n \n /// \n /// Event arguments for installation status change events.\n /// \n public class InstallationStatusChangedEventArgs : EventArgs\n {\n /// \n /// Gets the application information.\n /// \n public AppInfo AppInfo { get; }\n \n /// \n /// Gets the status message.\n /// \n public string StatusMessage { get; }\n \n /// \n /// Gets a value indicating whether the installation is complete.\n /// \n public bool IsComplete { get; }\n \n /// \n /// Gets a value indicating whether the installation was successful.\n /// \n public bool IsSuccess { get; }\n \n /// \n /// Gets a value indicating whether the installation was cancelled by the user.\n /// \n public bool IsCancelled { get; }\n \n /// \n /// Gets a value indicating whether the installation failed due to connectivity issues.\n /// \n public bool IsConnectivityIssue { get; }\n \n /// \n /// Gets the timestamp when the status changed.\n /// \n public DateTime Timestamp { get; }\n \n /// \n /// Initializes a new instance of the class.\n /// \n /// The application information.\n /// The status message.\n /// Whether the installation is complete.\n /// Whether the installation was successful.\n /// Whether the installation was cancelled by the user.\n /// Whether the installation failed due to connectivity issues.\n public InstallationStatusChangedEventArgs(\n AppInfo appInfo,\n string statusMessage,\n bool isComplete = false,\n bool isSuccess = false,\n bool isCancelled = false,\n bool isConnectivityIssue = false)\n {\n AppInfo = appInfo;\n StatusMessage = statusMessage;\n IsComplete = isComplete;\n IsSuccess = isSuccess;\n IsCancelled = isCancelled;\n IsConnectivityIssue = isConnectivityIssue;\n Timestamp = DateTime.Now;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/CountToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts an integer count to a Visibility value.\n /// Returns Visible if the count is greater than 0, otherwise returns Collapsed.\n /// \n public class CountToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is int count)\n {\n return count > 0 ? Visibility.Visible : Visibility.Collapsed;\n }\n \n return Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/AppliedStatusToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class AppliedStatusToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // If the status is Applied, return Visible, otherwise return Collapsed\n if (value is RegistrySettingStatus status)\n {\n return status == RegistrySettingStatus.Applied ? Visibility.Visible : Visibility.Collapsed;\n }\n \n return Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToReinstallableIconConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing MaterialDesignThemes.Wpf;\n\nnamespace Winhance.WPF.Converters\n{\n /// \n /// Converts a boolean value indicating whether an item can be reinstalled to the appropriate MaterialDesign icon.\n /// \n public class BooleanToReinstallableIconConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // Return the appropriate MaterialDesign PackIconKind\n return (bool)value ? PackIconKind.Sync : PackIconKind.SyncDisabled;\n }\n\n public object ConvertBack(\n object value,\n Type targetType,\n object parameter,\n CultureInfo culture\n )\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/RegistryModels.cs", "using Microsoft.Win32;\nusing System;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models;\n\npublic record RegistrySetting\n{\n public required string Category { get; init; }\n public required RegistryHive Hive { get; init; }\n public required string SubKey { get; init; }\n public required string Name { get; init; }\n\n /// \n /// The value shown in the tooltip to indicate the recommended value.\n /// \n public required object RecommendedValue { get; init; }\n\n /// \n /// The value shown in the tooltip to indicate the default value. (or null to delete the registry key).\n /// \n public object? DefaultValue { get; init; }\n\n /// \n /// The value to set when the toggle is ON (enabled).\n /// \n public object? EnabledValue { get; init; }\n\n /// \n /// The value to set when the toggle is OFF (disabled), or null to delete the registry key.\n /// \n public object? DisabledValue { get; init; }\n\n public required RegistryValueKind ValueType { get; init; }\n /// \n /// Description of the registry setting. This is optional as the parent OptimizationSetting\n /// typically already has a Description property that serves the same purpose.\n /// \n public string Description { get; init; } = string.Empty;\n\n /// \n /// Specifies the intended action for this registry setting.\n /// Default is Set for backward compatibility.\n /// \n public RegistryActionType ActionType { get; init; } = RegistryActionType.Set;\n\n /// \n /// Specifies whether the absence of the registry key/value means the feature is enabled.\n /// Default is false, meaning absence = not applied.\n /// When true, absence of the key/value means the feature is enabled (Applied).\n /// \n public bool AbsenceMeansEnabled { get; init; } = false;\n\n /// \n /// Specifies whether this setting is a primary setting when used in linked settings.\n /// For settings with LinkedSettingsLogic.Primary, only the primary setting's status is used.\n /// \n public bool IsPrimary { get; init; } = false;\n\n /// \n /// Specifies whether this setting is a Group Policy registry key.\n /// When true, the entire key will be deleted when disabling the setting instead of just changing the value.\n /// This is necessary for Windows to recognize that the policy is no longer applied.\n /// \n public bool IsGroupPolicy { get; init; } = false;\n \n /// \n /// Dictionary to store custom properties for specific control types like ComboBox.\n /// This allows storing additional information that doesn't fit into the standard registry setting model.\n /// \n public Dictionary? CustomProperties { get; set; }\n}\n\npublic enum RegistryAction\n{\n Apply,\n Test,\n Rollback\n}\n\npublic record ValuePair\n{\n public required object Value { get; init; }\n public required RegistryValueKind Type { get; init; }\n\n public ValuePair(object value, RegistryValueKind type)\n {\n Value = value;\n Type = type;\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/InverseBooleanToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean value to a Visibility value, with the boolean value inverted.\n /// True becomes Collapsed, False becomes Visible.\n /// \n public class InverseBooleanToVisibilityConverter : IValueConverter\n {\n /// \n /// Converts a boolean value to a Visibility value, with the boolean value inverted.\n /// \n /// The boolean value to convert.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// Visibility.Collapsed if the value is true, Visibility.Visible if the value is false.\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return boolValue ? Visibility.Collapsed : Visibility.Visible;\n }\n \n return Visibility.Visible;\n }\n \n /// \n /// Converts a Visibility value back to a boolean value, with the boolean value inverted.\n /// \n /// The Visibility value to convert back.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// False if the value is Visibility.Visible, true otherwise.\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is Visibility visibility)\n {\n return visibility != Visibility.Visible;\n }\n \n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Exceptions/RemovalException.cs", "using System;\n\nnamespace Winhance.Core.Features.SoftwareApps.Exceptions\n{\n /// \n /// Exception thrown when there is an error with removal operations.\n /// \n public class RemovalException : Exception\n {\n /// \n /// Initializes a new instance of the class.\n /// \n public RemovalException() : base()\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message.\n /// \n /// The message that describes the error.\n public RemovalException(string message) : base(message)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message\n /// and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception.\n public RemovalException(string message, Exception innerException) : base(message, innerException)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified item name, error message,\n /// a flag indicating whether the error is critical, and a reference to the inner exception that is the cause of this exception.\n /// \n /// The name of the item that failed to be removed.\n /// The error message.\n /// A flag indicating whether the error is critical.\n /// The exception that is the cause of the current exception.\n public RemovalException(string itemName, string errorMessage, bool isCritical, Exception innerException)\n : base($\"Failed to remove {itemName}: {errorMessage}\", innerException)\n {\n ItemName = itemName;\n IsCritical = isCritical;\n }\n\n /// \n /// Gets the name of the item that failed to be removed.\n /// \n public string? ItemName { get; }\n\n /// \n /// Gets a value indicating whether the error is critical.\n /// \n public bool IsCritical { get; }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/CustomUacSettings.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace Winhance.Core.Features.Optimize.Models\n{\n /// \n /// Represents custom User Account Control (UAC) settings that don't match standard Windows GUI options.\n /// \n [Serializable]\n public class CustomUacSettings\n {\n /// \n /// Gets or sets the ConsentPromptBehaviorAdmin registry value.\n /// \n [JsonProperty(\"ConsentPromptValue\")]\n public int ConsentPromptValue { get; set; }\n\n /// \n /// Gets or sets the PromptOnSecureDesktop registry value.\n /// \n [JsonProperty(\"SecureDesktopValue\")]\n public int SecureDesktopValue { get; set; }\n\n /// \n /// Gets or sets a timestamp when these settings were last detected or saved.\n /// \n [JsonProperty(\"LastUpdated\")]\n public DateTime LastUpdated { get; set; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n public CustomUacSettings()\n {\n // Default constructor for serialization\n }\n\n /// \n /// Initializes a new instance of the class with specific values.\n /// \n /// The ConsentPromptBehaviorAdmin registry value.\n /// The PromptOnSecureDesktop registry value.\n public CustomUacSettings(int consentPromptValue, int secureDesktopValue)\n {\n ConsentPromptValue = consentPromptValue;\n SecureDesktopValue = secureDesktopValue;\n LastUpdated = DateTime.Now;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IInternetConnectivityService.cs", "using System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for services that check and monitor internet connectivity.\n /// \n public interface IInternetConnectivityService\n {\n /// \n /// Checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// True if internet is connected, false otherwise.\n bool IsInternetConnected(bool forceCheck = false);\n\n /// \n /// Asynchronously checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// Cancellation token for the operation.\n /// True if internet is connected, false otherwise.\n Task IsInternetConnectedAsync(bool forceCheck = false, CancellationToken cancellationToken = default, bool userInitiatedCancellation = false);\n \n /// \n /// Event that is raised when the internet connectivity status changes.\n /// \n event EventHandler ConnectivityChanged;\n \n /// \n /// Starts monitoring internet connectivity at the specified interval.\n /// \n /// The interval in seconds between connectivity checks.\n /// Cancellation token to stop monitoring.\n /// A task representing the monitoring operation.\n Task StartMonitoringAsync(int intervalSeconds = 5, CancellationToken cancellationToken = default);\n \n /// \n /// Stops monitoring internet connectivity.\n /// \n void StopMonitoring();\n }\n \n /// \n /// Event arguments for connectivity change events.\n /// \n public class ConnectivityChangedEventArgs : EventArgs\n {\n /// \n /// Gets a value indicating whether the internet is connected.\n /// \n public bool IsConnected { get; }\n \n /// \n /// Gets a value indicating whether the connectivity change was due to user cancellation.\n /// \n public bool IsUserCancelled { get; }\n \n /// \n /// Gets the timestamp when the connectivity status changed.\n /// \n public DateTime Timestamp { get; }\n \n /// \n /// Initializes a new instance of the class.\n /// \n /// Whether the internet is connected.\n /// Whether the connectivity change was due to user cancellation.\n public ConnectivityChangedEventArgs(bool isConnected, bool isUserCancelled = false)\n {\n IsConnected = isConnected;\n IsUserCancelled = isUserCancelled;\n Timestamp = DateTime.Now;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Models/LogMessageViewModel.cs", "using System;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Models\n{\n /// \n /// View model for log messages displayed in the UI.\n /// \n public class LogMessageViewModel\n {\n /// \n /// Gets or sets the message content.\n /// \n public string Message { get; set; }\n \n /// \n /// Gets or sets the log level.\n /// \n public LogLevel Level { get; set; }\n \n /// \n /// Gets or sets the timestamp when the message was created.\n /// \n public DateTime Timestamp { get; set; }\n \n /// \n /// Gets the formatted message with timestamp.\n /// \n public string FormattedMessage => $\"[{Timestamp:HH:mm:ss}] {Message}\";\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// A simple boolean converter that returns the parameter when true, and null when false.\n /// Useful for conditional resource selection.\n /// \n public class BooleanConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return boolValue ? parameter : null;\n }\n \n return null;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return value != null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/IsPrimaryToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean IsPrimary value to a Visibility value.\n /// Returns Visible if the value is true, otherwise returns Collapsed.\n /// \n public class IsPrimaryToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isPrimary && isPrimary)\n {\n return Visibility.Visible;\n }\n \n return Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/CompositeScriptContentModifier.cs", "using System;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Implementation of IScriptContentModifier that delegates to specialized modifiers.\n /// \n public class CompositeScriptContentModifier : IScriptContentModifier\n {\n private readonly IPackageScriptModifier _packageModifier;\n private readonly ICapabilityScriptModifier _capabilityModifier;\n private readonly IFeatureScriptModifier _featureModifier;\n private readonly IRegistryScriptModifier _registryModifier;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The package script modifier.\n /// The capability script modifier.\n /// The feature script modifier.\n /// The registry script modifier.\n public CompositeScriptContentModifier(\n IPackageScriptModifier packageModifier,\n ICapabilityScriptModifier capabilityModifier,\n IFeatureScriptModifier featureModifier,\n IRegistryScriptModifier registryModifier)\n {\n _packageModifier = packageModifier ?? throw new ArgumentNullException(nameof(packageModifier));\n _capabilityModifier = capabilityModifier ?? throw new ArgumentNullException(nameof(capabilityModifier));\n _featureModifier = featureModifier ?? throw new ArgumentNullException(nameof(featureModifier));\n _registryModifier = registryModifier ?? throw new ArgumentNullException(nameof(registryModifier));\n }\n\n /// \n public string RemoveCapabilityFromScript(string scriptContent, string capabilityName)\n {\n return _capabilityModifier.RemoveCapabilityFromScript(scriptContent, capabilityName);\n }\n\n /// \n public string RemovePackageFromScript(string scriptContent, string packageName)\n {\n return _packageModifier.RemovePackageFromScript(scriptContent, packageName);\n }\n\n /// \n public string RemoveOptionalFeatureFromScript(string scriptContent, string featureName)\n {\n return _featureModifier.RemoveOptionalFeatureFromScript(scriptContent, featureName);\n }\n\n /// \n public string RemoveAppRegistrySettingsFromScript(string scriptContent, string appName)\n {\n return _registryModifier.RemoveAppRegistrySettingsFromScript(scriptContent, appName);\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Optimize/Interfaces/IPowerPlanService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Core.Features.Optimize.Interfaces\n{\n /// \n /// Provides functionality for managing Windows power plans.\n /// \n public interface IPowerPlanService\n {\n /// \n /// Gets the GUID of the currently active power plan.\n /// \n /// The GUID of the active power plan.\n Task GetActivePowerPlanGuidAsync();\n\n /// \n /// Sets the active power plan.\n /// \n /// The GUID of the power plan to set as active.\n /// True if the operation succeeded; otherwise, false.\n Task SetPowerPlanAsync(string planGuid);\n\n /// \n /// Ensures that a power plan with the specified GUID exists.\n /// If it doesn't exist, creates it from the source plan if specified.\n /// \n /// The GUID of the power plan to ensure exists.\n /// The GUID of the source plan to create from, if needed.\n /// True if the plan exists or was created successfully; otherwise, false.\n Task EnsurePowerPlanExistsAsync(string planGuid, string sourcePlanGuid = null);\n\n /// \n /// Gets a list of all available power plans.\n /// \n /// A list of available power plans.\n Task> GetAvailablePowerPlansAsync();\n \n /// \n /// Executes a PowerCfg command.\n /// \n /// The PowerCfg command to execute.\n /// True if the operation succeeded; otherwise, false.\n Task ExecutePowerCfgCommandAsync(string command);\n \n /// \n /// Applies a power setting using PowerCfg.\n /// \n /// The subgroup GUID.\n /// The setting GUID.\n /// The value to set.\n /// True if this is an AC (plugged in) setting; false for DC (battery) setting.\n /// True if the operation succeeded; otherwise, false.\n Task ApplyPowerSettingAsync(string subgroupGuid, string settingGuid, string value, bool isAcSetting);\n \n /// \n /// Applies a collection of PowerCfg settings.\n /// \n /// The collection of PowerCfg settings to apply.\n /// True if all operations succeeded; otherwise, false.\n Task ApplyPowerCfgSettingsAsync(List settings);\n \n /// \n /// Checks if a PowerCfg setting is currently applied.\n /// \n /// The PowerCfg setting to check.\n /// True if the setting is applied; otherwise, false.\n Task IsPowerCfgSettingAppliedAsync(PowerCfgSetting setting);\n \n /// \n /// Checks if all PowerCfg settings in a collection are currently applied.\n /// \n /// The collection of PowerCfg settings to check.\n /// True if all settings are applied; otherwise, false.\n Task AreAllPowerCfgSettingsAppliedAsync(List settings);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/GreaterThanOneConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converter that returns true if the input value is greater than one.\n /// \n public class GreaterThanOneConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is int count)\n {\n return count > 1;\n }\n return false;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/WinGetModels.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents the result of a package installation operation.\n /// \n public class InstallationResult\n {\n /// \n /// Gets or sets a value indicating whether the installation was successful.\n /// \n public bool Success { get; set; }\n\n /// \n /// Gets or sets an optional message providing additional information about the result.\n /// \n public string Message { get; set; }\n\n /// \n /// Gets or sets the package ID that was installed.\n /// \n public string PackageId { get; set; }\n\n /// \n /// Gets or sets the version of the package that was installed.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets the exit code from the installation process.\n /// \n public int ExitCode { get; set; }\n\n /// \n /// Gets or sets the standard output from the installation process.\n /// \n public string Output { get; set; }\n\n /// \n /// Gets or sets the error output from the installation process.\n /// \n public string Error { get; set; }\n }\n\n \n /// \n /// Represents options for package installation.\n /// \n public class InstallationOptions\n {\n /// \n /// Gets or sets the version of the package to install. If null, the latest version is installed.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets the source to install the package from.\n /// \n public string Source { get; set; }\n\n /// \n /// Gets or sets a value indicating whether to accept package agreements automatically.\n /// \n public bool AcceptPackageAgreements { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether to accept source agreements automatically.\n /// \n public bool AcceptSourceAgreements { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether to run the installation in silent mode.\n /// \n public bool Silent { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether to force the installation even if the package is already installed.\n /// \n public bool Force { get; set; }\n\n /// \n /// Gets or sets the installation scope (user or machine).\n /// \n public PackageInstallScope Scope { get; set; } = PackageInstallScope.User;\n\n /// \n /// Gets or sets the installation location.\n /// \n public string Location { get; set; }\n }\n\n\n /// \n /// Represents the result of a package upgrade operation.\n /// \n public class UpgradeResult : InstallationResult\n {\n /// \n /// Gets or sets the version that was upgraded from.\n /// \n public string PreviousVersion { get; set; }\n }\n\n /// \n /// Represents options for package upgrades.\n /// \n public class UpgradeOptions : InstallationOptions\n {\n // Inherits all properties from InstallationOptions\n }\n\n /// \n /// Represents the result of a package uninstallation operation.\n /// \n public class UninstallationResult\n {\n /// \n /// Gets or sets a value indicating whether the uninstallation was successful.\n /// \n public bool Success { get; set; }\n\n /// \n /// Gets or sets an optional message providing additional information about the result.\n /// \n public string Message { get; set; }\n\n /// \n /// Gets or sets the package ID that was uninstalled.\n /// \n public string PackageId { get; set; }\n\n /// \n /// Gets or sets the version of the package that was uninstalled.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets the exit code from the uninstallation process.\n /// \n public int ExitCode { get; set; }\n\n /// \n /// Gets or sets the standard output from the uninstallation process.\n /// \n public string Output { get; set; }\n\n /// \n /// Gets or sets the error output from the uninstallation process.\n /// \n public string Error { get; set; }\n }\n\n\n /// \n /// Represents options for package uninstallation.\n /// \n public class UninstallationOptions\n {\n /// \n /// Gets or sets a value indicating whether to run the uninstallation in silent mode.\n /// \n public bool Silent { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether to force the uninstallation.\n /// \n public bool Force { get; set; }\n\n /// \n /// Gets or sets the installation scope (user or machine) to uninstall from.\n /// \n public PackageInstallScope Scope { get; set; } = PackageInstallScope.User;\n }\n\n /// \n /// Represents information about a package.\n /// \n public class PackageInfo\n {\n /// \n /// Gets or sets the package ID.\n /// \n public string Id { get; set; }\n\n /// \n /// Gets or sets the package name.\n /// \n public string Name { get; set; }\n\n /// \n /// Gets or sets the package version.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets the package source.\n /// \n public string Source { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the package is installed.\n /// \n public bool IsInstalled { get; set; }\n\n /// \n /// Gets or sets the installed version if different from the available version.\n /// \n public string InstalledVersion { get; set; }\n }\n\n\n /// \n /// Represents options for package search.\n /// \n public class SearchOptions\n {\n /// \n /// Gets or sets the maximum number of results to return.\n /// \n public int? Count { get; set; }\n\n /// \n /// Gets or sets the source to search in.\n /// \n public string Source { get; set; }\n\n /// \n /// Gets or sets a value indicating whether to include packages that are already installed.\n /// \n public bool IncludeInstalled { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether to include packages that are not installed.\n /// \n public bool IncludeAvailable { get; set; } = true;\n }\n\n /// \n /// Represents the installation scope for a package.\n /// \n public enum PackageInstallScope\n {\n /// \n /// Install for the current user only.\n /// \n User,\n\n /// \n /// Install for all users (requires elevation).\n /// \n Machine\n }\n\n /// \n /// Represents the progress of a package installation.\n /// \n public class InstallationProgress\n {\n /// \n /// Gets or sets the current progress percentage (0-100).\n /// \n public int Percentage { get; set; }\n\n /// \n /// Gets or sets the current status message.\n /// \n public string Status { get; set; }\n\n /// \n /// Gets or sets the current operation being performed.\n /// \n public string Operation { get; set; }\n\n /// \n /// Gets or sets the package ID being processed.\n /// \n public string PackageId { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the progress is indeterminate.\n /// \n public bool IsIndeterminate { get; set; }\n \n /// \n /// Gets or sets a value indicating whether the operation was cancelled.\n /// \n public bool IsCancelled { get; set; }\n \n /// \n /// Gets or sets a value indicating whether an error occurred during the operation.\n /// \n public bool IsError { get; set; }\n \n /// \n /// Gets or sets a value indicating whether the operation failed due to connectivity issues.\n /// \n public bool IsConnectivityIssue { get; set; }\n }\n\n /// \n /// Represents the progress of a package upgrade operation.\n /// \n public class UpgradeProgress\n {\n /// \n /// Gets or sets the percentage of completion (0-100).\n /// \n public int Percentage { get; set; }\n\n /// \n /// Gets or sets the status message.\n /// \n public string Status { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the progress is indeterminate.\n /// \n public bool IsIndeterminate { get; set; }\n\n /// \n /// Gets or sets the package ID being processed.\n /// \n public string PackageId { get; set; }\n }\n\n /// \n /// Represents the progress of a package uninstallation operation.\n /// \n public class UninstallationProgress\n {\n /// \n /// Gets or sets the percentage of completion (0-100).\n /// \n public int Percentage { get; set; }\n\n /// \n /// Gets or sets the status message.\n /// \n public string Status { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the progress is indeterminate.\n /// \n public bool IsIndeterminate { get; set; }\n\n /// \n /// Gets or sets the package ID being processed.\n /// \n public string PackageId { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Exceptions/AppLoadingException.cs", "using System;\n\nnamespace Winhance.Core.Models.Exceptions\n{\n public enum AppLoadingErrorCode\n {\n Unknown,\n CacheFailure,\n Timeout,\n PackageManagerError,\n InvalidConfiguration,\n NetworkError\n }\n\n public class AppLoadingException : Exception\n {\n public AppLoadingErrorCode ErrorCode { get; }\n public Exception? OriginalException { get; }\n\n public AppLoadingException(AppLoadingErrorCode errorCode, string message, \n Exception? originalException = null)\n : base(message, originalException)\n {\n ErrorCode = errorCode;\n OriginalException = originalException;\n }\n }\n\n public class PackageManagerException : Exception\n {\n public string PackageId { get; }\n public string Operation { get; }\n public Exception? OriginalException { get; }\n\n public PackageManagerException(string packageId, string operation, string message,\n Exception? originalException = null)\n : base($\"Package {operation} failed for {packageId}: {message}\", originalException)\n {\n PackageId = packageId;\n Operation = operation;\n OriginalException = originalException;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/StartMenuLayouts.cs", "using System;\n\nnamespace Winhance.Core.Features.Customize.Models;\n\n/// \n/// Contains layout templates for Windows 10 and Windows 11 Start Menus.\n/// \npublic static class StartMenuLayouts\n{\n /// \n /// Gets the Windows 10 Start Menu layout XML template.\n /// \n public static string Windows10Layout => @\"\n\n \n \n \n \n \n \n\";\n\n /// \n /// Gets the Windows 11 Start Menu binary certificate template.\n /// This is a base64 encoded representation of the start2.bin file.\n /// \n public static string Windows11StartBinCertificate => @\"-----BEGIN CERTIFICATE-----\n4nrhSwH8TRucAIEL3m5RhU5aX0cAW7FJilySr5CE+V40mv9utV7aAZARAABc9u55\nLN8F4borYyXEGl8Q5+RZ+qERszeqUhhZXDvcjTF6rgdprauITLqPgMVMbSZbRsLN\n/O5uMjSLEr6nWYIwsMJkZMnZyZrhR3PugUhUKOYDqwySCY6/CPkL/Ooz/5j2R2hw\nWRGqc7ZsJxDFM1DWofjUiGjDUny+Y8UjowknQVaPYao0PC4bygKEbeZqCqRvSgPa\nlSc53OFqCh2FHydzl09fChaos385QvF40EDEgSO8U9/dntAeNULwuuZBi7BkWSIO\nmWN1l4e+TZbtSJXwn+EINAJhRHyCSNeku21dsw+cMoLorMKnRmhJMLvE+CCdgNKI\naPo/Krizva1+bMsI8bSkV/CxaCTLXodb/NuBYCsIHY1sTvbwSBRNMPvccw43RJCU\nKZRkBLkCVfW24ANbLfHXofHDMLxxFNUpBPSgzGHnueHknECcf6J4HCFBqzvSH1Tj\nQ3S6J8tq2yaQ+jFNkxGRMushdXNNiTNjDFYMJNvgRL2lu606PZeypEjvPg7SkGR2\n7a42GDSJ8n6HQJXFkOQPJ1mkU4qpA78U+ZAo9ccw8XQPPqE1eG7wzMGihTWfEMVs\nK1nsKyEZCLYFmKwYqdIF0somFBXaL/qmEHxwlPCjwRKpwLOue0Y8fgA06xk+DMti\nzWahOZNeZ54MN3N14S22D75riYEccVe3CtkDoL+4Oc2MhVdYEVtQcqtKqZ+DmmoI\n5BqkECeSHZ4OCguheFckK5Eq5Yf0CKRN+RY2OJ0ZCPUyxQnWdnOi9oBcZsz2NGzY\ng8ifO5s5UGscSDMQWUxPJQePDh8nPUittzJ+iplQqJYQ/9p5nKoDukzHHkSwfGms\n1GiSYMUZvaze7VSWOHrgZ6dp5qc1SQy0FSacBaEu4ziwx1H7w5NZj+zj2ZbxAZhr\n7Wfvt9K1xp58H66U4YT8Su7oq5JGDxuwOEbkltA7PzbFUtq65m4P4LvS4QUIBUqU\n0+JRyppVN5HPe11cCPaDdWhcr3LsibWXQ7f0mK8xTtPkOUb5pA2OUIkwNlzmwwS1\nNn69/13u7HmPSyofLck77zGjjqhSV22oHhBSGEr+KagMLZlvt9pnD/3I1R1BqItW\nKF3woyb/QizAqScEBsOKj7fmGA7f0KKQkpSpenF1Q/LNdyyOc77wbu2aywLGLN7H\nBCdwwjjMQ43FHSQPCA3+5mQDcfhmsFtORnRZWqVKwcKWuUJ7zLEIxlANZ7rDcC30\nFKmeUJuKk0Upvhsz7UXzDtNmqYmtg6vY/yPtG5Cc7XXGJxY2QJcbg1uqYI6gKtue\n00Mfpjw7XpUMQbIW9rXMA9PSWX6h2ln2TwlbrRikqdQXACZyhtuzSNLK7ifSqw4O\nJcZ8JrQ/xePmSd0z6O/MCTiUTFwG0E6WS1XBV1owOYi6jVif1zg75DTbXQGTNRvK\nKarodfnpYg3sgTe/8OAI1YSwProuGNNh4hxK+SmljqrYmEj8BNK3MNCyIskCcQ4u\ncyoJJHmsNaGFyiKp1543PktIgcs8kpF/SN86/SoB/oI7KECCCKtHNdFV8p9HO3t8\n5OsgGUYgvh7Z/Z+P7UGgN1iaYn7El9XopQ/XwK9zc9FBr73+xzE5Hh4aehNVIQdM\nMb+Rfm11R0Jc4WhqBLCC3/uBRzesyKUzPoRJ9IOxCwzeFwGQ202XVlPvklXQwgHx\nBfEAWZY1gaX6femNGDkRldzImxF87Sncnt9Y9uQty8u0IY3lLYNcAFoTobZmFkAQ\nvuNcXxObmHk3rZNAbRLFsXnWUKGjuK5oP2TyTNlm9fMmnf/E8deez3d8KOXW9YMZ\nDkA/iElnxcCKUFpwI+tWqHQ0FT96sgIP/EyhhCq6o/RnNtZvch9zW8sIGD7Lg0cq\nSzPYghZuNVYwr90qt7UDekEei4CHTzgWwlSWGGCrP6Oxjk1Fe+KvH4OYwEiDwyRc\nl7NRJseqpW1ODv8c3VLnTJJ4o3QPlAO6tOvon7vA1STKtXylbjWARNcWuxT41jtC\nCzrAroK2r9bCij4VbwHjmpQnhYbF/hCE1r71Z5eHdWXqpSgIWeS/1avQTStsehwD\n2+NGFRXI8mwLBLQN/qi8rqmKPi+fPVBjFoYDyDc35elpdzvqtN/mEp+xDrnAbwXU\nyfhkZvyo2+LXFMGFLdYtWTK/+T/4n03OJH1gr6j3zkoosewKTiZeClnK/qfc8YLw\nbCdwBm4uHsZ9I14OFCepfHzmXp9nN6a3u0sKi4GZpnAIjSreY4rMK8c+0FNNDLi5\nDKuck7+WuGkcRrB/1G9qSdpXqVe86uNojXk9P6TlpXyL/noudwmUhUNTZyOGcmhJ\nEBiaNbT2Awx5QNssAlZFuEfvPEAixBz476U8/UPb9ObHbsdcZjXNV89WhfYX04DM\n9qcMhCnGq25sJPc5VC6XnNHpFeWhvV/edYESdeEVwxEcExKEAwmEZlGJdxzoAH+K\nY+xAZdgWjPPL5FaYzpXc5erALUfyT+n0UTLcjaR4AKxLnpbRqlNzrWa6xqJN9NwA\n+xa38I6EXbQ5Q2kLcK6qbJAbkEL76WiFlkc5mXrGouukDvsjYdxG5Rx6OYxb41Ep\n1jEtinaNfXwt/JiDZxuXCMHdKHSH40aZCRlwdAI1C5fqoUkgiDdsxkEq+mGWxMVE\nZd0Ch9zgQLlA6gYlK3gt8+dr1+OSZ0dQdp3ABqb1+0oP8xpozFc2bK3OsJvucpYB\nOdmS+rfScY+N0PByGJoKbdNUHIeXv2xdhXnVjM5G3G6nxa3x8WFMJsJs2ma1xRT1\n8HKqjX9Ha072PD8Zviu/bWdf5c4RrphVqvzfr9wNRpfmnGOoOcbkRE4QrL5CqrPb\nVRujOBMPGAxNlvwq0w1XDOBDawZgK7660yd4MQFZk7iyZgUSXIo3ikleRSmBs+Mt\nr+3Og54Cg9QLPHbQQPmiMsu21IJUh0rTgxMVBxNUNbUaPJI1lmbkTcc7HeIk0Wtg\nRxwYc8aUn0f/V//c+2ZAlM6xmXmj6jIkOcfkSBd0B5z63N4trypD3m+w34bZkV1I\ncQ8h7SaUUqYO5RkjStZbvk2IDFSPUExvqhCstnJf7PZGilbsFPN8lYqcIvDZdaAU\nMunNh6f/RnhFwKHXoyWtNI6yK6dm1mhwy+DgPlA2nAevO+FC7Vv98Sl9zaVjaPPy\n3BRyQ6kISCL065AKVPEY0ULHqtIyfU5gMvBeUa5+xbU+tUx4ZeP/BdB48/LodyYV\nkkgqTafVxCvz4vgmPbnPjm/dlRbVGbyygN0Noq8vo2Ea8Z5zwO32coY2309AC7wv\nPp2wJZn6LKRmzoLWJMFm1A1Oa4RUIkEpA3AAL+5TauxfawpdtTjicoWGQ5gGNwum\n+evTnGEpDimE5kUU6uiJ0rotjNpB52I+8qmbgIPkY0Fwwal5Z5yvZJ8eepQjvdZ2\nUcdvlTS8oA5YayGi+ASmnJSbsr/v1OOcLmnpwPI+hRgPP+Hwu5rWkOT+SDomF1TO\nn/k7NkJ967X0kPx6XtxTPgcG1aKJwZBNQDKDP17/dlZ869W3o6JdgCEvt1nIOPty\nlGgvGERC0jCNRJpGml4/py7AtP0WOxrs+YS60sPKMATtiGzp34++dAmHyVEmelhK\napQBuxFl6LQN33+2NNn6L5twI4IQfnm6Cvly9r3VBO0Bi+rpjdftr60scRQM1qw+\n9dEz4xL9VEL6wrnyAERLY58wmS9Zp73xXQ1mdDB+yKkGOHeIiA7tCwnNZqClQ8Mf\nRnZIAeL1jcqrIsmkQNs4RTuE+ApcnE5DMcvJMgEd1fU3JDRJbaUv+w7kxj4/+G5b\nIU2bfh52jUQ5gOftGEFs1LOLj4Bny2XlCiP0L7XLJTKSf0t1zj2ohQWDT5BLo0EV\n5rye4hckB4QCiNyiZfavwB6ymStjwnuaS8qwjaRLw4JEeNDjSs/JC0G2ewulUyHt\nkEobZO/mQLlhso2lnEaRtK1LyoD1b4IEDbTYmjaWKLR7J64iHKUpiQYPSPxcWyei\no4kcyGw+QvgmxGaKsqSBVGogOV6YuEyoaM0jlfUmi2UmQkju2iY5tzCObNQ41nsL\ndKwraDrcjrn4CAKPMMfeUSvYWP559EFfDhDSK6Os6Sbo8R6Zoa7C2NdAicA1jPbt\n5ENSrVKf7TOrthvNH9vb1mZC1X2RBmriowa/iT+LEbmQnAkA6Y1tCbpzvrL+cX8K\npUTOAovaiPbab0xzFP7QXc1uK0XA+M1wQ9OF3XGp8PS5QRgSTwMpQXW2iMqihYPv\nHu6U1hhkyfzYZzoJCjVsY2xghJmjKiKEfX0w3RaxfrJkF8ePY9SexnVUNXJ1654/\nPQzDKsW58Au9QpIH9VSwKNpv003PksOpobM6G52ouCFOk6HFzSLfnlGZW0yyUQL3\nRRyEE2PP0LwQEuk2gxrW8eVy9elqn43S8CG2h2NUtmQULc/IeX63tmCOmOS0emW9\n66EljNdMk/e5dTo5XplTJRxRydXcQpgy9bQuntFwPPoo0fXfXlirKsav2rPSWayw\nKQK4NxinT+yQh//COeQDYkK01urc2G7SxZ6H0k6uo8xVp9tDCYqHk/lbvukoN0RF\ntUI4aLWuKet1O1s1uUAxjd50ELks5iwoqLJ/1bzSmTRMifehP07sbK/N1f4hLae+\njykYgzDWNfNvmPEiz0DwO/rCQTP6x69g+NJaFlmPFwGsKfxP8HqiNWQ6D3irZYcQ\nR5Mt2Iwzz2ZWA7B2WLYZWndRCosRVWyPdGhs7gkmLPZ+WWo/Yb7O1kIiWGfVuPNA\nMKmgPPjZy8DhZfq5kX20KF6uA0JOZOciXhc0PPAUEy/iQAtzSDYjmJ8HR7l4mYsT\nO3Mg3QibMK8MGGa4tEM8OPGktAV5B2J2QOe0f1r3vi3QmM+yukBaabwlJ+dUDQGm\n+Ll/1mO5TS+BlWMEAi13cB5bPRsxkzpabxq5kyQwh4vcMuLI0BOIfE2pDKny5jhW\n0C4zzv3avYaJh2ts6kvlvTKiSMeXcnK6onKHT89fWQ7Hzr/W8QbR/GnIWBbJMoTc\nWcgmW4fO3AC+YlnLVK4kBmnBmsLzLh6M2LOabhxKN8+0Oeoouww7g0HgHkDyt+MS\n97po6SETwrdqEFslylLo8+GifFI1bb68H79iEwjXojxQXcD5qqJPxdHsA32eWV0b\nqXAVojyAk7kQJfDIK+Y1q9T6KI4ew4t6iauJ8iVJyClnHt8z/4cXdMX37EvJ+2BS\nYKHv5OAfS7/9ZpKgILT8NxghgvguLB7G9sWNHntExPtuRLL4/asYFYSAJxUPm7U2\nxnp35Zx5jCXesd5OlKNdmhXq519cLl0RGZfH2ZIAEf1hNZqDuKesZ2enykjFlIec\nhZsLvEW/pJQnW0+LFz9N3x3vJwxbC7oDgd7A2u0I69Tkdzlc6FFJcfGabT5C3eF2\nEAC+toIobJY9hpxdkeukSuxVwin9zuBoUM4X9x/FvgfIE0dKLpzsFyMNlO4taCLc\nv1zbgUk2sR91JmbiCbqHglTzQaVMLhPwd8GU55AvYCGMOsSg3p952UkeoxRSeZRp\njQHr4bLN90cqNcrD3h5knmC61nDKf8e+vRZO8CVYR1eb3LsMz12vhTJGaQ4jd0Kz\nQyosjcB73wnE9b/rxfG1dRactg7zRU2BfBK/CHpIFJH+XztwMJxn27foSvCY6ktd\nuJorJvkGJOgwg0f+oHKDvOTWFO1GSqEZ5BwXKGH0t0udZyXQGgZWvF5s/ojZVcK3\nIXz4tKhwrI1ZKnZwL9R2zrpMJ4w6smQgipP0yzzi0ZvsOXRksQJNCn4UPLBhbu+C\neFBbpfe9wJFLD+8F9EY6GlY2W9AKD5/zNUCj6ws8lBn3aRfNPE+Cxy+IKC1NdKLw\neFdOGZr2y1K2IkdefmN9cLZQ/CVXkw8Qw2nOr/ntwuFV/tvJoPW2EOzRmF2XO8mQ\nDQv51k5/v4ZE2VL0dIIvj1M+KPw0nSs271QgJanYwK3CpFluK/1ilEi7JKDikT8X\nTSz1QZdkum5Y3uC7wc7paXh1rm11nwluCC7jiA==\n-----END CERTIFICATE-----\";\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/InverseBooleanConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean value to its inverse (true to false, false to true)\n /// \n public class InverseBooleanConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return !boolValue;\n }\n \n return value;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return !boolValue;\n }\n \n return value;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Interfaces/IVerificationMethod.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces\n{\n /// \n /// Defines the contract for different verification methods to check if a package is installed.\n /// \n public interface IVerificationMethod\n {\n /// \n /// Gets the name of the verification method.\n /// \n string Name { get; }\n\n /// \n /// Gets the priority of this verification method. Lower numbers indicate higher priority.\n /// \n int Priority { get; }\n\n /// \n /// Verifies if a package is installed using this verification method.\n /// \n /// The ID of the package to verify.\n /// Optional version to verify. If null, only the presence is checked.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the verification result.\n Task VerifyAsync(\n string packageId, \n string version = null, \n CancellationToken cancellationToken = default);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ISystemServices.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Models.Enums;\nusing Winhance.Core.Features.Customize.Enums;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for system-level services that interact with the Windows operating system.\n /// \n public interface ISystemServices\n {\n /// \n /// Gets the registry service.\n /// \n IRegistryService RegistryService { get; }\n\n /// \n /// Restarts the Windows Explorer process.\n /// \n void RestartExplorer();\n\n /// \n /// Checks if the current user is an administrator.\n /// \n /// True if the current user is an administrator; otherwise, false.\n bool IsAdministrator();\n\n /// \n /// Gets the Windows version.\n /// \n /// A string representing the Windows version.\n string GetWindowsVersion();\n\n /// \n /// Refreshes the desktop.\n /// \n void RefreshDesktop();\n\n /// \n /// Checks if a process is running.\n /// \n /// The name of the process to check.\n /// True if the process is running; otherwise, false.\n bool IsProcessRunning(string processName);\n\n /// \n /// Kills a process.\n /// \n /// The name of the process to kill.\n void KillProcess(string processName);\n\n /// \n /// Checks if the operating system is Windows 11.\n /// \n /// True if the operating system is Windows 11; otherwise, false.\n bool IsWindows11();\n\n /// \n /// Requires administrator privileges.\n /// \n /// True if the application is running with administrator privileges; otherwise, false.\n bool RequireAdministrator();\n\n /// \n /// Checks if dark mode is enabled.\n /// \n /// True if dark mode is enabled; otherwise, false.\n bool IsDarkModeEnabled();\n\n /// \n /// Sets dark mode.\n /// \n /// True to enable dark mode; false to disable it.\n void SetDarkMode(bool enabled);\n\n /// \n /// Sets the UAC level.\n /// \n /// The UAC level to set.\n void SetUacLevel(Winhance.Core.Models.Enums.UacLevel level);\n\n /// \n /// Gets the UAC level.\n /// \n /// The current UAC level.\n Winhance.Core.Models.Enums.UacLevel GetUacLevel();\n\n /// \n /// Refreshes the Windows GUI.\n /// \n /// A task that represents the asynchronous operation. The task result contains a value indicating whether the operation succeeded.\n Task RefreshWindowsGUI();\n\n /// \n /// Refreshes the Windows GUI.\n /// \n /// True to kill the Explorer process; otherwise, false.\n /// A task that represents the asynchronous operation. The task result contains a value indicating whether the operation succeeded.\n Task RefreshWindowsGUI(bool killExplorer);\n\n /// \n /// Checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// True if internet is connected, false otherwise.\n bool IsInternetConnected(bool forceCheck = false);\n\n /// \n /// Asynchronously checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// Cancellation token for the operation.\n /// True if internet is connected, false otherwise.\n Task IsInternetConnectedAsync(bool forceCheck = false, CancellationToken cancellationToken = default, bool userInitiatedCancellation = false);\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/IScriptUpdateService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\n/// \n/// Provides methods for updating script content.\n/// \npublic interface IScriptUpdateService\n{\n /// \n /// Updates an existing BloatRemoval script with new entries.\n /// \n /// The names of the applications to add or remove.\n /// Dictionary mapping app names to their registry settings.\n /// Dictionary mapping app names to their subpackages.\n /// True if this is an install operation (remove from script), false if it's a removal operation (add to script).\n /// The updated removal script.\n Task UpdateExistingBloatRemovalScriptAsync(\n List appNames,\n Dictionary> appsWithRegistry,\n Dictionary appSubPackages,\n bool isInstallOperation = false);\n\n /// \n /// Updates the capabilities array in the script by adding or removing capabilities.\n /// \n /// The script content.\n /// The capabilities to add or remove.\n /// True if this is an install operation (remove from script), false if it's a removal operation (add to script).\n /// The updated script content.\n string UpdateCapabilitiesArrayInScript(string scriptContent, List capabilities, bool isInstallOperation = false);\n\n /// \n /// Updates the packages array in the script by adding or removing packages.\n /// \n /// The script content.\n /// The packages to add or remove.\n /// True if this is an install operation (remove from script), false if it's a removal operation (add to script).\n /// The updated script content.\n string UpdatePackagesArrayInScript(string scriptContent, List packages, bool isInstallOperation = false);\n\n /// \n /// Updates the optional features in the script by adding or removing features.\n /// \n /// The script content.\n /// The features to add or remove.\n /// True if this is an install operation (remove from script), false if it's a removal operation (add to script).\n /// The updated script content.\n string UpdateOptionalFeaturesInScript(string scriptContent, List features, bool isInstallOperation = false);\n\n /// \n /// Updates the registry settings in the script by adding new settings.\n /// \n /// The script content.\n /// Dictionary mapping app names to their registry settings.\n /// The updated script content.\n string UpdateRegistrySettingsInScript(string scriptContent, Dictionary> appsWithRegistry);\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IRegistryService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides access to the Windows registry.\n /// \n public interface IRegistryService\n {\n /// \n /// Sets a value in the registry.\n /// \n /// The registry key path.\n /// The name of the value to set.\n /// The value to set.\n /// The type of the value.\n /// True if the operation succeeded; otherwise, false.\n bool SetValue(string keyPath, string valueName, object value, Microsoft.Win32.RegistryValueKind valueKind);\n\n /// \n /// Gets a value from the registry.\n /// \n /// The registry key path.\n /// The name of the value to get.\n /// The value from the registry, or null if it doesn't exist.\n object? GetValue(string keyPath, string valueName);\n\n /// \n /// Deletes a value from the registry.\n /// \n /// The registry key path.\n /// The name of the value to delete.\n /// True if the operation succeeded; otherwise, false.\n bool DeleteValue(string keyPath, string valueName);\n\n /// \n /// Deletes a value from the registry using hive and subkey.\n /// \n /// The registry hive.\n /// The registry subkey.\n /// The name of the value to delete.\n /// True if the operation succeeded; otherwise, false.\n Task DeleteValue(RegistryHive hive, string subKey, string valueName);\n\n /// \n /// Exports a registry key to a string.\n /// \n /// The registry key path to export.\n /// Whether to include subkeys in the export.\n /// The exported registry key as a string.\n Task ExportKey(string keyPath, bool includeSubKeys);\n\n /// \n /// Gets the status of a registry setting.\n /// \n /// The registry setting to check.\n /// The status of the registry setting.\n Task GetSettingStatusAsync(RegistrySetting setting);\n\n /// \n /// Gets the current value of a registry setting.\n /// \n /// The registry setting to check.\n /// The current value of the registry setting, or null if it doesn't exist.\n Task GetCurrentValueAsync(RegistrySetting setting);\n\n /// \n /// Determines whether a registry key exists.\n /// \n /// The registry key path.\n /// True if the key exists; otherwise, false.\n bool KeyExists(string keyPath);\n\n /// \n /// Creates a registry key.\n /// \n /// The registry key path.\n /// True if the operation succeeded; otherwise, false.\n bool CreateKey(string keyPath);\n\n /// \n /// Creates a registry key if it doesn't exist.\n /// \n /// The full path to the registry key.\n /// True if the key exists or was created successfully; otherwise, false.\n bool CreateKeyIfNotExists(string keyPath);\n\n /// \n /// Determines whether a registry value exists.\n /// \n /// The registry key path.\n /// The name of the value to check.\n /// True if the value exists; otherwise, false.\n bool ValueExists(string keyPath, string valueName);\n\n /// \n /// Deletes a registry key and all its values.\n /// \n /// The full path to the registry key to delete.\n /// True if the key was successfully deleted, false otherwise.\n bool DeleteKey(string keyPath);\n\n /// \n /// Deletes a registry key and all its values.\n /// \n /// The registry hive.\n /// The subkey path.\n /// True if the key was successfully deleted, false otherwise.\n Task DeleteKey(RegistryHive hive, string subKey);\n\n /// \n /// Tests a registry setting.\n /// \n /// The registry key path.\n /// The name of the value to test.\n /// The desired value.\n /// The status of the registry setting.\n RegistrySettingStatus TestRegistrySetting(string keyPath, string valueName, object desiredValue);\n\n /// \n /// Backs up the Windows registry.\n /// \n /// The path where the backup should be stored.\n /// True if the operation succeeded; otherwise, false.\n Task BackupRegistry(string backupPath);\n\n /// \n /// Restores the Windows registry from a backup.\n /// \n /// The path to the backup file.\n /// True if the operation succeeded; otherwise, false.\n Task RestoreRegistry(string backupPath);\n\n /// \n /// Applies customization settings to the registry.\n /// \n /// The settings to apply.\n /// True if all settings were applied successfully; otherwise, false.\n Task ApplyCustomizations(List settings);\n\n /// \n /// Restores customization settings to their default values.\n /// \n /// The settings to restore.\n /// True if all settings were restored successfully; otherwise, false.\n Task RestoreCustomizationDefaults(List settings);\n\n /// \n /// Applies power plan settings to the registry.\n /// \n /// The settings to apply.\n /// True if all settings were applied successfully; otherwise, false.\n Task ApplyPowerPlanSettings(List settings);\n\n /// \n /// Restores power plan settings to their default values.\n /// \n /// True if all settings were restored successfully; otherwise, false.\n Task RestoreDefaultPowerSettings();\n\n /// \n /// Gets the status of linked registry settings.\n /// \n /// The linked registry settings to check.\n /// The combined status of the linked registry settings.\n Task GetLinkedSettingsStatusAsync(LinkedRegistrySettings linkedSettings);\n\n /// \n /// Applies linked registry settings.\n /// \n /// The linked registry settings to apply.\n /// Whether to enable or disable the settings.\n /// True if all settings were applied successfully; otherwise, false.\n Task ApplyLinkedSettingsAsync(LinkedRegistrySettings linkedSettings, bool enable);\n\n /// \n /// Clears all registry caches to ensure fresh reads\n /// \n void ClearRegistryCaches();\n\n /// \n /// Gets the status of an optimization setting that may contain multiple registry settings.\n /// \n /// The optimization setting to check.\n /// The combined status of the optimization setting.\n Task GetOptimizationSettingStatusAsync(Winhance.Core.Features.Optimize.Models.OptimizationSetting setting);\n\n /// \n /// Applies an optimization setting that may contain multiple registry settings.\n /// \n /// The optimization setting to apply.\n /// Whether to enable or disable the setting.\n /// True if the setting was applied successfully; otherwise, false.\n Task ApplyOptimizationSettingAsync(Winhance.Core.Features.Optimize.Models.OptimizationSetting setting, bool enable);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ConfigurationServiceExtensions.cs", "using Microsoft.Extensions.DependencyInjection;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Extension methods for registering configuration services with the dependency injection container.\n /// \n public static class ConfigurationServiceExtensions\n {\n /// \n /// Adds all configuration services to the service collection.\n /// \n /// The service collection.\n /// The service collection for chaining.\n public static IServiceCollection AddConfigurationServices(this IServiceCollection services)\n {\n // Register the main configuration applier service\n services.AddTransient();\n \n // Register the property updater and view model refresher\n services.AddTransient();\n services.AddTransient();\n \n // Register all section-specific appliers\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n \n return services;\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/InstalledStatusToColorConverter.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Converters;\n\npublic class InstalledStatusToColorConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (bool)value \n ? new SolidColorBrush(Color.FromRgb(0, 255, 60)) // Electric Green (#00FF3C) \n : new SolidColorBrush(Color.FromRgb(255, 40, 0)); // Ferrari Red (#FF2800)\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/NullToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Converters\n{\n public class NullToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // If the value is null, return Visible, otherwise return Collapsed\n return value == null ? Visibility.Visible : Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/TaskProgressDetail.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents detailed progress information for a task.\n /// \n public class TaskProgressDetail\n {\n /// \n /// Gets or sets the progress value (0-100), or null if not applicable.\n /// \n public double? Progress { get; set; }\n \n /// \n /// Gets or sets the status text.\n /// \n public string StatusText { get; set; }\n \n /// \n /// Gets or sets a detailed message about the current operation.\n /// \n public string DetailedMessage { get; set; }\n \n /// \n /// Gets or sets the log level for the detailed message.\n /// \n public LogLevel LogLevel { get; set; } = LogLevel.Info;\n \n /// \n /// Gets or sets whether the progress is indeterminate.\n /// \n public bool IsIndeterminate { get; set; }\n \n /// \n /// Gets or sets additional information about the progress as key-value pairs.\n /// This can be used to provide more detailed information for logging or debugging.\n /// \n public Dictionary AdditionalInfo { get; set; } = new Dictionary();\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/RemovalScript.cs", "using System;\nusing System.IO;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a script for removing applications and preventing their reinstallation.\n/// \npublic class RemovalScript\n{\n /// \n /// Gets or sets the name of the script.\n /// \n public string Name { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the content of the script.\n /// \n public string Content { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the name of the scheduled task to create for running the script.\n /// \n public string TargetScheduledTaskName { get; init; } = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether the script should run on system startup.\n /// \n public bool RunOnStartup { get; init; }\n\n /// \n /// Gets the path where the script will be saved.\n /// \n public string ScriptPath => Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n \"Winhance\",\n \"Scripts\",\n $\"{Name}.ps1\");\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IInstallationService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Generic interface for installation services.\n /// \n /// The type of item to install, which must implement IInstallableItem.\n public interface IInstallationService where T : IInstallableItem\n {\n /// \n /// Installs an item.\n /// \n /// The item to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n Task> InstallAsync(\n T item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Checks if an item can be installed.\n /// \n /// The item to check.\n /// An operation result indicating if the item can be installed, with error details if not.\n Task> CanInstallAsync(T item);\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Interfaces/IWinGetInstaller.cs", "using System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces\n{\n /// \n /// Defines the contract for WinGet package installation and management.\n /// \n public interface IWinGetInstaller\n {\n /// \n /// Installs a package using WinGet.\n /// \n /// The ID of the package to install.\n /// Optional installation options.\n /// The display name to use in progress reporting.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the installation result.\n Task InstallPackageAsync(\n string packageId, \n InstallationOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Upgrades a package using WinGet.\n /// \n /// The ID of the package to upgrade.\n /// Optional upgrade options.\n /// The display name to use in progress reporting.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the upgrade result.\n Task UpgradePackageAsync(\n string packageId, \n UpgradeOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Uninstalls a package using WinGet.\n /// \n /// The ID of the package to uninstall.\n /// Optional uninstallation options.\n /// The display name to use in progress reporting.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the uninstallation result.\n Task UninstallPackageAsync(\n string packageId, \n UninstallationOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Gets information about an installed package.\n /// \n /// The ID of the package to get information about.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the package information.\n Task GetPackageInfoAsync(\n string packageId, \n CancellationToken cancellationToken = default);\n\n /// \n /// Searches for packages matching the given query.\n /// \n /// The search query.\n /// Optional search options.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the search results.\n Task> SearchPackagesAsync(\n string query, \n SearchOptions options = null, \n CancellationToken cancellationToken = default);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/ApplicationAction.cs", "using CommunityToolkit.Mvvm.ComponentModel;\nusing System;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Base class for application actions that can be performed in both Optimization and Customization features.\n /// \n public partial class ApplicationAction : ObservableObject\n {\n [ObservableProperty]\n private string _id = string.Empty;\n \n [ObservableProperty]\n private string _name = string.Empty;\n \n [ObservableProperty]\n private string _description = string.Empty;\n \n [ObservableProperty]\n private string _groupName = string.Empty;\n \n [ObservableProperty]\n private string _confirmationMessage = string.Empty;\n \n [ObservableProperty]\n private string _actionType = string.Empty;\n \n [ObservableProperty]\n private string _command = string.Empty;\n \n [ObservableProperty]\n private string _commandAction = string.Empty;\n \n /// \n /// Gets or sets the registry setting or other action to perform.\n /// \n public RegistrySetting? RegistrySetting { get; set; }\n \n /// \n /// Gets or sets optional additional actions to perform.\n /// \n public Func>? CustomAction { get; set; }\n \n /// \n /// Gets or sets a value indicating whether this action supports backup.\n /// \n public bool SupportsBackup { get; set; }\n \n /// \n /// Gets or sets optional backup action to perform.\n /// \n public Func>? BackupAction { get; set; }\n \n /// \n /// Gets or sets the parameters for this action.\n /// \n public Dictionary Parameters { get; set; } = new Dictionary();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IUnifiedConfigurationService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for managing unified configuration operations across the application.\n /// \n public interface IUnifiedConfigurationService\n {\n /// \n /// Creates a unified configuration file containing settings from all view models.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file.\n Task CreateUnifiedConfigurationAsync();\n\n /// \n /// Saves a unified configuration file.\n /// \n /// The unified configuration to save.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile config);\n\n /// \n /// Loads a unified configuration file.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file if successful, null otherwise.\n Task LoadUnifiedConfigurationAsync();\n\n /// \n /// Shows the unified configuration dialog to let the user select which sections to include.\n /// \n /// The unified configuration file.\n /// Whether this is a save dialog (true) or an import dialog (false).\n /// A dictionary of section names and their selection state.\n Task> ShowUnifiedConfigurationDialogAsync(UnifiedConfigurationFile config, bool isSaveDialog);\n\n /// \n /// Applies a unified configuration to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task ApplyUnifiedConfigurationAsync(UnifiedConfigurationFile config, IEnumerable selectedSections);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/UnifiedConfigurationFile.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents a unified configuration file that stores settings for multiple parts of the application.\n /// \n public class UnifiedConfigurationFile\n {\n /// \n /// Gets or sets the version of the configuration file format.\n /// \n public string Version { get; set; } = \"1.0\";\n\n /// \n /// Gets or sets the date and time when the configuration file was created.\n /// \n public DateTime CreatedAt { get; set; } = DateTime.UtcNow;\n\n /// \n /// Gets or sets the Windows Apps configuration section.\n /// \n public ConfigSection WindowsApps { get; set; } = new ConfigSection();\n\n /// \n /// Gets or sets the External Apps configuration section.\n /// \n public ConfigSection ExternalApps { get; set; } = new ConfigSection();\n\n /// \n /// Gets or sets the Customize configuration section.\n /// \n public ConfigSection Customize { get; set; } = new ConfigSection();\n\n /// \n /// Gets or sets the Optimize configuration section.\n /// \n public ConfigSection Optimize { get; set; } = new ConfigSection();\n }\n\n /// \n /// Represents a section in the unified configuration file.\n /// \n public class ConfigSection\n {\n /// \n /// Gets or sets a value indicating whether this section is included in the configuration.\n /// \n public bool IsIncluded { get; set; } = false;\n\n /// \n /// Gets or sets the collection of configuration items in this section.\n /// \n public List Items { get; set; } = new List();\n\n /// \n /// Gets or sets the description of this section.\n /// \n public string Description { get; set; }\n\n /// \n /// Gets or sets the icon for this section.\n /// \n public string Icon { get; set; }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IScriptGenerationService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for generating scripts for application removal and management.\n /// \n public interface IScriptGenerationService\n {\n /// \n /// Creates a batch removal script for applications.\n /// \n /// The application names to generate a removal script for.\n /// Dictionary mapping app names to registry settings.\n /// A removal script object.\n Task CreateBatchRemovalScriptAsync(\n List appNames,\n Dictionary> appsWithRegistry);\n\n /// \n /// Creates a batch removal script for a single application.\n /// \n /// The path where the script should be saved.\n /// The application to generate a removal script for.\n /// True if the script was created successfully; otherwise, false.\n Task CreateBatchRemovalScriptAsync(string scriptPath, AppInfo app);\n\n /// \n /// Updates the bloat removal script for an installed application.\n /// \n /// The application to update the script for.\n /// True if the script was updated successfully; otherwise, false.\n Task UpdateBloatRemovalScriptForInstalledAppAsync(AppInfo app);\n\n /// \n /// Registers a removal task in the Windows Task Scheduler.\n /// \n /// The script to register.\n /// A task representing the asynchronous operation.\n Task RegisterRemovalTaskAsync(RemovalScript script);\n\n /// \n /// Registers a removal task in the Windows Task Scheduler.\n /// \n /// The name of the task.\n /// The path to the script.\n /// True if the task was registered successfully; otherwise, false.\n Task RegisterRemovalTaskAsync(string taskName, string scriptPath);\n\n /// \n /// Saves a script to a file.\n /// \n /// The script to save.\n /// A task representing the asynchronous operation.\n Task SaveScriptAsync(RemovalScript script);\n\n /// \n /// Saves a script to a file.\n /// \n /// The path where the script should be saved.\n /// The content of the script.\n /// True if the script was saved successfully; otherwise, false.\n Task SaveScriptAsync(string scriptPath, string scriptContent);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppService.cs", "using System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Unified service interface for app discovery, loading, and status management.\n /// \n public interface IAppService\n {\n #region App Discovery & Loading\n\n /// \n /// Gets all installable applications.\n /// \n /// A collection of installable applications.\n Task> GetInstallableAppsAsync();\n\n /// \n /// Gets all standard (built-in) applications.\n /// \n /// A collection of standard applications.\n Task> GetStandardAppsAsync();\n\n /// \n /// Gets all available Windows capabilities.\n /// \n /// A collection of Windows capabilities.\n Task> GetCapabilitiesAsync();\n\n /// \n /// Gets all available Windows optional features.\n /// \n /// A collection of Windows optional features.\n Task> GetOptionalFeaturesAsync();\n\n #endregion\n\n #region Status Management\n\n /// \n /// Checks if an application is installed.\n /// \n /// The package name to check.\n /// The cancellation token.\n /// True if the application is installed; otherwise, false.\n Task IsAppInstalledAsync(string packageName, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if Microsoft Edge is installed.\n /// \n /// True if Edge is installed; otherwise, false.\n Task IsEdgeInstalledAsync();\n\n /// \n /// Checks if OneDrive is installed.\n /// \n /// True if OneDrive is installed; otherwise, false.\n Task IsOneDriveInstalledAsync();\n\n /// \n /// Gets the installation status of an item.\n /// \n /// The item to check.\n /// True if the item is installed; otherwise, false.\n Task GetItemInstallStatusAsync(IInstallableItem item);\n\n /// \n /// Gets the installation status of multiple items by package ID.\n /// \n /// The package IDs to check.\n /// A dictionary mapping package IDs to installation status.\n Task> GetBatchInstallStatusAsync(IEnumerable packageIds);\n\n /// \n /// Gets detailed installation status of an app.\n /// \n /// The app ID to check.\n /// The detailed installation status.\n Task GetInstallStatusAsync(string appId);\n\n /// \n /// Refreshes the installation status of multiple items.\n /// \n /// The items to refresh.\n /// A task representing the asynchronous operation.\n Task RefreshInstallationStatusAsync(IEnumerable items);\n\n /// \n /// Sets the installation status of an app.\n /// \n /// The app ID to update.\n /// The new installation status.\n /// True if the status was updated successfully; otherwise, false.\n Task SetInstallStatusAsync(string appId, InstallStatus status);\n\n /// \n /// Clears the status cache.\n /// \n void ClearStatusCache();\n\n #endregion\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/ExternalAppsCategoryViewModel.cs", "using System.Collections.ObjectModel;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.WPF.Features.SoftwareApps.Models;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n public partial class ExternalAppsCategoryViewModel : ObservableObject\n {\n [ObservableProperty]\n private string _name;\n\n [ObservableProperty]\n private ObservableCollection _apps = new();\n\n [ObservableProperty]\n private bool _isExpanded = true;\n\n public ExternalAppsCategoryViewModel(string name, ObservableCollection apps)\n {\n _name = name;\n _apps = apps;\n }\n\n public int AppCount => Apps.Count;\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScriptGenerationServiceExtensions.cs", "using Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Extension methods for registering script generation services.\n /// \n public static class ScriptGenerationServiceExtensions\n {\n /// \n /// Adds script generation services to the service collection.\n /// \n /// The service collection.\n /// The service collection.\n public static IServiceCollection AddScriptGenerationServices(this IServiceCollection services)\n {\n // Register script template provider\n services.AddSingleton();\n \n // Register script builder service\n services.AddSingleton();\n \n // Register script factory\n services.AddSingleton();\n \n // Register script generation service\n services.AddSingleton();\n \n // Register script content modifier\n services.AddSingleton();\n \n // Register composite script content modifier\n services.AddSingleton();\n \n // Register specialized script modifiers\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n \n // Register scheduled task service\n services.AddSingleton();\n \n // Register script update service\n services.AddSingleton();\n \n return services;\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IInstallationOrchestrator.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Orchestrates high-level installation and removal operations across different types of items.\n /// \n /// \n /// This is a higher-level service that coordinates operations across different specific services.\n /// \n public interface IInstallationOrchestrator\n {\n /// \n /// Installs an installable item based on its type.\n /// \n /// The item to install.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the asynchronous operation.\n Task InstallAsync(\n IInstallableItem item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Removes an installable item based on its type.\n /// \n /// The item to remove.\n /// A task representing the asynchronous operation.\n Task RemoveAsync(IInstallableItem item);\n\n /// \n /// Installs multiple items in batch.\n /// \n /// The items to install.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the asynchronous operation.\n Task InstallBatchAsync(\n IEnumerable items,\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Removes multiple items in batch.\n /// \n /// The items to remove.\n /// A list of results indicating success or failure for each item.\n Task> RemoveBatchAsync(\n IEnumerable items);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IPowerShellExecutionService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides functionality for executing PowerShell scripts.\n /// \n public interface IPowerShellExecutionService\n {\n /// \n /// Executes a PowerShell script.\n /// \n /// The script to execute.\n /// The progress reporter.\n /// The cancellation token.\n /// The output of the script.\n Task ExecuteScriptAsync(\n string script,\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Executes a PowerShell script file.\n /// \n /// The path to the script file.\n /// The arguments to pass to the script.\n /// The progress reporter.\n /// The cancellation token.\n /// The output of the script.\n Task ExecuteScriptFileAsync(\n string scriptPath,\n string arguments = \"\",\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToReinstallableTextConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Converters\n{\n /// \n /// Converts a boolean value indicating whether an item can be reinstalled to a descriptive text.\n /// \n public class BooleanToReinstallableTextConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (bool)value ? \"Is Installable\" : \"Is Not Installable\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Models/LinkedRegistrySettingWithValue.cs", "using System;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Models\n{\n /// \n /// Wrapper class for RegistrySetting that includes the current value.\n /// Used for displaying registry settings with their current values in tooltips.\n /// \n public class LinkedRegistrySettingWithValue\n {\n /// \n /// Gets the underlying registry setting.\n /// \n public RegistrySetting Setting { get; }\n\n /// \n /// Gets or sets the current value of the registry setting.\n /// \n public object? CurrentValue { get; set; }\n\n /// \n /// Creates a new instance of the LinkedRegistrySettingWithValue class.\n /// \n /// The registry setting.\n /// The current value of the registry setting.\n public LinkedRegistrySettingWithValue(RegistrySetting setting, object? currentValue)\n {\n Setting = setting ?? throw new ArgumentNullException(nameof(setting));\n CurrentValue = currentValue;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IWinGetInstallationService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces;\n\n/// \n/// Interface for services that handle WinGet-related installation operations.\n/// \npublic interface IWinGetInstallationService\n{\n /// \n /// Installs a package using WinGet.\n /// \n /// The package name or ID to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// The display name of the package for progress reporting.\n /// True if installation was successful; otherwise, false.\n Task InstallWithWingetAsync(\n string packageName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default,\n string? displayName = null);\n\n /// \n /// Installs WinGet if not already installed.\n /// \n Task InstallWinGetAsync(IProgress? progress = null);\n\n /// \n /// Checks if WinGet is installed on the system.\n /// \n /// True if WinGet is installed, false otherwise\n Task IsWinGetInstalledAsync();\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/ICustomAppInstallationService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces;\n\n/// \n/// Interface for services that handle custom application installations.\n/// \npublic interface ICustomAppInstallationService\n{\n /// \n /// Installs a custom application.\n /// \n /// Information about the application to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// True if installation was successful; otherwise, false.\n Task InstallCustomAppAsync(\n AppInfo appInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Checks if internet connection is available.\n /// \n /// True if internet connection is available; otherwise, false.\n Task CheckInternetConnectionAsync();\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IMessengerService.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides functionality for messaging between components.\n /// \n public interface IMessengerService\n {\n /// \n /// Sends a message of the specified type.\n /// \n /// The type of the message to send.\n /// The message to send.\n void Send(TMessage message);\n\n /// \n /// Registers a recipient for messages of the specified type.\n /// \n /// The type of message to register for.\n /// The recipient object.\n /// The action to perform when a message is received.\n void Register(object recipient, Action action);\n\n /// \n /// Unregisters a recipient from receiving messages.\n /// \n /// The recipient to unregister.\n void Unregister(object recipient);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/WindowsPackageModels.cs", "using Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\npublic record WindowsPackage\n{\n public required string Category { get; init; }\n public required string FriendlyName { get; init; }\n public required string PackageName { get; init; }\n public WindowsAppType AppType { get; init; }\n public IReadOnlyList? SubPackages { get; init; }\n public string? Description { get; init; }\n public IReadOnlyList? RegistrySettings { get; init; }\n public bool IsInstalled { get; init; }\n}\n\npublic record LegacyCapability\n{\n public required string FriendlyName { get; init; }\n public required string Name { get; init; }\n public bool IsInstalled { get; init; }\n}\n\npublic record WindowsService\n{\n public required string Name { get; init; }\n public required string DisplayName { get; init; }\n public required string Description { get; init; }\n public required ServiceStartupType RecommendedState { get; init; }\n public ServiceStartupType? CurrentState { get; init; }\n}"], ["/Winhance/src/Winhance.Core/Features/Customize/Interfaces/IThemeService.cs", "using System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.Customize.Interfaces\n{\n /// \n /// Interface for theme-related operations.\n /// \n public interface IThemeService\n {\n /// \n /// Checks if dark mode is enabled.\n /// \n /// True if dark mode is enabled; otherwise, false.\n bool IsDarkModeEnabled();\n\n /// \n /// Sets the theme mode.\n /// \n /// True to enable dark mode; false to enable light mode.\n /// True if the operation succeeded; otherwise, false.\n bool SetThemeMode(bool isDarkMode);\n\n /// \n /// Sets the theme mode and optionally changes the wallpaper.\n /// \n /// True to enable dark mode; false to enable light mode.\n /// True to change the wallpaper; otherwise, false.\n /// A task representing the asynchronous operation.\n Task ApplyThemeAsync(bool isDarkMode, bool changeWallpaper);\n\n /// \n /// Gets the name of the current theme.\n /// \n /// The name of the current theme (\"Light Mode\" or \"Dark Mode\").\n string GetCurrentThemeName();\n\n /// \n /// Refreshes the Windows GUI to apply theme changes.\n /// \n /// True to restart Explorer; otherwise, false.\n /// A task representing the asynchronous operation.\n Task RefreshGUIAsync(bool restartExplorer);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Customize/Interfaces/IWallpaperService.cs", "using System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.Customize.Interfaces\n{\n /// \n /// Interface for wallpaper operations.\n /// \n public interface IWallpaperService\n {\n /// \n /// Sets the desktop wallpaper.\n /// \n /// The path to the wallpaper image.\n /// A task representing the asynchronous operation.\n Task SetWallpaperAsync(string wallpaperPath);\n\n /// \n /// Sets the default wallpaper based on Windows version and theme.\n /// \n /// Whether the system is Windows 11.\n /// Whether dark mode is enabled.\n /// A task representing the asynchronous operation.\n Task SetDefaultWallpaperAsync(bool isWindows11, bool isDarkMode);\n\n /// \n /// Gets the default wallpaper path based on Windows version and theme.\n /// \n /// Whether the system is Windows 11.\n /// Whether dark mode is enabled.\n /// The path to the default wallpaper.\n string GetDefaultWallpaperPath(bool isWindows11, bool isDarkMode);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IDependencyManager.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Defines methods for managing dependencies between settings.\n /// \n public interface IDependencyManager\n {\n /// \n /// Determines if a setting can be enabled based on its dependencies.\n /// \n /// The ID of the setting to check.\n /// All available settings that might be dependencies.\n /// True if the setting can be enabled; otherwise, false.\n bool CanEnableSetting(string settingId, IEnumerable allSettings);\n \n /// \n /// Handles the disabling of a setting by automatically disabling any dependent settings.\n /// \n /// The ID of the setting that was disabled.\n /// All available settings that might depend on the disabled setting.\n void HandleSettingDisabled(string settingId, IEnumerable allSettings);\n \n /// \n /// Handles the enabling of a setting by automatically enabling any required settings.\n /// \n /// The ID of the setting that is being enabled.\n /// All available settings that might be required by the enabled setting.\n /// True if all required settings were enabled successfully; otherwise, false.\n bool HandleSettingEnabled(string settingId, IEnumerable allSettings);\n\n /// \n /// Gets a list of unsatisfied dependencies for a setting.\n /// \n /// The ID of the setting to check.\n /// All available settings that might be dependencies.\n /// A list of settings that are required by the specified setting but are not enabled.\n List GetUnsatisfiedDependencies(string settingId, IEnumerable allSettings);\n\n /// \n /// Enables all dependencies in the provided list.\n /// \n /// The dependencies to enable.\n /// True if all dependencies were enabled successfully; otherwise, false.\n bool EnableDependencies(IEnumerable dependencies);\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/RegistryScriptHelper.cs", "using System;\nusing Microsoft.Win32;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\n/// \n/// Provides helper methods for working with registry scripts.\n/// \npublic static class RegistryScriptHelper\n{\n /// \n /// Converts a RegistryValueKind to the corresponding reg.exe type string.\n /// \n /// The registry value kind.\n /// The reg.exe type string.\n public static string GetRegTypeString(RegistryValueKind valueKind)\n {\n return valueKind switch\n {\n RegistryValueKind.String => \"REG_SZ\",\n RegistryValueKind.ExpandString => \"REG_EXPAND_SZ\",\n RegistryValueKind.Binary => \"REG_BINARY\",\n RegistryValueKind.DWord => \"REG_DWORD\",\n RegistryValueKind.MultiString => \"REG_MULTI_SZ\",\n RegistryValueKind.QWord => \"REG_QWORD\",\n _ => \"REG_SZ\"\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppInstallationService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for installing Windows applications.\n /// \n public interface IAppInstallationService : IInstallationService\n {\n /// \n /// Installs an application.\n /// \n /// The application to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n Task> InstallAppAsync(AppInfo app, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if an application can be installed.\n /// \n /// The application to check.\n /// An operation result indicating if the application can be installed, with error details if not.\n Task> CanInstallAppAsync(AppInfo app);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/OptimizationEnums.cs", "namespace Winhance.Core.Features.Common.Enums;\n\npublic enum OptimizationCategory\n{\n Privacy,\n Gaming,\n Updates,\n Performance,\n GamingandPerformance,\n Personalization,\n Taskbar,\n StartMenu,\n Explorer,\n Notifications,\n Sound,\n Accessibility,\n Search,\n Services,\n Power\n}\n\npublic enum WindowsAppType\n{\n AppX,\n Capability,\n Special // For Edge, OneDrive, etc.\n}\n\npublic enum ServiceStartupType\n{\n Automatic = 2,\n Manual = 3,\n Disabled = 4\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScriptModifierServiceExtensions.cs", "using Microsoft.Extensions.DependencyInjection;\nusing System;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Extension methods for registering script modifier services with the dependency injection container.\n /// \n public static class ScriptModifierServiceExtensions\n {\n /// \n /// Adds script modifier services to the specified .\n /// \n /// The to add the services to.\n /// The so that additional calls can be chained.\n public static IServiceCollection AddScriptModifierServices(this IServiceCollection services)\n {\n // Register the specialized modifiers\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n\n // Register the composite modifier as the implementation of IScriptContentModifier\n services.AddTransient();\n\n return services;\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Interfaces/IInstallationVerifier.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces\n{\n /// \n /// Defines the contract for verifying software installations.\n /// \n public interface IInstallationVerifier\n {\n /// \n /// Verifies if a package is installed.\n /// \n /// The ID of the package to verify.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the verification result.\n Task VerifyInstallationAsync(\n string packageId, \n CancellationToken cancellationToken = default);\n\n /// \n /// Verifies if a package is installed with the specified version.\n /// \n /// The ID of the package to verify.\n /// The expected version of the package.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the verification result.\n Task VerifyInstallationAsync(\n string packageId, \n string version, \n CancellationToken cancellationToken = default);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IApplicationCloseService.cs", "using System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for handling application close functionality\n /// \n public interface IApplicationCloseService\n {\n /// \n /// Shows the support dialog if needed and handles the application close process\n /// \n /// A task representing the asynchronous operation\n Task CloseApplicationWithSupportDialogAsync();\n \n /// \n /// Saves the \"Don't show support dialog\" preference\n /// \n /// Whether to show the support dialog in the future\n /// A task representing the asynchronous operation\n Task SaveDontShowSupportPreferenceAsync(bool dontShow);\n \n /// \n /// Checks if the support dialog should be shown based on user preferences\n /// \n /// True if the dialog should be shown, false otherwise\n Task ShouldShowSupportDialogAsync();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/UacLevel.cs", "namespace Winhance.Core.Models.Enums\n{\n /// \n /// Represents User Account Control (UAC) levels in Windows.\n /// \n public enum UacLevel\n {\n /// \n /// Never notify the user when programs try to install software or make changes to the computer.\n /// \n NeverNotify = 0,\n\n /// \n /// Notify the user only when programs try to make changes to the computer, without dimming the desktop.\n /// \n NotifyNoDesktopDim = 1,\n\n /// \n /// Notify the user only when programs try to make changes to the computer (default).\n /// \n NotifyChangesOnly = 2,\n\n /// \n /// Always notify the user when programs try to install software or make changes to the computer\n /// or when the user makes changes to Windows settings.\n /// \n AlwaysNotify = 3,\n\n /// \n /// Custom UAC setting that doesn't match any of the standard Windows GUI options.\n /// This is used when the registry contains values that don't match the standard options.\n /// \n Custom = 99,\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Models/ApplicationSettingGroup.cs", "using CommunityToolkit.Mvvm.ComponentModel;\nusing System.Collections.ObjectModel;\n\nnamespace Winhance.WPF.Features.Common.Models\n{\n /// \n /// Base class for application setting groups used in both Optimization and Customization features.\n /// \n public partial class ApplicationSettingGroup : ObservableObject\n {\n [ObservableProperty]\n private string _name = string.Empty;\n\n [ObservableProperty]\n private string _description = string.Empty;\n\n [ObservableProperty]\n private bool _isSelected;\n \n [ObservableProperty]\n private bool _isGroupHeader;\n \n [ObservableProperty]\n private string _groupName = string.Empty;\n \n [ObservableProperty]\n private bool _isVisible = true;\n \n /// \n /// Gets the collection of settings in this group.\n /// \n public ObservableCollection Settings { get; } = new();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IConfigurationService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Defines methods for saving and loading application configuration files.\n /// \n public interface IConfigurationService\n {\n /// \n /// Saves a configuration file containing the selected items.\n /// \n /// The type of items to save.\n /// The collection of items to save.\n /// The type of configuration being saved.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task SaveConfigurationAsync(IEnumerable items, string configType);\n\n /// \n /// Loads a configuration file and returns the configuration file.\n /// \n /// The type of configuration being loaded.\n /// A task representing the asynchronous operation. Returns the configuration file if successful, null otherwise.\n Task LoadConfigurationAsync(string configType);\n\n /// \n /// Saves a unified configuration file containing settings for multiple parts of the application.\n /// \n /// The unified configuration to save.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile unifiedConfig);\n\n /// \n /// Loads a unified configuration file.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file if successful, null otherwise.\n Task LoadUnifiedConfigurationAsync();\n\n /// \n /// Creates a unified configuration file from individual configuration sections.\n /// \n /// Dictionary of section names and their corresponding configuration items.\n /// List of section names to include in the unified configuration.\n /// A unified configuration file.\n UnifiedConfigurationFile CreateUnifiedConfiguration(Dictionary> sections, IEnumerable includedSections);\n\n /// \n /// Extracts a specific section from a unified configuration file.\n /// \n /// The unified configuration file.\n /// The name of the section to extract.\n /// A configuration file containing only the specified section.\n ConfigurationFile ExtractSectionFromUnifiedConfiguration(UnifiedConfigurationFile unifiedConfig, string sectionName);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Exceptions/InstallationStatusException.cs", "using System;\n\nnamespace Winhance.Core.Features.SoftwareApps.Exceptions\n{\n /// \n /// Exception thrown when there is an error with installation status operations.\n /// \n public class InstallationStatusException : Exception\n {\n /// \n /// Initializes a new instance of the class.\n /// \n public InstallationStatusException() : base()\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message.\n /// \n /// The message that describes the error.\n public InstallationStatusException(string message) : base(message)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message\n /// and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception.\n public InstallationStatusException(string message, Exception innerException) : base(message, innerException)\n {\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IFeatureInstallationService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for installing Windows optional features.\n /// \n public interface IFeatureInstallationService : IInstallationService\n {\n /// \n /// Installs a feature.\n /// \n /// The feature to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n Task> InstallFeatureAsync(FeatureInfo feature, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if a feature can be installed.\n /// \n /// The feature to check.\n /// An operation result indicating if the feature can be installed, with error details if not.\n Task> CanInstallFeatureAsync(FeatureInfo feature);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/ICapabilityInstallationService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for installing Windows capabilities.\n /// \n public interface ICapabilityInstallationService : IInstallationService\n {\n /// \n /// Installs a capability.\n /// \n /// The capability to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n Task> InstallCapabilityAsync(CapabilityInfo capability, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if a capability can be installed.\n /// \n /// The capability to check.\n /// An operation result indicating if the capability can be installed, with error details if not.\n Task> CanInstallCapabilityAsync(CapabilityInfo capability);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IScriptFactory.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Factory for creating script objects.\n /// \n public interface IScriptFactory\n {\n /// \n /// Creates a batch removal script.\n /// \n /// The names of the applications to remove.\n /// Dictionary mapping app names to registry settings.\n /// Dictionary mapping app names to their subpackages.\n /// A removal script object.\n RemovalScript CreateBatchRemovalScript(\n List appNames,\n Dictionary> appsWithRegistry,\n Dictionary appSubPackages = null);\n\n /// \n /// Creates a single app removal script.\n /// \n /// The app to remove.\n /// A removal script object.\n RemovalScript CreateSingleAppRemovalScript(AppInfo app);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/CustomizationSetting.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Enums;\n\nnamespace Winhance.Core.Features.Customize.Models\n{\n /// \n /// Represents a setting that customizes the system by modifying registry values.\n /// \n public record CustomizationSetting : ApplicationSetting\n {\n /// \n /// Gets or sets the customization category for this setting.\n /// \n public required CustomizationCategory Category { get; init; }\n\n /// \n /// Gets or sets the linked settings for this setting.\n /// This allows grouping multiple settings together under a parent setting.\n /// \n public List LinkedSettings { get; init; } = new List();\n\n /// \n /// Gets or sets a value indicating whether this setting is only applicable to Windows 11.\n /// \n public bool IsWindows11Only { get; init; }\n\n /// \n /// Gets or sets a value indicating whether this setting is only applicable to Windows 10.\n /// \n public bool IsWindows10Only { get; init; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/ISpecialAppHandlerService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Provides functionality for handling special applications that require custom removal procedures.\n /// \n public interface ISpecialAppHandlerService\n {\n /// \n /// Gets all registered special app handlers.\n /// \n /// A collection of special app handlers.\n IEnumerable GetAllHandlers();\n\n /// \n /// Gets a special app handler by its type.\n /// \n /// The type of handler to retrieve.\n /// The requested special app handler, or null if not found.\n SpecialAppHandler? GetHandler(string handlerType);\n\n /// \n /// Removes Microsoft Edge.\n /// \n /// True if the operation succeeded; otherwise, false.\n Task RemoveEdgeAsync();\n\n /// \n /// Removes OneDrive.\n /// \n /// True if the operation succeeded; otherwise, false.\n Task RemoveOneDriveAsync();\n\n /// \n /// Removes OneNote.\n /// \n /// True if the operation succeeded; otherwise, false.\n Task RemoveOneNoteAsync();\n\n /// \n /// Removes a special application using its registered handler.\n /// \n /// The type of handler to use.\n /// True if the operation succeeded; otherwise, false.\n Task RemoveSpecialAppAsync(string handlerType);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IViewModel.cs", "namespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Base interface for all view models.\n /// \n public interface IViewModel\n {\n /// \n /// Called when navigation to the view model has occurred.\n /// \n /// The navigation parameter.\n void OnNavigatedTo(object? parameter = null);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/ConfigurationFile.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents a configuration file that stores application settings.\n /// \n public class ConfigurationFile\n {\n /// \n /// Gets or sets the type of configuration (e.g., \"ExternalApps\", \"WindowsApps\").\n /// \n public string ConfigType { get; set; }\n\n /// \n /// Gets or sets the version of the configuration file format.\n /// \n public string Version { get; set; } = \"1.0\";\n\n /// \n /// Gets or sets the date and time when the configuration file was created.\n /// \n public DateTime CreatedAt { get; set; } = DateTime.UtcNow;\n\n /// \n /// Gets or sets the collection of configuration items.\n /// \n public List Items { get; set; } = new List();\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Messages/ResetExpansionStateMessage.cs", "using System;\n\nnamespace Winhance.WPF.Features.Common.Messages\n{\n /// \n /// Message to notify the view to reset the expansion state of collapsible sections.\n /// \n public class ResetExpansionStateMessage\n {\n /// \n /// Gets the timestamp when the message was created.\n /// \n public DateTime Timestamp { get; } = DateTime.Now;\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/InstalledStatusToTextConverter.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Converters;\n\npublic class InstalledStatusToTextConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (bool)value ? \"Installed\" : \"Not Installed\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ISettingItem.cs", "using System.Collections.Generic;\nusing System.Windows.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Defines the common properties that all setting items should have.\n /// \n public interface ISettingItem\n {\n /// \n /// Gets or sets the unique identifier for the setting.\n /// \n string Id { get; set; }\n\n /// \n /// Gets or sets the name of the setting.\n /// \n string Name { get; set; }\n\n /// \n /// Gets or sets the description of the setting.\n /// \n string Description { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the setting is selected.\n /// \n bool IsSelected { get; set; }\n\n /// \n /// Gets or sets the group name that this setting belongs to.\n /// \n string GroupName { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the setting is visible in the UI.\n /// \n bool IsVisible { get; set; }\n\n /// \n /// Gets or sets the type of control used for this setting.\n /// \n ControlType ControlType { get; set; }\n\n /// \n /// Gets or sets the dependencies for this setting.\n /// \n List Dependencies { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the setting is being updated from code.\n /// \n bool IsUpdatingFromCode { get; set; }\n\n /// \n /// Gets the command to apply the setting.\n /// \n ICommand ApplySettingCommand { get; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ICommandService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for executing system commands related to optimizations.\n /// \n public interface ICommandService\n {\n /// \n /// Executes the specified command with elevated privileges if required.\n /// \n /// The command to execute.\n /// Whether the command requires elevation.\n /// The result of the command execution.\n Task<(bool Success, string Output, string Error)> ExecuteCommandAsync(string command, bool requiresElevation = true);\n \n /// \n /// Applies the command settings based on the enabled state.\n /// \n /// The command settings to apply.\n /// Whether the optimization is enabled.\n /// A result indicating success or failure with details.\n Task<(bool Success, string Message)> ApplyCommandSettingsAsync(IEnumerable settings, bool isEnabled);\n \n /// \n /// Gets the current state of a command setting.\n /// \n /// The command setting to check.\n /// True if the setting is in its enabled state, false otherwise.\n Task IsCommandSettingEnabledAsync(CommandSetting setting);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/CapabilityInfo.cs", "// This contains the model for Windows capability information\n\nusing System;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models\n{\n /// \n /// Represents information about a Windows capability.\n /// \n public class CapabilityInfo : IInstallableItem\n {\n public string PackageId => PackageName;\n public string DisplayName => Name;\n public InstallItemType ItemType => InstallItemType.Capability;\n public bool RequiresRestart { get; set; }\n\n /// \n /// Gets or sets the name of the capability.\n /// \n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description of the capability.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the package name of the capability.\n /// This is the identifier used by Windows to reference the capability.\n /// \n public string PackageName { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the category of the capability.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether the capability is installed.\n /// \n public bool IsInstalled { get; set; }\n\n /// \n /// Gets or sets the registry settings associated with this capability.\n /// \n public AppRegistrySetting[]? RegistrySettings { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the capability is protected by the system.\n /// \n public bool IsSystemProtected { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the capability can be reenabled after disabling.\n /// \n public bool CanBeReenabled { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether the capability is selected for installation or removal.\n /// \n public bool IsSelected { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/FeatureInfo.cs", "// This contains the model for Windows optional feature information\n\nusing System;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models\n{\n /// \n /// Represents information about a Windows optional feature.\n /// \n public class FeatureInfo : IInstallableItem\n {\n public string PackageId => PackageName;\n public string DisplayName => Name;\n public InstallItemType ItemType => InstallItemType.Feature;\n public bool RequiresRestart => RequiresReboot;\n\n /// \n /// Gets or sets the name of the feature.\n /// \n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description of the feature.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the package name of the feature.\n /// This is the identifier used by Windows to reference the feature.\n /// \n public string PackageName { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the category of the feature.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether the feature is installed.\n /// \n public bool IsInstalled { get; set; }\n\n /// \n /// Gets or sets the registry settings associated with this feature.\n /// \n public AppRegistrySetting[]? RegistrySettings { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the feature is protected by the system.\n /// \n public bool IsSystemProtected { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the feature requires a reboot after installation or removal.\n /// \n public bool RequiresReboot { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the feature can be reenabled after disabling.\n /// \n public bool CanBeReenabled { get; set; } = true;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IScriptBuilderService.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for building script content.\n /// \n public interface IScriptBuilderService\n {\n /// \n /// Builds a script for removing packages.\n /// \n /// The names of the packages to remove.\n /// The script content.\n string BuildPackageRemovalScript(IEnumerable packageNames);\n\n /// \n /// Builds a script for removing capabilities.\n /// \n /// The names of the capabilities to remove.\n /// The script content.\n string BuildCapabilityRemovalScript(IEnumerable capabilityNames);\n\n /// \n /// Builds a script for removing features.\n /// \n /// The names of the features to remove.\n /// The script content.\n string BuildFeatureRemovalScript(IEnumerable featureNames);\n\n /// \n /// Builds a script for registry operations.\n /// \n /// Dictionary mapping app names to registry settings.\n /// The script content.\n string BuildRegistryScript(Dictionary> registrySettings);\n\n /// \n /// Builds a complete removal script.\n /// \n /// The names of the packages to remove.\n /// The names of the capabilities to remove.\n /// The names of the features to remove.\n /// Dictionary mapping app names to registry settings.\n /// Dictionary mapping app names to their subpackages.\n /// The script content.\n string BuildCompleteRemovalScript(\n IEnumerable packageNames,\n IEnumerable capabilityNames,\n IEnumerable featureNames,\n Dictionary> registrySettings,\n Dictionary subPackages);\n\n /// \n /// Builds a script for removing a single app.\n /// \n /// The app to remove.\n /// The script content.\n string BuildSingleAppRemovalScript(AppInfo app);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppRemovalService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for removing Windows applications.\n /// \n public interface IAppRemovalService\n {\n /// \n /// Removes an application.\n /// \n /// The application to remove.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n Task> RemoveAppAsync(AppInfo app, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Generates a removal script for an application.\n /// \n /// The application to generate a removal script for.\n /// An operation result containing the removal script or error details.\n Task> GenerateRemovalScriptAsync(AppInfo app);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IFeatureRemovalService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for removing Windows optional features.\n /// \n public interface IFeatureRemovalService\n {\n /// \n /// Removes a feature.\n /// \n /// The feature to remove.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// True if the removal was successful; otherwise, false.\n Task RemoveFeatureAsync(FeatureInfo feature, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if a feature can be removed.\n /// \n /// The feature to check.\n /// True if the feature can be removed; otherwise, false.\n Task CanRemoveFeatureAsync(FeatureInfo feature);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppLoadingService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for loading application information and status.\n /// \n public interface IAppLoadingService\n {\n /// \n /// Loads applications and their installation status.\n /// \n /// An operation result containing a collection of applications with their installation status or error details.\n Task>> LoadAppsAsync();\n\n /// \n /// Refreshes the installation status of applications.\n /// \n /// The applications to refresh.\n /// An operation result indicating success or failure with error details.\n Task> RefreshInstallationStatusAsync(IEnumerable apps);\n\n /// \n /// Gets the installation status for an app by ID.\n /// \n /// The app ID.\n /// An operation result containing the installation status or error details.\n Task> GetInstallStatusAsync(string appId);\n\n /// \n /// Sets the installation status for an app.\n /// \n /// The app ID.\n /// The new status.\n /// An operation result indicating success or failure with error details.\n Task> SetInstallStatusAsync(string appId, InstallStatus status);\n\n /// \n /// Loads Windows capabilities.\n /// \n /// A collection of capability information.\n Task> LoadCapabilitiesAsync();\n\n /// \n /// Gets the installation status for an installable item.\n /// \n /// The installable item.\n /// True if the item is installed, false otherwise.\n Task GetItemInstallStatusAsync(IInstallableItem item);\n\n /// \n /// Gets the installation status for multiple package IDs.\n /// \n /// The package IDs to check.\n /// A dictionary mapping package IDs to their installation status.\n Task> GetBatchInstallStatusAsync(IEnumerable packageIds);\n\n /// \n /// Clears the status cache.\n /// \n void ClearStatusCache();\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/OptimizationSetting.cs", "using Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models\n{\n /// \n /// Represents a setting that optimizes the system by modifying registry values.\n /// \n public record OptimizationSetting : ApplicationSetting\n {\n /// \n /// Gets or sets the optimization category for this setting.\n /// \n public required OptimizationCategory Category { get; init; }\n \n /// \n /// Gets or sets custom properties for this setting.\n /// This can be used to store additional data specific to certain optimization types,\n /// such as PowerCfg settings.\n /// \n public Dictionary CustomProperties { get; init; } = new Dictionary();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/ICapabilityRemovalService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for removing Windows capabilities.\n /// \n public interface ICapabilityRemovalService\n {\n /// \n /// Removes a capability.\n /// \n /// The capability to remove.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// True if the removal was successful; otherwise, false.\n Task RemoveCapabilityAsync(CapabilityInfo capability, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if a capability can be removed.\n /// \n /// The capability to check.\n /// True if the capability can be removed; otherwise, false.\n Task CanRemoveCapabilityAsync(CapabilityInfo capability);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/RegistryTestResult.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents the result of a registry value test.\n /// \n public class RegistryTestResult\n {\n /// \n /// Gets or sets the registry key path.\n /// \n public string KeyPath { get; set; }\n\n /// \n /// Gets or sets the registry value name.\n /// \n public string ValueName { get; set; }\n\n /// \n /// Gets or sets the expected value.\n /// \n public object ExpectedValue { get; set; }\n\n /// \n /// Gets or sets the actual value.\n /// \n public object ActualValue { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the test was successful.\n /// \n public bool IsSuccess { get; set; }\n\n /// \n /// Gets or sets the test result message.\n /// \n public string Message { get; set; }\n\n /// \n /// Gets or sets the category of the registry setting.\n /// \n public string Category { get; set; }\n\n /// \n /// Gets or sets the description of the registry setting.\n /// \n public string Description { get; set; }\n\n /// \n /// Gets a formatted string representation of the test result.\n /// \n /// A formatted string representation of the test result.\n public override string ToString()\n {\n return $\"{(IsSuccess ? \"✓\" : \"✗\")} {KeyPath}\\\\{ValueName}: {Message}\";\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IFileSystemService.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Interfaces.Services\n{\n /// \n /// Provides access to the file system.\n /// \n public interface IFileSystemService\n {\n /// \n /// Determines whether the specified file exists.\n /// \n /// The file to check.\n /// True if the file exists; otherwise, false.\n bool FileExists(string path);\n\n /// \n /// Determines whether the specified directory exists.\n /// \n /// The directory to check.\n /// True if the directory exists; otherwise, false.\n bool DirectoryExists(string path);\n\n /// \n /// Creates a directory if it doesn't already exist.\n /// \n /// The directory to create.\n /// True if the directory was created or already exists; otherwise, false.\n bool CreateDirectory(string path);\n\n /// \n /// Deletes a file if it exists.\n /// \n /// The file to delete.\n /// True if the file was deleted or didn't exist; otherwise, false.\n bool DeleteFile(string path);\n\n /// \n /// Reads all text from a file.\n /// \n /// The file to read.\n /// The contents of the file.\n string ReadAllText(string path);\n\n /// \n /// Writes all text to a file.\n /// \n /// The file to write to.\n /// The text to write.\n /// True if the text was written successfully; otherwise, false.\n bool WriteAllText(string path, string contents);\n\n /// \n /// Gets all files in a directory that match the specified pattern.\n /// \n /// The directory to search.\n /// The search pattern.\n /// Whether to search subdirectories.\n /// A collection of file paths.\n IEnumerable GetFiles(string path, string pattern, bool recursive);\n\n /// \n /// Gets all directories in a directory that match the specified pattern.\n /// \n /// The directory to search.\n /// The search pattern.\n /// Whether to search subdirectories.\n /// A collection of directory paths.\n IEnumerable GetDirectories(string path, string pattern, bool recursive);\n\n /// \n /// Gets the path to a special folder, such as AppData, ProgramFiles, etc.\n /// \n /// The name of the special folder.\n /// The path to the special folder.\n string GetSpecialFolderPath(string specialFolder);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IVersionService.cs", "using System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n public interface IVersionService\n {\n /// \n /// Gets the current application version\n /// \n VersionInfo GetCurrentVersion();\n \n /// \n /// Checks if an update is available\n /// \n /// A task that resolves to true if an update is available, false otherwise\n Task CheckForUpdateAsync();\n \n /// \n /// Downloads and launches the installer for the latest version\n /// \n /// A task that completes when the download is initiated\n Task DownloadAndInstallUpdateAsync();\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Converters;\n\npublic class BooleanToVisibilityConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (bool)value ? Visibility.Visible : Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (Visibility)value == Visibility.Visible;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/RefreshResult.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents the result of a refresh operation for installation statuses.\n /// \n public class RefreshResult\n {\n /// \n /// Gets or sets a value indicating whether the refresh operation was successful.\n /// \n public bool Success { get; set; }\n\n /// \n /// Gets or sets the error message if the refresh operation failed.\n /// \n public string? ErrorMessage { get; set; }\n\n /// \n /// Gets or sets the collection of app IDs that were successfully refreshed.\n /// \n public IEnumerable RefreshedAppIds { get; set; } = new List();\n\n /// \n /// Gets or sets the collection of app IDs that failed to refresh.\n /// \n public IEnumerable FailedAppIds { get; set; } = new List();\n\n /// \n /// Gets or sets the number of successfully refreshed apps.\n /// \n public int SuccessCount { get; set; }\n\n /// \n /// Gets or sets the number of failed refreshed apps.\n /// \n public int FailedCount { get; set; }\n\n /// \n /// Gets or sets the collection of errors.\n /// \n public Dictionary Errors { get; set; } = new Dictionary();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IScheduledTaskService.cs", "using System.Threading.Tasks;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for a service that manages scheduled tasks for script execution.\n /// \n public interface IScheduledTaskService\n {\n /// \n /// Registers a scheduled task to run the specified script.\n /// \n /// The script to register as a scheduled task.\n /// True if the task was registered successfully, false otherwise.\n Task RegisterScheduledTaskAsync(RemovalScript script);\n\n /// \n /// Unregisters a scheduled task with the specified name.\n /// \n /// The name of the task to unregister.\n /// True if the task was unregistered successfully, false otherwise.\n Task UnregisterScheduledTaskAsync(string taskName);\n\n /// \n /// Checks if a scheduled task with the specified name is registered.\n /// \n /// The name of the task to check.\n /// True if the task exists, false otherwise.\n Task IsTaskRegisteredAsync(string taskName);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppDiscoveryService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for discovering and retrieving information about installed applications.\n /// \n public interface IAppDiscoveryService\n {\n /// \n /// Gets all standard (built-in) applications.\n /// \n /// A collection of standard applications.\n Task> GetStandardAppsAsync();\n\n /// \n /// Gets all installable third-party applications.\n /// \n /// A collection of installable applications.\n Task> GetInstallableAppsAsync();\n\n /// \n /// Gets all available Windows capabilities.\n /// \n /// A collection of Windows capabilities.\n Task> GetCapabilitiesAsync();\n\n /// \n /// Gets all available Windows optional features.\n /// \n /// A collection of Windows optional features.\n Task> GetOptionalFeaturesAsync();\n\n /// \n /// Checks if Microsoft Edge is installed.\n /// \n /// True if Edge is installed; otherwise, false.\n Task IsEdgeInstalledAsync();\n\n /// \n /// Checks if OneDrive is installed.\n /// \n /// True if OneDrive is installed; otherwise, false.\n Task IsOneDriveInstalledAsync();\n\n /// \n /// Checks if OneNote is installed.\n /// \n /// True if OneNote is installed; otherwise, false.\n Task IsOneNoteInstalledAsync();\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Enums/InstallationErrorType.cs", "using System;\n\nnamespace Winhance.Core.Features.SoftwareApps.Enums\n{\n /// \n /// Defines the types of errors that can occur during installation operations.\n /// \n public enum InstallationErrorType\n {\n /// \n /// An unknown error occurred during installation.\n /// \n UnknownError,\n\n /// \n /// A network-related error occurred during installation.\n /// \n NetworkError,\n\n /// \n /// A permission-related error occurred during installation.\n /// \n PermissionError,\n\n /// \n /// The package was not found in the repositories.\n /// \n PackageNotFoundError,\n\n /// \n /// WinGet is not installed and could not be installed automatically.\n /// \n WinGetNotInstalledError,\n\n /// \n /// The package is already installed.\n /// \n AlreadyInstalledError,\n\n /// \n /// The installation was cancelled by the user.\n /// \n CancelledByUserError,\n\n /// \n /// The system is in a state that prevents installation.\n /// \n SystemStateError,\n\n /// \n /// The package is corrupted or invalid.\n /// \n PackageCorruptedError,\n\n /// \n /// The package dependencies could not be resolved.\n /// \n DependencyResolutionError\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/CommandSetting.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents a command-based setting that can be executed to enable or disable an optimization.\n /// \n public class CommandSetting\n {\n /// \n /// Gets or sets the unique identifier for this command setting.\n /// \n public string Id { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the category this command belongs to.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description of what this command does.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the command to execute when the setting is enabled.\n /// \n public string EnabledCommand { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the command to execute when the setting is disabled.\n /// \n public string DisabledCommand { get; set; } = string.Empty;\n\n /// \n /// Gets or sets whether this command requires elevation.\n /// \n public bool RequiresElevation { get; set; } = true;\n\n /// \n /// Gets or sets whether this is the primary command in a group.\n /// \n public bool IsPrimary { get; set; } = true;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IScriptDetectionService.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for detecting the presence of script files used by Winhance to remove applications.\n /// \n public interface IScriptDetectionService\n {\n /// \n /// Checks if any removal scripts are present.\n /// \n /// True if any removal scripts are present, false otherwise.\n bool AreRemovalScriptsPresent();\n \n /// \n /// Gets information about all active removal scripts.\n /// \n /// A collection of script information objects.\n IEnumerable GetActiveScripts();\n }\n \n /// \n /// Represents information about a script file.\n /// \n public class ScriptInfo\n {\n /// \n /// Gets or sets the name of the script file.\n /// \n public string Name { get; set; }\n \n /// \n /// Gets or sets the description of what the script does.\n /// \n public string Description { get; set; }\n \n /// \n /// Gets or sets the full path to the script file.\n /// \n public string FilePath { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Theme/MaterialSymbols.cs", "namespace Winhance.WPF.Theme\n{\n /// \n /// Contains constants for Material Symbols icon names.\n /// \n public static class MaterialSymbols\n {\n // Sync icons\n public const string Sync = \"sync\";\n public const string SyncProblem = \"sync_problem\";\n\n // Other commonly used icons\n public const string Check = \"check\";\n public const string Close = \"close\";\n public const string Info = \"info\";\n public const string Warning = \"warning\";\n public const string Error = \"error\";\n public const string Settings = \"settings\";\n public const string Add = \"add\";\n public const string Remove = \"remove\";\n public const string Edit = \"edit\";\n public const string Delete = \"delete\";\n public const string Search = \"search\";\n public const string Download = \"download\";\n public const string Upload = \"upload\";\n public const string Refresh = \"refresh\";\n public const string Save = \"save\";\n public const string Menu = \"menu\";\n public const string Home = \"home\";\n public const string Person = \"person\";\n public const string Help = \"help\";\n public const string ArrowBack = \"arrow_back\";\n public const string ArrowForward = \"arrow_forward\";\n public const string ArrowUpward = \"arrow_upward\";\n public const string ArrowDownward = \"arrow_downward\";\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/PowerShellProgressData.cs", "using Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents progress data from PowerShell operations.\n /// \n public class PowerShellProgressData\n {\n /// \n /// Gets or sets the percent complete value (0-100).\n /// \n public int? PercentComplete { get; set; }\n\n /// \n /// Gets or sets the activity description.\n /// \n public string Activity { get; set; }\n\n /// \n /// Gets or sets the status description.\n /// \n public string StatusDescription { get; set; }\n\n /// \n /// Gets or sets the current operation description.\n /// \n public string CurrentOperation { get; set; }\n\n /// \n /// Gets or sets the PowerShell stream type.\n /// \n public PowerShellStreamType StreamType { get; set; }\n\n /// \n /// Gets or sets the message content.\n /// \n public string Message { get; set; }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ISettingsRegistry.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for a registry of settings.\n /// \n public interface ISettingsRegistry\n {\n /// \n /// Registers a setting in the registry.\n /// \n /// The setting to register.\n void RegisterSetting(ISettingItem setting);\n\n /// \n /// Gets a setting by its ID.\n /// \n /// The ID of the setting to get.\n /// The setting if found, otherwise null.\n ISettingItem? GetSettingById(string id);\n\n /// \n /// Gets all settings in the registry.\n /// \n /// A list of all settings.\n List GetAllSettings();\n\n /// \n /// Gets all settings of a specific type.\n /// \n /// The type of settings to get.\n /// A list of settings of the specified type.\n List GetSettingsByType() where T : ISettingItem;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IUacSettingsService.cs", "using System.Threading.Tasks;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Models.Enums;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for a service that manages UAC settings persistence.\n /// \n public interface IUacSettingsService\n {\n /// \n /// Saves custom UAC settings.\n /// \n /// The ConsentPromptBehaviorAdmin registry value.\n /// The PromptOnSecureDesktop registry value.\n /// A task representing the asynchronous operation.\n Task SaveCustomUacSettingsAsync(int consentPromptValue, int secureDesktopValue);\n\n /// \n /// Loads custom UAC settings.\n /// \n /// A CustomUacSettings object if settings exist, null otherwise.\n Task LoadCustomUacSettingsAsync();\n\n /// \n /// Checks if custom UAC settings exist.\n /// \n /// True if custom settings exist, false otherwise.\n Task HasCustomUacSettingsAsync();\n\n /// \n /// Gets custom UAC settings if they exist.\n /// \n /// The ConsentPromptBehaviorAdmin registry value.\n /// The PromptOnSecureDesktop registry value.\n /// True if custom settings were retrieved, false otherwise.\n bool TryGetCustomUacValues(out int consentPromptValue, out int secureDesktopValue);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/IViewModelRefresher.cs", "using System.Threading.Tasks;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Interface for a service that refreshes view models after configuration changes.\n /// \n public interface IViewModelRefresher\n {\n /// \n /// Refreshes a view model after configuration changes.\n /// \n /// The view model to refresh.\n /// A task representing the asynchronous operation.\n Task RefreshViewModelAsync(object viewModel);\n\n /// \n /// Refreshes a child view model after configuration changes.\n /// \n /// The child view model to refresh.\n /// A task representing the asynchronous operation.\n Task RefreshChildViewModelAsync(object childViewModel);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/ControlType.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Enums\n{\n /// \n /// Defines the type of control to use for a setting.\n /// \n public enum ControlType\n {\n /// \n /// A binary toggle (on/off) control.\n /// \n BinaryToggle,\n\n /// \n /// A three-state slider control.\n /// \n ThreeStateSlider,\n\n /// \n /// A combo box control for selecting from a list of options.\n /// \n ComboBox,\n\n /// \n /// A custom control.\n /// \n Custom,\n\n /// \n /// A slider control.\n /// \n Slider,\n\n /// \n /// A dropdown control.\n /// \n Dropdown,\n\n /// \n /// A color picker control.\n /// \n ColorPicker\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ISearchService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for services that handle search operations.\n /// \n public interface ISearchService\n {\n /// \n /// Filters a collection of items based on a search term.\n /// \n /// The type of items to filter.\n /// The collection of items to filter.\n /// The search term to filter by.\n /// A filtered collection of items that match the search term.\n IEnumerable FilterItems(IEnumerable items, string searchTerm) where T : ISearchable;\n\n /// \n /// Asynchronously filters a collection of items based on a search term.\n /// \n /// The type of items to filter.\n /// The collection of items to filter.\n /// The search term to filter by.\n /// A task that represents the asynchronous operation. The task result contains a filtered collection of items that match the search term.\n Task> FilterItemsAsync(IEnumerable items, string searchTerm) where T : ISearchable;\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ISectionConfigurationApplier.cs", "using System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Interface for services that apply configuration to specific sections.\n /// \n public interface ISectionConfigurationApplier\n {\n /// \n /// Gets the section name that this applier handles.\n /// \n string SectionName { get; }\n\n /// \n /// Applies the configuration to the section.\n /// \n /// The configuration file to apply.\n /// True if any items were updated, false otherwise.\n Task ApplyConfigAsync(ConfigurationFile configFile);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IConfigurationCoordinatorService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for coordinating configuration operations across multiple view models.\n /// \n public interface IConfigurationCoordinatorService\n {\n /// \n /// Creates a unified configuration file containing settings from all view models.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file.\n Task CreateUnifiedConfigurationAsync();\n\n /// \n /// Applies a unified configuration to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task ApplyUnifiedConfigurationAsync(UnifiedConfigurationFile config, IEnumerable selectedSections);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/IConfigurationPropertyUpdater.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Interface for a service that updates properties of configuration items.\n /// \n public interface IConfigurationPropertyUpdater\n {\n /// \n /// Updates properties of items based on the configuration.\n /// \n /// The items to update.\n /// The configuration file containing the updates.\n /// The number of items that were updated.\n Task UpdateItemsAsync(IEnumerable items, ConfigurationFile configFile);\n\n /// \n /// Updates additional properties of an item based on the configuration.\n /// \n /// The item to update.\n /// The configuration item containing the updates.\n /// True if any properties were updated, false otherwise.\n bool UpdateAdditionalProperties(object item, ConfigurationItem configItem);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IParameterSerializerService.cs", "namespace Winhance.Core.Interfaces.Services\n{\n /// \n /// Service for serializing and deserializing navigation parameters.\n /// \n public interface IParameterSerializerService\n {\n /// \n /// Serializes an object to a string.\n /// \n /// The object to serialize.\n /// The serialized string.\n string Serialize(object value);\n\n /// \n /// Deserializes a string to an object of the specified type.\n /// \n /// The type to deserialize to.\n /// The string to deserialize.\n /// The deserialized object.\n T Deserialize(string value);\n\n /// \n /// Deserializes a string to an object of the specified type.\n /// \n /// The type to deserialize to.\n /// The string to deserialize.\n /// The deserialized object.\n object Deserialize(System.Type type, string value);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IScriptTemplateProvider.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides templates for PowerShell scripts used in the application.\n /// \n public interface IScriptTemplateProvider\n {\n /// \n /// Gets the template for removing a package.\n /// \n /// The template string for package removal.\n string GetPackageRemovalTemplate();\n\n /// \n /// Gets the template for removing a capability.\n /// \n /// The template string for capability removal.\n string GetCapabilityRemovalTemplate();\n\n /// \n /// Gets the template for removing an optional feature.\n /// \n /// The template string for optional feature removal.\n string GetFeatureRemovalTemplate();\n\n /// \n /// Gets the template for a registry setting operation.\n /// \n /// True if this is a delete operation; false if it's a set operation.\n /// The template string for registry operations.\n string GetRegistrySettingTemplate(bool isDelete);\n\n /// \n /// Gets the header for a script.\n /// \n /// The name of the script.\n /// The header string for the script.\n string GetScriptHeader(string scriptName);\n\n /// \n /// Gets the footer for a script.\n /// \n /// The footer string for the script.\n string GetScriptFooter();\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Customize/Views/StartMenuCustomizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Customize.Views\n{\n /// \n /// Interaction logic for StartMenuCustomizationsView.xaml\n /// \n public partial class StartMenuCustomizationsView : UserControl\n {\n public StartMenuCustomizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Resources/Theme/IThemeManager.cs", "using System;\n\nnamespace Winhance.WPF.Features.Common.Resources.Theme\n{\n public interface IThemeManager : IDisposable\n {\n bool IsDarkTheme { get; set; }\n void ToggleTheme();\n void ApplyTheme();\n void LoadThemePreference();\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/CancellationReason.cs", "namespace Winhance.Core.Features.Common.Enums\n{\n /// \n /// Represents the reason for a cancellation operation.\n /// \n public enum CancellationReason\n {\n /// \n /// No cancellation occurred.\n /// \n None = 0,\n\n /// \n /// Cancellation was initiated by the user.\n /// \n UserCancelled = 1,\n\n /// \n /// Cancellation occurred due to internet connectivity issues.\n /// \n InternetConnectivityLost = 2,\n\n /// \n /// Cancellation occurred due to a system error.\n /// \n SystemError = 3\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/IConfigurationApplierService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Interface for the service that applies configuration settings to different view models.\n /// \n public interface IConfigurationApplierService\n {\n /// \n /// Applies configuration settings to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A dictionary of section names and their application result.\n Task> ApplySectionsAsync(UnifiedConfigurationFile config, IEnumerable selectedSections);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IOneDriveInstallationService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces;\n\n/// \n/// Interface for services that handle OneDrive installation.\n/// \npublic interface IOneDriveInstallationService\n{\n /// \n /// Installs OneDrive from the Microsoft download link.\n /// \n /// Optional progress reporter.\n /// Optional cancellation token.\n /// True if installation was successful; otherwise, false.\n Task InstallOneDriveAsync(\n IProgress? progress,\n CancellationToken cancellationToken);\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Exceptions/InstallationStatusException.cs", "using System;\n\nnamespace Winhance.Core.Models.Exceptions\n{\n public class InstallationStatusException : Exception\n {\n public InstallationStatusException(string message) : base(message)\n {\n }\n\n public InstallationStatusException(string message, Exception innerException) \n : base(message, innerException)\n {\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/AppModels.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\npublic enum AppInstallType\n{\n Store,\n WinGet,\n DirectDownload,\n Custom\n}\n\npublic enum TaskAction\n{\n Apply,\n Test,\n Rollback\n}\n\npublic record AppInstallConfig\n{\n public required string FriendlyName { get; init; }\n public required AppInstallType InstallType { get; init; }\n public string? PackageId { get; init; }\n public string? DownloadUrl { get; init; }\n public string? CustomInstallHandler { get; init; }\n public IDictionary? CustomProperties { get; init; }\n public bool IsInstalled { get; init; }\n}\n\npublic record InstallResult\n{\n public required bool Success { get; init; }\n public string? ErrorMessage { get; init; }\n public Exception? Exception { get; init; }\n}\n\npublic class RegistryTestResult\n{\n public string KeyPath { get; set; } = string.Empty;\n public string ValueName { get; set; } = string.Empty;\n public bool IsSuccess { get; set; }\n public object? ActualValue { get; set; }\n public object? ExpectedValue { get; set; }\n public string Message { get; set; } = string.Empty;\n public string Description { get; set; } = string.Empty;\n public string Category { get; set; } = string.Empty;\n}"], ["/Winhance/src/Winhance.Core/Features/UI/Interfaces/INotificationService.cs", "using System;\n\nnamespace Winhance.Core.Features.UI.Interfaces\n{\n /// \n /// Interface for notification services that can display toast notifications and other alerts.\n /// \n public interface INotificationService\n {\n /// \n /// Shows a toast notification.\n /// \n /// The title of the notification.\n /// The message content of the notification.\n /// The type of notification.\n void ShowToast(string title, string message, ToastType type);\n }\n\n /// \n /// Defines the types of toast notifications.\n /// \n public enum ToastType\n {\n /// \n /// Information notification.\n /// \n Information,\n\n /// \n /// Success notification.\n /// \n Success,\n\n /// \n /// Warning notification.\n /// \n Warning,\n\n /// \n /// Error notification.\n /// \n Error\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppVerificationService.cs", "using System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces;\n\n/// \n/// Interface for services that handle verification of application installations.\n/// \npublic interface IAppVerificationService\n{\n /// \n /// Verifies if an app is installed.\n /// \n /// The package name to verify.\n /// True if the app is installed; otherwise, false.\n Task VerifyAppInstallationAsync(string packageName);\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/UpdateOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for UpdateOptimizationsView.xaml\n /// \n public partial class UpdateOptimizationsView : UserControl\n {\n public UpdateOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/PowerOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for PowerOptimizationsView.xaml\n /// \n public partial class PowerOptimizationsView : UserControl\n {\n public PowerOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/SoundOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for SoundOptimizationsView.xaml\n /// \n public partial class SoundOptimizationsView : UserControl\n {\n public SoundOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/NotificationOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for NotificationOptimizationsView.xaml\n /// \n public partial class NotificationOptimizationsView : UserControl\n {\n public NotificationOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/ExplorerOptimizationsView.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for ExplorerOptimizationsView.xaml\n /// \n public partial class ExplorerOptimizationsView : UserControl\n {\n public ExplorerOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/PrivacyOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for PrivacyOptimizationsView.xaml\n /// \n public partial class PrivacyOptimizationsView : UserControl\n {\n public PrivacyOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/WindowsSecurityOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for WindowsSecurityOptimizationsView.xaml\n /// \n public partial class WindowsSecurityOptimizationsView : UserControl\n {\n public WindowsSecurityOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/GamingandPerformanceOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for GamingandPerformanceOptimizationsView.xaml\n /// \n public partial class GamingandPerformanceOptimizationsView : UserControl\n {\n public GamingandPerformanceOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IParameterSerializer.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for serializing and deserializing navigation parameters.\n /// \n public interface IParameterSerializer\n {\n /// \n /// Serializes an object to a string representation.\n /// \n /// The object to serialize.\n /// A string representation of the object.\n string Serialize(object parameter);\n\n /// \n /// Deserializes a string to an object of the specified type.\n /// \n /// The type to deserialize to.\n /// The string to deserialize.\n /// The deserialized object.\n object Deserialize(Type targetType, string value);\n\n /// \n /// Deserializes a string to an object of the specified type.\n /// \n /// The type to deserialize to.\n /// The string to deserialize.\n /// The deserialized object.\n T Deserialize(string serialized);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Customize/Views/WindowsThemeCustomizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Customize.Views\n{\n /// \n /// Interaction logic for WindowsThemeCustomizationsView.xaml\n /// \n public partial class WindowsThemeCustomizationsView : UserControl\n {\n public WindowsThemeCustomizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/LinkedSettingsLogic.cs", "namespace Winhance.Core.Features.Common.Enums;\n\n/// \n/// Defines the logic to use when determining the status of linked registry settings.\n/// \npublic enum LinkedSettingsLogic\n{\n /// \n /// If any of the linked settings is applied, the entire setting is considered applied.\n /// \n Any,\n \n /// \n /// All linked settings must be applied for the entire setting to be considered applied.\n /// \n All,\n \n /// \n /// Only use the first (primary) setting to determine the status.\n /// \n Primary,\n \n /// \n /// Use a custom logic defined in the code.\n /// \n Custom\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/PowerPlan.cs", "using System;\n\nnamespace Winhance.Core.Features.Optimize.Models\n{\n /// \n /// Represents a Windows power plan.\n /// \n public class PowerPlan\n {\n /// \n /// Gets or sets the name of the power plan.\n /// \n public string Name { get; set; }\n\n /// \n /// Gets or sets the GUID of the power plan.\n /// \n public string Guid { get; set; }\n\n /// \n /// Gets or sets the source GUID for plans that need to be created from another plan.\n /// \n public string SourceGuid { get; set; }\n\n /// \n /// Gets or sets the description of the power plan.\n /// \n public string Description { get; set; }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IVisibleSettingItem.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for setting items that can be shown or hidden in the UI.\n /// \n public interface IVisibleSettingItem\n {\n /// \n /// Gets or sets a value indicating whether this setting item is visible in the UI.\n /// \n bool IsVisible { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/IScriptContentModifier.cs", "using System;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\n/// \n/// Provides methods for modifying script content.\n/// \npublic interface IScriptContentModifier\n{\n /// \n /// Removes a capability from the script content.\n /// \n /// The script content.\n /// The name of the capability to remove.\n /// The updated script content.\n string RemoveCapabilityFromScript(string scriptContent, string capabilityName);\n\n /// \n /// Removes a package from the script content.\n /// \n /// The script content.\n /// The name of the package to remove.\n /// The updated script content.\n string RemovePackageFromScript(string scriptContent, string packageName);\n\n /// \n /// Removes an optional feature from the script content.\n /// \n /// The script content.\n /// The name of the optional feature to remove.\n /// The updated script content.\n string RemoveOptionalFeatureFromScript(string scriptContent, string featureName);\n\n /// \n /// Removes app-specific registry settings from the script content.\n /// \n /// The script content.\n /// The name of the app whose registry settings should be removed.\n /// The updated script content.\n string RemoveAppRegistrySettingsFromScript(string scriptContent, string appName);\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Views/WindowsAppsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Views\n{\n /// \n /// Interaction logic for WindowsAppsView.xaml\n /// \n public partial class WindowsAppsView : UserControl\n {\n public WindowsAppsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/Views/TaskbarCustomizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Customize.Views\n{\n /// \n /// Interaction logic for TaskbarCustomizationsView.xaml\n /// \n public partial class TaskbarCustomizationsView : UserControl\n {\n public TaskbarCustomizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/Views/ExplorerCustomizationsView.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Customize.Views\n{\n /// \n /// Interaction logic for ExplorerCustomizationsView.xaml\n /// \n public partial class ExplorerCustomizationsView : UserControl\n {\n public ExplorerCustomizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IInstallationStatusService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n public interface IInstallationStatusService\n {\n Task GetInstallStatusAsync(string appId);\n Task RefreshStatusAsync(IEnumerable appIds);\n Task SetInstallStatusAsync(string appId, InstallStatus status);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/IDesignTimeDataService.cs", "using System.Collections.Generic;\nusing Winhance.WPF.Features.SoftwareApps.Models;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Interface for providing design-time data for the application.\n /// This allows for proper visualization in the designer without running the application.\n /// \n public interface IDesignTimeDataService\n {\n /// \n /// Gets a collection of sample third-party applications for design-time.\n /// \n /// A collection of ThirdPartyApp instances.\n IEnumerable GetSampleThirdPartyApps();\n\n /// \n /// Gets a collection of sample Windows applications for design-time.\n /// \n /// A collection of WindowsApp instances.\n IEnumerable GetSampleWindowsApps();\n\n /// \n /// Gets a collection of sample Windows capabilities for design-time.\n /// \n /// A collection of WindowsApp instances configured as capabilities.\n IEnumerable GetSampleWindowsCapabilities();\n\n /// \n /// Gets a collection of sample Windows features for design-time.\n /// \n /// A collection of WindowsApp instances configured as features.\n IEnumerable GetSampleWindowsFeatures();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/OptimizationConfig.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.Common.Models;\n\npublic class OptimizationConfig\n{\n public required IDictionary> RegistrySettings { get; init; }\n public required IReadOnlyList WindowsPackages { get; init; }\n public required IReadOnlyList LegacyCapabilities { get; init; }\n public required IReadOnlyList Services { get; init; }\n}"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/CustomizationGroup.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Customize.Enums;\n\nnamespace Winhance.Core.Features.Customize.Models\n{\n /// \n /// Represents a group of customization settings.\n /// \n public record CustomizationGroup\n {\n /// \n /// Gets or sets the name of the customization group.\n /// \n public required string Name { get; init; }\n\n /// \n /// Gets or sets the category of the customization group.\n /// \n public required CustomizationCategory Category { get; init; }\n\n /// \n /// Gets or sets the settings in the customization group.\n /// \n public required IReadOnlyList Settings { get; init; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/RegistryActionType.cs", "namespace Winhance.Core.Features.Common.Enums;\n\n/// \n/// Defines the intended action for a registry setting.\n/// \npublic enum RegistryActionType\n{\n /// \n /// The setting is intended to set a specific value.\n /// \n Set,\n \n /// \n /// The setting is intended to remove a key or value.\n /// \n Remove,\n \n /// \n /// The setting is intended to modify an existing value.\n /// \n Modify\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Enums/CustomizationCategory.cs", "namespace Winhance.Core.Features.Customize.Enums;\n\n/// \n/// Defines the categories for customization settings.\n/// \npublic enum CustomizationCategory\n{\n /// \n /// Theme-related customization settings.\n /// \n Theme,\n \n /// \n /// Taskbar-related customization settings.\n /// \n Taskbar,\n \n /// \n /// Start menu-related customization settings.\n /// \n StartMenu,\n \n /// \n /// Explorer-related customization settings.\n /// \n Explorer,\n \n /// \n /// Notification-related customization settings.\n /// \n Notifications,\n \n /// \n /// Sound-related customization settings.\n /// \n Sound,\n \n /// \n /// Accessibility-related customization settings.\n /// \n Accessibility\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ISearchable.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for objects that can be searched.\n /// \n public interface ISearchable\n {\n /// \n /// Determines if the object matches the given search term.\n /// \n /// The search term to match against.\n /// True if the object matches the search term, false otherwise.\n bool MatchesSearch(string searchTerm);\n \n /// \n /// Gets the searchable properties of the object.\n /// \n /// An array of property names that should be searched.\n string[] GetSearchableProperties();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/RegistrySettingStatus.cs", "namespace Winhance.Core.Features.Common.Enums;\n\npublic enum RegistrySettingStatus\n{\n Unknown, // Status couldn't be determined\n NotApplied, // Registry key doesn't exist or has default value\n Applied, // Current value matches recommended value\n Modified, // Value exists but doesn't match recommended or default\n Error // Error occurred while checking status\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/IFeatureScriptModifier.cs", "using System;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Provides methods for modifying feature-related script content.\n /// \n public interface IFeatureScriptModifier\n {\n /// \n /// Removes an optional feature from the script content.\n /// \n /// The script content.\n /// The name of the optional feature to remove.\n /// The updated script content.\n string RemoveOptionalFeatureFromScript(string scriptContent, string featureName);\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ICapabilityScriptModifier.cs", "using System;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Provides methods for modifying capability-related script content.\n /// \n public interface ICapabilityScriptModifier\n {\n /// \n /// Removes a capability from the script content.\n /// \n /// The script content.\n /// The name of the capability to remove.\n /// The updated script content.\n string RemoveCapabilityFromScript(string scriptContent, string capabilityName);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/IInstallableItem.cs", "namespace Winhance.Core.Features.Common.Models\n{\n public interface IInstallableItem\n {\n string PackageId { get; }\n string DisplayName { get; }\n InstallItemType ItemType { get; }\n bool IsInstalled { get; set; }\n bool RequiresRestart { get; }\n }\n\n public enum InstallItemType\n {\n WindowsApp,\n Capability,\n Feature,\n ThirdParty\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/IRegistryScriptModifier.cs", "using System;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Provides methods for modifying registry-related script content.\n /// \n public interface IRegistryScriptModifier\n {\n /// \n /// Removes app-specific registry settings from the script content.\n /// \n /// The script content.\n /// The name of the app whose registry settings should be removed.\n /// The updated script content.\n string RemoveAppRegistrySettingsFromScript(string scriptContent, string appName);\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/IPackageScriptModifier.cs", "using System;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Provides methods for modifying package-related script content.\n /// \n public interface IPackageScriptModifier\n {\n /// \n /// Removes a package from the script content.\n /// \n /// The script content.\n /// The name of the package to remove.\n /// The updated script content.\n string RemovePackageFromScript(string scriptContent, string packageName);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/PowerShellStreamType.cs", "namespace Winhance.Core.Features.Common.Enums\n{\n /// \n /// Defines the types of PowerShell streams.\n /// \n public enum PowerShellStreamType\n {\n /// \n /// The output stream.\n /// \n Output,\n \n /// \n /// The error stream.\n /// \n Error,\n \n /// \n /// The warning stream.\n /// \n Warning,\n \n /// \n /// The verbose stream.\n /// \n Verbose,\n \n /// \n /// The debug stream.\n /// \n Debug,\n \n /// \n /// The information stream.\n /// \n Information,\n \n /// \n /// The progress stream.\n /// \n Progress\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Customize/Enums/CustomizationSettingType.cs", "using System;\n\nnamespace Winhance.Core.Features.Customize.Enums\n{\n /// \n /// Defines the type of customization setting.\n /// \n public enum CustomizationSettingType\n {\n /// \n /// A standard setting.\n /// \n Standard,\n\n /// \n /// A slider setting.\n /// \n Slider,\n\n /// \n /// A dropdown setting.\n /// \n Dropdown,\n\n /// \n /// A color picker setting.\n /// \n ColorPicker\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/LogLevel.cs", "namespace Winhance.Core.Features.Common.Enums\n{\n public enum LogLevel\n {\n Info,\n Warning,\n Error,\n Success,\n Debug\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/InstallStatus.cs", "namespace Winhance.Core.Features.Common.Models\n{\n public enum InstallStatus\n {\n Success,\n NotFound,\n Failed,\n Pending\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 19:10:26", "created_task_model": "DeepSeek-R1", "function_skeleton": "private void MainWindow_PreviewMouseWheel (object sender, MouseWheelEventArgs e) {}", "code_description": "This code segment functions to: Handle mouse wheel input events and translate vertical scrolling actions into corresponding navigation commands for a scrollable user interface component, ensuring event propagation is properly managed."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n private void MainWindow_PreviewMouseWheel(object sender, MouseWheelEventArgs e)\n {\n try\n {\n var scrollViewer = FindVisualChild(this);\n if (scrollViewer == null)\n {\n LogDebug(\"PreviewMouseWheel: ScrollViewer not found\");\n return;\n }\n\n // Only handle vertical scrolling\n if (scrollViewer.VerticalScrollBarVisibility != ScrollBarVisibility.Disabled)\n {\n double currentOffset = scrollViewer.VerticalOffset;\n double scrollStep = 50; // Pixel-based scrolling\n \n if (e.Delta > 0 && currentOffset > 0) // Scrolling up\n {\n scrollViewer.ScrollToVerticalOffset(Math.Max(0, currentOffset - scrollStep));\n e.Handled = true;\n }\n else if (e.Delta < 0 && currentOffset < scrollViewer.ScrollableHeight) // Scrolling down\n {\n scrollViewer.ScrollToVerticalOffset(Math.Min(scrollViewer.ScrollableHeight, currentOffset + scrollStep));\n e.Handled = true;\n }\n\n LogDebug($\"Handled mouse wheel - Delta: {e.Delta}, New Offset: {scrollViewer.VerticalOffset}\");\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error handling mouse wheel event: {ex.Message}\", ex);\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-10-44"}, "editdistance_info": {"edit_distance": 24.9012, "calculate_time": "2025-08-20 19:10:44", "true_code_clean": "private void MainWindow_PreviewMouseWheel(object sender, MouseWheelEventArgs e)\n {\n var scrollViewer = FindVisualChild(this);\n if (scrollViewer != null)\n {\n if (e.Delta < 0)\n {\n scrollViewer.LineDown();\n }\n else\n {\n scrollViewer.LineUp();\n }\n e.Handled = true;\n }\n }", "predict_code_clean": "private void MainWindow_PreviewMouseWheel(object sender, MouseWheelEventArgs e)\n {\n try\n {\n var scrollViewer = FindVisualChild(this);\n if (scrollViewer == null)\n {\n LogDebug(\"PreviewMouseWheel: ScrollViewer not found\");\n return;\n }\n if (scrollViewer.VerticalScrollBarVisibility != ScrollBarVisibility.Disabled)\n {\n double currentOffset = scrollViewer.VerticalOffset;\n double scrollStep = 50; \n if (e.Delta > 0 && currentOffset > 0) \n {\n scrollViewer.ScrollToVerticalOffset(Math.Max(0, currentOffset - scrollStep));\n e.Handled = true;\n }\n else if (e.Delta < 0 && currentOffset < scrollViewer.ScrollableHeight) \n {\n scrollViewer.ScrollToVerticalOffset(Math.Min(scrollViewer.ScrollableHeight, currentOffset + scrollStep));\n e.Handled = true;\n }\n LogDebug($\"Handled mouse wheel - Delta: {e.Delta}, New Offset: {scrollViewer.VerticalOffset}\");\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error handling mouse wheel event: {ex.Message}\", ex);\n }\n }"}} {"repo_name": "Winhance", "file_name": "/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppInstallationCoordinatorService.cs", "inference_info": {"prefix_code": "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Coordinates the installation of applications, handling connectivity monitoring,\n /// user notifications, and installation state management.\n /// \n public class AppInstallationCoordinatorService : IAppInstallationCoordinatorService\n {\n private readonly IAppInstallationService _appInstallationService;\n private readonly IInternetConnectivityService _connectivityService;\n private readonly ILogService _logService;\n private readonly INotificationService _notificationService;\n private readonly IDialogService _dialogService;\n \n /// \n /// Event that is raised when the installation status changes.\n /// \n public event EventHandler InstallationStatusChanged;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The application installation service.\n /// The internet connectivity service.\n /// The logging service.\n /// The notification service.\n /// The dialog service.\n public AppInstallationCoordinatorService(\n IAppInstallationService appInstallationService,\n IInternetConnectivityService connectivityService,\n ILogService logService,\n INotificationService notificationService = null,\n IDialogService dialogService = null)\n {\n _appInstallationService = appInstallationService ?? throw new ArgumentNullException(nameof(appInstallationService));\n _connectivityService = connectivityService ?? throw new ArgumentNullException(nameof(connectivityService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _notificationService = notificationService;\n _dialogService = dialogService;\n }\n\n /// \n /// Installs an application with connectivity monitoring and proper cancellation handling.\n /// \n /// The application information.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the installation operation with the result.\n public async Task InstallAppAsync(\n AppInfo appInfo,\n IProgress progress,\n CancellationToken cancellationToken = default)\n {\n if (appInfo == null)\n throw new ArgumentNullException(nameof(appInfo));\n \n // Create a linked cancellation token source that will be cancelled if either:\n // 1. The original cancellation token is cancelled (user initiated)\n // 2. We detect a connectivity issue and cancel the installation\n using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n \n // Update status\n var initialStatus = $\"Installing {appInfo.Name}...\";\n RaiseStatusChanged(appInfo, initialStatus);\n \n // Start connectivity monitoring\n var connectivityMonitoringTask = StartConnectivityMonitoring(appInfo, linkedCts);\n \n try\n {\n // Perform the installation\n var installationResult = await _appInstallationService.InstallAppAsync(\n appInfo, \n progress, \n linkedCts.Token);\n \n // Stop connectivity monitoring\n linkedCts.Cancel();\n try { await connectivityMonitoringTask; } catch (OperationCanceledException) { /* Expected */ }\n \n if (installationResult.Success)\n {\n var successMessage = $\"Successfully installed {appInfo.Name}\";\n RaiseStatusChanged(appInfo, successMessage, true, true);\n \n return new InstallationCoordinationResult\n {\n Success = true,\n AppInfo = appInfo\n };\n }\n else\n {\n var errorMessage = installationResult.ErrorMessage ?? $\"Failed to install {appInfo.Name}\";\n RaiseStatusChanged(appInfo, errorMessage, true, false);\n \n return new InstallationCoordinationResult\n {\n Success = false,\n ErrorMessage = errorMessage,\n AppInfo = appInfo\n };\n }\n }\n catch (OperationCanceledException)\n {\n // Stop connectivity monitoring\n linkedCts.Cancel();\n try { await connectivityMonitoringTask; } catch (OperationCanceledException) { /* Expected */ }\n \n // Determine if this was a user cancellation or a connectivity issue\n bool wasConnectivityIssue = await connectivityMonitoringTask.ContinueWith(t => \n {\n // If the task completed normally, check its result\n if (t.Status == TaskStatus.RanToCompletion)\n {\n return t.Result;\n }\n // If the task was cancelled, assume it was a user cancellation\n return false;\n });\n \n if (wasConnectivityIssue)\n {\n var connectivityMessage = $\"Installation of {appInfo.Name} was stopped due to internet connectivity issues\";\n RaiseStatusChanged(appInfo, connectivityMessage, true, false, false, true);\n \n return new InstallationCoordinationResult\n {\n Success = false,\n WasCancelled = false,\n WasConnectivityIssue = true,\n ErrorMessage = \"Internet connection lost during installation. Please check your network connection and try again.\",\n AppInfo = appInfo\n };\n }\n else\n {\n var cancelMessage = $\"Installation of {appInfo.Name} was cancelled by user\";\n RaiseStatusChanged(appInfo, cancelMessage, true, false, true);\n \n return new InstallationCoordinationResult\n {\n Success = false,\n WasCancelled = true,\n WasConnectivityIssue = false,\n ErrorMessage = \"Installation was cancelled by user\",\n AppInfo = appInfo\n };\n }\n }\n catch (Exception ex)\n {\n // Stop connectivity monitoring\n linkedCts.Cancel();\n try { await connectivityMonitoringTask; } catch (OperationCanceledException) { /* Expected */ }\n \n // Log the error\n _logService.LogError($\"Error installing {appInfo.Name}: {ex.Message}\", ex);\n \n // Check if the exception is related to internet connectivity\n bool isConnectivityIssue = ex.Message.Contains(\"internet\") || \n ex.Message.Contains(\"connection\") || \n ex.Message.Contains(\"network\") ||\n ex.Message.Contains(\"pipeline has been stopped\");\n \n string errorMessage = isConnectivityIssue\n ? \"Internet connection lost during installation. Please check your network connection and try again.\"\n : ex.Message;\n \n RaiseStatusChanged(appInfo, $\"Error installing {appInfo.Name}: {errorMessage}\", true, false, false, isConnectivityIssue);\n \n return new InstallationCoordinationResult\n {\n Success = false,\n WasCancelled = false,\n WasConnectivityIssue = isConnectivityIssue,\n ErrorMessage = errorMessage,\n AppInfo = appInfo\n };\n }\n }\n \n /// \n /// Starts monitoring internet connectivity during installation.\n /// \n /// The application information.\n /// The cancellation token source.\n /// A task that completes when monitoring is stopped, with a result indicating if a connectivity issue was detected.\n ", "suffix_code": "\n \n /// \n /// Raises the InstallationStatusChanged event.\n /// \n /// The application information.\n /// The status message.\n /// Whether the installation is complete.\n /// Whether the installation was successful.\n /// Whether the installation was cancelled by the user.\n /// Whether the installation failed due to connectivity issues.\n private void RaiseStatusChanged(\n AppInfo appInfo,\n string statusMessage,\n bool isComplete = false,\n bool isSuccess = false,\n bool isCancelled = false,\n bool isConnectivityIssue = false)\n {\n _logService.LogInformation(statusMessage);\n \n InstallationStatusChanged?.Invoke(\n this,\n new InstallationStatusChangedEventArgs(\n appInfo,\n statusMessage,\n isComplete,\n isSuccess,\n isCancelled,\n isConnectivityIssue\n )\n );\n }\n }\n}\n", "middle_code": "private async Task StartConnectivityMonitoring(AppInfo appInfo, CancellationTokenSource cts)\n {\n bool connectivityIssueDetected = false;\n EventHandler connectivityChangedHandler = null;\n connectivityChangedHandler = (sender, args) =>\n {\n if (cts.Token.IsCancellationRequested)\n {\n return; \n }\n if (args.IsUserCancelled)\n {\n var message = $\"Installation of {appInfo.Name} was cancelled by user\";\n RaiseStatusChanged(appInfo, message, false, false, true);\n }\n else if (!args.IsConnected)\n {\n connectivityIssueDetected = true;\n var message = $\"Error: Internet connection lost while installing {appInfo.Name}. Installation stopped.\";\n RaiseStatusChanged(appInfo, message, false, false, false, true);\n _notificationService?.ShowToast(\n \"Internet Connection Lost\",\n \"Internet connection has been lost during installation. Installation has been stopped.\",\n ToastType.Error\n );\n if (_dialogService != null)\n {\n _ = _dialogService.ShowInformationAsync(\n $\"The installation of {appInfo.Name} has been stopped because internet connection was lost. Please check your network connection and try again when your internet connection is stable.\",\n \"Internet Connection Lost\"\n );\n }\n cts.Cancel();\n }\n };\n try\n {\n _connectivityService.ConnectivityChanged += connectivityChangedHandler;\n await _connectivityService.StartMonitoringAsync(5, cts.Token);\n try\n {\n await Task.Delay(-1, cts.Token);\n }\n catch (OperationCanceledException)\n {\n }\n return connectivityIssueDetected;\n }\n finally\n {\n if (connectivityChangedHandler != null)\n {\n _connectivityService.ConnectivityChanged -= connectivityChangedHandler;\n }\n _connectivityService.StopMonitoring();\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/ExternalAppsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.SoftwareApps.Models;\nusing ToastType = Winhance.Core.Features.UI.Interfaces.ToastType;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n public partial class ExternalAppsViewModel : BaseInstallationViewModel\n {\n [ObservableProperty]\n private bool _isInitialized = false;\n\n private readonly IAppInstallationService _appInstallationService;\n private readonly IAppService _appDiscoveryService;\n private readonly IConfigurationService _configurationService;\n\n [ObservableProperty]\n private string _statusText = \"Ready\";\n\n // ObservableCollection to store category view models\n private ObservableCollection _categories = new();\n\n // Public property to expose the categories\n public ObservableCollection Categories => _categories;\n\n public ExternalAppsViewModel(\n ITaskProgressService progressService,\n ISearchService searchService,\n IPackageManager packageManager,\n IAppInstallationService appInstallationService,\n IAppService appDiscoveryService,\n IConfigurationService configurationService,\n Services.SoftwareAppsDialogService dialogService,\n IInternetConnectivityService connectivityService,\n IAppInstallationCoordinatorService appInstallationCoordinatorService\n )\n : base(\n progressService,\n searchService,\n packageManager,\n appInstallationService,\n appInstallationCoordinatorService,\n connectivityService,\n dialogService\n )\n {\n _appInstallationService = appInstallationService;\n _appDiscoveryService = appDiscoveryService;\n _configurationService = configurationService;\n }\n\n // SaveConfig and ImportConfig methods removed as part of unified configuration cleanup\n\n /// \n /// Applies the current search text to filter items.\n /// \n protected override void ApplySearch()\n {\n if (Items == null || Items.Count == 0)\n return;\n\n // Filter items based on search text\n var filteredItems = FilterItems(Items);\n\n // Clear all categories\n foreach (var category in Categories)\n {\n category.Apps.Clear();\n }\n\n // Group filtered items by category\n var appsByCategory = new Dictionary>();\n\n foreach (var app in filteredItems)\n {\n string category = app.Category;\n if (string.IsNullOrEmpty(category))\n {\n category = \"Other\";\n }\n\n if (!appsByCategory.ContainsKey(category))\n {\n appsByCategory[category] = new List();\n }\n\n appsByCategory[category].Add(app);\n }\n\n // Update categories with filtered items\n foreach (var category in Categories)\n {\n if (appsByCategory.TryGetValue(category.Name, out var apps))\n {\n // Sort apps alphabetically within the category\n var sortedApps = apps.OrderBy(a => a.Name);\n\n foreach (var app in sortedApps)\n {\n category.Apps.Add(app);\n }\n }\n }\n\n // Hide empty categories if search is active\n if (IsSearchActive)\n {\n foreach (var category in Categories)\n {\n category.IsExpanded = category.Apps.Count > 0;\n }\n }\n }\n\n public override async Task LoadItemsAsync()\n {\n if (_packageManager == null)\n return;\n\n IsLoading = true;\n StatusText = \"Loading external apps...\";\n\n try\n {\n Items.Clear();\n _categories.Clear();\n\n var apps = await _packageManager.GetInstallableAppsAsync();\n\n // Group apps by category\n var appsByCategory = new Dictionary>();\n\n foreach (var app in apps)\n {\n var externalApp = ExternalApp.FromAppInfo(app);\n Items.Add(externalApp);\n\n // Group by category\n string category = app.Category;\n if (string.IsNullOrEmpty(category))\n {\n category = \"Other\";\n }\n\n if (!appsByCategory.ContainsKey(category))\n {\n appsByCategory[category] = new List();\n }\n\n appsByCategory[category].Add(externalApp);\n }\n\n // Sort categories alphabetically\n var sortedCategories = appsByCategory.Keys.OrderBy(c => c).ToList();\n\n // Create category view models with sorted apps\n foreach (var categoryName in sortedCategories)\n {\n // Sort apps alphabetically within the category\n var sortedApps = appsByCategory[categoryName].OrderBy(a => a.Name).ToList();\n\n // Create observable collection for the category\n var appsCollection = new ObservableCollection(sortedApps);\n\n // Create and add the category view model\n _categories.Add(\n new ExternalAppsCategoryViewModel(categoryName, appsCollection)\n );\n }\n\n StatusText = $\"Loaded {Items.Count} external apps\";\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error loading external apps: {ex.Message}\";\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n public override async Task CheckInstallationStatusAsync()\n {\n if (_appDiscoveryService == null)\n return;\n\n IsLoading = true;\n StatusText = \"Checking installation status...\";\n\n try\n {\n var statusResults = await _appDiscoveryService.GetBatchInstallStatusAsync(\n Items.Select(a => a.PackageName)\n );\n\n foreach (var app in Items)\n {\n if (statusResults.TryGetValue(app.PackageName, out bool isInstalled))\n {\n app.IsInstalled = isInstalled;\n }\n }\n StatusText = \"Installation status check complete\";\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error checking installation status: {ex.Message}\";\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n [RelayCommand]\n public async Task InstallApp(ExternalApp app)\n {\n if (app == null || _appInstallationService == null)\n return;\n\n // Check for internet connectivity before starting installation\n bool isInternetConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(true);\n if (!isInternetConnected)\n {\n StatusText = \"No internet connection available. Installation cannot proceed.\";\n\n // Show dialog informing the user about the connectivity issue\n await ShowNoInternetConnectionDialogAsync();\n return;\n }\n\n IsLoading = true;\n StatusText = $\"Installing {app.Name}...\";\n\n // Setup cancellation for the installation process\n using var cts = new System.Threading.CancellationTokenSource();\n var cancellationToken = cts.Token;\n\n // Start a background task to periodically check internet connectivity during installation\n var connectivityCheckTask = StartPeriodicConnectivityCheck(app.Name, cts);\n\n try\n {\n var progress = _progressService.CreateDetailedProgress();\n\n try\n {\n var operationResult = await _appInstallationService.InstallAppAsync(\n app.ToAppInfo(),\n progress,\n cancellationToken\n );\n\n // Cancel the connectivity check task as installation is complete\n cts.Cancel();\n\n // Wait for the connectivity check task to complete\n try\n {\n await connectivityCheckTask;\n }\n catch (OperationCanceledException)\n { /* Expected when we cancel */\n }\n\n if (operationResult.Success)\n {\n app.IsInstalled = true;\n StatusText = $\"Successfully installed {app.Name}\";\n\n // Show success dialog\n _dialogService.ShowInformationAsync(\n \"Installation Complete\",\n $\"{app.Name} was successfully installed.\",\n new[] { app.Name },\n \"The application has been installed successfully.\"\n );\n }\n else\n {\n string errorMessage =\n operationResult.ErrorMessage\n ?? $\"Failed to install {app.Name}. Please try again.\";\n StatusText = errorMessage;\n\n // Store the error message for later reference\n app.LastOperationError = errorMessage;\n\n // Show error dialog\n _dialogService.ShowInformationAsync(\n \"Installation Failed\",\n $\"Failed to install {app.Name}.\",\n new[] { $\"{app.Name}: {errorMessage}\" },\n \"There was an error during installation. Please try again later.\"\n );\n }\n }\n catch (OperationCanceledException)\n {\n // Set cancellation reason to UserCancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n \n // Cancel the connectivity check task\n cts.Cancel();\n\n // Wait for the connectivity check task to complete\n try\n {\n await connectivityCheckTask;\n }\n catch (OperationCanceledException)\n { /* Expected when we cancel */\n }\n \n // For single app installations, use the ShowCancellationDialogAsync method directly\n // which will use CustomDialog with a simpler message\n await ShowCancellationDialogAsync(true, false); // User-initiated cancellation\n \n // Reset cancellation reason after showing dialog\n CurrentCancellationReason = CancellationReason.None;\n \n StatusText = $\"Installation of {app.Name} was cancelled\";\n }\n catch (System.Exception ex)\n {\n // Cancel the connectivity check task\n cts.Cancel();\n\n // Wait for the connectivity check task to complete\n try\n {\n await connectivityCheckTask;\n }\n catch (OperationCanceledException)\n { /* Expected when we cancel */\n }\n\n // Check if the exception is related to internet connectivity\n bool isConnectivityIssue =\n ex.Message.Contains(\"internet\", StringComparison.OrdinalIgnoreCase)\n || ex.Message.Contains(\"connection\", StringComparison.OrdinalIgnoreCase)\n || ex.Message.Contains(\"network\", StringComparison.OrdinalIgnoreCase)\n || ex.Message.Contains(\"pipeline has been stopped\", StringComparison.OrdinalIgnoreCase);\n\n if (isConnectivityIssue && CurrentCancellationReason == CancellationReason.None)\n {\n // Use the centralized cancellation handling for connectivity issues\n await HandleCancellationAsync(true); // Connectivity-related cancellation\n }\n \n string errorMessage = isConnectivityIssue\n ? \"Internet connection lost during installation. Please check your network connection and try again.\"\n : ex.Message;\n\n // Store the error message for later reference\n app.LastOperationError = errorMessage;\n\n StatusText = $\"Error installing {app.Name}: {errorMessage}\";\n\n // Only show error dialog if it's not a connectivity issue (which is already handled by HandleCancellationAsync)\n if (!isConnectivityIssue)\n {\n _dialogService.ShowInformationAsync(\n \"Installation Failed\",\n $\"Failed to install {app.Name}.\",\n new[] { $\"{app.Name}: {errorMessage}\" },\n \"There was an error during installation. Please try again later.\"\n );\n }\n }\n }\n catch (System.Exception ex)\n {\n // This is a fallback catch-all to ensure the application doesn't crash\n // Cancel the connectivity check task\n cts.Cancel();\n\n // Wait for the connectivity check task to complete\n try\n {\n await connectivityCheckTask;\n }\n catch (OperationCanceledException)\n { /* Expected when we cancel */\n }\n\n // Store the error message for later reference\n app.LastOperationError = ex.Message;\n\n StatusText = $\"Error installing {app.Name}: {ex.Message}\";\n\n // Show error dialog\n _dialogService.ShowInformationAsync(\n \"Installation Failed\",\n $\"Failed to install {app.Name}.\",\n new[] { $\"{app.Name}: {ex.Message}\" },\n \"There was an error during installation. Please try again later.\"\n );\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Starts a periodic check for internet connectivity during installation.\n /// \n /// The name of the app being installed\n /// Cancellation token source to cancel the task\n /// A task that completes when the installation is done or cancelled\n private async Task StartPeriodicConnectivityCheck(\n string appName,\n System.Threading.CancellationTokenSource cts\n )\n {\n try\n {\n // Check connectivity every 5 seconds during installation\n while (!cts.Token.IsCancellationRequested)\n {\n await Task.Delay(5000, cts.Token); // 5 seconds delay between checks\n\n if (cts.Token.IsCancellationRequested)\n break;\n\n bool isConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(\n false,\n cts.Token\n );\n\n if (!isConnected)\n {\n // Only set connectivity loss if no other cancellation reason is set\n if (CurrentCancellationReason == CancellationReason.None)\n {\n // Update status to inform user about connectivity issue\n StatusText =\n $\"Error: Internet connection lost while installing {appName}. Installation stopped.\";\n\n // Show a non-blocking toast notification\n if (_packageManager.NotificationService != null)\n {\n _packageManager.NotificationService.ShowToast(\n \"Internet Connection Lost\",\n \"Internet connection has been lost during installation. Installation has been stopped.\",\n ToastType.Error\n );\n }\n\n // Use the centralized cancellation handling instead of showing dialog directly\n await HandleCancellationAsync(true); // Connectivity-related cancellation\n }\n \n // Cancel the installation process\n cts.Cancel();\n break;\n }\n }\n }\n catch (OperationCanceledException)\n {\n // Task was cancelled, which is expected when installation completes or is stopped\n }\n catch (Exception ex)\n {\n // Log any unexpected errors but don't disrupt the installation process\n System.Diagnostics.Debug.WriteLine($\"Error in connectivity check: {ex.Message}\");\n }\n }\n\n [RelayCommand]\n public void ClearSelectedItems()\n {\n // Clear all selected items\n foreach (var app in Items)\n {\n app.IsSelected = false;\n }\n\n // Update the UI for all categories\n foreach (var category in Categories)\n {\n foreach (var app in category.Apps)\n {\n app.IsSelected = false;\n }\n }\n\n StatusText = \"All selections cleared\";\n }\n\n [RelayCommand]\n public async Task InstallApps()\n {\n if (_appInstallationService == null)\n return;\n\n // Get all selected apps regardless of installation status\n var selectedApps = Items.Where(a => a.IsSelected).ToList();\n\n if (!selectedApps.Any())\n {\n StatusText = \"No apps selected for installation\";\n await ShowNoItemsSelectedDialogAsync(\"installation\");\n return;\n }\n\n // Check for internet connectivity before starting batch installation\n bool isInternetConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(true);\n if (!isInternetConnected)\n {\n StatusText = \"No internet connection available. Installation cannot proceed.\";\n\n // Show dialog informing the user about the connectivity issue\n await ShowNoInternetConnectionDialogAsync();\n return;\n }\n\n // Show confirmation dialog\n bool? dialogResult = await ShowConfirmItemsDialogAsync(\n \"install\",\n selectedApps.Select(a => a.Name),\n selectedApps.Count\n );\n\n // If user didn't confirm, exit\n if (dialogResult != true)\n {\n return;\n }\n\n // Setup cancellation for the installation process\n using var cts = new System.Threading.CancellationTokenSource();\n\n // Start a background task to periodically check internet connectivity during installation\n var connectivityCheckTask = StartBatchConnectivityCheck(cts);\n\n // Use the ExecuteWithProgressAsync method from BaseViewModel to handle progress reporting\n await ExecuteWithProgressAsync(\n async (progress, cancellationToken) =>\n {\n int successCount = 0;\n int currentItem = 0;\n int totalSelected = selectedApps.Count;\n\n foreach (var app in selectedApps)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n await HandleCancellationAsync(false); // User-initiated cancellation\n cts.Cancel(); // Ensure all tasks are cancelled\n return successCount; // Exit the method immediately\n }\n\n try\n {\n var operationResult = await _appInstallationService.InstallAppAsync(\n app.ToAppInfo(),\n progress,\n cancellationToken\n );\n\n if (operationResult.Success)\n {\n app.IsInstalled = true;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Successfully installed {app.Name}\",\n DetailedMessage = $\"Successfully installed app: {app.Name}\",\n LogLevel = LogLevel.Success,\n AdditionalInfo = new Dictionary\n {\n { \"AppName\", app.Name },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Install\" },\n { \"OperationStatus\", \"Success\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n else\n {\n string errorMessage =\n operationResult.ErrorMessage ?? $\"Failed to install {app.Name}\";\n\n // Store the error message for later reference\n app.LastOperationError = errorMessage;\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Error installing {app.Name}\",\n DetailedMessage = errorMessage,\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppName\", app.Name },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Install\" },\n { \"OperationStatus\", \"Error\" },\n { \"ErrorMessage\", errorMessage },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n catch (OperationCanceledException)\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Installation of {app.Name} was cancelled\",\n DetailedMessage =\n $\"The installation of {app.Name} was cancelled.\",\n LogLevel = LogLevel.Warning,\n AdditionalInfo = new Dictionary\n {\n { \"AppName\", app.Name },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Install\" },\n { \"OperationStatus\", \"Cancelled\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n\n // Use the centralized cancellation handling\n await HandleCancellationAsync(false); // User-initiated cancellation\n cts.Cancel();\n return successCount; // Exit the method immediately\n }\n catch (System.Exception ex)\n {\n // Check if the exception is related to internet connectivity\n bool isConnectivityIssue =\n ex.Message.Contains(\"internet\", StringComparison.OrdinalIgnoreCase) ||\n ex.Message.Contains(\"connection\", StringComparison.OrdinalIgnoreCase) ||\n ex.Message.Contains(\"network\", StringComparison.OrdinalIgnoreCase) ||\n ex.Message.Contains(\"pipeline has been stopped\", StringComparison.OrdinalIgnoreCase);\n\n if (isConnectivityIssue && CurrentCancellationReason == CancellationReason.None)\n {\n // Set the cancellation reason to connectivity issue\n await HandleCancellationAsync(true); // Connectivity-related cancellation\n }\n \n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Error installing {app.Name}\",\n DetailedMessage = $\"Error installing {app.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppName\", app.Name },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Install\" },\n { \"OperationStatus\", \"Error\" },\n { \"ErrorMessage\", ex.Message },\n { \"ErrorType\", ex.GetType().Name },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n { \"IsConnectivityIssue\", isConnectivityIssue.ToString() },\n },\n }\n );\n }\n }\n\n // Cancel the connectivity check task as installation is complete\n cts.Cancel();\n\n // Wait for the connectivity check task to complete\n try\n {\n await connectivityCheckTask;\n }\n catch (OperationCanceledException)\n { /* Expected when we cancel */\n }\n\n // Only proceed with normal completion reporting if not cancelled\n // Final report\n // Check if any failures were due to internet connectivity issues\n bool hasInternetIssues = selectedApps.Any(a =>\n !a.IsInstalled\n && (\n a.LastOperationError?.Contains(\"Internet connection\") == true\n || a.LastOperationError?.Contains(\"No internet\") == true\n )\n );\n\n string statusText =\n successCount == totalSelected\n ? $\"Successfully installed {successCount} of {totalSelected} apps\"\n : hasInternetIssues ? $\"Installation incomplete: Internet connection issues\"\n : $\"Installation incomplete: {successCount} of {totalSelected} apps installed\";\n\n string detailedMessage =\n successCount == totalSelected\n ? $\"Task completed: {successCount} of {totalSelected} apps installed successfully\"\n : hasInternetIssues\n ? $\"Task not completed: {successCount} of {totalSelected} apps installed. Installation failed due to internet connection issues\"\n : $\"Task completed: {successCount} of {totalSelected} apps installed successfully\";\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = statusText,\n DetailedMessage = detailedMessage,\n LogLevel =\n successCount == totalSelected ? LogLevel.Success : LogLevel.Warning,\n AdditionalInfo = new Dictionary\n {\n { \"OperationType\", \"Install\" },\n {\n \"OperationStatus\",\n successCount == totalSelected ? \"Complete\" : \"PartialSuccess\"\n },\n { \"SuccessCount\", successCount.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n { \"SuccessRate\", $\"{(successCount * 100.0 / totalSelected):F1}%\" },\n { \"CompletionTime\", DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\") },\n },\n }\n );\n\n // For normal completion (not cancelled), collect success and failure information\n var successItems = new List();\n var failedItems = new List();\n\n // Add successful items to the list\n foreach (var app in selectedApps.Where(a => a.IsInstalled))\n {\n successItems.Add(app.Name);\n }\n\n // Add failed items to the list\n foreach (var app in selectedApps.Where(a => !a.IsInstalled))\n {\n failedItems.Add(app.Name);\n }\n\n // Check if any failures are due to internet connectivity issues\n bool hasConnectivityIssues = hasInternetIssues;\n bool isFailure = successCount < totalSelected;\n \n // Important: Check if the operation was cancelled by the user\n // This ensures we show the correct dialog even if the cancellation happened in a different part of the code\n if (failedItems != null && failedItems.Any(item => item.Contains(\"cancelled by user\", StringComparison.OrdinalIgnoreCase)))\n {\n // Set the cancellation reason to UserCancelled if it's not already set\n if (CurrentCancellationReason == CancellationReason.None)\n {\n CurrentCancellationReason = CancellationReason.UserCancelled;\n }\n }\n \n // Show result dialog using the base class method which handles cancellation scenarios properly\n ShowOperationResultDialog(\n \"Install\",\n successCount,\n totalSelected,\n successItems,\n failedItems,\n null // no skipped items\n );\n\n return successCount;\n },\n $\"Installing {selectedApps.Count} apps\",\n false\n );\n }\n\n /// \n /// Starts a periodic check for internet connectivity during batch installation.\n /// \n /// Cancellation token source to cancel the task\n /// A task that completes when the installation is done or cancelled\n private async Task StartBatchConnectivityCheck(System.Threading.CancellationTokenSource cts)\n {\n try\n {\n // Check connectivity every 15 seconds during batch installation (reduced frequency)\n while (!cts.Token.IsCancellationRequested)\n {\n await Task.Delay(15000, cts.Token); // 15 seconds delay between checks (increased from 5)\n\n // If cancellation was already requested (e.g., by the user), don't proceed with connectivity check\n if (cts.Token.IsCancellationRequested)\n {\n // Important: Do NOT set cancellation reason here, as it might overwrite UserCancelled\n break;\n }\n\n // Check if user cancellation has already been set\n if (CurrentCancellationReason == CancellationReason.UserCancelled)\n {\n // User already cancelled, don't change the reason\n break;\n }\n\n bool isConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(\n false,\n cts.Token\n );\n\n if (!isConnected)\n {\n // Only set connectivity loss if no other cancellation reason is set\n if (CurrentCancellationReason == CancellationReason.None)\n {\n // Update status to inform user about connectivity issue\n StatusText =\n \"Error: Internet connection lost during installation. Installation stopped.\";\n\n // Show a non-blocking toast notification\n if (_packageManager.NotificationService != null)\n {\n _packageManager.NotificationService.ShowToast(\n \"Internet Connection Lost\",\n \"Internet connection has been lost during installation. Installation has been stopped.\",\n ToastType.Error\n );\n }\n\n // Use the centralized cancellation handling\n await HandleCancellationAsync(true); // Connectivity-related cancellation\n }\n \n cts.Cancel();\n return; // Exit the method immediately\n }\n }\n }\n catch (OperationCanceledException)\n {\n // Task was cancelled, which is expected when installation completes or is stopped\n // Do NOT set cancellation reason here, as it might have been set by the main task\n }\n catch (Exception ex)\n {\n // Log any unexpected errors but don't disrupt the installation process\n System.Diagnostics.Debug.WriteLine(\n $\"Error in batch connectivity check: {ex.Message}\"\n );\n }\n }\n\n public async Task LoadAppsAndCheckInstallationStatusAsync()\n {\n if (IsInitialized)\n {\n System.Diagnostics.Debug.WriteLine(\n \"ExternalAppsViewModel already initialized, skipping LoadAppsAndCheckInstallationStatusAsync\"\n );\n return;\n }\n\n System.Diagnostics.Debug.WriteLine(\n \"Starting ExternalAppsViewModel LoadAppsAndCheckInstallationStatusAsync\"\n );\n await LoadItemsAsync();\n await CheckInstallationStatusAsync();\n\n // Mark as initialized after loading is complete\n IsInitialized = true;\n System.Diagnostics.Debug.WriteLine(\n \"Completed ExternalAppsViewModel LoadAppsAndCheckInstallationStatusAsync\"\n );\n }\n\n public override async void OnNavigatedTo(object parameter)\n {\n try\n {\n // Only load data if not already initialized\n if (!IsInitialized)\n {\n await LoadAppsAndCheckInstallationStatusAsync();\n }\n }\n catch (System.Exception ex)\n {\n // Handle any exceptions\n StatusText = $\"Error loading apps: {ex.Message}\";\n IsLoading = false;\n }\n }\n\n #region BaseInstallationViewModel Abstract Method Implementations\n\n /// \n /// Gets the name of an external app.\n /// \n /// The external app.\n /// The name of the app.\n protected override string GetAppName(ExternalApp app)\n {\n return app.Name;\n }\n\n /// \n /// Converts an external app to an AppInfo object.\n /// \n /// The external app to convert.\n /// The AppInfo object.\n protected override AppInfo ToAppInfo(ExternalApp app)\n {\n return app.ToAppInfo();\n }\n\n /// \n /// Gets the selected external apps.\n /// \n /// The selected external apps.\n protected override IEnumerable GetSelectedApps()\n {\n return Items.Where(a => a.IsSelected);\n }\n\n /// \n /// Sets the installation status of an external app.\n /// \n /// The external app.\n /// Whether the app is installed.\n protected override void SetInstallationStatus(ExternalApp app, bool isInstalled)\n {\n app.IsInstalled = isInstalled;\n }\n\n #endregion\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/BaseInstallationViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.SoftwareApps.Services;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n /// \n /// Base view model for installation operations.\n /// Provides common functionality for both WindowsAppsViewModel and ExternalAppsViewModel.\n /// \n /// The type of app (WindowsApp or ExternalApp)\n public abstract class BaseInstallationViewModel : SearchableViewModel\n where T : class, ISearchable\n {\n protected readonly IAppInstallationService _appInstallationService;\n protected readonly IAppInstallationCoordinatorService _appInstallationCoordinatorService;\n protected readonly IInternetConnectivityService _connectivityService;\n protected readonly SoftwareAppsDialogService _dialogService;\n\n /// \n /// Gets or sets the reason for cancellation if an operation was cancelled.\n /// \n protected CancellationReason CurrentCancellationReason { get; set; } =\n CancellationReason.None;\n\n /// \n /// Gets or sets the status text.\n /// \n public string StatusText { get; set; } = \"Ready\";\n\n /// \n /// Gets or sets a value indicating whether the view model is initialized.\n /// \n public bool IsInitialized { get; set; } = false;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The search service.\n /// The package manager.\n /// The app installation service.\n /// The app installation coordinator service.\n /// The internet connectivity service.\n /// The specialized dialog service for software apps.\n protected BaseInstallationViewModel(\n ITaskProgressService progressService,\n ISearchService searchService,\n IPackageManager packageManager,\n IAppInstallationService appInstallationService,\n IAppInstallationCoordinatorService appInstallationCoordinatorService,\n IInternetConnectivityService connectivityService,\n SoftwareAppsDialogService dialogService\n )\n : base(progressService, searchService, packageManager)\n {\n _appInstallationService =\n appInstallationService\n ?? throw new ArgumentNullException(nameof(appInstallationService));\n _appInstallationCoordinatorService =\n appInstallationCoordinatorService\n ?? throw new ArgumentNullException(nameof(appInstallationCoordinatorService));\n _connectivityService =\n connectivityService ?? throw new ArgumentNullException(nameof(connectivityService));\n _dialogService =\n dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n }\n\n /// \n /// Loads apps and checks their installation status.\n /// \n /// A task representing the asynchronous operation.\n public async Task LoadAppsAndCheckInstallationStatusAsync()\n {\n if (IsInitialized)\n {\n System.Diagnostics.Debug.WriteLine(\n $\"{GetType().Name} already initialized, skipping LoadAppsAndCheckInstallationStatusAsync\"\n );\n return;\n }\n\n System.Diagnostics.Debug.WriteLine(\n $\"Starting {GetType().Name} LoadAppsAndCheckInstallationStatusAsync\"\n );\n await LoadItemsAsync();\n await CheckInstallationStatusAsync();\n\n // Mark as initialized after loading is complete\n IsInitialized = true;\n System.Diagnostics.Debug.WriteLine(\n $\"Completed {GetType().Name} LoadAppsAndCheckInstallationStatusAsync\"\n );\n }\n\n /// \n /// Checks if internet connectivity is available.\n /// \n /// Whether to show a dialog if connectivity is not available.\n /// True if internet is connected, false otherwise.\n protected async Task CheckInternetConnectivityAsync(bool showDialog = true)\n {\n bool isInternetConnected = await _connectivityService.IsInternetConnectedAsync(true);\n if (!isInternetConnected && showDialog)\n {\n StatusText = \"No internet connection available. Installation cannot proceed.\";\n\n // Show dialog informing the user about the connectivity issue\n await ShowNoInternetConnectionDialogAsync();\n }\n return isInternetConnected;\n }\n\n /// \n /// Shows a confirmation dialog for an operation.\n /// \n /// Type of operation (Install/Remove)\n /// List of apps selected for the operation\n /// List of apps that will be skipped (optional)\n /// Dialog result (true if confirmed, false if canceled)\n protected async Task ShowOperationConfirmationDialogAsync(\n string operationType,\n IEnumerable selectedApps,\n IEnumerable? skippedApps = null\n )\n {\n string title = $\"Confirm {operationType}\";\n string headerText = $\"The following items will be {GetPastTense(operationType)}:\";\n\n // Create list of app names for the dialog\n var appNames = selectedApps.Select(a => GetAppName(a)).ToList();\n\n // Create footer text\n string footerText = \"Do you want to continue?\";\n\n // If there are skipped apps, add information about them\n if (skippedApps != null && skippedApps.Any())\n {\n var skippedNames = skippedApps.Select(a => GetAppName(a)).ToList();\n footerText =\n $\"Note: The following {skippedApps.Count()} item(s) cannot be {GetPastTense(operationType)} and will be skipped:\\n\";\n footerText += string.Join(\", \", skippedNames);\n footerText +=\n $\"\\n\\nDo you want to continue with the remaining {selectedApps.Count()} item(s)?\";\n }\n\n // Build the message\n string message = $\"{headerText}\\n\";\n foreach (var name in appNames)\n {\n message += $\"{name}\\n\";\n }\n message += $\"\\n{footerText}\";\n\n // Show the confirmation dialog\n return await _dialogService.ShowConfirmationAsync(message, title);\n }\n\n /// \n /// Centralized method to handle the entire cancellation process.\n /// This method manages the cancellation state, logs the cancellation event,\n /// shows the appropriate dialog, and ensures proper cleanup.\n /// \n /// True if the cancellation was due to connectivity issues, false if user-initiated.\n /// A task that represents the asynchronous operation.\n protected async Task HandleCancellationAsync(bool isConnectivityIssue)\n {\n // Set the appropriate cancellation reason (state management)\n CurrentCancellationReason = isConnectivityIssue\n ? CancellationReason.InternetConnectivityLost\n : CancellationReason.UserCancelled;\n\n // Log the cancellation (diagnostics)\n System.Diagnostics.Debug.WriteLine(\n $\"[DEBUG] Installation {(isConnectivityIssue ? \"stopped due to connectivity loss\" : \"cancelled by user\")} - showing dialog\"\n );\n\n // Show the appropriate dialog (UI presentation - delegated to specialized method)\n await ShowCancellationDialogAsync(!isConnectivityIssue, isConnectivityIssue);\n\n // Reset cancellation reason after showing dialog (cleanup)\n CurrentCancellationReason = CancellationReason.None;\n }\n\n /// \n /// Shows an operation result dialog after operations complete.\n /// \n /// Type of operation (Install/Remove)\n /// Number of successful operations\n /// Total number of operations attempted\n /// List of successfully processed items\n /// List of failed items (optional)\n /// List of skipped items (optional)\n protected void ShowOperationResultDialog(\n string operationType,\n int successCount,\n int totalCount,\n IEnumerable successItems,\n IEnumerable? failedItems = null,\n IEnumerable? skippedItems = null\n )\n {\n // Determine if this was a user-initiated cancellation or connectivity issue\n bool isUserCancelled = CurrentCancellationReason == CancellationReason.UserCancelled;\n bool isConnectivityIssue =\n CurrentCancellationReason == CancellationReason.InternetConnectivityLost;\n\n // If the operation was cancelled by the user, use CustomDialog for a simpler message\n if (isUserCancelled)\n {\n string title = \"Installation Aborted by User\";\n string headerText = \"Installation aborted by user\";\n string message = \"The installation process was cancelled by the user.\";\n string footerText =\n successCount > 0\n ? $\"Some items were successfully {GetPastTense(operationType)} before cancellation.\"\n : $\"No items were {GetPastTense(operationType)} before cancellation.\";\n\n // Use CustomDialog directly instead of SoftwareAppsDialog\n CustomDialog.ShowInformation(title, headerText, message, footerText);\n\n // Reset cancellation reason after showing dialog\n CurrentCancellationReason = CancellationReason.None;\n return;\n }\n // If the operation was cancelled due to connectivity issues\n else if (isConnectivityIssue)\n {\n // Use the dialog service with the connectivity issue flag\n _dialogService.ShowOperationResult(\n operationType,\n successCount,\n totalCount,\n successItems,\n failedItems,\n skippedItems,\n true, // Connectivity issue flag\n false // Not a user cancellation\n );\n\n // Reset cancellation reason after showing dialog\n CurrentCancellationReason = CancellationReason.None;\n return;\n }\n\n // For normal operation results (no cancellation)\n // Check if any failures are due to internet connectivity issues\n bool hasConnectivityIssues = false;\n if (failedItems != null)\n {\n hasConnectivityIssues = failedItems.Any(item =>\n item.Contains(\"internet\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\"connection\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\"network\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\n \"pipeline has been stopped\",\n StringComparison.OrdinalIgnoreCase\n )\n );\n }\n\n // For normal operation results, use the dialog service\n _dialogService.ShowOperationResult(\n operationType,\n successCount,\n totalCount,\n successItems,\n failedItems,\n skippedItems,\n hasConnectivityIssues,\n false // Not a user cancellation\n );\n }\n\n /// \n /// Shows a dialog informing the user that no internet connection is available.\n /// \n protected Task ShowNoInternetConnectionDialogAsync()\n {\n // Use CustomDialog directly instead of SoftwareAppsDialog\n CustomDialog.ShowInformation(\n \"Internet Connection Required\",\n \"No internet connection available\",\n \"Internet connection is required to install apps.\",\n \"Please check your network connection and try again.\"\n );\n return Task.CompletedTask;\n }\n\n /// \n /// Shows a dialog informing the user that no items were selected for an operation.\n /// \n /// The action being performed (e.g., \"installation\", \"removal\")\n protected Task ShowNoItemsSelectedDialogAsync(string action)\n {\n return _dialogService.ShowInformationAsync(\n $\"No items were selected for {action}.\",\n $\"No Items Selected\",\n $\"Check the boxes next to the items you want to {action} and try again.\"\n );\n }\n\n /// \n /// Shows a confirmation dialog for an operation on multiple items.\n /// \n /// The action being performed (e.g., \"install\", \"remove\")\n /// The names of the items\n /// The number of items\n /// True if confirmed, false otherwise\n protected Task ShowConfirmItemsDialogAsync(\n string action,\n IEnumerable itemNames,\n int count\n )\n {\n var formattedItemNames = itemNames.Select(name => $\" {name}\");\n\n return _dialogService.ShowConfirmationAsync(\n $\"The following items will be {action}ed:\\n\"\n + string.Join(\"\\n\", formattedItemNames)\n + $\"\\n\\nDo you want to {action} {count} item(s)?\",\n $\"Confirm {CapitalizeFirstLetter(action)}\"\n );\n }\n\n /// \n /// Shows a dialog informing the user that items cannot be reinstalled.\n /// \n /// The names of the items that cannot be reinstalled\n /// Whether this is for a single item or multiple items\n protected Task ShowCannotReinstallDialogAsync(IEnumerable itemNames, bool isSingle)\n {\n string title = isSingle ? \"Cannot Install Item\" : \"Cannot Install Items\";\n string message = isSingle\n ? $\"{itemNames.First()} cannot be reinstalled.\"\n : \"None of the selected items can be reinstalled.\";\n\n return _dialogService.ShowInformationAsync(\n message,\n title,\n \"These items are already installed and cannot be reinstalled.\"\n );\n }\n\n /// \n /// Shows a dialog informing the user about the operation results.\n /// \n /// The action that was performed (e.g., \"install\", \"remove\")\n /// The number of successful operations\n /// The total number of operations attempted\n /// The names of successfully processed items\n /// The names of failed items (optional)\n protected Task ShowOperationResultDialogAsync(\n string action,\n int successCount,\n int totalCount,\n IEnumerable successItems,\n IEnumerable? failedItems = null\n )\n {\n string title = $\"{CapitalizeFirstLetter(action)} Results\";\n string message = $\"{successCount} of {totalCount} items were successfully {action}ed.\";\n\n return _dialogService.ShowInformationAsync(\n message,\n title,\n $\"The operation completed with {successCount} successes and {totalCount - successCount} failures.\"\n );\n }\n\n /// \n /// Shows a dialog informing the user about installation cancellation.\n /// Uses CustomDialog directly to ensure proper text formatting for long messages.\n /// \n /// True if the cancellation was initiated by the user, false otherwise.\n /// True if the cancellation was due to connectivity issues, false otherwise.\n /// A task that represents the asynchronous operation.\n protected Task ShowCancellationDialogAsync(bool isUserCancelled, bool isConnectivityIssue)\n {\n string title = isUserCancelled ? \"Installation Aborted\" : \"Internet Connection Lost\";\n\n string headerText = isUserCancelled\n ? \"Installation aborted by user\"\n : \"Installation stopped due to internet connection loss\";\n\n string message = isUserCancelled\n ? \"The installation process was cancelled by the user.\"\n : \"The installation process was stopped because the internet connection was lost.\\nThis is required to ensure installations complete properly and prevent corrupted installations.\";\n\n string footerText = isUserCancelled\n ? \"You can restart the installation when you're ready.\"\n : \"Please check your network connection and try again when your internet connection is stable.\";\n\n // Use CustomDialog directly instead of SoftwareAppsDialog\n CustomDialog.ShowInformation(title, headerText, message, footerText);\n return Task.CompletedTask;\n }\n\n /// \n /// Gets the past tense form of an operation type\n /// \n /// The operation type (e.g., \"Install\", \"Remove\")\n /// The past tense form of the operation type\n protected string GetPastTense(string operationType)\n {\n if (string.IsNullOrEmpty(operationType))\n return string.Empty;\n\n return operationType.Equals(\"Remove\", StringComparison.OrdinalIgnoreCase)\n ? \"removed\"\n : $\"{operationType.ToLower()}ed\";\n }\n\n /// \n /// Gets the name of an app.\n /// \n /// The app.\n /// The name of the app.\n protected abstract string GetAppName(T app);\n\n /// \n /// Converts an app to an AppInfo object.\n /// \n /// The app to convert.\n /// The AppInfo object.\n protected abstract AppInfo ToAppInfo(T app);\n\n /// \n /// Gets the selected apps.\n /// \n /// The selected apps.\n protected abstract IEnumerable GetSelectedApps();\n\n /// \n /// Sets the installation status of an app.\n /// \n /// The app.\n /// Whether the app is installed.\n protected abstract void SetInstallationStatus(T app, bool isInstalled);\n\n /// \n /// Capitalizes the first letter of a string.\n /// \n /// The input string\n /// The string with the first letter capitalized\n protected string CapitalizeFirstLetter(string input)\n {\n if (string.IsNullOrEmpty(input))\n return string.Empty;\n\n return char.ToUpper(input[0]) + input.Substring(1);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/InternetConnectivityService.cs", "using System;\nusing System.Net.Http;\nusing System.Net.NetworkInformation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service for checking and monitoring internet connectivity.\n /// \n public class InternetConnectivityService : IInternetConnectivityService, IDisposable\n {\n // List of reliable domains to check for internet connectivity\n private static readonly string[] _connectivityCheckUrls = new string[]\n {\n \"https://www.microsoft.com\",\n \"https://www.google.com\",\n \"https://www.cloudflare.com\",\n };\n\n // HttpClient for internet connectivity checks\n private readonly HttpClient _httpClient;\n\n // Cache the internet connectivity status to avoid frequent checks\n private bool? _cachedInternetStatus = null;\n private DateTime _lastInternetCheckTime = DateTime.MinValue;\n private readonly TimeSpan _internetStatusCacheDuration = TimeSpan.FromSeconds(10); // Cache for 10 seconds\n private readonly ILogService _logService;\n \n // Monitoring-related fields\n private CancellationTokenSource _monitoringCts;\n private Task _monitoringTask;\n private bool _isMonitoring;\n private int _monitoringIntervalSeconds;\n\n /// \n /// Event that is raised when the internet connectivity status changes.\n /// \n public event EventHandler ConnectivityChanged;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public InternetConnectivityService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n\n // Initialize HttpClient with a timeout\n _httpClient = new HttpClient();\n _httpClient.Timeout = TimeSpan.FromSeconds(5); // Short timeout for connectivity checks\n }\n\n /// \n /// Checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// True if internet is connected, false otherwise.\n public bool IsInternetConnected(bool forceCheck = false)\n {\n try\n {\n // Return cached result if it's still valid and force check is not requested\n if (\n !forceCheck\n && _cachedInternetStatus.HasValue\n && (DateTime.Now - _lastInternetCheckTime) < _internetStatusCacheDuration\n )\n {\n _logService.LogInformation(\n $\"Using cached internet connectivity status: {_cachedInternetStatus.Value}\"\n );\n return _cachedInternetStatus.Value;\n }\n\n // First check: NetworkInterface.GetIsNetworkAvailable()\n bool isNetworkAvailable = NetworkInterface.GetIsNetworkAvailable();\n if (!isNetworkAvailable)\n {\n _logService.LogInformation(\n \"Network is not available according to NetworkInterface.GetIsNetworkAvailable()\"\n );\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n return false;\n }\n\n // Second check: Ping network interfaces\n bool hasInternetAccess = false;\n try\n {\n NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();\n foreach (NetworkInterface ni in interfaces)\n {\n if (\n ni.OperationalStatus == OperationalStatus.Up\n && (\n ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211\n || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet\n )\n && ni.GetIPProperties().GatewayAddresses.Count > 0\n )\n {\n hasInternetAccess = true;\n break;\n }\n }\n\n if (!hasInternetAccess)\n {\n _logService.LogInformation(\n \"No active network interfaces with gateway addresses found\"\n );\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.LogWarning($\"Error checking network interfaces: {ex.Message}\");\n // Continue to the next check even if this one fails\n }\n\n // Third check: Try to connect to reliable domains\n foreach (string url in _connectivityCheckUrls)\n {\n try\n {\n // Make a HEAD request to minimize data transfer\n var request = new HttpRequestMessage(HttpMethod.Head, url);\n var response = _httpClient.SendAsync(request).GetAwaiter().GetResult();\n\n if (response.IsSuccessStatusCode)\n {\n _logService.LogInformation($\"Successfully connected to {url}\");\n _cachedInternetStatus = true;\n _lastInternetCheckTime = DateTime.Now;\n return true;\n }\n }\n catch (Exception ex)\n {\n _logService.LogInformation($\"Failed to connect to {url}: {ex.Message}\");\n // Try the next URL\n }\n }\n\n // If we get here, all connectivity checks failed\n _logService.LogWarning(\"All internet connectivity checks failed\");\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n return false;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking internet connectivity\", ex);\n return false;\n }\n }\n\n /// \n /// Asynchronously checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// Cancellation token for the operation.\n /// True if internet is connected, false otherwise.\n public async Task IsInternetConnectedAsync(\n bool forceCheck = false,\n CancellationToken cancellationToken = default,\n bool userInitiatedCancellation = false\n )\n {\n try\n {\n // Check for cancellation before doing anything\n if (cancellationToken.IsCancellationRequested)\n {\n _logService.LogInformation(userInitiatedCancellation ? \"Internet connectivity check was cancelled by user\" : \"Internet connectivity check was cancelled as part of operation cancellation\");\n throw new OperationCanceledException(cancellationToken);\n }\n \n // Return cached result if it's still valid and force check is not requested\n if (\n !forceCheck\n && _cachedInternetStatus.HasValue\n && (DateTime.Now - _lastInternetCheckTime) < _internetStatusCacheDuration\n )\n {\n _logService.LogInformation(\n $\"Using cached internet connectivity status: {_cachedInternetStatus.Value}\"\n );\n return _cachedInternetStatus.Value;\n }\n\n // First check: NetworkInterface.GetIsNetworkAvailable()\n bool isNetworkAvailable = NetworkInterface.GetIsNetworkAvailable();\n if (!isNetworkAvailable)\n {\n _logService.LogInformation(\n \"Network is not available according to NetworkInterface.GetIsNetworkAvailable()\"\n );\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false));\n \n return false;\n }\n\n // Second check: Ping network interfaces\n bool hasInternetAccess = false;\n try\n {\n // Check for cancellation before network interface check\n if (cancellationToken.IsCancellationRequested)\n {\n _logService.LogInformation(userInitiatedCancellation ? \"Internet connectivity check was cancelled by user\" : \"Internet connectivity check was cancelled as part of operation cancellation\");\n throw new OperationCanceledException(cancellationToken);\n }\n \n NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();\n foreach (NetworkInterface ni in interfaces)\n {\n if (\n ni.OperationalStatus == OperationalStatus.Up\n && (\n ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211\n || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet\n )\n && ni.GetIPProperties().GatewayAddresses.Count > 0\n )\n {\n hasInternetAccess = true;\n break;\n }\n }\n\n if (!hasInternetAccess)\n {\n _logService.LogInformation(\n \"No active network interfaces with gateway addresses found\"\n );\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false));\n \n return false;\n }\n }\n catch (OperationCanceledException)\n {\n // This is a user-initiated cancellation, not a connectivity issue\n _logService.LogInformation(userInitiatedCancellation ? \"Internet connectivity check was cancelled by user\" : \"Internet connectivity check was cancelled as part of operation cancellation\");\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false, userInitiatedCancellation));\n \n throw; // Re-throw to be handled by the caller\n }\n catch (Exception ex)\n {\n _logService.LogWarning($\"Error checking network interfaces: {ex.Message}\");\n // Continue to the next check even if this one fails\n }\n\n // Third check: Try to connect to reliable domains\n foreach (string url in _connectivityCheckUrls)\n {\n try\n {\n // Check for cancellation before making the request\n if (cancellationToken.IsCancellationRequested)\n {\n // This is a user-initiated cancellation, not a connectivity issue\n _logService.LogInformation(userInitiatedCancellation ? \"Internet connectivity check was cancelled by user\" : \"Internet connectivity check was cancelled as part of operation cancellation\");\n throw new OperationCanceledException(cancellationToken);\n }\n \n // Make a HEAD request to minimize data transfer\n var request = new HttpRequestMessage(HttpMethod.Head, url);\n var response = await _httpClient.SendAsync(request, cancellationToken);\n\n if (response.IsSuccessStatusCode)\n {\n _logService.LogInformation($\"Successfully connected to {url}\");\n _cachedInternetStatus = true;\n _lastInternetCheckTime = DateTime.Now;\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(true));\n \n return true;\n }\n }\n catch (OperationCanceledException)\n {\n // This is a user-initiated cancellation, not a connectivity issue\n _logService.LogInformation(userInitiatedCancellation ? \"Internet connectivity check was cancelled by user\" : \"Internet connectivity check was cancelled as part of operation cancellation\");\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false, userInitiatedCancellation));\n \n throw; // Re-throw to be handled by the caller\n }\n catch (Exception ex)\n {\n _logService.LogInformation($\"Failed to connect to {url}: {ex.Message}\");\n // Try the next URL\n }\n }\n\n // If we get here, all connectivity checks failed\n _logService.LogWarning(\"All internet connectivity checks failed\");\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false));\n \n return false;\n }\n catch (OperationCanceledException)\n {\n // This is a user-initiated cancellation, not a connectivity issue\n _logService.LogInformation(\"Internet connectivity check was cancelled by user\");\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false, true));\n \n throw; // Re-throw to be handled by the caller\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking internet connectivity\", ex);\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false));\n \n return false;\n }\n }\n \n /// \n /// Starts monitoring internet connectivity at the specified interval.\n /// \n /// The interval in seconds between connectivity checks.\n /// Cancellation token to stop monitoring.\n /// A task representing the monitoring operation.\n public async Task StartMonitoringAsync(int intervalSeconds = 5, CancellationToken cancellationToken = default)\n {\n if (_isMonitoring)\n {\n _logService.LogWarning(\"Internet connectivity monitoring is already active\");\n return;\n }\n \n _monitoringIntervalSeconds = intervalSeconds;\n _monitoringCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n _isMonitoring = true;\n \n _logService.LogInformation($\"Starting internet connectivity monitoring with {intervalSeconds} second interval\");\n \n _monitoringTask = Task.Run(async () =>\n {\n try\n {\n bool? lastStatus = null;\n \n while (!_monitoringCts.Token.IsCancellationRequested)\n {\n try\n {\n bool currentStatus = await IsInternetConnectedAsync(true, _monitoringCts.Token);\n \n // Only raise the event if the status has changed\n if (lastStatus == null || lastStatus.Value != currentStatus)\n {\n _logService.LogInformation($\"Internet connectivity status changed: {currentStatus}\");\n lastStatus = currentStatus;\n }\n \n // Wait for the specified interval\n await Task.Delay(TimeSpan.FromSeconds(_monitoringIntervalSeconds), _monitoringCts.Token);\n }\n catch (OperationCanceledException)\n {\n // Check if this is a user-initiated cancellation or just the monitoring being stopped\n if (_monitoringCts.Token.IsCancellationRequested)\n {\n _logService.LogInformation(\"Internet connectivity monitoring was cancelled\");\n break;\n }\n \n // If it's a user-initiated cancellation during a connectivity check, continue monitoring\n _logService.LogInformation(\"Internet connectivity check was cancelled by user, continuing monitoring\");\n await Task.Delay(TimeSpan.FromSeconds(_monitoringIntervalSeconds), _monitoringCts.Token);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error during internet connectivity monitoring\", ex);\n await Task.Delay(TimeSpan.FromSeconds(_monitoringIntervalSeconds), _monitoringCts.Token);\n }\n }\n }\n catch (OperationCanceledException)\n {\n // Expected when monitoring is stopped\n _logService.LogInformation(\"Internet connectivity monitoring was stopped\");\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error in internet connectivity monitoring task\", ex);\n }\n finally\n {\n _isMonitoring = false;\n }\n }, _monitoringCts.Token);\n \n await Task.CompletedTask;\n }\n \n /// \n /// Stops monitoring internet connectivity.\n /// \n public void StopMonitoring()\n {\n if (!_isMonitoring)\n {\n return;\n }\n \n _logService.LogInformation(\"Stopping internet connectivity monitoring\");\n \n try\n {\n _monitoringCts?.Cancel();\n _monitoringCts?.Dispose();\n _monitoringCts = null;\n _monitoringTask = null;\n _isMonitoring = false;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error stopping internet connectivity monitoring\", ex);\n }\n }\n \n /// \n /// Raises the ConnectivityChanged event.\n /// \n /// The event arguments.\n protected virtual void OnConnectivityChanged(ConnectivityChangedEventArgs args)\n {\n if (_isMonitoring)\n {\n ConnectivityChanged?.Invoke(this, args);\n }\n }\n \n /// \n /// Disposes the resources used by the service.\n /// \n public void Dispose()\n {\n StopMonitoring();\n _httpClient?.Dispose();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/WindowsAppsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.SoftwareApps.Models;\nusing ToastType = Winhance.Core.Features.UI.Interfaces.ToastType;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n public partial class WindowsAppsViewModel : BaseInstallationViewModel\n {\n private readonly IAppInstallationService _appInstallationService;\n private readonly ICapabilityInstallationService _capabilityService;\n private readonly IFeatureInstallationService _featureService;\n private readonly IFeatureRemovalService _featureRemovalService;\n private readonly IAppService _appDiscoveryService;\n private readonly IConfigurationService _configurationService;\n private readonly IScriptDetectionService _scriptDetectionService;\n private readonly IInternetConnectivityService _connectivityService;\n private readonly IAppInstallationCoordinatorService _appInstallationCoordinatorService;\n\n [ObservableProperty]\n private string _statusText = \"Ready\";\n\n [ObservableProperty]\n private bool _isRemovingApps;\n\n [ObservableProperty]\n private ObservableCollection _activeScripts = new();\n\n // Flag to prevent duplicate initialization\n [ObservableProperty]\n private bool _isInitialized = false;\n\n // For binding in the WindowsAppsView - filtered collections\n // Standard Windows Apps (Appx packages)\n public System.Collections.ObjectModel.ObservableCollection WindowsApps { get; } =\n new();\n\n // Windows Capabilities\n public System.Collections.ObjectModel.ObservableCollection Capabilities { get; } =\n new();\n\n // Optional Features\n public System.Collections.ObjectModel.ObservableCollection OptionalFeatures { get; } =\n new();\n\n public WindowsAppsViewModel(\n ITaskProgressService progressService,\n ISearchService searchService,\n IPackageManager packageManager,\n IAppInstallationService appInstallationService,\n ICapabilityInstallationService capabilityService,\n IFeatureInstallationService featureService,\n IFeatureRemovalService featureRemovalService,\n IConfigurationService configurationService,\n IScriptDetectionService scriptDetectionService,\n IInternetConnectivityService connectivityService,\n IAppInstallationCoordinatorService appInstallationCoordinatorService,\n Services.SoftwareAppsDialogService dialogService\n )\n : base(\n progressService,\n searchService,\n packageManager,\n appInstallationService,\n appInstallationCoordinatorService,\n connectivityService,\n dialogService\n )\n {\n _appInstallationService = appInstallationService;\n _capabilityService = capabilityService;\n _featureService = featureService;\n _featureRemovalService = featureRemovalService;\n _appDiscoveryService = packageManager?.AppDiscoveryService;\n _configurationService = configurationService;\n _scriptDetectionService = scriptDetectionService;\n _connectivityService = connectivityService;\n _appInstallationCoordinatorService = appInstallationCoordinatorService;\n }\n\n // SaveConfig and ImportConfig methods removed as part of unified configuration cleanup\n\n /// \n /// Applies the current search text to filter items.\n /// \n protected override void ApplySearch()\n {\n if (Items == null || Items.Count == 0)\n return;\n\n // Clear all collections\n WindowsApps.Clear();\n Capabilities.Clear();\n OptionalFeatures.Clear();\n\n // Filter items based on search text\n var filteredItems = FilterItems(Items);\n\n // Add filtered items to their respective collections\n foreach (var app in filteredItems)\n {\n switch (app.AppType)\n {\n case Models.WindowsAppType.StandardApp:\n WindowsApps.Add(app);\n break;\n case Models.WindowsAppType.Capability:\n Capabilities.Add(app);\n break;\n case Models.WindowsAppType.OptionalFeature:\n OptionalFeatures.Add(app);\n break;\n }\n }\n\n // Sort the filtered collections\n SortCollections();\n }\n\n /// \n /// Refreshes the script status information.\n /// \n public void RefreshScriptStatus()\n {\n if (_scriptDetectionService == null)\n return;\n\n IsRemovingApps = _scriptDetectionService.AreRemovalScriptsPresent();\n\n ActiveScripts.Clear();\n foreach (var script in _scriptDetectionService.GetActiveScripts())\n {\n ActiveScripts.Add(script);\n }\n }\n\n public override async Task LoadItemsAsync()\n {\n if (_appDiscoveryService == null)\n return;\n\n IsLoading = true;\n StatusText = \"Loading Windows apps...\";\n\n try\n {\n // Clear all collections\n Items.Clear();\n WindowsApps.Clear();\n Capabilities.Clear();\n OptionalFeatures.Clear();\n\n // Load standard Windows apps (Appx packages)\n var apps = await _appDiscoveryService.GetStandardAppsAsync();\n\n // Load capabilities\n var capabilities = await _appDiscoveryService.GetCapabilitiesAsync();\n\n // Load optional features\n var features = await _appDiscoveryService.GetOptionalFeaturesAsync();\n\n // Convert all to WindowsApp objects and add to the main collection\n foreach (var app in apps)\n {\n var windowsApp = WindowsApp.FromAppInfo(app);\n // AppType is already set in FromAppInfo\n Items.Add(windowsApp);\n WindowsApps.Add(windowsApp);\n }\n\n foreach (var capability in capabilities)\n {\n var windowsApp = WindowsApp.FromCapabilityInfo(capability);\n // AppType is already set in FromCapabilityInfo\n Items.Add(windowsApp);\n Capabilities.Add(windowsApp);\n }\n\n foreach (var feature in features)\n {\n var windowsApp = WindowsApp.FromFeatureInfo(feature);\n // AppType is already set in FromFeatureInfo\n Items.Add(windowsApp);\n OptionalFeatures.Add(windowsApp);\n }\n\n StatusText =\n $\"Loaded {WindowsApps.Count} apps, {Capabilities.Count} capabilities, and {OptionalFeatures.Count} features\";\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error loading Windows apps: {ex.Message}\";\n }\n finally\n {\n IsLoading = false;\n\n // Check script status\n RefreshScriptStatus();\n }\n }\n\n public override async Task CheckInstallationStatusAsync()\n {\n if (_appDiscoveryService == null)\n return;\n\n IsLoading = true;\n StatusText = \"Checking installation status...\";\n\n try\n {\n var statusResults = await _appDiscoveryService.GetBatchInstallStatusAsync(\n Items.Select(a => a.PackageName)\n );\n\n foreach (var app in Items)\n {\n if (statusResults.TryGetValue(app.PackageName, out bool isInstalled))\n {\n app.IsInstalled = isInstalled;\n }\n }\n\n // Sort all collections after we have the installation status\n SortCollections();\n\n StatusText = \"Installation status check complete\";\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error checking installation status: {ex.Message}\";\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n private void SortCollections()\n {\n // Sort apps within each collection by installed status (installed first) then alphabetically\n SortCollection(WindowsApps);\n SortCollection(Capabilities);\n SortCollection(OptionalFeatures);\n }\n\n private void SortCollection(\n System.Collections.ObjectModel.ObservableCollection collection\n )\n {\n var sorted = collection\n .OrderByDescending(app => app.IsInstalled) // Installed first\n .ThenBy(app => app.Name) // Then alphabetically\n .ToList();\n\n collection.Clear();\n foreach (var app in sorted)\n {\n collection.Add(app);\n }\n }\n\n #region Dialog Helper Methods\n\n /// \n /// Gets the past tense form of an operation type\n /// \n /// The operation type (e.g., \"Install\", \"Remove\")\n /// The past tense form of the operation type\n private string GetPastTense(string operationType)\n {\n if (string.IsNullOrEmpty(operationType))\n return string.Empty;\n\n return operationType.Equals(\"Remove\", StringComparison.OrdinalIgnoreCase)\n ? \"removed\"\n : $\"{operationType.ToLower()}ed\";\n }\n\n /// \n /// Shows a confirmation dialog before performing operations.\n /// \n /// Type of operation (Install/Remove)\n /// List of apps selected for the operation\n /// List of apps that will be skipped (optional)\n /// Dialog result (true if confirmed, false if canceled)\n private bool? ShowOperationConfirmationDialog(\n string operationType,\n IEnumerable selectedApps,\n IEnumerable? skippedApps = null\n )\n {\n // Use the base class implementation that uses the dialog service\n var result = ShowOperationConfirmationDialogAsync(\n operationType,\n selectedApps,\n skippedApps\n )\n .GetAwaiter()\n .GetResult();\n return result ? true : (bool?)false;\n }\n\n /// \n /// Shows an operation result dialog after operations complete.\n /// \n /// Type of operation (Install/Remove)\n /// Number of successful operations\n /// Total number of operations attempted\n /// List of successfully processed items\n /// List of failed items (optional)\n /// List of skipped items (optional)\n private void ShowOperationResultDialog(\n string operationType,\n int successCount,\n int totalCount,\n IEnumerable successItems,\n IEnumerable? failedItems = null,\n IEnumerable? skippedItems = null\n )\n {\n // Use the base class implementation that uses the dialog service\n base.ShowOperationResultDialog(\n operationType,\n successCount,\n totalCount,\n successItems,\n failedItems,\n skippedItems\n );\n }\n\n #endregion\n\n public async Task LoadAppsAndCheckInstallationStatusAsync()\n {\n if (IsInitialized)\n {\n System.Diagnostics.Debug.WriteLine(\n \"WindowsAppsViewModel already initialized, skipping LoadAppsAndCheckInstallationStatusAsync\"\n );\n return;\n }\n\n System.Diagnostics.Debug.WriteLine(\"Starting LoadAppsAndCheckInstallationStatusAsync\");\n await LoadItemsAsync();\n await CheckInstallationStatusAsync();\n\n // Set Select All to true by default when view loads\n IsAllSelected = true;\n\n // Mark as initialized after loading is complete\n IsInitialized = true;\n\n // Check script status\n RefreshScriptStatus();\n System.Diagnostics.Debug.WriteLine(\"Completed LoadAppsAndCheckInstallationStatusAsync\");\n }\n\n [RelayCommand]\n public async Task InstallApp(WindowsApp app)\n {\n if (app == null || _appInstallationService == null)\n System.Diagnostics.Debug.WriteLine(\n \"Starting LoadAppsAndCheckInstallationStatusAsync\"\n );\n await LoadItemsAsync();\n await CheckInstallationStatusAsync();\n\n // Set Select All to true by default when view loads\n IsAllSelected = true;\n bool isInternetConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(true);\n if (!isInternetConnected)\n {\n StatusText = \"No internet connection available. Installation cannot proceed.\";\n\n // Show dialog informing the user about the connectivity issue\n await ShowNoInternetConnectionDialogAsync();\n return;\n }\n\n // Show confirmation dialog\n bool? dialogResult = ShowOperationConfirmationDialog(\"Install\", new[] { app });\n\n // If user didn't confirm, exit\n if (dialogResult != true)\n {\n return;\n }\n\n IsLoading = true;\n StatusText = $\"Installing {app.Name}...\";\n\n // Setup cancellation for the installation process\n using var cts = new System.Threading.CancellationTokenSource();\n var cancellationToken = cts.Token;\n\n try\n {\n var progress = _progressService.CreateDetailedProgress();\n\n // Subscribe to installation status changes\n void OnInstallationStatusChanged(\n object sender,\n InstallationStatusChangedEventArgs e\n )\n {\n if (e.AppInfo.PackageID == app.PackageID)\n {\n StatusText = e.StatusMessage;\n }\n }\n\n // Register for status updates\n _appInstallationCoordinatorService.InstallationStatusChanged +=\n OnInstallationStatusChanged;\n\n try\n {\n // Use the coordinator service to handle installation, connectivity monitoring, and status reporting\n var coordinationResult =\n await _appInstallationCoordinatorService.InstallAppAsync(\n app.ToAppInfo(),\n progress,\n cancellationToken\n );\n\n if (coordinationResult.Success)\n {\n app.IsInstalled = true;\n StatusText = $\"Successfully installed {app.Name}\";\n\n // Show result dialog\n ShowOperationResultDialog(\"Install\", 1, 1, new[] { app.Name });\n }\n else\n {\n string errorMessage =\n coordinationResult.ErrorMessage\n ?? $\"Failed to install {app.Name}. Please try again.\";\n StatusText = errorMessage;\n\n // Determine the type of failure for the dialog\n if (coordinationResult.WasCancelled)\n {\n // Show cancellation dialog\n ShowOperationResultDialog(\n \"Install\",\n 0,\n 1,\n Array.Empty(),\n new[] { $\"{app.Name}: Installation was cancelled by user\" }\n );\n }\n else if (coordinationResult.WasConnectivityIssue)\n {\n // Show connectivity issue dialog\n ShowOperationResultDialog(\n \"Install\",\n 0,\n 1,\n Array.Empty(),\n new[]\n {\n $\"{app.Name}: Internet connection lost during installation. Please check your network connection and try again.\",\n }\n );\n }\n else\n {\n // Show general error dialog\n ShowOperationResultDialog(\n \"Install\",\n 0,\n 1,\n Array.Empty(),\n new[] { $\"{app.Name}: {errorMessage}\" }\n );\n }\n }\n }\n finally\n {\n // Always unregister from the event\n _appInstallationCoordinatorService.InstallationStatusChanged -=\n OnInstallationStatusChanged;\n }\n }\n catch (System.Exception ex)\n {\n // This should rarely happen as most exceptions are handled by the coordinator service\n StatusText = $\"Error installing {app.Name}: {ex.Message}\";\n\n // Show error dialog\n ShowOperationResultDialog(\n \"Install\",\n 0,\n 1,\n Array.Empty(),\n new[] { $\"{app.Name}: {ex.Message}\" }\n );\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n // The StartPeriodicConnectivityCheck method has been removed as this functionality is now handled by the AppInstallationCoordinatorService\n\n [RelayCommand]\n public async Task RemoveApp(WindowsApp app)\n {\n if (app == null || _packageManager == null)\n return;\n\n // Show confirmation dialog\n bool? dialogResult = ShowOperationConfirmationDialog(\"Remove\", new[] { app });\n\n // If user didn't confirm, exit\n if (dialogResult != true)\n {\n return;\n }\n\n IsLoading = true;\n StatusText = $\"Removing {app.Name}...\";\n bool success = false;\n\n try\n {\n // Check if this is a special app that requires special handling\n if (app.IsSpecialHandler && !string.IsNullOrEmpty(app.SpecialHandlerType))\n {\n // Use the appropriate special handler method\n switch (app.SpecialHandlerType)\n {\n case \"Edge\":\n success = await _packageManager.RemoveEdgeAsync();\n break;\n case \"OneDrive\":\n success = await _packageManager.RemoveOneDriveAsync();\n break;\n case \"OneNote\":\n success = await _packageManager.RemoveOneNoteAsync();\n break;\n default:\n success = await _packageManager.RemoveSpecialAppAsync(\n app.SpecialHandlerType\n );\n break;\n }\n\n if (success)\n {\n app.IsInstalled = false;\n StatusText = $\"Successfully removed special app: {app.Name}\";\n }\n else\n {\n StatusText = $\"Failed to remove special app: {app.Name}\";\n }\n }\n else\n {\n // Regular app removal\n bool isCapability =\n app.AppType\n == Winhance.WPF.Features.SoftwareApps.Models.WindowsAppType.Capability;\n success = await _packageManager.RemoveAppAsync(app.PackageName, isCapability);\n if (success)\n {\n app.IsInstalled = false;\n StatusText = $\"Successfully removed {app.Name}\";\n }\n else\n {\n StatusText = $\"Failed to remove {app.Name}\";\n }\n }\n\n // Show result dialog\n ShowOperationResultDialog(\n \"Remove\",\n success ? 1 : 0,\n 1,\n success ? new[] { app.Name } : Array.Empty(),\n success ? Array.Empty() : new[] { app.Name }\n );\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error removing {app.Name}: {ex.Message}\";\n\n // Show error dialog\n ShowOperationResultDialog(\n \"Remove\",\n 0,\n 1,\n Array.Empty(),\n new[] { $\"{app.Name}: {ex.Message}\" }\n );\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n public override async void OnNavigatedTo(object parameter)\n {\n try\n {\n // Only load data if not already initialized\n if (!IsInitialized)\n {\n await LoadAppsAndCheckInstallationStatusAsync();\n IsInitialized = true;\n }\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error loading apps: {ex.Message}\";\n IsLoading = false;\n // Log the error or handle it appropriately\n }\n }\n\n // Add IsAllSelected property for the \"Select All\" checkbox\n private bool _isAllSelected;\n public bool IsAllSelected\n {\n get => _isAllSelected;\n set\n {\n if (SetProperty(ref _isAllSelected, value))\n {\n // Apply to all items across all categories\n foreach (var app in WindowsApps)\n {\n app.IsSelected = value;\n }\n\n foreach (var capability in Capabilities)\n {\n capability.IsSelected = value;\n }\n\n foreach (var feature in OptionalFeatures)\n {\n feature.IsSelected = value;\n }\n }\n }\n }\n\n [RelayCommand]\n public async Task RemoveApps()\n {\n if (_packageManager == null)\n return;\n\n // Get selected items from all categories\n var selectedApps = WindowsApps.Where(a => a.IsSelected).ToList();\n var selectedCapabilities = Capabilities.Where(a => a.IsSelected).ToList();\n var selectedFeatures = OptionalFeatures.Where(a => a.IsSelected).ToList();\n\n // Combine all selected items\n var allSelectedItems = selectedApps\n .Concat(selectedCapabilities.Cast())\n .Concat(selectedFeatures.Cast())\n .ToList();\n\n int totalSelected = allSelectedItems.Count;\n\n if (totalSelected == 0)\n {\n StatusText = \"No items selected for removal\";\n return;\n }\n\n // Show confirmation dialog\n bool? dialogResult = ShowOperationConfirmationDialog(\"Remove\", allSelectedItems);\n\n // If user didn't confirm, exit\n if (dialogResult != true)\n {\n return;\n }\n\n // Use the ExecuteWithProgressAsync method from BaseViewModel to handle progress reporting\n await ExecuteWithProgressAsync(\n async (progress, cancellationToken) =>\n {\n int successCount = 0;\n int currentItem = 0;\n\n // Process standard Windows apps\n foreach (var app in selectedApps)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Removing app {app.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage = $\"Removing Windows App: {app.Name}\",\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", app.AppType.ToString() },\n { \"PackageName\", app.PackageName },\n { \"IsSystemProtected\", app.IsSystemProtected.ToString() },\n { \"CanBeReinstalled\", app.CanBeReinstalled.ToString() },\n { \"OperationType\", \"Remove\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n\n try\n {\n // Check if this is a special app that requires special handling\n if (\n app.IsSpecialHandler\n && !string.IsNullOrEmpty(app.SpecialHandlerType)\n )\n {\n // Use the appropriate special handler method\n bool success = false;\n switch (app.SpecialHandlerType)\n {\n case \"Edge\":\n success = await _packageManager.RemoveEdgeAsync();\n break;\n case \"OneDrive\":\n success = await _packageManager.RemoveOneDriveAsync();\n break;\n case \"OneNote\":\n success = await _packageManager.RemoveOneNoteAsync();\n break;\n default:\n success = await _packageManager.RemoveSpecialAppAsync(\n app.SpecialHandlerType\n );\n break;\n }\n\n if (success)\n {\n app.IsInstalled = false;\n successCount++;\n }\n }\n else\n {\n // Regular app removal\n bool success = await _packageManager.RemoveAppAsync(\n app.PackageName,\n false\n );\n if (success)\n {\n app.IsInstalled = false;\n successCount++;\n }\n }\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Successfully removed {app.Name}\",\n DetailedMessage =\n $\"Successfully removed Windows App: {app.Name}\",\n LogLevel = LogLevel.Success,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", app.AppType.ToString() },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Success\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Error removing {app.Name}\",\n DetailedMessage = $\"Error removing {app.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", app.AppType.ToString() },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Error\" },\n { \"ErrorMessage\", ex.Message },\n { \"ErrorType\", ex.GetType().Name },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n\n // Process capabilities\n foreach (var capability in selectedCapabilities)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Removing capability {capability.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage = $\"Removing Windows Capability: {capability.Name}\",\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", capability.AppType.ToString() },\n { \"PackageName\", capability.PackageName },\n {\n \"IsSystemProtected\",\n capability.IsSystemProtected.ToString()\n },\n { \"CanBeReinstalled\", capability.CanBeReinstalled.ToString() },\n { \"OperationType\", \"Remove\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n\n try\n {\n bool success = await _packageManager.RemoveAppAsync(\n capability.PackageName,\n true\n );\n\n if (success)\n {\n capability.IsInstalled = false;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Successfully removed capability {capability.Name}\",\n DetailedMessage =\n $\"Successfully removed Windows Capability: {capability.Name}\",\n LogLevel = LogLevel.Success,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", capability.AppType.ToString() },\n { \"PackageName\", capability.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Success\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n else\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Failed to remove capability {capability.Name}\",\n DetailedMessage =\n $\"Failed to remove Windows Capability: {capability.Name}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", capability.AppType.ToString() },\n { \"PackageName\", capability.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Error\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Error removing capability {capability.Name}\",\n DetailedMessage =\n $\"Error removing capability {capability.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", capability.AppType.ToString() },\n { \"PackageName\", capability.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Error\" },\n { \"ErrorMessage\", ex.Message },\n { \"ErrorType\", ex.GetType().Name },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n\n // Process optional features\n foreach (var feature in selectedFeatures)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Removing feature {feature.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage = $\"Removing Windows Feature: {feature.Name}\",\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", feature.AppType.ToString() },\n { \"PackageName\", feature.PackageName },\n { \"IsSystemProtected\", feature.IsSystemProtected.ToString() },\n { \"CanBeReinstalled\", feature.CanBeReinstalled.ToString() },\n { \"OperationType\", \"Remove\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n\n try\n {\n if (_featureRemovalService != null)\n {\n bool success = await _featureRemovalService.RemoveFeatureAsync(\n feature.ToFeatureInfo()\n );\n if (success)\n {\n feature.IsInstalled = false;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Successfully removed feature {feature.Name}\",\n DetailedMessage =\n $\"Successfully removed Windows Feature: {feature.Name}\",\n LogLevel = LogLevel.Success,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", feature.AppType.ToString() },\n { \"PackageName\", feature.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Success\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n else\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Failed to remove feature {feature.Name}\",\n DetailedMessage =\n $\"Failed to remove Windows Feature: {feature.Name}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", feature.AppType.ToString() },\n { \"PackageName\", feature.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Error\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Error removing feature {feature.Name}\",\n DetailedMessage =\n $\"Error removing feature {feature.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", feature.AppType.ToString() },\n { \"PackageName\", feature.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Error\" },\n { \"ErrorMessage\", ex.Message },\n { \"ErrorType\", ex.GetType().Name },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n\n // Final report\n progress.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText =\n $\"Successfully removed {successCount} of {totalSelected} items\",\n DetailedMessage =\n $\"Task completed: {successCount} of {totalSelected} items removed successfully\",\n LogLevel =\n successCount == totalSelected ? LogLevel.Success : LogLevel.Warning,\n AdditionalInfo = new Dictionary\n {\n { \"OperationType\", \"Remove\" },\n {\n \"OperationStatus\",\n successCount == totalSelected ? \"Complete\" : \"PartialSuccess\"\n },\n { \"SuccessCount\", successCount.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n { \"SuccessRate\", $\"{(successCount * 100.0 / totalSelected):F1}%\" },\n { \"StandardAppsCount\", selectedApps.Count.ToString() },\n { \"CapabilitiesCount\", selectedCapabilities.Count.ToString() },\n { \"FeaturesCount\", selectedFeatures.Count.ToString() },\n {\n \"CompletionTime\",\n System.DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\")\n },\n },\n }\n );\n\n // Refresh the UI\n SortCollections();\n\n // Check if the operation was cancelled by the user or due to connectivity issues\n if (CurrentCancellationReason == CancellationReason.UserCancelled)\n {\n // Log the user cancellation\n System.Diagnostics.Debug.WriteLine(\"[DEBUG] Installation cancelled by user - showing user cancellation dialog\");\n \n // Show the cancellation dialog\n await ShowCancellationDialogAsync(true, false);\n \n // Reset cancellation reason after showing dialog\n CurrentCancellationReason = CancellationReason.None;\n return successCount;\n }\n else if (CurrentCancellationReason == CancellationReason.InternetConnectivityLost)\n {\n // Log the connectivity loss\n System.Diagnostics.Debug.WriteLine(\"[DEBUG] Installation stopped due to connectivity loss - showing connectivity loss dialog\");\n \n // Show the connectivity loss dialog\n await ShowCancellationDialogAsync(false, true);\n \n // Reset cancellation reason after showing dialog\n CurrentCancellationReason = CancellationReason.None;\n return successCount;\n }\n \n // Only proceed with normal completion reporting if not cancelled\n // For normal completion (not cancelled), collect success and failure information\n var successItems = new List();\n var failedItems = new List();\n\n // Add successful items to the list\n foreach (var app in selectedApps.Where(a => !a.IsInstalled))\n {\n successItems.Add(app.Name);\n }\n foreach (var capability in selectedCapabilities.Where(c => !c.IsInstalled))\n {\n successItems.Add(capability.Name);\n }\n foreach (var feature in selectedFeatures.Where(f => !f.IsInstalled))\n {\n successItems.Add(feature.Name);\n }\n\n // Add failed items to the list\n foreach (var app in selectedApps.Where(a => a.IsInstalled))\n {\n failedItems.Add(app.Name);\n }\n foreach (var capability in selectedCapabilities.Where(c => c.IsInstalled))\n {\n failedItems.Add(capability.Name);\n }\n foreach (var feature in selectedFeatures.Where(f => f.IsInstalled))\n {\n failedItems.Add(feature.Name);\n }\n\n // Show result dialog\n ShowOperationResultDialog(\n \"Remove\",\n successCount,\n totalSelected,\n successItems,\n failedItems\n );\n\n return successCount;\n },\n $\"Removing {totalSelected} items\",\n false\n );\n }\n\n [RelayCommand]\n public async Task InstallApps()\n {\n if (\n _packageManager == null\n || _appInstallationService == null\n || _capabilityService == null\n || _featureService == null\n )\n return;\n\n // Get all selected items\n var selectedApps = WindowsApps.Where(a => a.IsSelected).ToList();\n var selectedCapabilities = Capabilities.Where(a => a.IsSelected).ToList();\n var selectedFeatures = OptionalFeatures.Where(a => a.IsSelected).ToList();\n\n // Check if anything is selected at all\n int totalSelected =\n selectedApps.Count + selectedCapabilities.Count + selectedFeatures.Count;\n\n if (totalSelected == 0)\n {\n StatusText = \"No items selected for installation\";\n await ShowNoItemsSelectedDialogAsync(\"installation\");\n return;\n }\n\n // Identify items that cannot be reinstalled\n var nonReinstallableApps = selectedApps.Where(a => !a.CanBeReinstalled).ToList();\n var nonReinstallableCapabilities = selectedCapabilities\n .Where(c => !c.CanBeReinstalled)\n .ToList();\n var nonReinstallableFeatures = selectedFeatures\n .Where(f => !f.CanBeReinstalled)\n .ToList();\n\n var allNonReinstallableItems = nonReinstallableApps\n .Concat(nonReinstallableCapabilities)\n .Concat(nonReinstallableFeatures)\n .ToList();\n\n // Remove non-reinstallable items from the selected items\n var installableApps = selectedApps.Except(nonReinstallableApps).ToList();\n var installableCapabilities = selectedCapabilities\n .Except(nonReinstallableCapabilities)\n .ToList();\n var installableFeatures = selectedFeatures.Except(nonReinstallableFeatures).ToList();\n\n var allInstallableItems = installableApps\n .Concat(installableCapabilities.Cast())\n .Concat(installableFeatures.Cast())\n .ToList();\n\n if (allInstallableItems.Count == 0)\n {\n if (allNonReinstallableItems.Any())\n {\n // Show dialog explaining that all selected items cannot be reinstalled\n await ShowCannotReinstallDialogAsync(\n allNonReinstallableItems.Select(a => a.Name),\n false\n );\n }\n else\n {\n StatusText = \"No items selected for installation\";\n }\n return;\n }\n\n // Show confirmation dialog, including information about skipped items\n // Show confirmation dialog\n bool? dialogResult = await ShowConfirmItemsDialogAsync(\n \"install\",\n allInstallableItems.Select(a => a.Name),\n allInstallableItems.Count\n );\n\n // If user didn't confirm, exit\n if (dialogResult != true)\n {\n return;\n }\n\n // Check for internet connectivity before starting installation\n bool isInternetConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(true);\n if (!isInternetConnected)\n {\n StatusText = \"No internet connection available. Installation cannot proceed.\";\n\n // Show dialog informing the user about the connectivity issue\n await ShowNoInternetConnectionDialogAsync();\n return;\n }\n\n // Use the ExecuteWithProgressAsync method from BaseViewModel to handle progress reporting\n await ExecuteWithProgressAsync(\n async (progress, cancellationToken) =>\n {\n int successCount = 0;\n int currentItem = 0;\n\n // Process standard Windows apps\n foreach (var app in installableApps)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Installing app {app.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage = $\"Installing Windows App: {app.Name}\",\n }\n );\n\n try\n {\n var result = await _appInstallationService.InstallAppAsync(\n app.ToAppInfo(),\n progress,\n cancellationToken\n );\n\n // Only mark as successful if the operation actually succeeded\n if (result.Success && result.Result)\n {\n app.IsInstalled = true;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage = $\"Successfully installed {app.Name}\",\n LogLevel = LogLevel.Success,\n }\n );\n }\n else\n {\n // The operation returned but was not successful\n string errorMessage =\n result.ErrorMessage\n ?? \"Unknown error occurred during installation\";\n\n // Check if it's an internet connectivity issue\n if (\n errorMessage.Contains(\"internet\")\n || errorMessage.Contains(\"connection\")\n )\n {\n errorMessage =\n $\"No internet connection available. Please check your network connection and try again.\";\n }\n\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage =\n $\"Failed to install {app.Name}: {errorMessage}\",\n LogLevel = LogLevel.Error,\n }\n );\n }\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage = $\"Error installing {app.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n }\n }\n\n // Process capabilities\n foreach (var capability in installableCapabilities)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Installing capability {capability.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage =\n $\"Installing Windows Capability: {capability.Name}\",\n }\n );\n\n try\n {\n await _capabilityService.InstallCapabilityAsync(\n capability.ToCapabilityInfo(),\n progress,\n cancellationToken\n );\n capability.IsInstalled = true;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage =\n $\"Successfully installed capability {capability.Name}\",\n LogLevel = LogLevel.Success,\n }\n );\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage =\n $\"Error installing capability {capability.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n }\n }\n\n // Process optional features\n foreach (var feature in installableFeatures)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Installing feature {feature.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage = $\"Installing Windows Feature: {feature.Name}\",\n }\n );\n\n try\n {\n await _featureService.InstallFeatureAsync(\n feature.ToFeatureInfo(),\n progress,\n cancellationToken\n );\n feature.IsInstalled = true;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage =\n $\"Successfully installed feature {feature.Name}\",\n LogLevel = LogLevel.Success,\n }\n );\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage =\n $\"Error installing feature {feature.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n }\n }\n\n // Final report\n progress.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText =\n $\"Successfully installed {successCount} of {totalSelected} items\",\n DetailedMessage =\n $\"Task completed: {successCount} of {totalSelected} items installed successfully\",\n LogLevel =\n successCount == totalSelected ? LogLevel.Success : LogLevel.Warning,\n }\n );\n\n // Refresh the UI\n SortCollections();\n\n // Collect success, failure, and skipped information for the result dialog\n var successItems = new List();\n var failedItems = new List();\n var skippedItems = allNonReinstallableItems.Select(i => i.Name).ToList();\n\n // Add successful items to the list\n foreach (var app in installableApps.Where(a => a.IsInstalled))\n {\n successItems.Add(app.Name);\n }\n foreach (var capability in installableCapabilities.Where(c => c.IsInstalled))\n {\n successItems.Add(capability.Name);\n }\n foreach (var feature in installableFeatures.Where(f => f.IsInstalled))\n {\n successItems.Add(feature.Name);\n }\n\n // Add failed items to the list\n foreach (var app in installableApps.Where(a => !a.IsInstalled))\n {\n failedItems.Add(app.Name);\n }\n foreach (var capability in installableCapabilities.Where(c => !c.IsInstalled))\n {\n failedItems.Add(capability.Name);\n }\n foreach (var feature in installableFeatures.Where(f => !f.IsInstalled))\n {\n failedItems.Add(feature.Name);\n }\n\n // Show result dialog\n ShowOperationResultDialog(\n \"Install\",\n successCount,\n totalSelected + skippedItems.Count,\n successItems,\n failedItems,\n skippedItems\n );\n\n return successCount;\n },\n $\"Installing {totalSelected} items\",\n false\n );\n }\n\n #region BaseInstallationViewModel Abstract Method Implementations\n\n /// \n /// Gets the name of a Windows app.\n /// \n /// The Windows app.\n /// The name of the app.\n protected override string GetAppName(WindowsApp app)\n {\n return app.Name;\n }\n\n /// \n /// Converts a Windows app to an AppInfo object.\n /// \n /// The Windows app to convert.\n /// The AppInfo object.\n protected override AppInfo ToAppInfo(WindowsApp app)\n {\n return app.ToAppInfo();\n }\n\n /// \n /// Gets the selected Windows apps.\n /// \n /// The selected Windows apps.\n protected override IEnumerable GetSelectedApps()\n {\n return Items.Where(a => a.IsSelected);\n }\n\n /// \n /// Sets the installation status of a Windows app.\n /// \n /// The Windows app.\n /// Whether the app is installed.\n protected override void SetInstallationStatus(WindowsApp app, bool isInstalled)\n {\n app.IsInstalled = isInstalled;\n }\n\n #endregion\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppInstallationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Net.Http;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Enums;\nusing Winhance.Core.Features.SoftwareApps.Exceptions;\nusing Winhance.Core.Features.SoftwareApps.Helpers;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that installs standard applications.\n/// \npublic class AppInstallationService\n : BaseInstallationService,\n IAppInstallationService,\n IDisposable\n{\n private readonly string _tempDir = Path.Combine(Path.GetTempPath(), \"WinhanceInstaller\");\n private readonly HttpClient _httpClient;\n private readonly IScriptUpdateService _scriptUpdateService;\n private readonly ISystemServices _systemServices;\n private readonly IWinGetInstallationService _winGetInstallationService;\n private IProgress? _currentProgress;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The PowerShell execution service.\n /// The script update service.\n /// The system services.\n /// The WinGet installation service.\n public AppInstallationService(\n ILogService logService,\n IPowerShellExecutionService powerShellService,\n IScriptUpdateService scriptUpdateService,\n ISystemServices systemServices,\n IWinGetInstallationService winGetInstallationService\n )\n : base(logService, powerShellService)\n {\n _httpClient = new HttpClient();\n _scriptUpdateService = scriptUpdateService;\n _systemServices = systemServices;\n _winGetInstallationService = winGetInstallationService;\n Directory.CreateDirectory(_tempDir);\n }\n\n /// \n public Task> InstallAppAsync(\n AppInfo appInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default\n )\n {\n return InstallItemAsync(appInfo, progress, cancellationToken);\n }\n\n /// \n public Task> CanInstallAppAsync(AppInfo appInfo)\n {\n return CanInstallItemAsync(appInfo);\n }\n\n /// \n protected override async Task> PerformInstallationAsync(\n AppInfo appInfo,\n IProgress? progress,\n CancellationToken cancellationToken\n )\n {\n _currentProgress = progress;\n\n try\n {\n // Check for internet connectivity before starting the installation\n bool isConnected = await _systemServices.IsInternetConnectedAsync(\n true,\n cancellationToken\n );\n if (!isConnected)\n {\n string errorMessage =\n \"No internet connection available. Please check your network connection and try again.\";\n _logService.LogError(errorMessage);\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Installation failed: No internet connection\",\n DetailedMessage = errorMessage,\n LogLevel = LogLevel.Error,\n }\n );\n // Explicitly log failure for the specific app\n _logService.LogError(\n $\"Failed to install app: {appInfo.Name} - No internet connection\"\n );\n return OperationResult.Failed(errorMessage, false);\n }\n\n // Set up a periodic internet connectivity check\n var connectivityCheckTimer = new System.Timers.Timer(5000); // Check every 5 seconds\n bool installationCancelled = false;\n\n connectivityCheckTimer.Elapsed += async (s, e) =>\n {\n try\n {\n bool isStillConnected = await _systemServices.IsInternetConnectedAsync(\n false,\n cancellationToken\n );\n if (!isStillConnected && !installationCancelled)\n {\n installationCancelled = true;\n _logService.LogError(\"Internet connection lost during installation\");\n progress?.Report(\n new TaskProgressDetail\n {\n StatusText = \"Error: Internet connection lost\",\n DetailedMessage =\n \"Internet connection has been lost. Installation has been stopped.\",\n LogLevel = LogLevel.Error,\n }\n );\n\n // Stop the timer\n connectivityCheckTimer.Stop();\n\n // Throw an exception to stop the installation process\n throw new OperationCanceledException(\n \"Installation stopped due to internet connection loss\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in connectivity check: {ex.Message}\");\n connectivityCheckTimer.Stop();\n }\n };\n\n // Start the connectivity check timer\n connectivityCheckTimer.Start();\n bool success = false;\n\n // Verify internet connection again before attempting installation\n isConnected = await _systemServices.IsInternetConnectedAsync(true, cancellationToken);\n if (!isConnected)\n {\n string errorMessage =\n \"No internet connection available. Please check your network connection and try again.\";\n _logService.LogError(errorMessage);\n _logService.LogError(\n $\"Failed to install app: {appInfo.Name} - No internet connection\"\n );\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Installation failed: No internet connection\",\n DetailedMessage = errorMessage,\n LogLevel = LogLevel.Error,\n }\n );\n return OperationResult.Failed(errorMessage, false);\n }\n\n if (appInfo.PackageName.Equals(\"OneDrive\", StringComparison.OrdinalIgnoreCase))\n {\n // Special handling for OneDrive\n success = await InstallOneDriveAsync(progress, cancellationToken);\n }\n else if (appInfo.IsCustomInstall)\n {\n success = await InstallCustomAppAsync(appInfo, progress, cancellationToken);\n }\n else\n {\n // Use WinGet for all standard apps, including appx packages\n // Use PackageID if available, otherwise fall back to PackageName\n string packageIdentifier = !string.IsNullOrEmpty(appInfo.PackageID)\n ? appInfo.PackageID\n : appInfo.PackageName;\n\n // Pass the app's display name to use in progress messages\n try\n {\n // Pass the app's name for display in progress messages\n success = await _winGetInstallationService.InstallWithWingetAsync(\n packageIdentifier,\n progress,\n cancellationToken,\n appInfo.Name\n );\n\n // Double-check success - if WinGet returned success but we have no internet, consider it a failure\n if (success)\n {\n bool stillConnected = await _systemServices.IsInternetConnectedAsync(\n true,\n cancellationToken\n );\n if (!stillConnected)\n {\n _logService.LogError(\n $\"Internet connection lost during installation of {appInfo.Name}\"\n );\n success = false;\n throw new Exception(\"Internet connection lost during installation\");\n }\n }\n }\n catch (Exception ex)\n {\n success = false;\n _logService.LogError($\"Failed to install {appInfo.Name}: {ex.Message}\");\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Installation of {appInfo.Name} failed\",\n DetailedMessage = $\"Error: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n }\n }\n\n // If success is still false, ensure we log the failure\n if (!success)\n {\n _logService.LogError($\"Failed to install app: {appInfo.Name}\");\n }\n\n // Only update BloatRemoval.ps1 if installation was successful AND it's not an external app\n // External apps should never be added to BloatRemoval.ps1\n if (success && !IsExternalApp(appInfo))\n {\n try\n {\n _logService.LogInformation(\n $\"Starting BloatRemoval.ps1 script update for {appInfo.Name}\"\n );\n\n // Update the BloatRemoval.ps1 script to remove the installed app from the removal list\n var appNames = new List { appInfo.PackageName };\n _logService.LogInformation(\n $\"Removing package name from BloatRemoval.ps1: {appInfo.PackageName}\"\n );\n\n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n\n // Add any subpackages if present\n if (appInfo.SubPackages != null && appInfo.SubPackages.Length > 0)\n {\n _logService.LogInformation(\n $\"Adding {appInfo.SubPackages.Length} subpackages for {appInfo.Name}\"\n );\n appSubPackages.Add(appInfo.PackageName, appInfo.SubPackages);\n }\n\n // Add registry settings if present\n if (appInfo.RegistrySettings != null && appInfo.RegistrySettings.Length > 0)\n {\n _logService.LogInformation(\n $\"Adding {appInfo.RegistrySettings.Length} registry settings for {appInfo.Name}\"\n );\n appsWithRegistry.Add(\n appInfo.PackageName,\n new List(appInfo.RegistrySettings)\n );\n }\n\n _logService.LogInformation(\n $\"Updating BloatRemoval.ps1 to remove {appInfo.Name} from removal list\"\n );\n var result = await _scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n true\n ); // true = install operation, so remove from script\n\n _logService.LogInformation(\n $\"Successfully updated BloatRemoval.ps1 script - {appInfo.Name} will no longer be removed\"\n );\n _logService.LogInformation($\"Script update result: {result?.Name ?? \"null\"}\");\n }\n catch (Exception ex)\n {\n _logService.LogError(\n $\"Error updating BloatRemoval.ps1 script for {appInfo.Name}\",\n ex\n );\n _logService.LogError($\"Exception details: {ex.Message}\");\n _logService.LogError($\"Stack trace: {ex.StackTrace}\");\n // Don't fail the installation if script update fails\n }\n }\n else if (success)\n {\n _logService.LogInformation(\n $\"Skipping BloatRemoval.ps1 update because {appInfo.Name} is an external app\"\n );\n }\n else\n {\n _logService.LogInformation(\n $\"Skipping BloatRemoval.ps1 update because installation of {appInfo.Name} was not successful\"\n );\n }\n\n if (success)\n {\n _logService.LogSuccess($\"Successfully installed app: {appInfo.Name}\");\n return OperationResult.Succeeded(success);\n }\n else\n {\n // Double check internet connectivity as a possible cause of failure\n bool internetAvailable = await _systemServices.IsInternetConnectedAsync(\n true,\n cancellationToken\n );\n if (!internetAvailable)\n {\n string errorMessage =\n $\"Installation of {appInfo.Name} failed: No internet connection. Please check your network connection and try again.\";\n _logService.LogError(errorMessage);\n return OperationResult.Failed(errorMessage, false);\n }\n\n // Generic failure\n string failMessage = $\"Installation of {appInfo.Name} failed for unknown reasons.\";\n _logService.LogError(failMessage);\n return OperationResult.Failed(failMessage, false);\n }\n }\n catch (OperationCanceledException)\n {\n _logService.LogWarning($\"Installation of {appInfo.Name} was cancelled by user\");\n return OperationResult.Failed(\"Installation cancelled by user\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error installing {appInfo.Name}\", ex);\n\n // Check if the error might be related to internet connectivity\n bool isConnected = await _systemServices.IsInternetConnectedAsync(\n true,\n cancellationToken\n );\n if (!isConnected)\n {\n string errorMessage =\n $\"Installation failed: No internet connection. Please check your network connection and try again.\";\n _logService.LogError(errorMessage);\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Installation failed: No internet connection\",\n DetailedMessage = errorMessage,\n LogLevel = LogLevel.Error,\n }\n );\n return OperationResult.Failed(errorMessage, false);\n }\n\n return OperationResult.Failed($\"Error installing {appInfo.Name}: {ex.Message}\");\n }\n finally\n {\n // Dispose any timers or resources\n if (progress is IProgress progressReporter)\n {\n // Find and dispose the timer if it exists\n var field = GetType()\n .GetField(\n \"_connectivityCheckTimer\",\n System.Reflection.BindingFlags.NonPublic\n | System.Reflection.BindingFlags.Instance\n );\n if (field != null)\n {\n var timer = field.GetValue(this) as System.Timers.Timer;\n timer?.Stop();\n timer?.Dispose();\n }\n }\n\n _currentProgress = null;\n }\n }\n\n /// \n /// Determines if an app is an external app (third-party) rather than a Windows built-in app.\n /// External apps should not be added to the BloatRemoval script.\n /// \n /// The app to check\n /// True if the app is an external app, false otherwise\n private bool IsExternalApp(AppInfo appInfo)\n {\n // Consider all apps with IsCustomInstall as external apps\n if (appInfo.IsCustomInstall)\n return true;\n\n // Check if the package name starts with Microsoft or matches known Windows app patterns\n bool isMicrosoftApp = appInfo.PackageName.StartsWith(\n \"Microsoft.\",\n StringComparison.OrdinalIgnoreCase\n );\n\n // Check if the app is a number-based Microsoft Store app ID\n bool isStoreAppId =\n !string.IsNullOrEmpty(appInfo.PackageID)\n && (\n appInfo.PackageID.All(c => char.IsLetterOrDigit(c) || c == '.')\n && (appInfo.PackageID.Length == 9 || appInfo.PackageID.Length == 12)\n ); // Microsoft Store app IDs are typically 9 or 12 chars\n\n // Check if it's an optional feature or capability, which are Windows components\n bool isWindowsComponent =\n appInfo.Type == AppType.Capability || appInfo.Type == AppType.OptionalFeature;\n\n // Any third-party app with a period in its name is likely an external app (e.g., VideoLAN.VLC)\n bool isThirdPartyNamedApp =\n !isMicrosoftApp && appInfo.PackageName.Contains('.') && !isWindowsComponent;\n\n // If it's a Microsoft app or Windows component, it's not external\n // Otherwise, it's likely an external app\n return isThirdPartyNamedApp\n || appInfo.IsCustomInstall\n || (!isMicrosoftApp && !isStoreAppId && !isWindowsComponent);\n }\n\n /// \n public Task InstallCustomAppAsync(\n AppInfo appInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default\n )\n {\n // Implementation remains in this class for now\n // In future refactoring phases, this can be moved to a specialized service\n _currentProgress = progress;\n\n try\n {\n // Handle different custom app installations based on package name\n switch (appInfo.PackageName.ToLowerInvariant())\n {\n // Special handling for OneDrive\n case \"onedrive\":\n return InstallOneDriveAsync(progress, cancellationToken);\n\n // Add custom app installation logic here\n // case \"some-app\":\n // return await InstallSomeAppAsync(progress, cancellationToken);\n\n default:\n throw new NotSupportedException(\n $\"Custom installation for '{appInfo.PackageName}' is not supported.\"\n );\n }\n }\n catch (Exception ex)\n {\n var errorType = InstallationErrorHelper.DetermineErrorType(ex.Message);\n var errorMessage = InstallationErrorHelper.GetUserFriendlyErrorMessage(errorType);\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Error in custom installation for {appInfo.Name}: {errorMessage}\",\n DetailedMessage = $\"Exception during custom installation: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"ErrorType\", errorType.ToString() },\n { \"PackageName\", appInfo.PackageName },\n { \"AppName\", appInfo.Name },\n { \"IsCustomInstall\", \"True\" },\n { \"OriginalError\", ex.Message },\n },\n }\n );\n\n return Task.FromResult(false);\n }\n }\n\n /// \n /// Installs an app using WinGet.\n /// \n /// The package name to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// Optional display name for the app.\n /// True if installation was successful; otherwise, false.\n public Task InstallWithWingetAsync(\n string packageName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default,\n string displayName = null\n )\n {\n return _winGetInstallationService.InstallWithWingetAsync(\n packageName,\n progress,\n cancellationToken,\n displayName\n );\n }\n\n /// \n /// Disposes the resources used by the service.\n /// \n public void Dispose()\n {\n _httpClient.Dispose();\n GC.SuppressFinalize(this);\n }\n\n /// \n /// Installs OneDrive from the Microsoft download link.\n /// \n /// Optional progress reporter.\n /// Optional cancellation token.\n /// True if installation was successful; otherwise, false.\n private async Task InstallOneDriveAsync(\n IProgress? progress,\n CancellationToken cancellationToken\n )\n {\n try\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Starting OneDrive installation...\",\n DetailedMessage = \"Downloading OneDrive installer from Microsoft\",\n }\n );\n\n // Download OneDrive from the specific URL\n string downloadUrl = \"https://go.microsoft.com/fwlink/p/?LinkID=2182910\";\n string installerPath = Path.Combine(_tempDir, \"OneDriveSetup.exe\");\n\n using (var client = new HttpClient())\n {\n var response = await client.GetAsync(downloadUrl, cancellationToken);\n if (!response.IsSuccessStatusCode)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Failed to download OneDrive installer\",\n DetailedMessage = $\"HTTP error: {response.StatusCode}\",\n LogLevel = LogLevel.Error,\n }\n );\n return false;\n }\n\n using (\n var fileStream = new FileStream(\n installerPath,\n FileMode.Create,\n FileAccess.Write,\n FileShare.None\n )\n )\n {\n await response.Content.CopyToAsync(fileStream, cancellationToken);\n }\n }\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 50,\n StatusText = \"Installing OneDrive...\",\n DetailedMessage = \"Running OneDrive installer\",\n }\n );\n\n // Run the installer\n using (var process = new System.Diagnostics.Process())\n {\n process.StartInfo.FileName = installerPath;\n process.StartInfo.Arguments = \"/silent\";\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.RedirectStandardError = true;\n process.StartInfo.CreateNoWindow = true;\n\n process.Start();\n await Task.Run(() => process.WaitForExit(), cancellationToken);\n\n bool success = process.ExitCode == 0;\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = success\n ? \"OneDrive installed successfully\"\n : \"OneDrive installation failed\",\n DetailedMessage = $\"Installer exited with code: {process.ExitCode}\",\n LogLevel = success ? LogLevel.Success : LogLevel.Error,\n }\n );\n\n return success;\n }\n }\n catch (Exception ex)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Error installing OneDrive\",\n DetailedMessage = $\"Exception: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppInstallationCoordinatorService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Coordinates the installation of applications, handling connectivity monitoring,\n /// user notifications, and installation state management.\n /// \n public interface IAppInstallationCoordinatorService\n {\n /// \n /// Installs an application with connectivity monitoring and proper cancellation handling.\n /// \n /// The application information.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the installation operation with the result.\n Task InstallAppAsync(\n AppInfo appInfo,\n IProgress progress,\n CancellationToken cancellationToken = default);\n \n /// \n /// Event that is raised when the installation status changes.\n /// \n event EventHandler InstallationStatusChanged;\n }\n \n /// \n /// Result of an installation coordination operation.\n /// \n public class InstallationCoordinationResult\n {\n /// \n /// Gets or sets a value indicating whether the installation was successful.\n /// \n public bool Success { get; set; }\n \n /// \n /// Gets or sets the error message if the installation failed.\n /// \n public string ErrorMessage { get; set; }\n \n /// \n /// Gets or sets a value indicating whether the installation was cancelled by the user.\n /// \n public bool WasCancelled { get; set; }\n \n /// \n /// Gets or sets a value indicating whether the installation failed due to connectivity issues.\n /// \n public bool WasConnectivityIssue { get; set; }\n \n /// \n /// Gets or sets the application information.\n /// \n public AppInfo AppInfo { get; set; }\n }\n \n /// \n /// Event arguments for installation status change events.\n /// \n public class InstallationStatusChangedEventArgs : EventArgs\n {\n /// \n /// Gets the application information.\n /// \n public AppInfo AppInfo { get; }\n \n /// \n /// Gets the status message.\n /// \n public string StatusMessage { get; }\n \n /// \n /// Gets a value indicating whether the installation is complete.\n /// \n public bool IsComplete { get; }\n \n /// \n /// Gets a value indicating whether the installation was successful.\n /// \n public bool IsSuccess { get; }\n \n /// \n /// Gets a value indicating whether the installation was cancelled by the user.\n /// \n public bool IsCancelled { get; }\n \n /// \n /// Gets a value indicating whether the installation failed due to connectivity issues.\n /// \n public bool IsConnectivityIssue { get; }\n \n /// \n /// Gets the timestamp when the status changed.\n /// \n public DateTime Timestamp { get; }\n \n /// \n /// Initializes a new instance of the class.\n /// \n /// The application information.\n /// The status message.\n /// Whether the installation is complete.\n /// Whether the installation was successful.\n /// Whether the installation was cancelled by the user.\n /// Whether the installation failed due to connectivity issues.\n public InstallationStatusChangedEventArgs(\n AppInfo appInfo,\n string statusMessage,\n bool isComplete = false,\n bool isSuccess = false,\n bool isCancelled = false,\n bool isConnectivityIssue = false)\n {\n AppInfo = appInfo;\n StatusMessage = statusMessage;\n IsComplete = isComplete;\n IsSuccess = isSuccess;\n IsCancelled = isCancelled;\n IsConnectivityIssue = isConnectivityIssue;\n Timestamp = DateTime.Now;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Implementations/WinGetInstaller.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.Logging;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Verification;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.Extensions;\nusing Winhance.Infrastructure.Features.Common.Utilities;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Utilities;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Implementations\n{\n /// \n /// Implements the interface for managing packages with WinGet.\n /// \n public class WinGetInstaller : IWinGetInstaller\n {\n private const string WinGetExe = \"winget.exe\";\n private readonly IPowerShellExecutionService _powerShellService;\n private readonly ITaskProgressService _taskProgressService;\n private readonly IInstallationVerifier _installationVerifier;\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The PowerShell factory for executing commands.\n /// The task progress service for reporting progress.\n /// The installation verifier to check if packages are installed.\n /// The logging service for logging messages.\n public WinGetInstaller(\n IPowerShellExecutionService powerShellService,\n ITaskProgressService taskProgressService,\n IInstallationVerifier installationVerifier = null,\n ILogService logService = null\n )\n {\n _powerShellService =\n powerShellService ?? throw new ArgumentNullException(nameof(powerShellService));\n _taskProgressService =\n taskProgressService ?? throw new ArgumentNullException(nameof(taskProgressService));\n _installationVerifier =\n installationVerifier\n ?? new CompositeInstallationVerifier(GetDefaultVerificationMethods());\n _logService = logService;\n }\n\n /// \n public async Task InstallPackageAsync(\n string packageId,\n InstallationOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n options ??= new InstallationOptions();\n var arguments = new StringBuilder(\n $\"install --id {EscapeArgument(packageId)} --accept-package-agreements --accept-source-agreements --disable-interactivity --silent --force\"\n );\n\n if (!string.IsNullOrWhiteSpace(options.Version))\n arguments.Append($\" --version {EscapeArgument(options.Version)}\");\n\n // Force parameter is now always included\n // Interactive is disabled with --disable-interactivity\n // Silent is now always included\n\n try\n {\n // Create a wrapper function that will be passed to the extension method\n Func, Task> operation = async (\n progress\n ) =>\n {\n var commandResult = await ExecuteWinGetCommandAsync(\n WinGetExe,\n arguments.ToString(),\n progress,\n cancellationToken\n )\n .ConfigureAwait(false);\n\n // Convert the command result to an InstallationResult\n return new InstallationResult\n {\n Success = commandResult.ExitCode == 0,\n Message =\n commandResult.ExitCode == 0\n ? $\"Successfully installed {packageId}\"\n : $\"Failed to install {packageId}. Exit code: {commandResult.ExitCode}. Error: {commandResult.Error}\",\n PackageId = packageId,\n Version = options?.Version,\n };\n };\n\n // Use the display name if provided, otherwise use packageId\n string nameToDisplay = displayName ?? packageId;\n\n // Use the extension method to track progress\n var result = await _taskProgressService\n .TrackWinGetInstallationAsync(operation, nameToDisplay, cancellationToken)\n .ConfigureAwait(false);\n\n if (result.ExitCode != 0)\n {\n return new InstallationResult\n {\n Success = false,\n Message =\n $\"Failed to install {packageId}. Exit code: {result.ExitCode}. Error: {result.Error}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n\n // For Microsoft Store apps, trust the WinGet exit code as the primary indicator of success\n bool isMicrosoftStoreApp =\n packageId.All(char.IsLetterOrDigit) && !packageId.Contains('.');\n\n if (isMicrosoftStoreApp)\n {\n _logService?.LogInformation(\n $\"Microsoft Store app detected: {packageId}. Using WinGet exit code for success determination.\"\n );\n\n // For Microsoft Store apps, trust the exit code\n return new InstallationResult\n {\n Success = true, // WinGet command succeeded, so consider the installation successful\n Message = $\"Successfully installed {packageId} {options.Version}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n\n // For regular apps, try verification with a longer delay\n try\n {\n // Add a longer delay for verification to allow Windows to complete registration\n await Task.Delay(TimeSpan.FromSeconds(3), cancellationToken)\n .ConfigureAwait(false);\n\n var verification = await _installationVerifier\n .VerifyInstallationAsync(packageId, options.Version, cancellationToken)\n .ConfigureAwait(false);\n\n // If verification succeeds, great! If not, but WinGet reported success, trust WinGet\n bool success = verification.IsVerified || result.ExitCode == 0;\n\n return new InstallationResult\n {\n Success = success,\n Message = success\n ? $\"Successfully installed {packageId} {options.Version}\"\n : $\"Installation may have failed: {verification.Message}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n catch (Exception ex)\n {\n _logService?.LogWarning(\n $\"Verification failed with error: {ex.Message}. Using WinGet exit code for success determination.\"\n );\n\n // If verification throws an exception, trust the WinGet exit code\n return new InstallationResult\n {\n Success = true, // WinGet command succeeded, so consider the installation successful\n Message =\n $\"Successfully installed {packageId} {options.Version} (verification skipped due to error)\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n return new InstallationResult\n {\n Success = false,\n Message = $\"Error installing {packageId}: {ex.Message}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n }\n\n /// \n public async Task UpgradePackageAsync(\n string packageId,\n UpgradeOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n options ??= new UpgradeOptions();\n var arguments = new StringBuilder(\n $\"upgrade --id {EscapeArgument(packageId)} --accept-package-agreements --accept-source-agreements --disable-interactivity --silent --force\"\n );\n\n // Force parameter is now always included\n // Interactive is disabled with --disable-interactivity\n // Silent is now always included\n\n try\n {\n // Create a wrapper function that will be passed to the extension method\n Func, Task> operation = async (\n progress\n ) =>\n {\n // Create an adapter since ExecuteWinGetCommandAsync expects InstallationProgress\n var progressAdapter = new Progress(p =>\n {\n // Convert InstallationProgress to UpgradeProgress\n progress.Report(\n new UpgradeProgress\n {\n Percentage = p.Percentage,\n Status = p.Status,\n IsIndeterminate = p.IsIndeterminate,\n }\n );\n });\n\n var commandResult = await ExecuteWinGetCommandAsync(\n WinGetExe,\n arguments.ToString(),\n progressAdapter,\n cancellationToken\n )\n .ConfigureAwait(false);\n\n // Convert the command result to an UpgradeResult\n return new UpgradeResult\n {\n Success = commandResult.ExitCode == 0,\n Message =\n commandResult.ExitCode == 0\n ? $\"Successfully upgraded {packageId}\"\n : $\"Failed to upgrade {packageId}. Exit code: {commandResult.ExitCode}. Error: {commandResult.Error}\",\n PackageId = packageId,\n Version = options?.Version,\n };\n };\n\n // Use the display name if provided, otherwise use packageId\n string nameToDisplay = displayName ?? packageId;\n\n // Use the extension method to track progress\n var result = await _taskProgressService\n .TrackWinGetUpgradeAsync(operation, nameToDisplay, cancellationToken)\n .ConfigureAwait(false);\n\n if (result.ExitCode != 0)\n {\n return new UpgradeResult\n {\n Success = false,\n Message =\n $\"Failed to upgrade {packageId}. Exit code: {result.ExitCode}. Error: {result.Error}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n\n // For Microsoft Store apps, trust the WinGet exit code as the primary indicator of success\n bool isMicrosoftStoreApp =\n packageId.All(char.IsLetterOrDigit) && !packageId.Contains('.');\n\n if (isMicrosoftStoreApp)\n {\n _logService?.LogInformation(\n $\"Microsoft Store app detected: {packageId}. Using WinGet exit code for success determination.\"\n );\n\n // For Microsoft Store apps, trust the exit code\n return new UpgradeResult\n {\n Success = true, // WinGet command succeeded, so consider the upgrade successful\n Message = $\"Successfully upgraded {packageId} to {options.Version}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n\n // For regular apps, try verification with a longer delay\n try\n {\n // Add a longer delay for verification to allow Windows to complete registration\n await Task.Delay(TimeSpan.FromSeconds(3), cancellationToken)\n .ConfigureAwait(false);\n\n var verificationResult = await _installationVerifier\n .VerifyInstallationAsync(packageId, options.Version, cancellationToken)\n .ConfigureAwait(false);\n\n // If verification succeeds, great! If not, but WinGet reported success, trust WinGet\n bool success = verificationResult.IsVerified || result.ExitCode == 0;\n\n return new UpgradeResult\n {\n Success = success,\n Message = success\n ? $\"Successfully upgraded {packageId} to {options.Version}\"\n : $\"Upgrade may have failed: {verificationResult.Message}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n catch (Exception ex)\n {\n _logService?.LogWarning(\n $\"Verification failed with error: {ex.Message}. Using WinGet exit code for success determination.\"\n );\n\n // If verification throws an exception, trust the WinGet exit code\n return new UpgradeResult\n {\n Success = true, // WinGet command succeeded, so consider the upgrade successful\n Message =\n $\"Successfully upgraded {packageId} to {options.Version} (verification skipped due to error)\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n }\n catch (Exception ex)\n {\n return new UpgradeResult\n {\n Success = false,\n Message = $\"Error upgrading {packageId}: {ex.Message}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n }\n\n /// \n public async Task UninstallPackageAsync(\n string packageId,\n UninstallationOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n options ??= new UninstallationOptions();\n var arguments = new StringBuilder(\n $\"uninstall --id {EscapeArgument(packageId)} --accept-package-agreements --accept-source-agreements --disable-interactivity --silent --force\"\n );\n\n // Force parameter is now always included\n // Interactive is disabled with --disable-interactivity\n // Silent is now always included\n\n try\n {\n // Create a wrapper function that will be passed to the extension method\n Func, Task> operation =\n async (progress) =>\n {\n // Create an adapter since ExecuteWinGetCommandAsync expects InstallationProgress\n var progressAdapter = new Progress(p =>\n {\n // Convert InstallationProgress to UninstallationProgress\n progress.Report(\n new UninstallationProgress\n {\n Percentage = p.Percentage,\n Status = p.Status,\n IsIndeterminate = p.IsIndeterminate,\n }\n );\n });\n\n var commandResult = await ExecuteWinGetCommandAsync(\n WinGetExe,\n arguments.ToString(),\n progressAdapter,\n cancellationToken\n )\n .ConfigureAwait(false);\n\n // Convert the command result to an UninstallationResult\n return new UninstallationResult\n {\n Success = commandResult.ExitCode == 0,\n Message =\n commandResult.ExitCode == 0\n ? $\"Successfully uninstalled {packageId}\"\n : $\"Failed to uninstall {packageId}. Exit code: {commandResult.ExitCode}. Error: {commandResult.Error}\",\n PackageId = packageId,\n };\n };\n\n // Use the display name if provided, otherwise use packageId\n string nameToDisplay = displayName ?? packageId;\n\n // Use the extension method to track progress\n var result = await _taskProgressService\n .TrackWinGetUninstallationAsync(operation, nameToDisplay, cancellationToken)\n .ConfigureAwait(false);\n\n if (result.ExitCode != 0)\n {\n return new UninstallationResult\n {\n Success = false,\n Message =\n $\"Failed to uninstall {packageId}. Exit code: {result.ExitCode}. Error: {result.Error}\",\n PackageId = packageId,\n };\n }\n\n // Verify uninstallation (should return false if successfully uninstalled)\n var verification = await _installationVerifier\n .VerifyInstallationAsync(packageId, null, cancellationToken)\n .ConfigureAwait(false);\n\n return new UninstallationResult\n {\n Success = !verification.IsVerified,\n Message = !verification.IsVerified\n ? $\"Successfully uninstalled {packageId}\"\n : $\"Uninstallation may have failed: {verification.Message}\",\n PackageId = packageId,\n };\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n return new UninstallationResult\n {\n Success = false,\n Message = $\"Error uninstalling {packageId}: {ex.Message}\",\n PackageId = packageId,\n };\n }\n }\n\n /// \n public async Task GetPackageInfoAsync(\n string packageId,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n try\n {\n var arguments = $\"show --id {EscapeArgument(packageId)} --accept-source-agreements\";\n var result = await ExecuteWinGetCommandAsync(\n WinGetExe,\n arguments,\n null,\n cancellationToken\n )\n .ConfigureAwait(false);\n\n if (result.ExitCode != 0)\n {\n return null;\n }\n\n return ParsePackageInfo(result.Output);\n }\n catch (Exception)\n {\n return null;\n }\n }\n\n /// \n public async Task> SearchPackagesAsync(\n string query,\n SearchOptions options = null,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(query))\n throw new ArgumentException(\n \"Search query cannot be null or whitespace.\",\n nameof(query)\n );\n\n options ??= new SearchOptions();\n var arguments = new StringBuilder(\n $\"search {EscapeArgument(query)} --accept-source-agreements\"\n );\n\n if (options.IncludeAvailable)\n arguments.Append(\" --available\");\n\n if (options.Count > 0)\n arguments.Append($\" --max {options.Count}\");\n\n try\n {\n var result = await ExecuteWinGetCommandAsync(\n WinGetExe,\n arguments.ToString(),\n null,\n cancellationToken\n )\n .ConfigureAwait(false);\n\n if (result.ExitCode != 0)\n {\n return Enumerable.Empty();\n }\n\n return ParsePackageList(result.Output);\n }\n catch (Exception)\n {\n return Enumerable.Empty();\n }\n }\n\n private IEnumerable GetDefaultVerificationMethods()\n {\n return new IVerificationMethod[]\n {\n new WinGetVerificationMethod(),\n new AppxPackageVerificationMethod(),\n new RegistryVerificationMethod(),\n new FileSystemVerificationMethod(),\n };\n }\n\n /// \n /// Checks if WinGet is available in the PATH.\n /// \n /// True if WinGet is in the PATH, false otherwise.\n private bool IsWinGetInPath()\n {\n var pathEnv = Environment.GetEnvironmentVariable(\"PATH\") ?? string.Empty;\n return pathEnv\n .Split(Path.PathSeparator)\n .Any(p => !string.IsNullOrEmpty(p) && File.Exists(Path.Combine(p, WinGetExe)));\n }\n \n /// \n /// Tries to verify WinGet is working by running a simple command (winget -v)\n /// \n /// True if WinGet command works, false otherwise\n private bool TryVerifyWinGetCommand()\n {\n try\n {\n _logService?.LogInformation(\"Verifying WinGet by running 'winget -v' command\");\n \n // Create a process to run WinGet version command\n var processStartInfo = new ProcessStartInfo\n {\n FileName = WinGetExe,\n Arguments = \"-v\",\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n UseShellExecute = false,\n CreateNoWindow = true,\n };\n \n using (var process = new Process { StartInfo = processStartInfo })\n {\n try\n {\n if (process.Start())\n {\n // Wait for the process to exit with a timeout\n if (process.WaitForExit(5000)) // 5 second timeout\n {\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n \n // If we got output and no error, WinGet is working\n if (!string.IsNullOrWhiteSpace(output) && string.IsNullOrWhiteSpace(error))\n {\n _logService?.LogInformation($\"WinGet command verification successful, version: {output.Trim()}\");\n return true;\n }\n else if (!string.IsNullOrWhiteSpace(error))\n {\n _logService?.LogWarning($\"WinGet command verification failed with error: {error.Trim()}\");\n }\n }\n else\n {\n // Process didn't exit within timeout\n _logService?.LogWarning(\"WinGet command verification timed out\");\n try { process.Kill(); } catch { }\n }\n }\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error verifying WinGet command: {ex.Message}\");\n }\n }\n \n // Try an alternative approach - using WindowsApps path directly\n string windowsAppsPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Microsoft\\\\WindowsApps\"\n );\n \n if (Directory.Exists(windowsAppsPath))\n {\n processStartInfo.FileName = Path.Combine(windowsAppsPath, WinGetExe);\n _logService?.LogInformation($\"Trying alternative WinGet path: {processStartInfo.FileName}\");\n \n if (File.Exists(processStartInfo.FileName))\n {\n using (var process = new Process { StartInfo = processStartInfo })\n {\n try\n {\n if (process.Start())\n {\n if (process.WaitForExit(5000))\n {\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n \n if (!string.IsNullOrWhiteSpace(output) && string.IsNullOrWhiteSpace(error))\n {\n _logService?.LogInformation($\"Alternative WinGet path verification successful, version: {output.Trim()}\");\n return true;\n }\n }\n }\n }\n catch { }\n }\n }\n }\n \n return false;\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error in TryVerifyWinGetCommand: {ex.Message}\", ex);\n return false;\n }\n }\n\n private async Task TryInstallWinGetAsync(CancellationToken cancellationToken)\n {\n try\n {\n _logService?.LogInformation(\"WinGet not found. Attempting to install WinGet...\");\n\n // Create a progress adapter for the task progress service\n var progressAdapter = new Progress(progress =>\n {\n _taskProgressService?.UpdateDetailedProgress(progress);\n });\n\n // Use the WinGetInstallationScript to install WinGet\n var result = await WinGetInstallationScript.InstallWinGetAsync(\n progressAdapter,\n _logService,\n cancellationToken\n );\n\n bool success = result.Success;\n string message = result.Message;\n\n if (success)\n {\n _logService?.LogInformation(\"WinGet was successfully installed.\");\n return true;\n }\n else\n {\n _logService?.LogError($\"Failed to install WinGet: {message}\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error installing WinGet: {ex.Message}\", ex);\n return false;\n }\n }\n\n private async Task<(string WinGetPath, bool JustInstalled)> FindWinGetPathAsync(\n CancellationToken cancellationToken = default\n )\n {\n // First try to verify WinGet by running a command\n if (TryVerifyWinGetCommand())\n {\n _logService?.LogInformation(\"WinGet command verified and working\");\n return (WinGetExe, false);\n }\n\n // Check if winget is in the PATH\n if (IsWinGetInPath())\n {\n return (WinGetExe, false);\n }\n\n // Check common installation paths\n var possiblePaths = new[]\n {\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n @\"Microsoft\\WindowsApps\\winget.exe\"\n ),\n @\"C:\\Program Files\\WindowsApps\\Microsoft.DesktopAppInstaller_*\\winget.exe\",\n };\n\n // Try to find WinGet in common locations\n string foundPath = null;\n foreach (var pathPattern in possiblePaths)\n {\n if (pathPattern.Contains(\"*\"))\n {\n // Handle wildcard paths\n var directory = Path.GetDirectoryName(pathPattern);\n var filePattern = Path.GetFileName(pathPattern);\n \n if (Directory.Exists(directory))\n {\n var matchingFiles = Directory.GetFiles(directory, filePattern, SearchOption.AllDirectories);\n if (matchingFiles.Length > 0)\n {\n foundPath = matchingFiles[0];\n _logService?.LogInformation($\"Found WinGet at: {foundPath}\");\n return (foundPath, false);\n }\n }\n }\n else if (File.Exists(pathPattern))\n {\n foundPath = pathPattern;\n _logService?.LogInformation($\"Found WinGet at: {foundPath}\");\n return (foundPath, false);\n }\n }\n\n // If WinGet is not found, try to install it\n if (await TryInstallWinGetAsync(cancellationToken))\n {\n _logService?.LogInformation(\"WinGet installation completed, verifying installation\");\n \n // First try to verify WinGet by running a command after installation\n if (TryVerifyWinGetCommand())\n {\n _logService?.LogInformation(\"WinGet command verified and working after installation\");\n return (WinGetExe, true);\n }\n \n // After installation, check if it's now in the PATH\n if (IsWinGetInPath())\n {\n return (WinGetExe, true);\n }\n\n // Check the common paths again\n foreach (var pathPattern in possiblePaths)\n {\n if (pathPattern.Contains(\"*\"))\n {\n // Handle wildcard paths\n var directory = Path.GetDirectoryName(pathPattern);\n var filePattern = Path.GetFileName(pathPattern);\n \n if (Directory.Exists(directory))\n {\n var matchingFiles = Directory.GetFiles(directory, filePattern, SearchOption.AllDirectories);\n if (matchingFiles.Length > 0)\n {\n foundPath = matchingFiles[0];\n _logService?.LogInformation($\"Found WinGet at: {foundPath}\");\n return (foundPath, true);\n }\n }\n }\n else if (File.Exists(pathPattern))\n {\n foundPath = pathPattern;\n _logService?.LogInformation($\"Found WinGet at: {foundPath}\");\n return (foundPath, true);\n }\n }\n }\n\n // If we still can't find it, throw an exception\n throw new InvalidOperationException(\"WinGet not found and installation failed.\");\n }\n\n private string FindWinGetPath()\n {\n try\n {\n // Call the async method synchronously\n var result = FindWinGetPathAsync().GetAwaiter().GetResult();\n return result.WinGetPath;\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error finding WinGet: {ex.Message}\", ex);\n throw;\n }\n }\n\n // Installation states have been moved to WinGetOutputParser.InstallationState\n\n private async Task<(int ExitCode, string Output, string Error)> ExecuteWinGetCommandAsync(\n string command,\n string arguments,\n IProgress progressAdapter = null,\n CancellationToken cancellationToken = default\n )\n {\n var commandLine = $\"{command} {arguments}\";\n _logService?.LogInformation($\"Executing WinGet command: {commandLine}\");\n\n try\n {\n // Find WinGet path or install it if not found\n string winGetPath;\n bool justInstalled = false;\n try\n {\n (winGetPath, justInstalled) = await FindWinGetPathAsync(cancellationToken);\n }\n catch (InvalidOperationException ex)\n {\n _logService?.LogError($\"WinGet error: {ex.Message}\");\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = $\"Error: {ex.Message}\",\n Percentage = 0,\n IsIndeterminate = false,\n }\n );\n return (1, string.Empty, ex.Message);\n }\n \n // If WinGet was just installed, we might need to wait a moment for permissions to be set up\n // This is especially important on LTSC editions where there can be a delay\n if (justInstalled)\n {\n _logService?.LogInformation(\"WinGet was just installed. Waiting briefly before proceeding...\");\n await Task.Delay(2000, cancellationToken); // Wait 2 seconds\n \n // Notify the user that WinGet was installed and we're continuing with the app installation\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"WinGet was successfully installed. Continuing with application installation...\",\n Percentage = 30,\n IsIndeterminate = false,\n }\n );\n \n // For LTSC editions, we need to use a different approach after installation\n // Try to use the full path to WinGet if it's not just \"winget.exe\"\n if (!string.Equals(winGetPath, WinGetExe, StringComparison.OrdinalIgnoreCase))\n {\n _logService?.LogInformation($\"Using full path to WinGet: {winGetPath}\");\n \n // Check if the file exists and is accessible\n if (File.Exists(winGetPath))\n {\n try\n {\n // Test file access permissions\n using (File.OpenRead(winGetPath)) { }\n _logService?.LogInformation(\"Successfully verified file access to WinGet executable\");\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Access issue with WinGet executable: {ex.Message}\");\n _logService?.LogInformation(\"Falling back to using 'winget.exe' command\");\n winGetPath = WinGetExe; // Fall back to using just the command name\n }\n }\n }\n }\n\n // Create a process to run WinGet directly\n var processStartInfo = new ProcessStartInfo\n {\n FileName = winGetPath,\n Arguments = arguments,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n UseShellExecute = false,\n CreateNoWindow = true,\n };\n\n _logService?.LogInformation(\n $\"Starting process: {processStartInfo.FileName} {processStartInfo.Arguments}\"\n );\n\n var process = new Process\n {\n StartInfo = processStartInfo,\n EnableRaisingEvents = true,\n };\n\n var outputBuilder = new StringBuilder();\n var errorBuilder = new StringBuilder();\n\n // Progress tracking is now handled by WinGetOutputParser\n\n // Create an output parser for processing WinGet output\n var outputParser = new WinGetOutputParser(_logService);\n \n // Report initial progress with more detailed status\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Searching for package...\",\n Percentage = 5,\n IsIndeterminate = false,\n }\n );\n\n process.OutputDataReceived += (sender, e) =>\n {\n if (e.Data != null)\n {\n outputBuilder.AppendLine(e.Data);\n \n // Parse the output line and get progress update\n var progress = outputParser.ParseOutputLine(e.Data);\n \n // Report progress if available\n if (progress != null)\n {\n progressAdapter?.Report(progress);\n }\n }\n };\n \n // The parsing functionality has been moved to WinGetOutputParser\n\n process.ErrorDataReceived += (sender, e) =>\n {\n if (e.Data != null)\n {\n errorBuilder.AppendLine(e.Data);\n _logService?.LogError($\"WinGet error: {e.Data}\");\n }\n };\n\n // Start the process\n if (!process.Start())\n {\n _logService?.LogError(\"Failed to start WinGet process\");\n return (1, string.Empty, \"Failed to start WinGet process\");\n }\n\n // Begin reading output and error streams\n process.BeginOutputReadLine();\n process.BeginErrorReadLine();\n\n // Create a task that completes when the process exits\n var processExitTask = Task.Run(\n () =>\n {\n process.WaitForExit();\n return process.ExitCode;\n },\n cancellationToken\n );\n\n // Wait for the process to exit or cancellation\n int exitCode;\n try\n {\n // Create a flag to track whether cancellation was due to user action or connectivity issues\n bool isCancellationDueToConnectivity = false;\n \n // Register cancellation callback to kill the process when cancellation is requested\n using var cancelRegistration = cancellationToken.Register(() =>\n {\n _logService?.LogWarning(\"Cancellation requested, attempting to kill WinGet process\");\n try\n {\n // Check if cancellation is due to connectivity issues\n // This is determined by examining the cancellation token's source\n // The AppInstallationCoordinatorService will set this flag when cancelling due to connectivity\n if (cancellationToken.IsCancellationRequested)\n {\n // We can't directly check the reason for cancellation from the token itself,\n // but the AppInstallationCoordinatorService will handle this distinction\n _logService?.LogWarning(\"WinGet process cancellation requested\");\n }\n \n if (!process.HasExited)\n {\n // Report cancellation progress immediately\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Cancelling installation...\",\n Percentage = 0,\n IsIndeterminate = true,\n IsCancelled = true\n }\n );\n \n // Kill the process and all child processes in a background task\n // to prevent UI stalling\n Task.Run(() => \n {\n try \n {\n KillProcessAndChildren(process.Id);\n _logService?.LogWarning(\"WinGet process and all child processes were killed due to cancellation\");\n \n // Update progress after killing processes\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Installation was cancelled\",\n Percentage = 0,\n IsIndeterminate = false,\n IsCancelled = true\n }\n );\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error killing processes: {ex.Message}\");\n }\n });\n }\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error killing WinGet process: {ex.Message}\");\n }\n });\n \n exitCode = await processExitTask;\n _logService?.LogInformation($\"WinGet process exited with code: {exitCode}\");\n\n // Report completion progress\n if (exitCode == 0)\n {\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Installation completed successfully\",\n Percentage = 100,\n IsIndeterminate = false,\n }\n );\n }\n else\n {\n // Report failure progress\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = $\"Installation failed with exit code: {exitCode}\",\n Percentage = 100,\n IsIndeterminate = false,\n IsError = true\n }\n );\n }\n }\n catch (OperationCanceledException)\n {\n _logService?.LogWarning(\"WinGet process execution was cancelled\");\n\n // Try to kill the process if it's still running\n if (!process.HasExited)\n {\n try\n {\n // Report cancellation progress immediately\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Cancelling installation...\",\n Percentage = 0,\n IsIndeterminate = true,\n IsCancelled = true\n }\n );\n \n // Kill the process and all child processes in a background task\n Task.Run(() => \n {\n try \n {\n KillProcessAndChildren(process.Id);\n _logService?.LogWarning(\n \"WinGet process and all child processes were killed due to cancellation\"\n );\n \n // Update progress after killing processes\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Installation was cancelled\",\n Percentage = 0,\n IsIndeterminate = false,\n IsCancelled = true\n }\n );\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error killing processes: {ex.Message}\");\n }\n });\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error killing WinGet process: {ex.Message}\");\n }\n }\n \n // Report cancellation progress\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Installation was cancelled\",\n Percentage = 0,\n IsIndeterminate = false,\n IsCancelled = true\n }\n );\n\n throw;\n }\n\n string output = outputBuilder.ToString();\n string error = errorBuilder.ToString();\n\n return (exitCode, output, error);\n }\n catch (Exception ex) when (!(ex is OperationCanceledException))\n {\n _logService?.LogError($\"Error executing WinGet command: {ex.Message}\", ex);\n\n // Report error progress\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = $\"Error: {ex.Message}\",\n Percentage = 0,\n IsIndeterminate = false,\n }\n );\n\n return (1, string.Empty, ex.Message);\n }\n }\n\n // These methods have been moved to WinGetOutputParser class:\n // - DetermineInstallationState\n // - CalculateProgressPercentage\n // - GetStatusMessage\n\n // Original FindWinGetPath method removed to avoid duplication\n\n /// \n /// Kills a process and all of its children recursively with optimizations to prevent UI stalling.\n /// \n /// The process ID to kill.\n private void KillProcessAndChildren(int pid)\n {\n try\n {\n // First, directly kill any Windows Store processes that might be related to the installation\n // This is a more direct approach to ensure the installation is cancelled\n KillWindowsStoreProcesses();\n \n // Get the process by ID\n Process process = null;\n try\n {\n process = Process.GetProcessById(pid);\n }\n catch (ArgumentException)\n {\n _logService?.LogWarning($\"Process with ID {pid} not found\");\n return;\n }\n \n // Use a more efficient approach to kill the process and its children\n // with a timeout to prevent hanging\n using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)))\n {\n try\n {\n // Kill the process directly first\n if (!process.HasExited)\n {\n try\n {\n process.Kill(true); // true = kill entire process tree (Windows 10 1809+)\n _logService?.LogInformation($\"Killed process tree {process.ProcessName} (ID: {pid})\");\n return; // If this works, we're done\n }\n catch (PlatformNotSupportedException)\n {\n // Process.Kill(true) is not supported on this platform, continue with fallback\n _logService?.LogInformation(\"Process.Kill(true) not supported, using fallback method\");\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error killing process tree: {ex.Message}, using fallback method\");\n }\n }\n \n // Fallback: Kill the process and its children manually\n KillProcessTree(pid, cts.Token);\n }\n catch (OperationCanceledException)\n {\n _logService?.LogWarning(\"Process killing operation timed out\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error in KillProcessAndChildren for PID {pid}: {ex.Message}\");\n }\n }\n \n /// \n /// Kills the Windows Store processes that might be related to the installation.\n /// \n private void KillWindowsStoreProcesses()\n {\n try\n {\n // Target specific processes known to be related to Windows Store installations\n string[] targetProcessNames = new[] { \n \"WinStore.App\", \n \"WinStore.Mobile\", \n \"WindowsPackageManagerServer\", \n \"AppInstaller\",\n \"Microsoft.WindowsStore\"\n };\n \n foreach (var processName in targetProcessNames)\n {\n try\n {\n var processes = Process.GetProcessesByName(processName);\n foreach (var process in processes)\n {\n try\n {\n if (!process.HasExited)\n {\n process.Kill();\n _logService?.LogInformation($\"Killed Windows Store process: {processName}\");\n }\n }\n finally\n {\n process.Dispose();\n }\n }\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error killing Windows Store process {processName}: {ex.Message}\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error killing Windows Store processes: {ex.Message}\");\n }\n }\n \n /// \n /// Kills a process tree efficiently with cancellation support.\n /// \n /// The process ID to kill.\n /// Cancellation token to prevent hanging.\n private void KillProcessTree(int pid, CancellationToken cancellationToken)\n {\n try\n {\n // Get direct child processes using a more efficient method\n var childProcessIds = GetChildProcessIds(pid);\n \n // Kill child processes first\n foreach (var childPid in childProcessIds)\n {\n cancellationToken.ThrowIfCancellationRequested();\n \n try\n {\n // Recursively kill child process trees\n KillProcessTree(childPid, cancellationToken);\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error killing child process {childPid}: {ex.Message}\");\n }\n }\n \n // Kill the parent process\n try\n {\n var process = Process.GetProcessById(pid);\n if (!process.HasExited)\n {\n process.Kill();\n _logService?.LogInformation($\"Killed process {process.ProcessName} (ID: {pid})\");\n }\n process.Dispose();\n }\n catch (ArgumentException)\n {\n // Process already exited\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error killing process {pid}: {ex.Message}\");\n }\n }\n catch (OperationCanceledException)\n {\n throw; // Rethrow to be handled by the caller\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error in KillProcessTree for PID {pid}: {ex.Message}\");\n }\n }\n \n /// \n /// Gets the child process IDs for a given process ID efficiently.\n /// \n /// The parent process ID.\n /// A list of child process IDs.\n private List GetChildProcessIds(int parentId)\n {\n var result = new List();\n \n try\n {\n // Use a more efficient query that only gets the data we need\n using (var searcher = new System.Management.ManagementObjectSearcher(\n $\"SELECT ProcessId FROM Win32_Process WHERE ParentProcessId = {parentId}\"))\n {\n searcher.Options.Timeout = TimeSpan.FromSeconds(1); // Set a timeout to prevent hanging\n \n foreach (var obj in searcher.Get())\n {\n try\n {\n result.Add(Convert.ToInt32(obj[\"ProcessId\"]));\n }\n catch\n {\n // Skip this entry if conversion fails\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error getting child process IDs: {ex.Message}\");\n }\n \n return result;\n }\n \n private string EscapeArgument(string arg)\n {\n if (string.IsNullOrEmpty(arg))\n return \"\\\"\\\"\";\n\n // Escape any double quotes\n arg = arg.Replace(\"\\\"\", \"\\\\\\\"\");\n\n // Surround with quotes if it contains spaces\n if (arg.Contains(\" \"))\n arg = $\"\\\"{arg}\\\"\";\n\n return arg;\n }\n\n private PackageInfo ParsePackageInfo(string output)\n {\n if (string.IsNullOrWhiteSpace(output))\n return null;\n\n var info = new PackageInfo();\n var lines = output.Split(\n new[] { \"\\r\\n\", \"\\r\", \"\\n\" },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n foreach (var line in lines)\n {\n if (!line.Contains(\":\"))\n continue;\n\n var parts = line.Split(new[] { ':' }, 2);\n if (parts.Length != 2)\n continue;\n\n var key = parts[0].Trim().ToLowerInvariant();\n var value = parts[1].Trim();\n\n switch (key)\n {\n case \"id\":\n info.Id = value;\n break;\n case \"name\":\n info.Name = value;\n break;\n case \"version\":\n info.Version = value;\n break;\n // Description property doesn't exist in PackageInfo\n case \"description\":\n // info.Description = value;\n break;\n }\n }\n\n return info;\n }\n\n private IEnumerable ParsePackageList(string output)\n {\n if (string.IsNullOrWhiteSpace(output))\n yield break;\n\n var lines = output.Split(\n new[] { \"\\r\\n\", \"\\r\", \"\\n\" },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n // Skip header lines\n bool headerPassed = false;\n for (int i = 0; i < lines.Length; i++)\n {\n var line = lines[i].Trim();\n\n // Skip empty lines\n if (string.IsNullOrWhiteSpace(line))\n continue;\n\n // Skip until we find a line with dashes (header separator)\n if (!headerPassed)\n {\n if (line.Contains(\"---\"))\n {\n headerPassed = true;\n }\n continue;\n }\n\n // Parse package info from the line\n var parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (parts.Length < 3)\n continue;\n\n yield return new PackageInfo\n {\n Name = parts[0],\n Id = parts[1],\n Version = parts[2],\n Source = parts.Length > 3 ? parts[3] : string.Empty,\n IsInstalled = line.Contains(\"[Installed]\"),\n };\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Services/SoftwareAppsDialogService.cs", "using System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.SoftwareApps.Views;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Services\n{\n /// \n /// Specialized dialog service for the SoftwareApps feature.\n /// This service uses the SoftwareAppsDialog for consistent UI in the SoftwareApps feature.\n /// \n public class SoftwareAppsDialogService\n {\n private readonly ILogService _logService;\n\n public SoftwareAppsDialogService(ILogService logService)\n {\n _logService = logService;\n }\n\n /// \n /// Shows a message to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n public Task ShowMessageAsync(string message, string title = \"\")\n {\n SoftwareAppsDialog.ShowInformationAsync(title, message, new[] { message }, \"\");\n return Task.CompletedTask;\n }\n\n /// \n /// Shows a confirmation dialog to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n /// The text for the OK button.\n /// The text for the Cancel button.\n /// A task that represents the asynchronous operation, with a boolean result indicating whether the user confirmed the action.\n public Task ShowConfirmationAsync(\n string message,\n string title = \"\",\n string okButtonText = \"OK\",\n string cancelButtonText = \"Cancel\"\n )\n {\n // Parse apps from the message if it contains a list\n if (\n message.Contains(\"following\")\n && (message.Contains(\"install\") || message.Contains(\"remove\"))\n )\n {\n var lines = message.Split('\\n');\n var apps = lines\n .Skip(1) // Skip the header line\n .Where(line =>\n !string.IsNullOrWhiteSpace(line) && !line.Contains(\"Do you want to\")\n )\n .TakeWhile(line => !line.Contains(\"Do you want to\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line =>\n line.Contains(\"cannot be\")\n || line.Contains(\"action cannot\")\n || line.Contains(\"Some selected\")\n )\n .Select(line => line.Trim())\n );\n\n var result = SoftwareAppsDialog.ShowConfirmationAsync(\n title,\n headerText,\n apps,\n footerText\n );\n return Task.FromResult(result ?? false);\n }\n else\n {\n // For simple confirmation messages\n var result = SoftwareAppsDialog.ShowConfirmationAsync(\n title,\n message,\n new[] { message },\n \"\"\n );\n return Task.FromResult(result ?? false);\n }\n }\n\n /// \n /// Shows an information dialog to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n /// The text for the button.\n /// A task that represents the asynchronous operation.\n public Task ShowInformationAsync(\n string message,\n string title = \"Information\",\n string buttonText = \"OK\"\n )\n {\n // Parse apps from the message if it contains a list\n if (\n message.Contains(\"following\")\n && (message.Contains(\"installed\") || message.Contains(\"removed\"))\n )\n {\n var lines = message.Split('\\n');\n var apps = lines\n .Where(line => line.StartsWith(\"+\") || line.StartsWith(\"-\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line => line.Contains(\"Failed\") || line.Contains(\"startup task\"))\n .Select(line => line.Trim())\n );\n\n SoftwareAppsDialog.ShowInformationAsync(title, headerText, apps, footerText);\n }\n else\n {\n // For simple information messages\n SoftwareAppsDialog.ShowInformationAsync(title, message, new[] { message }, \"\");\n }\n return Task.CompletedTask;\n }\n\n /// \n /// Shows an information dialog to the user with custom header, apps list, and footer.\n /// \n /// The title of the dialog.\n /// The header text to display.\n /// The collection of app names or messages to display.\n /// The footer text to display.\n /// A task that represents the asynchronous operation.\n public Task ShowInformationAsync(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n SoftwareAppsDialog.ShowInformationAsync(title, headerText, apps, footerText);\n return Task.CompletedTask;\n }\n\n /// \n /// Shows a warning dialog to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n /// The text for the button.\n /// A task that represents the asynchronous operation.\n public Task ShowWarningAsync(\n string message,\n string title = \"Warning\",\n string buttonText = \"OK\"\n )\n {\n SoftwareAppsDialog.ShowInformationAsync(title, message, new[] { message }, \"\");\n return Task.CompletedTask;\n }\n\n /// \n /// Shows an input dialog to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n /// The default value for the input.\n /// A task that represents the asynchronous operation, with the user's input as the result.\n public Task ShowInputAsync(\n string message,\n string title = \"\",\n string defaultValue = \"\"\n )\n {\n // Input dialogs are not supported by SoftwareAppsDialog\n // Fallback to a confirmation dialog\n var result = SoftwareAppsDialog.ShowConfirmationAsync(\n title,\n message,\n new[] { message },\n \"\"\n );\n return Task.FromResult(result == true ? defaultValue : null);\n }\n\n /// \n /// Shows a Yes/No/Cancel dialog to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n /// A task that represents the asynchronous operation, with a boolean result indicating the user's choice (true for Yes, false for No, null for Cancel).\n public Task ShowYesNoCancelAsync(string message, string title = \"\")\n {\n // Parse apps from the message if it contains a list\n if (\n message.Contains(\"following\")\n && (message.Contains(\"install\") || message.Contains(\"remove\"))\n )\n {\n var lines = message.Split('\\n');\n var apps = lines\n .Where(line => line.StartsWith(\"+\") || line.StartsWith(\"-\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line =>\n line.Contains(\"cannot be\")\n || line.Contains(\"action cannot\")\n || line.Contains(\"Some selected\")\n )\n .Select(line => line.Trim())\n );\n\n var result = SoftwareAppsDialog.ShowYesNoCancel(\n title,\n headerText,\n apps,\n footerText\n );\n return Task.FromResult(result);\n }\n else\n {\n // For simple messages\n var result = SoftwareAppsDialog.ShowYesNoCancel(\n title,\n message,\n new[] { message },\n \"\"\n );\n return Task.FromResult(result);\n }\n }\n\n /// \n /// Shows an operation result dialog to the user.\n /// \n /// The type of operation (e.g., \"Install\", \"Remove\").\n /// The number of successful operations.\n /// The total number of operations.\n /// The list of successfully processed items.\n /// The list of failed items.\n /// The list of skipped items.\n /// Whether there were connectivity issues.\n public void ShowOperationResult(\n string operationType,\n int successCount,\n int totalCount,\n IEnumerable successItems,\n IEnumerable failedItems = null,\n IEnumerable skippedItems = null,\n bool hasConnectivityIssues = false,\n bool isUserCancelled = false\n )\n {\n // Get the past tense form of the operation type\n string GetPastTense(string op)\n {\n if (string.IsNullOrEmpty(op))\n return string.Empty;\n\n return op.Equals(\"Remove\", System.StringComparison.OrdinalIgnoreCase)\n ? \"removed\"\n : $\"{op.ToLower()}ed\";\n }\n\n // Check if any failures are due to internet connectivity issues or user cancellation\n bool isFailure = successCount < totalCount;\n\n string title;\n if (isUserCancelled)\n {\n title = \"Installation Aborted\";\n }\n else if (hasConnectivityIssues)\n {\n title = \"Internet Connection Lost\";\n }\n else\n {\n title = isFailure\n ? $\"{operationType} Operation Failed\"\n : $\"{operationType} Results\";\n }\n\n string headerText;\n if (isUserCancelled)\n {\n headerText = $\"Installation aborted by user\";\n }\n else if (hasConnectivityIssues)\n {\n headerText = \"Installation stopped due to internet connection loss\";\n }\n else\n {\n headerText =\n successCount > 0 && successCount == totalCount\n ? $\"The following items were successfully {GetPastTense(operationType)}:\"\n : (\n successCount > 0\n ? $\"Successfully {GetPastTense(operationType)} {successCount} of {totalCount} items.\"\n : $\"Unable to {operationType.ToLowerInvariant()} {totalCount} of {totalCount} items.\"\n );\n }\n\n // Create list of items for the dialog\n var resultItems = new List();\n\n // For connectivity issues or user cancellation, add a clear explanation\n if (isUserCancelled)\n {\n resultItems.Add(\"The installation process was cancelled by the user.\");\n resultItems.Add(\"\");\n if (successCount > 0)\n {\n resultItems.Add(\"Successfully installed items:\");\n }\n }\n else if (hasConnectivityIssues)\n {\n resultItems.Add(\n \"The installation process was stopped because the internet connection was lost.\"\n );\n resultItems.Add(\n \"This is required to ensure installations complete properly and prevent corrupted installations.\"\n );\n resultItems.Add(\"\");\n resultItems.Add(\"Failed items:\");\n }\n\n // Add successful items directly to the list\n if (successItems != null && successItems.Any())\n {\n if (!hasConnectivityIssues) // Only show success items if not a connectivity issue\n {\n foreach (var item in successItems)\n {\n resultItems.Add(item);\n }\n }\n }\n else if (!hasConnectivityIssues) // Only show this message if not a connectivity issue\n {\n resultItems.Add($\"No items were {GetPastTense(operationType)}.\");\n }\n\n // Add skipped items if any\n if (skippedItems != null && skippedItems.Any() && !hasConnectivityIssues) // Only show if not a connectivity issue\n {\n resultItems.Add($\"Skipped items: {skippedItems.Count()}\");\n foreach (var item in skippedItems.Take(5))\n {\n resultItems.Add($\" - {item}\");\n }\n if (skippedItems.Count() > 5)\n {\n resultItems.Add($\" - ... and {skippedItems.Count() - 5} more\");\n }\n }\n\n // Add failed items if any\n if (failedItems != null && failedItems.Any())\n {\n if (!hasConnectivityIssues) // Only show the header if not already shown for connectivity issues\n {\n resultItems.Add($\"Failed items: {failedItems.Count()}\");\n }\n\n foreach (var item in failedItems.Take(5))\n {\n resultItems.Add($\" - {item}\");\n }\n if (failedItems.Count() > 5)\n {\n resultItems.Add($\" - ... and {failedItems.Count() - 5} more\");\n }\n }\n\n // Create footer text\n string footerText;\n if (isUserCancelled)\n {\n footerText =\n successCount > 0\n ? $\"Some items were successfully {GetPastTense(operationType)} before cancellation.\"\n : $\"No items were {GetPastTense(operationType)} before cancellation.\";\n }\n else if (hasConnectivityIssues)\n {\n footerText =\n \"Please check your network connection and try again when your internet connection is stable.\";\n }\n else\n {\n // Check if we have any connectivity-related failures\n bool hasConnectivityFailures =\n failedItems != null\n && failedItems.Any(item =>\n item.Contains(\"internet\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\"connection\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\"network\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\n \"pipeline has been stopped\",\n StringComparison.OrdinalIgnoreCase\n )\n );\n\n footerText =\n successCount == totalCount\n ? $\"All items were successfully {GetPastTense(operationType)}.\"\n : (\n successCount > 0\n ? (\n hasConnectivityFailures\n ? $\"Some items could not be {GetPastTense(operationType)}. Please check your internet connection and try again.\"\n : $\"Some items could not be {GetPastTense(operationType)}. Please try again later.\"\n )\n : (\n hasConnectivityFailures\n ? $\"Installation failed. Please check your internet connection and try again.\"\n : $\"Installation failed. Please try again later.\"\n )\n );\n }\n\n // Show the information dialog\n SoftwareAppsDialog.ShowInformationAsync(title, headerText, resultItems, footerText);\n }\n\n /// \n /// Gets the past tense form of an operation type\n /// \n /// The operation type (e.g., \"Install\", \"Remove\")\n /// The past tense form of the operation type\n private string GetPastTense(string operationType)\n {\n if (string.IsNullOrEmpty(operationType))\n return string.Empty;\n\n return operationType.Equals(\"Remove\", StringComparison.OrdinalIgnoreCase)\n ? \"removed\"\n : $\"{operationType.ToLower()}ed\";\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/InstallationOrchestrator.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Exceptions;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Orchestrates the installation and removal of applications, capabilities, and features.\n/// \npublic class InstallationOrchestrator : IInstallationOrchestrator\n{\n private readonly IAppInstallationService _appInstallationService;\n private readonly ICapabilityInstallationService _capabilityInstallationService;\n private readonly IFeatureInstallationService _featureInstallationService;\n private readonly IAppRemovalService _appRemovalService;\n private readonly ICapabilityRemovalService _capabilityRemovalService;\n private readonly IFeatureRemovalService _featureRemovalService;\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The app installation service.\n /// The capability installation service.\n /// The feature installation service.\n /// The app removal service.\n /// The capability removal service.\n /// The feature removal service.\n /// The log service.\n public InstallationOrchestrator(\n IAppInstallationService appInstallationService,\n ICapabilityInstallationService capabilityInstallationService,\n IFeatureInstallationService featureInstallationService,\n IAppRemovalService appRemovalService,\n ICapabilityRemovalService capabilityRemovalService,\n IFeatureRemovalService featureRemovalService,\n ILogService logService)\n {\n _appInstallationService = appInstallationService ?? throw new ArgumentNullException(nameof(appInstallationService));\n _capabilityInstallationService = capabilityInstallationService ?? throw new ArgumentNullException(nameof(capabilityInstallationService));\n _featureInstallationService = featureInstallationService ?? throw new ArgumentNullException(nameof(featureInstallationService));\n _appRemovalService = appRemovalService ?? throw new ArgumentNullException(nameof(appRemovalService));\n _capabilityRemovalService = capabilityRemovalService ?? throw new ArgumentNullException(nameof(capabilityRemovalService));\n _featureRemovalService = featureRemovalService ?? throw new ArgumentNullException(nameof(featureRemovalService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Installs an application, capability, or feature.\n /// \n /// The item to install.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the asynchronous operation.\n public async Task InstallAsync(\n IInstallableItem item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (item == null)\n {\n throw new ArgumentNullException(nameof(item));\n }\n\n _logService.LogInformation($\"Installing {item.DisplayName}\");\n\n try\n {\n if (item is AppInfo appInfo)\n {\n await _appInstallationService.InstallAppAsync(appInfo, progress, cancellationToken);\n }\n else if (item is CapabilityInfo capabilityInfo)\n {\n // Assuming InstallCapabilityAsync should be called for single items\n await _capabilityInstallationService.InstallCapabilityAsync(capabilityInfo, progress, cancellationToken);\n }\n else if (item is FeatureInfo featureInfo)\n {\n // Corrected method name\n await _featureInstallationService.InstallFeatureAsync(featureInfo, progress, cancellationToken);\n }\n else\n {\n throw new ArgumentException($\"Unsupported item type: {item.GetType().Name}\", nameof(item));\n }\n\n _logService.LogSuccess($\"Successfully installed {item.DisplayName}\");\n }\n catch (Exception ex) when (ex is not InstallationException)\n {\n _logService.LogError($\"Failed to install {item.DisplayName}\", ex);\n throw new InstallationException(item.DisplayName, $\"Installation failed for {item.DisplayName}\", false, ex);\n }\n }\n\n /// \n /// Removes an application, capability, or feature.\n /// \n /// The item to remove.\n /// A task representing the asynchronous operation.\n public async Task RemoveAsync(IInstallableItem item)\n {\n if (item == null)\n {\n throw new ArgumentNullException(nameof(item));\n }\n\n _logService.LogInformation($\"Removing {item.DisplayName}\");\n\n try\n {\n if (item is AppInfo appInfo)\n {\n await _appRemovalService.RemoveAppAsync(appInfo);\n }\n else if (item is CapabilityInfo capabilityInfo)\n {\n await _capabilityRemovalService.RemoveCapabilityAsync(capabilityInfo);\n }\n else if (item is FeatureInfo featureInfo)\n {\n await _featureRemovalService.RemoveFeatureAsync(featureInfo);\n }\n else\n {\n throw new ArgumentException($\"Unsupported item type: {item.GetType().Name}\", nameof(item));\n }\n\n _logService.LogSuccess($\"Successfully removed {item.DisplayName}\");\n }\n catch (Exception ex) when (ex is not RemovalException)\n {\n _logService.LogError($\"Failed to remove {item.DisplayName}\", ex);\n throw new RemovalException(item.DisplayName, ex.Message, true, ex);\n }\n }\n\n /// \n /// Installs multiple items in batch.\n /// \n /// The items to install.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the asynchronous operation.\n public async Task InstallBatchAsync(\n IEnumerable items,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (items == null)\n {\n throw new ArgumentNullException(nameof(items));\n }\n\n var itemsList = new List(items);\n _logService.LogInformation($\"Installing {itemsList.Count} items in batch\");\n\n int totalItems = itemsList.Count;\n int completedItems = 0;\n\n foreach (var item in itemsList)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n _logService.LogWarning(\"Batch installation cancelled\");\n break;\n }\n\n try\n {\n // Create a progress wrapper that scales the progress to the current item's portion\n var itemProgress = progress != null\n ? new Progress(detail =>\n {\n // Scale the progress to the current item's portion of the total\n double scaledProgress = (completedItems * 100.0 + (detail.Progress ?? 0)) / totalItems;\n \n progress.Report(new TaskProgressDetail\n {\n Progress = scaledProgress,\n StatusText = $\"[{completedItems + 1}/{totalItems}] {detail.StatusText}\",\n DetailedMessage = detail.DetailedMessage,\n LogLevel = detail.LogLevel\n });\n })\n : null;\n\n await InstallAsync(item, itemProgress, cancellationToken);\n completedItems++;\n\n // Report overall progress\n progress?.Report(new TaskProgressDetail\n {\n Progress = completedItems * 100.0 / totalItems,\n StatusText = $\"Completed {completedItems} of {totalItems} items\",\n DetailedMessage = $\"Successfully installed {item.DisplayName}\"\n });\n }\n catch (Exception ex) when (ex is not InstallationException)\n {\n _logService.LogError($\"Error installing {item.DisplayName}\", ex);\n \n // Report error but continue with next item\n progress?.Report(new TaskProgressDetail\n {\n Progress = completedItems * 100.0 / totalItems,\n StatusText = $\"Error installing {item.DisplayName}\",\n DetailedMessage = ex.Message,\n LogLevel = Winhance.Core.Features.Common.Enums.LogLevel.Error\n });\n\n throw new InstallationException($\"Error installing {item.DisplayName}: {ex.Message}\", ex);\n }\n }\n\n _logService.LogInformation($\"Batch installation completed. {completedItems} of {totalItems} items installed successfully.\");\n }\n\n /// \n /// Removes multiple items in batch.\n /// \n /// The items to remove.\n /// A list of results indicating success or failure for each item.\n public async Task> RemoveBatchAsync(\n IEnumerable items)\n {\n if (items == null)\n {\n throw new ArgumentNullException(nameof(items));\n }\n\n var itemsList = new List(items);\n _logService.LogInformation($\"Removing {itemsList.Count} items in batch\");\n\n var results = new List<(string Name, bool Success, string? Error)>();\n\n foreach (var item in itemsList)\n {\n try\n {\n await RemoveAsync(item);\n results.Add((item.DisplayName, true, null));\n }\n catch (Exception ex) when (ex is not RemovalException)\n {\n _logService.LogError($\"Error removing {item.DisplayName}\", ex);\n results.Add((item.DisplayName, false, new RemovalException(item.DisplayName, ex.Message, true, ex).Message));\n }\n }\n\n int successCount = results.Count(r => r.Success);\n _logService.LogInformation($\"Batch removal completed. {successCount} of {results.Count} items removed successfully.\");\n\n return results;\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/WindowsSystemService.cs", "using System;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Services;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.Customize.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Models.Enums;\n\n// We're now using the UacLevel from Models.Enums directly\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Contains detailed information about the Windows version\n /// \n public class WindowsVersionInfo\n {\n /// \n /// The full OS version\n /// \n public Version Version { get; set; }\n\n /// \n /// The major version number\n /// \n public int MajorVersion { get; set; }\n\n /// \n /// The minor version number\n /// \n public int MinorVersion { get; set; }\n\n /// \n /// The build number\n /// \n public int BuildNumber { get; set; }\n\n /// \n /// The product name from registry\n /// \n public string ProductName { get; set; }\n\n /// \n /// Whether this is Windows 11 based on build number\n /// \n public bool IsWindows11ByBuild { get; set; }\n\n /// \n /// Whether this is Windows 11 based on product name\n /// \n public bool IsWindows11ByProductName { get; set; }\n\n /// \n /// Whether this is Windows 11 (combined determination)\n /// \n public bool IsWindows11 { get; set; }\n\n /// \n /// Whether this is Windows 10\n /// \n public bool IsWindows10 { get; set; }\n }\n\n public class WindowsSystemService : ISystemServices\n {\n // Dependencies\n private readonly IRegistryService _registryService;\n private readonly ILogService _logService;\n private readonly IThemeService _themeService;\n private readonly IUacSettingsService _uacSettingsService;\n private readonly IInternetConnectivityService _connectivityService;\n\n public WindowsSystemService(\n IRegistryService registryService,\n ILogService logService,\n IInternetConnectivityService connectivityService,\n IThemeService themeService = null,\n IUacSettingsService uacSettingsService = null\n ) // Optional to maintain backward compatibility\n {\n _registryService =\n registryService ?? throw new ArgumentNullException(nameof(registryService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _connectivityService =\n connectivityService ?? throw new ArgumentNullException(nameof(connectivityService));\n _themeService = themeService; // May be null if not provided\n _uacSettingsService = uacSettingsService; // May be null if not provided\n }\n\n /// \n /// Gets the registry service.\n /// \n public IRegistryService RegistryService => _registryService;\n\n public bool IsAdministrator()\n {\n try\n {\n#if WINDOWS\n WindowsIdentity identity = WindowsIdentity.GetCurrent();\n WindowsPrincipal principal = new WindowsPrincipal(identity);\n bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);\n\n _logService.LogInformation(\n $\"Administrator check completed. Is Administrator: {isAdmin}\"\n );\n return isAdmin;\n#else\n _logService.LogWarning(\"Administrator check is not supported on this platform.\");\n return false;\n#endif\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking administrator status\", ex);\n return false;\n }\n }\n\n /// \n /// Gets detailed Windows version information including build number and product name\n /// \n /// A WindowsVersionInfo object containing detailed version information\n private WindowsVersionInfo GetWindowsVersionInfo()\n {\n var result = new WindowsVersionInfo();\n\n try\n {\n var osVersion = Environment.OSVersion;\n result.Version = osVersion.Version;\n result.MajorVersion = osVersion.Version.Major;\n result.MinorVersion = osVersion.Version.Minor;\n result.BuildNumber = osVersion.Version.Build;\n\n // Check if Windows 11 using build number\n result.IsWindows11ByBuild =\n result.MajorVersion == 10 && result.BuildNumber >= 22000;\n\n // Check registry ProductName for more reliable detection\n try\n {\n using (\n var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(\n @\"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\"\n )\n )\n {\n if (key != null)\n {\n result.ProductName = key.GetValue(\"ProductName\") as string;\n result.IsWindows11ByProductName =\n result.ProductName != null\n && result.ProductName.Contains(\"Windows 11\");\n\n // Log the actual product name for debugging\n _logService.LogInformation(\n $\"Windows registry ProductName: {result.ProductName}\"\n );\n }\n }\n }\n catch (Exception regEx)\n {\n _logService.LogWarning($\"Error reading registry ProductName: {regEx.Message}\");\n }\n\n // Log detailed version information\n _logService.LogInformation(\n $\"Windows build number: {result.BuildNumber}, IsWin11ByBuild: {result.IsWindows11ByBuild}, IsWin11ByProductName: {result.IsWindows11ByProductName}\"\n );\n\n // Determine if this is Windows 11 using both methods, with ProductName taking precedence if available\n result.IsWindows11 =\n result.IsWindows11ByProductName\n || (result.IsWindows11ByBuild && !result.IsWindows11ByProductName == false);\n result.IsWindows10 = result.MajorVersion == 10 && !result.IsWindows11;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error getting Windows version info\", ex);\n }\n\n return result;\n }\n\n public string GetWindowsVersion()\n {\n try\n {\n var versionInfo = GetWindowsVersionInfo();\n string versionString;\n\n if (versionInfo.MajorVersion == 10)\n {\n versionString = versionInfo.IsWindows11 ? \"Windows 11\" : \"Windows 10\";\n }\n else\n {\n versionString = $\"Windows {versionInfo.Version}\";\n }\n\n _logService.LogInformation($\"Detected Windows version: {versionString}\");\n return versionString;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error detecting Windows version\", ex);\n return \"Unknown Windows Version\";\n }\n }\n\n public void RestartExplorer()\n {\n try\n {\n _logService.LogInformation(\"Attempting to restart Explorer\");\n\n // Kill all explorer processes\n var explorerProcesses = Process.GetProcessesByName(\"explorer\");\n foreach (var process in explorerProcesses)\n {\n _logService.LogInformation($\"Killing Explorer process (PID: {process.Id})\");\n process.Kill();\n }\n\n // Wait a moment - using Thread.Sleep since we can't use await anymore\n Thread.Sleep(1000);\n\n // Restart explorer\n Process.Start(\"explorer.exe\");\n\n _logService.LogSuccess(\"Explorer restarted successfully\");\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to restart Explorer\", ex);\n }\n }\n\n public void RefreshDesktop()\n {\n try\n {\n [DllImport(\"user32.dll\", SetLastError = true)]\n static extern bool SystemParametersInfo(\n uint uiAction,\n uint uiParam,\n IntPtr pvParam,\n uint fWinIni\n );\n\n const uint SPI_SETDESKWALLPAPER = 0x0014;\n const uint SPIF_UPDATEINIFILE = 0x01;\n const uint SPIF_SENDCHANGE = 0x02;\n\n _logService.LogInformation(\"Attempting to refresh desktop\");\n SystemParametersInfo(\n SPI_SETDESKWALLPAPER,\n 0,\n IntPtr.Zero,\n SPIF_UPDATEINIFILE | SPIF_SENDCHANGE\n );\n\n _logService.LogSuccess(\"Desktop refreshed successfully\");\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to refresh desktop\", ex);\n }\n }\n\n public bool IsProcessRunning(string processName)\n {\n try\n {\n bool isRunning = Process.GetProcessesByName(processName).Length > 0;\n _logService.LogInformation($\"Process check for {processName}: {isRunning}\");\n return isRunning;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking if process {processName} is running\", ex);\n return false;\n }\n }\n\n public void KillProcess(string processName)\n {\n try\n {\n _logService.LogInformation($\"Attempting to kill process: {processName}\");\n\n var processes = Process.GetProcessesByName(processName);\n foreach (var process in processes)\n {\n _logService.LogInformation(\n $\"Killing process {processName} (PID: {process.Id})\"\n );\n process.Kill();\n }\n\n _logService.LogSuccess($\"Killed all instances of {processName}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to kill process {processName}\", ex);\n }\n }\n\n // IsInternetConnected method has been moved to InternetConnectivityService\n\n // IsInternetConnectedAsync method has been moved to InternetConnectivityService\n\n public bool IsWindows11()\n {\n try\n {\n // Use our centralized version detection method\n var versionInfo = GetWindowsVersionInfo();\n\n _logService.LogInformation(\n $\"Windows 11 check completed. Is Windows 11: {versionInfo.IsWindows11} (By build: {versionInfo.IsWindows11ByBuild}, By ProductName: {versionInfo.IsWindows11ByProductName})\"\n );\n return versionInfo.IsWindows11;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking Windows 11 version\", ex);\n return false;\n }\n }\n\n public bool RequireAdministrator()\n {\n try\n {\n if (!IsAdministrator())\n {\n _logService.LogWarning(\n \"Application requires administrator privileges. Attempting to elevate.\"\n );\n\n ProcessStartInfo startInfo = new ProcessStartInfo\n {\n UseShellExecute = true,\n WorkingDirectory = Environment.CurrentDirectory,\n FileName =\n Process.GetCurrentProcess().MainModule?.FileName\n ?? throw new InvalidOperationException(\"MainModule is null\"),\n Verb = \"runas\",\n };\n\n try\n {\n // Start the elevated process and capture the Process object\n Process elevatedProcess = Process.Start(startInfo);\n\n // If elevatedProcess is null, it means the UAC prompt was canceled or denied\n if (elevatedProcess == null)\n {\n _logService.LogWarning(\n \"User denied UAC elevation. Application will exit.\"\n );\n Environment.Exit(1); // Exit with error code to indicate denial\n return false;\n }\n\n _logService.LogInformation(\n \"Elevation request accepted. Exiting current process.\"\n );\n Environment.Exit(0);\n }\n catch (System.ComponentModel.Win32Exception w32Ex)\n when (w32Ex.NativeErrorCode == 1223)\n {\n // Error code 1223 specifically means \"The operation was canceled by the user\"\n // This happens when the user clicks \"No\" on the UAC prompt\n _logService.LogWarning(\"User denied UAC elevation. Application will exit.\");\n Environment.Exit(1); // Exit with error code to indicate denial\n return false;\n }\n catch (Exception elevationEx)\n {\n _logService.LogError(\"Failed to elevate privileges\", elevationEx);\n Environment.Exit(1); // Exit with error code to indicate failure\n return false;\n }\n }\n\n _logService.LogInformation(\"Application is running with administrator privileges\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Unexpected error during privilege elevation\", ex);\n return false;\n }\n }\n\n public bool IsDarkModeEnabled()\n {\n // Delegate to ThemeService if available, otherwise use legacy implementation\n if (_themeService != null)\n {\n try\n {\n return _themeService.IsDarkModeEnabled();\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Error using ThemeService.IsDarkModeEnabled: {ex.Message}. Falling back to legacy implementation.\"\n );\n // Fall through to legacy implementation\n }\n }\n\n // Legacy implementation\n try\n {\n using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(\n WindowsThemeSettings.Registry.ThemesPersonalizeSubKey\n );\n\n if (key == null)\n {\n _logService.LogWarning(\"Could not open registry key for dark mode check\");\n return false;\n }\n\n var value = key.GetValue(WindowsThemeSettings.Registry.AppsUseLightThemeName);\n bool isDarkMode = value != null && (int)value == 0;\n\n _logService.LogInformation(\n $\"Dark mode check completed. Is Dark Mode: {isDarkMode}\"\n );\n return isDarkMode;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking dark mode status\", ex);\n return false;\n }\n }\n\n public void SetDarkMode(bool enabled)\n {\n // Delegate to ThemeService if available, otherwise use legacy implementation\n if (_themeService != null)\n {\n try\n {\n _themeService.SetThemeMode(enabled);\n return;\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Error using ThemeService.SetThemeMode: {ex.Message}. Falling back to legacy implementation.\"\n );\n // Fall through to legacy implementation\n }\n }\n\n // Legacy implementation\n try\n {\n _logService.LogInformation(\n $\"Attempting to {(enabled ? \"enable\" : \"disable\")} dark mode\"\n );\n\n string[] keys = new[] { WindowsThemeSettings.Registry.ThemesPersonalizeSubKey };\n\n string[] values = new[]\n {\n WindowsThemeSettings.Registry.AppsUseLightThemeName,\n WindowsThemeSettings.Registry.SystemUsesLightThemeName,\n };\n\n foreach (var key in keys)\n {\n using var registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(\n key,\n true\n );\n if (registryKey == null)\n {\n _logService.LogWarning($\"Could not open registry key: {key}\");\n continue;\n }\n\n foreach (var value in values)\n {\n registryKey.SetValue(\n value,\n enabled ? 0 : 1,\n Microsoft.Win32.RegistryValueKind.DWord\n );\n _logService.LogInformation($\"Set {value} to {(enabled ? 0 : 1)}\");\n }\n }\n\n _logService.LogSuccess(\n $\"Dark mode {(enabled ? \"enabled\" : \"disabled\")} successfully\"\n );\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to {(enabled ? \"enable\" : \"disable\")} dark mode\", ex);\n }\n }\n\n public void SetUacLevel(Winhance.Core.Models.Enums.UacLevel level)\n {\n try\n {\n // No need to convert as we're already using the Core UacLevel\n Winhance.Core.Models.Enums.UacLevel coreLevel = level;\n\n // Special handling for Custom UAC level\n if (coreLevel == Winhance.Core.Models.Enums.UacLevel.Custom)\n {\n // For Custom level, try to get the saved custom settings and apply them\n if (_uacSettingsService != null && _uacSettingsService.TryGetCustomUacValues(\n out int customConsentPromptValue, \n out int customSecureDesktopValue))\n {\n _logService.Log(\n LogLevel.Info,\n $\"Applying saved custom UAC settings: ConsentPrompt={customConsentPromptValue}, SecureDesktop={customSecureDesktopValue}\"\n );\n \n string registryPath = $\"HKLM\\\\{UacOptimizations.RegistryPath}\";\n \n // Set the ConsentPromptBehaviorAdmin value\n _registryService.SetValue(\n registryPath,\n UacOptimizations.ConsentPromptName,\n customConsentPromptValue,\n UacOptimizations.ValueKind\n );\n \n // Set the PromptOnSecureDesktop value\n _registryService.SetValue(\n registryPath,\n UacOptimizations.SecureDesktopName,\n customSecureDesktopValue,\n UacOptimizations.ValueKind\n );\n \n return;\n }\n else\n {\n // No saved custom settings found\n _logService.Log(\n LogLevel.Warning,\n \"Custom UAC level selected but no saved settings found - preserving current registry settings\"\n );\n return;\n }\n }\n\n // Get both registry values for the selected UAC level\n if (\n !UacOptimizations.UacLevelToConsentPromptValue.TryGetValue(\n coreLevel,\n out int consentPromptValue\n )\n || !UacOptimizations.UacLevelToSecureDesktopValue.TryGetValue(\n coreLevel,\n out int secureDesktopValue\n )\n )\n {\n throw new ArgumentException($\"Invalid UAC level: {level}\");\n }\n\n string fullPath = $\"HKLM\\\\{UacOptimizations.RegistryPath}\";\n\n bool keyExists = _registryService.KeyExists(fullPath);\n if (!keyExists)\n {\n _logService.Log(\n LogLevel.Info,\n $\"UAC registry key doesn't exist, creating: {fullPath}\"\n );\n _registryService.CreateKey(fullPath);\n }\n\n // Set the ConsentPromptBehaviorAdmin value\n _registryService.SetValue(\n fullPath,\n UacOptimizations.ConsentPromptName,\n consentPromptValue,\n UacOptimizations.ValueKind\n );\n\n // Set the PromptOnSecureDesktop value\n _registryService.SetValue(\n fullPath,\n UacOptimizations.SecureDesktopName,\n secureDesktopValue,\n UacOptimizations.ValueKind\n );\n\n string levelName = UacOptimizations.UacLevelNames.TryGetValue(\n coreLevel,\n out string name\n )\n ? name\n : coreLevel.ToString();\n _logService.Log(\n LogLevel.Info,\n $\"UAC level set to {levelName} (ConsentPrompt: {consentPromptValue}, SecureDesktop: {secureDesktopValue})\"\n );\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting UAC level: {ex.Message}\");\n throw;\n }\n }\n\n public Winhance.Core.Models.Enums.UacLevel GetUacLevel()\n {\n try\n {\n string fullPath = $\"HKLM\\\\{UacOptimizations.RegistryPath}\";\n\n // Get both registry values needed to determine the UAC level\n var consentPromptValue = _registryService.GetValue(\n fullPath,\n UacOptimizations.ConsentPromptName\n );\n var secureDesktopValue = _registryService.GetValue(\n fullPath,\n UacOptimizations.SecureDesktopName\n );\n\n // Convert to integers with appropriate defaults if values are null\n var consentPromptInt = Convert.ToInt32(consentPromptValue ?? 5); // Default to 5 (Notify)\n var secureDesktopInt = Convert.ToInt32(secureDesktopValue ?? 1); // Default to 1 (Enabled)\n\n _logService.Log(\n LogLevel.Info,\n $\"UAC registry values retrieved: ConsentPrompt={consentPromptInt}, SecureDesktop={secureDesktopInt}\"\n );\n\n // Determine the UacLevel from both registry values\n Winhance.Core.Models.Enums.UacLevel coreLevel =\n UacOptimizations.GetUacLevelFromRegistryValues(\n consentPromptInt,\n secureDesktopInt,\n _uacSettingsService\n );\n string levelName = UacOptimizations.UacLevelNames.TryGetValue(\n coreLevel,\n out string name\n )\n ? name\n : coreLevel.ToString();\n\n _logService.Log(LogLevel.Info, $\"UAC level mapped to: {levelName}\");\n\n // Return the Core UacLevel directly\n return coreLevel;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting UAC level: {ex.Message}\");\n return Winhance.Core.Models.Enums.UacLevel.NotifyChangesOnly; // Default value\n }\n }\n\n public async Task RefreshWindowsGUI(bool killExplorer)\n {\n try\n {\n _logService.Log(\n LogLevel.Info,\n $\"Refreshing Windows GUI (killExplorer: {killExplorer})\"\n );\n\n // Define Windows message constants\n const int HWND_BROADCAST = 0xffff;\n const uint WM_SYSCOLORCHANGE = 0x0015;\n const uint WM_SETTINGCHANGE = 0x001A;\n const uint WM_THEMECHANGE = 0x031A;\n\n // Import Windows API functions\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\n static extern IntPtr SendMessage(\n IntPtr hWnd,\n uint Msg,\n IntPtr wParam,\n IntPtr lParam\n );\n\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n static extern IntPtr SendMessageTimeout(\n IntPtr hWnd,\n uint Msg,\n IntPtr wParam,\n IntPtr lParam,\n uint fuFlags,\n uint uTimeout,\n out IntPtr lpdwResult\n );\n\n SendMessage((IntPtr)HWND_BROADCAST, WM_SYSCOLORCHANGE, IntPtr.Zero, IntPtr.Zero);\n SendMessage((IntPtr)HWND_BROADCAST, WM_THEMECHANGE, IntPtr.Zero, IntPtr.Zero);\n\n if (killExplorer)\n {\n _logService.Log(\n LogLevel.Info,\n \"Refreshing Windows GUI by terminating Explorer process\"\n );\n\n await Task.Delay(500);\n\n bool explorerWasRunning = Process.GetProcessesByName(\"explorer\").Length > 0;\n\n if (explorerWasRunning)\n {\n _logService.Log(\n LogLevel.Info,\n \"Terminating Explorer processes - Windows will restart it automatically\"\n );\n\n foreach (var process in Process.GetProcessesByName(\"explorer\"))\n {\n try\n {\n process.Kill();\n _logService.Log(\n LogLevel.Info,\n $\"Killed Explorer process (PID: {process.Id})\"\n );\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to kill Explorer process: {ex.Message}\"\n );\n }\n }\n\n _logService.Log(\n LogLevel.Info,\n \"Waiting for Windows to automatically restart Explorer\"\n );\n\n // Wait for Explorer to be terminated completely\n await Task.Delay(1000);\n\n // Check if Explorer has restarted automatically\n int retryCount = 0;\n const int maxRetries = 5;\n bool explorerRestarted = false;\n\n while (retryCount < maxRetries && !explorerRestarted)\n {\n if (Process.GetProcessesByName(\"explorer\").Length > 0)\n {\n explorerRestarted = true;\n _logService.Log(\n LogLevel.Info,\n \"Explorer process restarted automatically\"\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Explorer not restarted yet, waiting... (Attempt {retryCount + 1}/{maxRetries})\"\n );\n retryCount++;\n await Task.Delay(1000);\n }\n }\n\n // If Explorer didn't restart automatically, start it manually\n if (!explorerRestarted)\n {\n _logService.Log(\n LogLevel.Warning,\n \"Explorer did not restart automatically, starting it manually\"\n );\n try\n {\n Process.Start(\"explorer.exe\");\n _logService.Log(LogLevel.Info, \"Explorer process started manually\");\n\n // Wait for Explorer to initialize\n await Task.Delay(2000);\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Error,\n $\"Failed to start Explorer manually: {ex.Message}\"\n );\n return false;\n }\n }\n }\n }\n else\n {\n _logService.Log(\n LogLevel.Info,\n \"Refreshing Windows GUI without killing Explorer\"\n );\n }\n\n string themeChanged = \"ImmersiveColorSet\";\n IntPtr themeChangedPtr = Marshal.StringToHGlobalUni(themeChanged);\n\n try\n {\n IntPtr result;\n SendMessageTimeout(\n (IntPtr)HWND_BROADCAST,\n WM_SETTINGCHANGE,\n IntPtr.Zero,\n themeChangedPtr,\n 0x0000,\n 1000,\n out result\n );\n\n SendMessage((IntPtr)HWND_BROADCAST, WM_SETTINGCHANGE, IntPtr.Zero, IntPtr.Zero);\n }\n finally\n {\n Marshal.FreeHGlobal(themeChangedPtr);\n }\n\n _logService.Log(LogLevel.Info, \"Windows GUI refresh completed successfully\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error refreshing Windows GUI: {ex.Message}\");\n return false;\n }\n }\n\n public Task RefreshWindowsGUI()\n {\n return RefreshWindowsGUI(true);\n }\n\n /// \n /// Checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// True if internet is connected, false otherwise.\n public bool IsInternetConnected(bool forceCheck = false)\n {\n return _connectivityService.IsInternetConnected(forceCheck);\n }\n\n /// \n /// Asynchronously checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// Cancellation token for the operation.\n /// True if internet is connected, false otherwise.\n public async Task IsInternetConnectedAsync(\n bool forceCheck = false,\n CancellationToken cancellationToken = default,\n bool userInitiatedCancellation = false\n )\n {\n return await _connectivityService.IsInternetConnectedAsync(\n forceCheck,\n cancellationToken,\n userInitiatedCancellation\n );\n }\n\n private async Task RunCommand(string command, string arguments)\n {\n try\n {\n using var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = command,\n Arguments = arguments,\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n },\n };\n\n process.Start();\n await process.WaitForExitAsync();\n\n if (process.ExitCode != 0)\n {\n _logService.Log(LogLevel.Warning, $\"Command failed: {command} {arguments}\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error running command: {ex.Message}\");\n throw;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/FeatureInstallationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that enables Windows optional features.\n/// \npublic class FeatureInstallationService : BaseInstallationService, IFeatureInstallationService\n{\n private readonly FeatureCatalog _featureCatalog;\n private readonly IScriptUpdateService _scriptUpdateService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The PowerShell execution service.\n /// The script update service.\n public FeatureInstallationService(\n ILogService logService,\n IPowerShellExecutionService powerShellService,\n IScriptUpdateService scriptUpdateService)\n : base(logService, powerShellService)\n {\n // Create a default feature catalog\n _featureCatalog = FeatureCatalog.CreateDefault();\n _scriptUpdateService = scriptUpdateService ?? throw new ArgumentNullException(nameof(scriptUpdateService));\n }\n\n /// \n public Task> InstallFeatureAsync(\n FeatureInfo featureInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n return InstallItemAsync(featureInfo, progress, cancellationToken);\n }\n\n /// \n public Task> CanInstallFeatureAsync(FeatureInfo featureInfo)\n {\n return CanInstallItemAsync(featureInfo);\n }\n\n /// \n protected override async Task> PerformInstallationAsync(\n FeatureInfo featureInfo,\n IProgress? progress,\n CancellationToken cancellationToken)\n {\n var result = await InstallFeatureAsync(featureInfo.PackageName, progress, cancellationToken);\n \n // Only update BloatRemoval.ps1 script if installation was successful\n if (result.Success)\n {\n try\n {\n _logService.LogInformation($\"Starting BloatRemoval.ps1 script update for {featureInfo.Name}\");\n \n // Update the BloatRemoval.ps1 script to remove the installed feature from the removal list\n var appNames = new List { featureInfo.PackageName };\n _logService.LogInformation($\"Removing feature name from BloatRemoval.ps1: {featureInfo.PackageName}\");\n \n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n\n // Add registry settings if present\n if (featureInfo.RegistrySettings != null && featureInfo.RegistrySettings.Length > 0)\n {\n _logService.LogInformation($\"Adding {featureInfo.RegistrySettings.Length} registry settings for {featureInfo.Name}\");\n appsWithRegistry.Add(featureInfo.PackageName, new List(featureInfo.RegistrySettings));\n }\n\n _logService.LogInformation($\"Updating BloatRemoval.ps1 to remove {featureInfo.Name} from removal list\");\n \n // Make sure we're explicitly identifying this as an optional feature\n _logService.LogInformation($\"Ensuring {featureInfo.Name} is identified as an optional feature\");\n \n var scriptResult = await _scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n true); // true = install operation, so remove from script\n \n _logService.LogInformation($\"Successfully updated BloatRemoval.ps1 script - {featureInfo.Name} will no longer be removed\");\n _logService.LogInformation($\"Script update result: {scriptResult?.Name ?? \"null\"}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for {featureInfo.Name}\", ex);\n _logService.LogError($\"Exception details: {ex.Message}\");\n _logService.LogError($\"Stack trace: {ex.StackTrace}\");\n // Don't fail the installation if script update fails\n }\n }\n else\n {\n _logService.LogInformation($\"Skipping BloatRemoval.ps1 update because installation of {featureInfo.Name} was not successful\");\n }\n \n return result;\n }\n\n\n /// \n /// Installs a Windows optional feature by name.\n /// \n /// The name of the feature to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n private async Task> InstallFeatureAsync(\n string featureName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n try\n {\n // Get the friendly name of the feature from the catalog\n string friendlyName = GetFriendlyName(featureName);\n \n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Enabling {friendlyName}...\",\n DetailedMessage = $\"Starting to enable optional feature: {featureName}\"\n });\n\n _logService.LogInformation($\"Attempting to enable optional feature: {featureName}\");\n \n // Create a progress handler that overrides the generic \"Operation: Running\" text\n var progressHandler = new Progress(detail => {\n // If we get a generic \"Operation: Running\" status, replace it with our more descriptive one\n if (detail.StatusText != null && detail.StatusText.StartsWith(\"Operation:\"))\n {\n // Keep the percentage but replace the generic text with the friendly name\n detail.StatusText = $\"Enabling {friendlyName}...\";\n if (detail.Progress.HasValue)\n {\n detail.StatusText = $\"Enabling {friendlyName}... ({detail.Progress:F0}%)\";\n }\n }\n \n // Forward the updated progress to the original progress reporter\n progress?.Report(detail);\n });\n\n // Define the PowerShell script - Embed featureName, output parseable string\n // Output format: STATUS|Message|RebootRequired (e.g., SUCCESS|Feature enabled|True)\n string script = $@\"\n try {{\n $featureName = '{featureName}' # Embed featureName directly\n Write-Information \"\"Checking feature status: $featureName\"\"\n # Progress reporting needs to be handled by the caller based on script output or duration\n\n # Check if the feature exists\n $feature = Get-WindowsOptionalFeature -Online -FeatureName $featureName -ErrorAction SilentlyContinue\n\n if (-not $feature) {{\n Write-Warning \"\"Feature not found: $featureName\"\"\n return \"\"FAILURE|Feature not found: $featureName\"\"\n }}\n\n # Check if the feature is already enabled\n if ($feature.State -eq 'Enabled') {{\n Write-Information \"\"Feature is already enabled: $featureName\"\"\n return \"\"SUCCESS|Feature is already enabled|False\"\"\n }}\n\n Write-Information \"\"Enabling feature: $featureName\"\"\n\n # Enable the feature\n $result = Enable-WindowsOptionalFeature -Online -FeatureName $featureName -NoRestart\n\n # Check if the feature was enabled successfully\n $feature = Get-WindowsOptionalFeature -Online -FeatureName $featureName\n\n if ($feature.State -eq 'Enabled') {{\n $rebootNeeded = if ($result.RestartNeeded) {{ 'True' }} else {{ 'False' }}\n return \"\"SUCCESS|Feature enabled successfully|$rebootNeeded\"\"\n }} else {{\n Write-Warning \"\"Failed to enable feature: $featureName\"\"\n return \"\"FAILURE|Failed to enable feature\"\"\n }}\n }}\n catch {{\n Write-Error \"\"Error enabling feature: $($_.Exception.Message)\"\"\n return \"\"FAILURE|$($_.Exception.Message)\"\"\n }}\n \";\n\n // Execute PowerShell using the correct interface method with our custom progress handler\n string resultString = await _powerShellService.ExecuteScriptAsync(\n script,\n progressHandler, // Use our custom progress handler instead of passing progress directly\n cancellationToken);\n\n // Process the result string\n if (!string.IsNullOrEmpty(resultString))\n {\n var parts = resultString.Split('|');\n if (parts.Length >= 2)\n {\n string status = parts[0];\n string message = parts[1];\n bool rebootRequired = parts.Length > 2 && bool.TryParse(parts[2], out bool req) && req;\n\n if (status.Equals(\"SUCCESS\", StringComparison.OrdinalIgnoreCase))\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 100,\n StatusText = $\"Successfully enabled {GetFriendlyName(featureName)}\",\n DetailedMessage = message\n });\n _logService.LogSuccess($\"Successfully enabled optional feature: {featureName}. {message}\");\n\n if (rebootRequired)\n {\n progress?.Report(new TaskProgressDetail\n {\n StatusText = \"A system restart is required to complete the installation\",\n DetailedMessage = \"Please restart your computer to complete the installation\",\n LogLevel = LogLevel.Warning\n });\n _logService.LogWarning($\"A system restart is required for {GetFriendlyName(featureName)}\");\n }\n return OperationResult.Succeeded(true); // Indicate success\n }\n else // FAILURE\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0, // Indicate failure\n StatusText = $\"Failed to enable {GetFriendlyName(featureName)}\",\n DetailedMessage = message,\n LogLevel = LogLevel.Error\n });\n _logService.LogError($\"Failed to enable optional feature: {featureName}. {message}\");\n return OperationResult.Failed(message); // Indicate failure with message\n }\n }\n else\n {\n // Handle unexpected script output format\n _logService.LogError($\"Unexpected script output format for {featureName}: {resultString}\");\n progress?.Report(new TaskProgressDetail { StatusText = \"Error processing script result\", LogLevel = LogLevel.Error });\n return OperationResult.Failed(\"Unexpected script output format: \" + resultString); // Indicate failure with message\n }\n }\n else\n {\n // Handle case where script returned empty string\n _logService.LogError($\"Empty result returned when enabling optional feature: {featureName}\");\n progress?.Report(new TaskProgressDetail { StatusText = \"Script returned no result\", LogLevel = LogLevel.Error });\n return OperationResult.Failed(\"Script returned no result\"); // Indicate failure with message\n }\n }\n catch (OperationCanceledException)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Operation cancelled when enabling {GetFriendlyName(featureName)}\",\n DetailedMessage = \"The operation was cancelled by the user\",\n LogLevel = LogLevel.Warning,\n }\n );\n\n _logService.LogWarning($\"Operation cancelled when enabling optional feature: {featureName}\");\n return OperationResult.Failed(\"The operation was cancelled by the user\"); // Return cancellation result\n }\n catch (Exception ex)\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Error enabling {GetFriendlyName(featureName)}\",\n DetailedMessage = $\"Exception: {ex.Message}\",\n LogLevel = LogLevel.Error\n });\n _logService.LogError($\"Error enabling optional feature: {featureName}\", ex);\n return OperationResult.Failed($\"Error enabling optional feature: {ex.Message}\", ex); // Indicate failure with exception\n }\n }\n\n /// \n /// Gets the friendly name of a feature from its package name.\n /// \n /// The package name of the feature.\n /// The friendly name of the feature, or the package name if not found.\n private string GetFriendlyName(string packageName)\n {\n // Look up the feature in the catalog by its package name\n var feature = _featureCatalog.Features.FirstOrDefault(f => \n f.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase));\n \n // Return the friendly name if found, otherwise return the package name\n return feature?.Name ?? packageName;\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/CapabilityInstallationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that enables Windows capabilities.\n/// \npublic class CapabilityInstallationService : BaseInstallationService, ICapabilityInstallationService\n{\n private readonly CapabilityCatalog _capabilityCatalog;\n private readonly IScriptUpdateService _scriptUpdateService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The PowerShell execution service.\n /// The script update service.\n public CapabilityInstallationService(\n ILogService logService,\n IPowerShellExecutionService powerShellService,\n IScriptUpdateService scriptUpdateService\n ) : base(logService, powerShellService)\n {\n // Create a default capability catalog\n _capabilityCatalog = CapabilityCatalog.CreateDefault();\n _scriptUpdateService = scriptUpdateService ?? throw new ArgumentNullException(nameof(scriptUpdateService));\n }\n\n /// \n public Task> InstallCapabilityAsync(\n CapabilityInfo capabilityInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default\n )\n {\n return InstallItemAsync(capabilityInfo, progress, cancellationToken);\n }\n\n /// \n public Task> CanInstallCapabilityAsync(CapabilityInfo capabilityInfo)\n {\n return CanInstallItemAsync(capabilityInfo);\n }\n\n /// \n protected override async Task> PerformInstallationAsync(\n CapabilityInfo capabilityInfo,\n IProgress? progress,\n CancellationToken cancellationToken)\n {\n var result = await InstallCapabilityAsync(capabilityInfo.PackageName, progress, cancellationToken);\n \n // Only update BloatRemoval.ps1 script if installation was successful\n if (result.Success)\n {\n try\n {\n _logService.LogInformation($\"Starting BloatRemoval.ps1 script update for {capabilityInfo.Name}\");\n \n // Update the BloatRemoval.ps1 script to remove the installed capability from the removal list\n var appNames = new List { capabilityInfo.PackageName };\n _logService.LogInformation($\"Removing capability name from BloatRemoval.ps1: {capabilityInfo.PackageName}\");\n \n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n\n // Add registry settings if present\n if (capabilityInfo.RegistrySettings != null && capabilityInfo.RegistrySettings.Length > 0)\n {\n _logService.LogInformation($\"Adding {capabilityInfo.RegistrySettings.Length} registry settings for {capabilityInfo.Name}\");\n appsWithRegistry.Add(capabilityInfo.PackageName, new List(capabilityInfo.RegistrySettings));\n }\n\n _logService.LogInformation($\"Updating BloatRemoval.ps1 to remove {capabilityInfo.Name} from removal list\");\n \n // Check if the capability name already includes a version (~~~~)\n string fullCapabilityName = capabilityInfo.PackageName;\n if (!fullCapabilityName.Contains(\"~~~~\"))\n {\n // We don't have a version in the package name, but we might be able to extract it from installed capabilities\n _logService.LogInformation($\"Package name doesn't include version information: {fullCapabilityName}\");\n _logService.LogInformation($\"Using package name as is: {fullCapabilityName}\");\n }\n else\n {\n _logService.LogInformation($\"Using full capability name with version: {fullCapabilityName}\");\n }\n \n // Always use the package name as provided\n appNames = new List { fullCapabilityName };\n \n var scriptResult = await _scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n true); // true = install operation, so remove from script\n \n _logService.LogInformation($\"Successfully updated BloatRemoval.ps1 script - {capabilityInfo.Name} will no longer be removed\");\n _logService.LogInformation($\"Script update result: {scriptResult?.Name ?? \"null\"}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for {capabilityInfo.Name}\", ex);\n _logService.LogError($\"Exception details: {ex.Message}\");\n _logService.LogError($\"Stack trace: {ex.StackTrace}\");\n // Don't fail the installation if script update fails\n }\n }\n else\n {\n _logService.LogInformation($\"Skipping BloatRemoval.ps1 update because installation of {capabilityInfo.Name} was not successful\");\n }\n \n return result;\n }\n\n /// \n /// Installs a Windows capability by name.\n /// \n /// The name of the capability to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n private async Task> InstallCapabilityAsync(\n string capabilityName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default\n )\n {\n try\n {\n // Get the friendly name of the capability from the catalog\n string friendlyName = GetFriendlyName(capabilityName);\n \n // Set a more descriptive initial status using the friendly name\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Enabling {friendlyName}...\",\n DetailedMessage = $\"Starting to enable capability: {capabilityName}\",\n }\n );\n\n _logService.LogInformation($\"Attempting to enable capability: {capabilityName}\");\n \n // Create a progress handler that overrides the generic \"Operation: Running\" text\n var progressHandler = new Progress(detail => {\n // If we get a generic \"Operation: Running\" status, replace it with our more descriptive one\n if (detail.StatusText != null && detail.StatusText.StartsWith(\"Operation:\"))\n {\n // Keep the percentage but replace the generic text with the friendly name\n detail.StatusText = $\"Enabling {friendlyName}...\";\n if (detail.Progress.HasValue)\n {\n detail.StatusText = $\"Enabling {friendlyName}... ({detail.Progress:F0}%)\";\n }\n }\n \n // Forward the updated progress to the original progress reporter\n progress?.Report(detail);\n });\n\n // Define the PowerShell script - Embed capabilityName, output parseable string\n // Output format: STATUS|Message|RebootRequired (e.g., SUCCESS|Installed 1 of 1|True)\n string script = $@\"\n try {{\n $capabilityNamePattern = '{capabilityName}*' # Embed pattern directly\n Write-Information \"\"Searching for capability: $capabilityNamePattern\"\"\n # Progress reporting needs to be handled by the caller based on script output or duration\n\n # Find matching capabilities\n $capabilities = Get-WindowsCapability -Online | Where-Object {{ $_.Name -like $capabilityNamePattern -and $_.State -ne 'Installed' }}\n\n if ($capabilities.Count -eq 0) {{\n # Check if it's already installed\n $alreadyInstalled = Get-WindowsCapability -Online | Where-Object {{ $_.Name -like $capabilityNamePattern -and $_.State -eq 'Installed' }}\n if ($alreadyInstalled) {{\n return \"\"SUCCESS|Capability already installed|False\"\"\n }} else {{\n Write-Warning \"\"No matching capabilities found: $capabilityNamePattern\"\"\n return \"\"FAILURE|No matching capabilities found\"\"\n }}\n }}\n\n $totalCapabilities = $capabilities.Count\n $rebootRequired = $false\n $installedCount = 0\n $errorMessages = @()\n\n foreach ($capability in $capabilities) {{\n Write-Information \"\"Installing capability: $($capability.Name)\"\"\n try {{\n $result = Add-WindowsCapability -Online -Name $capability.Name\n if ($result.RestartNeeded) {{\n $rebootRequired = $true\n }}\n $installedCount++\n }}\n catch {{\n $errMsg = \"\"Failed to install capability: $($capability.Name). $($_.Exception.Message)\"\"\n Write-Error $errMsg\n $errorMessages += $errMsg\n }}\n }}\n\n if ($installedCount -gt 0) {{\n $rebootNeededStr = if ($rebootRequired) {{ 'True' }} else {{ 'False' }}\n $finalMessage = \"\"Successfully installed $installedCount of $totalCapabilities capabilities.\"\"\n if ($errorMessages.Count -gt 0) {{\n $finalMessage += \"\" Errors: $($errorMessages -join '; ')\"\"\n }}\n return \"\"SUCCESS|$finalMessage|$rebootNeededStr\"\"\n }} else {{\n $finalMessage = \"\"Failed to install any capabilities.\"\"\n if ($errorMessages.Count -gt 0) {{\n $finalMessage += \"\" Errors: $($errorMessages -join '; ')\"\"\n }}\n return \"\"FAILURE|$finalMessage\"\"\n }}\n }}\n catch {{\n Write-Error \"\"Error enabling capability: $($_.Exception.Message)\"\"\n return \"\"FAILURE|$($_.Exception.Message)\"\"\n }}\n \";\n\n // Execute PowerShell using the correct interface method with our custom progress handler\n string resultString = await _powerShellService.ExecuteScriptAsync(\n script,\n progressHandler, // Use our custom progress handler instead of passing progress directly\n cancellationToken);\n\n // Process the result string\n if (!string.IsNullOrEmpty(resultString))\n {\n var parts = resultString.Split('|');\n if (parts.Length >= 2)\n {\n string status = parts[0];\n string message = parts[1];\n bool rebootRequired = parts.Length > 2 && bool.TryParse(parts[2], out bool req) && req;\n\n if (status.Equals(\"SUCCESS\", StringComparison.OrdinalIgnoreCase))\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 100,\n StatusText = $\"Successfully enabled {GetFriendlyName(capabilityName)}\",\n DetailedMessage = message\n });\n _logService.LogSuccess($\"Successfully enabled capability: {capabilityName}. {message}\");\n\n if (rebootRequired)\n {\n progress?.Report(new TaskProgressDetail\n {\n StatusText = \"A system restart is required to complete the installation\",\n DetailedMessage = \"Please restart your computer to complete the installation\",\n LogLevel = LogLevel.Warning\n });\n _logService.LogWarning($\"A system restart is required for {GetFriendlyName(capabilityName)}\");\n }\n return OperationResult.Succeeded(true); // Indicate success\n }\n else // FAILURE\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0, // Indicate failure\n StatusText = $\"Failed to enable {GetFriendlyName(capabilityName)}\",\n DetailedMessage = message,\n LogLevel = LogLevel.Error\n });\n _logService.LogError($\"Failed to enable capability: {capabilityName}. {message}\");\n return OperationResult.Failed(message); // Indicate failure with message\n }\n }\n else\n {\n // Handle unexpected script output format\n _logService.LogError($\"Unexpected script output format for {capabilityName}: {resultString}\");\n progress?.Report(new TaskProgressDetail { StatusText = \"Error processing script result\", LogLevel = LogLevel.Error });\n return OperationResult.Failed(\"Unexpected script output format: \" + resultString); // Indicate failure with message\n }\n }\n else\n {\n // Handle case where script returned empty string\n _logService.LogError($\"Empty result returned when enabling capability: {capabilityName}\");\n progress?.Report(new TaskProgressDetail { StatusText = \"Script returned no result\", LogLevel = LogLevel.Error });\n return OperationResult.Failed(\"Script returned no result\"); // Indicate failure with message\n }\n }\n catch (OperationCanceledException)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Operation cancelled when enabling {GetFriendlyName(capabilityName)}\",\n DetailedMessage = \"The operation was cancelled by the user\",\n LogLevel = LogLevel.Warning,\n }\n );\n\n _logService.LogWarning($\"Operation cancelled when enabling capability: {capabilityName}\");\n return OperationResult.Failed(\"The operation was cancelled by the user\"); // Return cancellation result\n }\n catch (Exception ex)\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Error enabling {GetFriendlyName(capabilityName)}\",\n DetailedMessage = $\"Exception: {ex.Message}\",\n LogLevel = LogLevel.Error\n });\n _logService.LogError($\"Error enabling capability: {capabilityName}\", ex);\n return OperationResult.Failed($\"Error enabling capability: {ex.Message}\", ex); // Indicate failure with exception\n }\n }\n\n // Note: CheckInstalled is not part of the ICapabilityInstallationService interface\n // It should likely be moved or removed if not used elsewhere.\n // For now, commenting it out to fix build errors.\n /*\n public bool CheckInstalled(CapabilityInfo capabilityInfo)\n {\n // ... (Implementation needs fixing similar to InstallCapabilityAsync)\n }\n */\n\n // Note: InstallCapabilitiesAsync is not part of the ICapabilityInstallationService interface\n // It should likely be moved or removed if not used elsewhere.\n // For now, commenting it out to fix build errors.\n /*\n public Task InstallCapabilitiesAsync(IEnumerable capabilities)\n {\n return InstallCapabilitiesAsync(capabilities, null, default);\n }\n\n public async Task InstallCapabilitiesAsync(\n IEnumerable capabilities,\n IProgress? progress,\n CancellationToken cancellationToken)\n {\n // ... (Implementation needs fixing similar to InstallCapabilityAsync)\n }\n */\n\n // Note: RemoveCapabilitiesAsync is not part of the ICapabilityInstallationService interface\n // It should likely be moved or removed if not used elsewhere.\n // For now, commenting it out to fix build errors.\n /*\n public async Task RemoveCapabilitiesAsync(IEnumerable capabilities)\n {\n // ... (Implementation needs fixing similar to InstallCapabilityAsync)\n }\n\n private async Task RemoveCapabilityAsync(CapabilityInfo capabilityInfo)\n {\n // ... (Implementation needs fixing similar to InstallCapabilityAsync)\n }\n */\n\n /// \n /// Gets the friendly name of a capability from its package name.\n /// \n /// The package name of the capability.\n /// The friendly name of the capability, or the package name if not found.\n private string GetFriendlyName(string packageName)\n {\n // Remove any version information from the package name (e.g., \"Media.WindowsMediaPlayer~~~~0.0.12.0\" -> \"Media.WindowsMediaPlayer\")\n string basePackageName = packageName.Split('~')[0];\n \n // Look up the capability in the catalog by its package name\n var capability = _capabilityCatalog.Capabilities.FirstOrDefault(c =>\n c.PackageName.Equals(basePackageName, StringComparison.OrdinalIgnoreCase));\n \n // Return the friendly name if found, otherwise return the package name\n return capability?.Name ?? packageName;\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/CustomAppInstallationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Enums;\nusing Winhance.Core.Features.SoftwareApps.Exceptions;\nusing Winhance.Core.Features.SoftwareApps.Helpers;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that handles custom application installations.\n/// \npublic class CustomAppInstallationService : ICustomAppInstallationService\n{\n private readonly ILogService _logService;\n private readonly IOneDriveInstallationService _oneDriveInstallationService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The OneDrive installation service.\n public CustomAppInstallationService(\n ILogService logService,\n IOneDriveInstallationService oneDriveInstallationService)\n {\n _logService = logService;\n _oneDriveInstallationService = oneDriveInstallationService;\n }\n\n /// \n public async Task InstallCustomAppAsync(\n AppInfo appInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n try\n {\n // Handle different custom app installations based on package name\n switch (appInfo.PackageName.ToLowerInvariant())\n {\n case \"onedrive\":\n return await _oneDriveInstallationService.InstallOneDriveAsync(progress, cancellationToken);\n\n // Add other custom app installation cases here\n // case \"some-app\":\n // return await InstallSomeAppAsync(progress, cancellationToken);\n\n default:\n throw new NotSupportedException(\n $\"Custom installation for '{appInfo.PackageName}' is not supported.\"\n );\n }\n }\n catch (Exception ex)\n {\n var errorType = InstallationErrorHelper.DetermineErrorType(ex.Message);\n var errorMessage = InstallationErrorHelper.GetUserFriendlyErrorMessage(errorType);\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Error in custom installation for {appInfo.Name}: {errorMessage}\",\n DetailedMessage = $\"Exception during custom installation: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"ErrorType\", errorType.ToString() },\n { \"PackageName\", appInfo.PackageName },\n { \"AppName\", appInfo.Name },\n { \"IsCustomInstall\", \"True\" },\n { \"OriginalError\", ex.Message }\n }\n }\n );\n\n return false;\n }\n }\n\n /// \n public async Task CheckInternetConnectionAsync()\n {\n try\n {\n // Try to reach a reliable site to check for internet connectivity\n using var client = new HttpClient();\n client.Timeout = TimeSpan.FromSeconds(5);\n var response = await client.GetAsync(\"https://www.google.com\");\n return response.IsSuccessStatusCode;\n }\n catch\n {\n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/PackageManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Manages packages and applications on the system.\n /// Acts as a facade for more specialized services.\n /// \n public class PackageManager : IPackageManager\n {\n private readonly IAppRemovalService _appRemovalService;\n private readonly AppRemovalServiceAdapter _appRemovalServiceAdapter;\n private readonly ICapabilityRemovalService _capabilityRemovalService;\n private readonly IFeatureRemovalService _featureRemovalService;\n\n /// \n public ILogService LogService { get; }\n\n /// \n public IAppService AppDiscoveryService { get; }\n\n /// \n /// \n /// This property is maintained for backward compatibility.\n /// It returns an adapter that converts IAppRemovalService to IInstallationService<AppInfo>.\n /// New code should use dependency injection to get IAppRemovalService directly.\n /// \n public IInstallationService AppRemovalService => _appRemovalServiceAdapter;\n\n /// \n public ISpecialAppHandlerService SpecialAppHandlerService { get; }\n\n /// \n public IScriptGenerationService ScriptGenerationService { get; }\n\n /// \n public ISystemServices SystemServices { get; }\n\n /// \n public INotificationService NotificationService { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The app discovery service.\n /// The installation service.\n /// The special app handler service.\n /// The script generation service.\n public PackageManager(\n ILogService logService,\n IAppService appDiscoveryService,\n IAppRemovalService appRemovalService,\n ICapabilityRemovalService capabilityRemovalService,\n IFeatureRemovalService featureRemovalService,\n ISpecialAppHandlerService specialAppHandlerService,\n IScriptGenerationService scriptGenerationService,\n ISystemServices systemServices,\n INotificationService notificationService\n )\n {\n LogService = logService;\n AppDiscoveryService = appDiscoveryService;\n _appRemovalService = appRemovalService;\n _appRemovalServiceAdapter = new AppRemovalServiceAdapter(appRemovalService);\n _capabilityRemovalService = capabilityRemovalService;\n _featureRemovalService = featureRemovalService;\n SpecialAppHandlerService = specialAppHandlerService;\n ScriptGenerationService = scriptGenerationService;\n SystemServices = systemServices;\n NotificationService = notificationService;\n }\n\n /// \n public async Task> GetInstallableAppsAsync()\n {\n return await AppDiscoveryService.GetInstallableAppsAsync();\n }\n\n /// \n public async Task> GetStandardAppsAsync()\n {\n return await AppDiscoveryService.GetStandardAppsAsync();\n }\n\n /// \n public async Task> GetCapabilitiesAsync()\n {\n return await AppDiscoveryService.GetCapabilitiesAsync();\n }\n\n /// \n public async Task> GetOptionalFeaturesAsync()\n {\n return await AppDiscoveryService.GetOptionalFeaturesAsync();\n }\n\n /// \n public async Task RemoveAppAsync(string packageName, bool isCapability)\n {\n // Get all standard apps to check the app type\n var allRemovableApps = (await AppDiscoveryService.GetStandardAppsAsync()).ToList();\n var appInfo = allRemovableApps.FirstOrDefault(a => a.PackageName == packageName);\n\n // If not found in standard apps and isCapability is true, create a CapabilityInfo directly\n if (appInfo == null && isCapability)\n {\n LogService.LogInformation(\n $\"App not found in standard apps but isCapability is true. Treating {packageName} as a capability.\"\n );\n return await _capabilityRemovalService.RemoveCapabilityAsync(\n new CapabilityInfo { Name = packageName, PackageName = packageName }\n );\n }\n else if (appInfo == null)\n {\n LogService.LogWarning($\"App not found: {packageName}\");\n return false;\n }\n\n // First check if this is a special app that requires special handling\n if (appInfo.RequiresSpecialHandling && !string.IsNullOrEmpty(appInfo.SpecialHandlerType))\n {\n LogService.LogInformation(\n $\"Using special handler for app: {packageName}, handler type: {appInfo.SpecialHandlerType}\"\n );\n \n bool success = false;\n switch (appInfo.SpecialHandlerType)\n {\n case \"Edge\":\n success = await SpecialAppHandlerService.RemoveEdgeAsync();\n break;\n case \"OneDrive\":\n success = await SpecialAppHandlerService.RemoveOneDriveAsync();\n break;\n case \"OneNote\":\n success = await SpecialAppHandlerService.RemoveOneNoteAsync();\n break;\n default:\n success = await SpecialAppHandlerService.RemoveSpecialAppAsync(\n appInfo.SpecialHandlerType\n );\n break;\n }\n \n if (success)\n {\n LogService.LogSuccess($\"Successfully removed special app: {packageName}\");\n }\n else\n {\n LogService.LogError($\"Failed to remove special app: {packageName}\");\n }\n \n return success; // Exit early, don't continue with standard removal process\n }\n\n // If not a special app, proceed with normal removal based on app type\n bool result = false;\n switch (appInfo.Type)\n {\n case AppType.OptionalFeature:\n result = await _featureRemovalService.RemoveFeatureAsync(\n new FeatureInfo { Name = packageName }\n );\n break;\n case AppType.Capability:\n result = await _capabilityRemovalService.RemoveCapabilityAsync(\n new CapabilityInfo { Name = packageName, PackageName = packageName }\n );\n break;\n \n case AppType.StandardApp:\n default:\n var appResult = await _appRemovalService.RemoveAppAsync(appInfo);\n result = appResult.Success && appResult.Result;\n break;\n }\n\n // Only create and register BloatRemoval script for non-special apps\n if (!appInfo.RequiresSpecialHandling)\n {\n // Prepare data for the correct CreateBatchRemovalScriptAsync overload\n var appNamesList = new List { packageName };\n var appsWithRegistry = new Dictionary>();\n\n if (appInfo?.RegistrySettings != null && appInfo.RegistrySettings.Length > 0)\n {\n appsWithRegistry[packageName] = appInfo.RegistrySettings.ToList();\n }\n\n try\n {\n // Call the overload that returns RemovalScript\n var removalScript = await ScriptGenerationService.CreateBatchRemovalScriptAsync(\n appNamesList,\n appsWithRegistry\n );\n\n // Save the RemovalScript object\n await ScriptGenerationService.SaveScriptAsync(removalScript);\n\n // Register the RemovalScript object\n await ScriptGenerationService.RegisterRemovalTaskAsync(removalScript);\n }\n catch (Exception ex)\n {\n LogService.LogError(\n $\"Failed to create or register removal script for {packageName}\",\n ex\n );\n // Don't change result value, as the app removal itself might have succeeded\n }\n }\n \n return result;\n }\n\n /// \n public async Task IsAppInstalledAsync(\n string packageName,\n CancellationToken cancellationToken = default\n )\n {\n var status = await AppDiscoveryService.GetBatchInstallStatusAsync(\n new[] { packageName }\n );\n return status.TryGetValue(packageName, out var isInstalled) && isInstalled;\n }\n\n /// \n public async Task RemoveEdgeAsync()\n {\n return await SpecialAppHandlerService.RemoveEdgeAsync();\n }\n\n /// \n public async Task RemoveOneDriveAsync()\n {\n return await SpecialAppHandlerService.RemoveOneDriveAsync();\n }\n\n /// \n public async Task RemoveOneNoteAsync()\n {\n return await SpecialAppHandlerService.RemoveOneNoteAsync();\n }\n\n /// \n public async Task RemoveSpecialAppAsync(string appHandlerType)\n {\n return await SpecialAppHandlerService.RemoveSpecialAppAsync(appHandlerType);\n }\n\n /// \n public async Task> RemoveAppsInBatchAsync(\n List<(string PackageName, bool IsCapability, string? SpecialHandlerType)> apps\n )\n {\n var results = new List<(string Name, bool Success, string? Error)>();\n var standardApps = new List();\n var capabilities = new List();\n var features = new List();\n var specialHandlers = new Dictionary>();\n\n // Get all standard apps to check for optional features\n var allRemovableApps = (await AppDiscoveryService.GetStandardAppsAsync()).ToList();\n\n // Categorize apps by type\n foreach (var app in apps)\n {\n if (app.SpecialHandlerType != null)\n {\n if (!specialHandlers.ContainsKey(app.SpecialHandlerType))\n {\n specialHandlers[app.SpecialHandlerType] = new List();\n }\n specialHandlers[app.SpecialHandlerType].Add(app.PackageName);\n }\n else\n {\n // Check app type\n var appInfo = allRemovableApps.FirstOrDefault(a =>\n a.PackageName.Equals(app.PackageName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (appInfo != null)\n {\n switch (appInfo.Type)\n {\n case AppType.OptionalFeature:\n features.Add(new FeatureInfo { Name = app.PackageName });\n break;\n case AppType.Capability:\n capabilities.Add(new CapabilityInfo {\n Name = app.PackageName,\n PackageName = app.PackageName\n });\n break;\n case AppType.StandardApp:\n default:\n standardApps.Add(appInfo);\n break;\n }\n }\n else\n {\n // If we couldn't determine the app type from the app info, use the IsCapability flag\n if (app.IsCapability)\n {\n LogService.LogInformation(\n $\"App not found in standard apps but IsCapability is true. Treating {app.PackageName} as a capability.\"\n );\n capabilities.Add(new CapabilityInfo {\n Name = app.PackageName,\n PackageName = app.PackageName,\n });\n }\n else\n {\n standardApps.Add(new AppInfo { PackageName = app.PackageName });\n }\n }\n }\n }\n\n // Process standard apps\n if (standardApps.Any())\n {\n foreach (var app in standardApps)\n {\n try\n {\n await _appRemovalService.RemoveAppAsync(app); // Pass AppInfo object\n results.Add((app.PackageName, true, null));\n }\n catch (Exception ex)\n {\n results.Add((app.PackageName, false, ex.Message));\n }\n }\n }\n\n // Process capabilities\n if (capabilities.Any())\n {\n foreach (var capability in capabilities)\n {\n try\n {\n await _capabilityRemovalService.RemoveCapabilityAsync(capability); // Pass CapabilityInfo object\n results.Add((capability.Name, true, null));\n }\n catch (Exception ex)\n {\n results.Add((capability.Name, false, ex.Message));\n }\n }\n }\n\n // Process optional features\n if (features.Any())\n {\n foreach (var feature in features)\n {\n try\n {\n await _featureRemovalService.RemoveFeatureAsync(feature); // Pass FeatureInfo object\n results.Add((feature.Name, true, null));\n }\n catch (Exception ex)\n {\n results.Add((feature.Name, false, ex.Message));\n }\n }\n }\n\n // Process special handlers\n foreach (var handler in specialHandlers)\n {\n switch (handler.Key)\n {\n case \"Edge\":\n foreach (var app in handler.Value)\n {\n var success = await SpecialAppHandlerService.RemoveEdgeAsync();\n results.Add((app, success, success ? null : \"Failed to remove Edge\"));\n }\n break;\n case \"OneDrive\":\n foreach (var app in handler.Value)\n {\n var success = await SpecialAppHandlerService.RemoveOneDriveAsync();\n results.Add(\n (app, success, success ? null : \"Failed to remove OneDrive\")\n );\n }\n break;\n case \"OneNote\":\n foreach (var app in handler.Value)\n {\n var success = await SpecialAppHandlerService.RemoveOneNoteAsync();\n results.Add(\n (app, success, success ? null : \"Failed to remove OneNote\")\n );\n }\n break;\n default:\n foreach (var app in handler.Value)\n {\n var success = await SpecialAppHandlerService.RemoveSpecialAppAsync(\n handler.Key\n );\n results.Add(\n (app, success, success ? null : $\"Failed to remove {handler.Key}\")\n );\n }\n break;\n }\n }\n\n // Create batch removal script for successful removals (excluding special apps)\n try\n {\n var successfulApps = results.Where(r => r.Success).Select(r => r.Name).ToList();\n \n // Filter out special apps from the successful apps list\n var nonSpecialSuccessfulAppInfos = allRemovableApps\n .Where(a => successfulApps.Contains(a.PackageName)\n && (!a.RequiresSpecialHandling || string.IsNullOrEmpty(a.SpecialHandlerType))\n )\n .ToList();\n\n LogService.LogInformation(\n $\"Creating batch removal script for {nonSpecialSuccessfulAppInfos.Count} non-special apps\"\n );\n \n foreach (var app in nonSpecialSuccessfulAppInfos)\n {\n try\n {\n await ScriptGenerationService.UpdateBloatRemovalScriptForInstalledAppAsync(app);\n }\n catch (Exception ex)\n {\n LogService.LogWarning(\n $\"Failed to update removal script for {app.PackageName}: {ex.Message}\"\n );\n }\n }\n }\n catch (Exception ex)\n {\n LogService.LogError(\"Failed to create batch removal script\", ex);\n }\n\n return results;\n }\n\n /// \n public async Task RegisterRemovalTaskAsync(RemovalScript script)\n {\n // Call the correct overload that takes a RemovalScript object\n await ScriptGenerationService.RegisterRemovalTaskAsync(script);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppDiscoveryService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service for discovering and querying applications on the system.\n/// \npublic class AppDiscoveryService\n : Winhance.Core.Features.SoftwareApps.Interfaces.IAppDiscoveryService\n{\n private readonly ILogService _logService;\n private readonly ExternalAppCatalog _externalAppCatalog;\n private readonly WindowsAppCatalog _windowsAppCatalog;\n private readonly CapabilityCatalog _capabilityCatalog;\n private readonly FeatureCatalog _featureCatalog;\n private readonly TimeSpan _powershellTimeout = TimeSpan.FromSeconds(10); // Add a timeout for PowerShell commands\n private Dictionary _installationStatusCache = new Dictionary(\n StringComparer.OrdinalIgnoreCase\n );\n private DateTime _lastCacheRefresh = DateTime.MinValue;\n private readonly TimeSpan _cacheLifetime = TimeSpan.FromMinutes(5);\n private readonly object _cacheLock = new object();\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public AppDiscoveryService(ILogService logService)\n {\n _logService = logService;\n _externalAppCatalog = ExternalAppCatalog.CreateDefault();\n _windowsAppCatalog = WindowsAppCatalog.CreateDefault();\n _capabilityCatalog = CapabilityCatalog.CreateDefault();\n _featureCatalog = FeatureCatalog.CreateDefault();\n }\n\n /// \n public async Task> GetInstallableAppsAsync()\n {\n try\n {\n _logService.LogInformation(\"Getting installable external apps list\");\n var installableApps = _externalAppCatalog.ExternalApps.ToList();\n\n // Return the apps without checking installation status initially\n // This will allow the UI to load faster\n _logService.LogInformation($\"Found {installableApps.Count} installable external apps\");\n return installableApps;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error retrieving installable external apps\", ex);\n return new List();\n }\n }\n\n /// \n public async Task> GetStandardAppsAsync()\n {\n try\n {\n _logService.LogInformation(\"Getting standard Windows apps list\");\n var standardApps = _windowsAppCatalog.WindowsApps.ToList();\n\n // Return the apps without checking installation status initially\n // This will allow the UI to load faster\n _logService.LogInformation($\"Found {standardApps.Count} standard Windows apps\");\n return standardApps;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error retrieving standard Windows apps\", ex);\n return new List();\n }\n }\n\n /// \n public async Task> GetCapabilitiesAsync()\n {\n try\n {\n _logService.LogInformation(\"Getting Windows capabilities list\");\n var capabilities = _capabilityCatalog.Capabilities.ToList();\n\n // Return the capabilities without checking installation status initially\n // This will allow the UI to load faster\n _logService.LogInformation($\"Found {capabilities.Count} capabilities\");\n return capabilities;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error retrieving capabilities\", ex);\n return new List();\n }\n }\n\n /// \n public async Task> GetOptionalFeaturesAsync()\n {\n try\n {\n _logService.LogInformation(\"Getting Windows optional features list\");\n var features = _featureCatalog.Features.ToList();\n\n // Return the features without checking installation status initially\n // This will allow the UI to load faster\n _logService.LogInformation($\"Found {features.Count} optional features\");\n return features;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error retrieving optional features\", ex);\n return new List();\n }\n }\n\n /// \n public async Task IsAppInstalledAsync(string packageName)\n {\n return await IsAppInstalledAsync(packageName, CancellationToken.None);\n }\n\n /// \n public async Task IsAppInstalledAsync(\n string packageName,\n CancellationToken cancellationToken = default\n )\n {\n try\n {\n // Check cache first\n lock (_cacheLock)\n {\n if (_installationStatusCache.TryGetValue(packageName, out bool cachedStatus))\n {\n // Only use cache if it's fresh\n if (DateTime.Now - _lastCacheRefresh < _cacheLifetime)\n {\n return cachedStatus;\n }\n }\n }\n\n // Determine item type more efficiently by using a type flag in the item itself\n // This avoids searching through collections each time\n bool isCapability = _capabilityCatalog.Capabilities.Any(c =>\n c.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase)\n );\n bool isFeature =\n !isCapability\n && _featureCatalog.Features.Any(f =>\n f.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase)\n );\n\n bool isInstalled = false;\n\n // Check if this app has subpackages\n string[]? subPackages = null;\n if (!isCapability && !isFeature)\n {\n // Find the app definition to check for subpackages\n var appDefinition = _windowsAppCatalog.WindowsApps.FirstOrDefault(a =>\n a.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (appDefinition?.SubPackages != null && appDefinition.SubPackages.Length > 0)\n {\n subPackages = appDefinition.SubPackages;\n _logService.LogInformation(\n $\"App {packageName} has {subPackages.Length} subpackages\"\n );\n }\n }\n\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n\n if (isCapability)\n {\n // Check capability status\n powerShell.AddScript(\n @\"\n param($capabilityName)\n try {\n $capability = Get-WindowsCapability -Online |\n Where-Object { $_.Name -like \"\"$capabilityName*\"\" } |\n Select-Object -First 1\n return $capability -ne $null -and $capability.State -eq 'Installed'\n }\n catch {\n return $false\n }\n \"\n );\n powerShell.AddParameter(\"capabilityName\", packageName);\n }\n else if (isFeature)\n {\n // Check feature status\n powerShell.AddScript(\n @\"\n param($featureName)\n try {\n $feature = Get-WindowsOptionalFeature -Online |\n Where-Object { $_.FeatureName -eq $featureName }\n return $feature -ne $null -and $feature.State -eq 'Enabled'\n }\n catch {\n return $false\n }\n \"\n );\n powerShell.AddParameter(\"featureName\", packageName);\n }\n else\n {\n // Check standard app status using the same approach as the original PowerShell script\n // But also check subpackages if the main package is not installed\n using var powerShellForAppx = PowerShellFactory.CreateForAppxCommands(_logService);\n powerShellForAppx.AddScript(\n @\"\n param($packageName, $subPackages)\n try {\n # Check main package\n $appx = Get-AppxPackage -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $packageName }\n $isInstalled = ($appx -ne $null)\n Write-Output \"\"Checking if $packageName is installed: $isInstalled\"\"\n \n # If not installed and we have subpackages, check those too\n if (-not $isInstalled -and $subPackages -ne $null) {\n foreach ($subPackage in $subPackages) {\n Write-Output \"\"Checking subpackage: $subPackage\"\"\n $subAppx = Get-AppxPackage -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $subPackage }\n if ($subAppx -ne $null) {\n $isInstalled = $true\n Write-Output \"\"Subpackage $subPackage is installed\"\"\n break\n }\n }\n }\n \n return $isInstalled\n }\n catch {\n Write-Output \"\"Error checking if $packageName is installed: $_\"\"\n return $false\n }\n \"\n );\n powerShellForAppx.AddParameter(\"packageName\", packageName);\n powerShellForAppx.AddParameter(\"subPackages\", subPackages);\n\n // Execute with timeout\n var task = Task.Run(() => powerShellForAppx.Invoke());\n if (await Task.WhenAny(task, Task.Delay(_powershellTimeout)) == task)\n {\n var result = await task;\n isInstalled = result.FirstOrDefault();\n }\n else\n {\n _logService.LogWarning(\n $\"Timeout checking installation status for {packageName}\"\n );\n isInstalled = false;\n }\n }\n\n // Cache the result\n lock (_cacheLock)\n {\n _installationStatusCache[packageName] = isInstalled;\n _lastCacheRefresh = DateTime.Now;\n }\n\n return isInstalled;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking if item is installed: {packageName}\", ex);\n return false;\n }\n }\n\n /// \n /// Efficiently checks installation status for multiple items at once.\n /// \n /// The package names to check.\n /// A dictionary mapping package names to their installation status.\n public async Task> GetInstallationStatusBatchAsync(\n IEnumerable packageNames\n )\n {\n var result = new Dictionary(StringComparer.OrdinalIgnoreCase);\n var packageList = packageNames.ToList();\n\n if (!packageList.Any())\n return result;\n\n try\n {\n // Check for special apps that need custom detection logic\n var oneNotePackage = \"Microsoft.Office.OneNote\";\n bool hasOneNote = packageList.Any(p =>\n p.Equals(oneNotePackage, StringComparison.OrdinalIgnoreCase)\n );\n bool oneNoteInstalled = false;\n\n // If OneNote is in the list, check it separately using our special detection\n if (hasOneNote)\n {\n oneNoteInstalled = await IsOneNoteInstalledAsync();\n _logService.LogInformation(\n $\"OneNote special registry check result: {oneNoteInstalled}\"\n );\n // Remove OneNote from the list as we'll handle it separately\n packageList = packageList\n .Where(p => !p.Equals(oneNotePackage, StringComparison.OrdinalIgnoreCase))\n .ToList();\n }\n\n // Group items by type for batch processing\n var capabilities = packageList\n .Where(p =>\n _capabilityCatalog.Capabilities.Any(c =>\n c.PackageName.Equals(p, StringComparison.OrdinalIgnoreCase)\n )\n )\n .ToList();\n\n var features = packageList\n .Where(p =>\n _featureCatalog.Features.Any(f =>\n f.PackageName.Equals(p, StringComparison.OrdinalIgnoreCase)\n )\n )\n .ToList();\n\n var standardApps = packageList.Except(capabilities).Except(features).ToList();\n\n // Process capabilities in batch\n if (capabilities.Any())\n {\n var capabilityStatuses = await GetCapabilitiesStatusBatchAsync(capabilities);\n foreach (var pair in capabilityStatuses)\n {\n result[pair.Key] = pair.Value;\n }\n }\n\n // Process features in batch\n if (features.Any())\n {\n var featureStatuses = await GetFeaturesStatusBatchAsync(features);\n foreach (var pair in featureStatuses)\n {\n result[pair.Key] = pair.Value;\n }\n }\n\n // Process standard apps in batch\n if (standardApps.Any())\n {\n var appStatuses = await GetStandardAppsStatusBatchAsync(standardApps);\n foreach (var pair in appStatuses)\n {\n result[pair.Key] = pair.Value;\n }\n }\n\n // Add OneNote result if it was in the original list\n if (hasOneNote)\n {\n // Check if OneNote is also detected via AppX package\n bool appxOneNoteInstalled = false;\n if (result.TryGetValue(oneNotePackage, out bool appxInstalled))\n {\n appxOneNoteInstalled = appxInstalled;\n }\n\n // Use either the registry check or AppX check - if either is true, OneNote is installed\n result[oneNotePackage] = oneNoteInstalled || appxOneNoteInstalled;\n _logService.LogInformation(\n $\"Final OneNote installation status: {result[oneNotePackage]} (Registry: {oneNoteInstalled}, AppX: {appxOneNoteInstalled})\"\n );\n }\n\n // Cache all results\n lock (_cacheLock)\n {\n foreach (var pair in result)\n {\n _installationStatusCache[pair.Key] = pair.Value;\n }\n _lastCacheRefresh = DateTime.Now;\n }\n\n return result;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking batch installation status\", ex);\n return packageList.ToDictionary(p => p, p => false, StringComparer.OrdinalIgnoreCase);\n }\n }\n\n private async Task> GetCapabilitiesStatusBatchAsync(\n List capabilities\n )\n {\n var result = new Dictionary(StringComparer.OrdinalIgnoreCase);\n\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n\n // Get all installed capabilities in one query\n powerShell.AddScript(\n @\"\n try {\n $installedCapabilities = Get-WindowsCapability -Online | Where-Object { $_.State -eq 'Installed' }\n return $installedCapabilities | Select-Object -ExpandProperty Name\n }\n catch {\n return @()\n }\n \"\n );\n\n var task = Task.Run(() => powerShell.Invoke());\n if (await Task.WhenAny(task, Task.Delay(_powershellTimeout)) == task)\n {\n var installedCapabilities = (await task).ToList();\n\n // Check each capability against the installed list\n foreach (var capability in capabilities)\n {\n result[capability] = installedCapabilities.Any(c =>\n c.StartsWith(capability, StringComparison.OrdinalIgnoreCase)\n );\n }\n }\n else\n {\n _logService.LogWarning(\"Timeout getting installed capabilities\");\n foreach (var capability in capabilities)\n {\n result[capability] = false;\n }\n }\n\n return result;\n }\n\n private async Task> GetFeaturesStatusBatchAsync(List features)\n {\n var result = new Dictionary(StringComparer.OrdinalIgnoreCase);\n\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n\n // Get all enabled features in one query\n powerShell.AddScript(\n @\"\n try {\n $enabledFeatures = Get-WindowsOptionalFeature -Online | Where-Object { $_.State -eq 'Enabled' }\n return $enabledFeatures | Select-Object -ExpandProperty FeatureName\n }\n catch {\n return @()\n }\n \"\n );\n\n var task = Task.Run(() => powerShell.Invoke());\n if (await Task.WhenAny(task, Task.Delay(_powershellTimeout)) == task)\n {\n var enabledFeatures = (await task).ToList();\n\n // Check each feature against the enabled list\n foreach (var feature in features)\n {\n result[feature] = enabledFeatures.Any(f =>\n f.Equals(feature, StringComparison.OrdinalIgnoreCase)\n );\n }\n }\n else\n {\n _logService.LogWarning(\"Timeout getting enabled features\");\n foreach (var feature in features)\n {\n result[feature] = false;\n }\n }\n\n return result;\n }\n\n private async Task> GetStandardAppsStatusBatchAsync(List apps)\n {\n var result = new Dictionary(StringComparer.OrdinalIgnoreCase);\n\n using var powerShell = PowerShellFactory.CreateForAppxCommands(_logService);\n // No need to set execution policy as it's already done in the factory\n\n // Get all installed apps in one query using the same approach as the original PowerShell script\n powerShell.AddScript(\n @\"\n try {\n $installedApps = @(Get-AppxPackage | Select-Object -ExpandProperty Name)\n \n # Log the count for diagnostic purposes\n Write-Output \"\"Found $($installedApps.Count) installed apps\"\"\n \n # Return the array of names\n return $installedApps\n }\n catch {\n Write-Output \"\"Error getting installed apps: $_\"\"\n return @()\n }\n \"\n );\n\n var task = Task.Run(() => powerShell.Invoke());\n if (await Task.WhenAny(task, Task.Delay(_powershellTimeout)) == task)\n {\n var installedApps = (await task).ToList();\n\n // Check each app against the installed list\n foreach (var app in apps)\n {\n // First check if the main package is installed\n bool isInstalled = installedApps.Any(a =>\n a.Equals(app, StringComparison.OrdinalIgnoreCase)\n );\n\n // If not installed, check if it has subpackages and if any of them are installed\n if (!isInstalled)\n {\n var appDefinition = _windowsAppCatalog.WindowsApps.FirstOrDefault(a =>\n a.PackageName.Equals(app, StringComparison.OrdinalIgnoreCase)\n );\n\n if (appDefinition?.SubPackages != null && appDefinition.SubPackages.Length > 0)\n {\n foreach (var subPackage in appDefinition.SubPackages)\n {\n if (\n installedApps.Any(a =>\n a.Equals(subPackage, StringComparison.OrdinalIgnoreCase)\n )\n )\n {\n isInstalled = true;\n _logService.LogInformation(\n $\"App {app} is installed via subpackage {subPackage}\"\n );\n break;\n }\n }\n }\n }\n\n result[app] = isInstalled;\n }\n }\n else\n {\n _logService.LogWarning(\"Timeout getting installed apps\");\n foreach (var app in apps)\n {\n result[app] = false;\n }\n }\n\n return result;\n }\n\n /// \n public async Task IsEdgeInstalledAsync()\n {\n try\n {\n _logService.LogInformation(\"Checking if Microsoft Edge is installed\");\n\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n\n // Only check the specific registry key as requested\n powerShell.AddScript(\n @\"\n try {\n $result = Get-ItemProperty \"\"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\msedge.exe\"\" -ErrorAction SilentlyContinue\n return $result -ne $null\n }\n catch {\n Write-Output \"\"Error checking Edge registry key: $($_.Exception.Message)\"\"\n return $false\n }\n \"\n );\n\n var result = await ExecuteWithTimeoutAsync(powerShell, 15);\n bool isInstalled = result.FirstOrDefault();\n\n _logService.LogInformation($\"Edge registry check result: {isInstalled}\");\n return isInstalled;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking Edge installation\", ex);\n return false;\n }\n }\n\n /// \n public async Task IsOneDriveInstalledAsync()\n {\n try\n {\n _logService.LogInformation(\"Checking if OneDrive is installed\");\n\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n\n // Check the specific registry keys\n powerShell.AddScript(\n @\"\n try {\n # Check the two specific registry keys\n $hklmKey = Get-ItemProperty \"\"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneDriveSetup.exe\"\" -ErrorAction SilentlyContinue\n $hkcuKey = Get-ItemProperty \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneDriveSetup.exe\"\" -ErrorAction SilentlyContinue\n \n # Return true if either key exists\n return ($hklmKey -ne $null) -or ($hkcuKey -ne $null)\n }\n catch {\n Write-Output \"\"Error checking OneDrive registry: $($_.Exception.Message)\"\"\n return $false\n }\n \"\n );\n\n var result = await ExecuteWithTimeoutAsync(powerShell, 15);\n bool isInstalled = result.FirstOrDefault();\n\n _logService.LogInformation($\"OneDrive registry check result: {isInstalled}\");\n return isInstalled;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking OneDrive installation\", ex);\n return false;\n }\n }\n\n /// \n public async Task IsOneNoteInstalledAsync()\n {\n try\n {\n _logService.LogInformation(\"Checking if OneNote is installed\");\n\n // First, try a simpler, more direct approach without recursive searches\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n\n // Use a more targeted, non-recursive approach for better performance and reliability\n powerShell.AddScript(\n @\"\n try {\n # Check for OneNote in common registry locations using direct paths instead of recursive searches\n \n # Check standard uninstall keys\n $installed = $false\n \n # Check for OneNote in standard uninstall locations\n $hklmKeys = Get-ChildItem \"\"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\"\" -ErrorAction SilentlyContinue | \n Get-ItemProperty -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like \"\"*OneNote*\"\" }\n if ($hklmKeys) { $installed = $true }\n \n $hkcuKeys = Get-ChildItem \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\"\" -ErrorAction SilentlyContinue | \n Get-ItemProperty -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like \"\"*OneNote*\"\" }\n if ($hkcuKeys) { $installed = $true }\n \n # Check for Wow6432Node registry keys (for 32-bit apps on 64-bit Windows)\n $hklmWowKeys = Get-ChildItem \"\"HKLM:\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\"\" -ErrorAction SilentlyContinue | \n Get-ItemProperty -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like \"\"*OneNote*\"\" }\n if ($hklmWowKeys) { $installed = $true }\n \n # Check for UWP/Store app version\n try {\n $appxPackage = Get-AppxPackage -Name Microsoft.Office.OneNote -ErrorAction SilentlyContinue\n if ($appxPackage) { $installed = $true }\n } catch {\n # Ignore errors with AppX commands\n }\n \n return $installed\n }\n catch {\n Write-Output \"\"Error checking OneNote registry: $($_.Exception.Message)\"\"\n return $false\n }\n \"\n );\n\n // Use a shorter timeout to prevent hanging\n var result = await ExecuteWithTimeoutAsync(powerShell, 10);\n bool isInstalled = result.FirstOrDefault();\n\n _logService.LogInformation($\"OneNote registry check result: {isInstalled}\");\n return isInstalled;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking OneNote installation\", ex);\n // Don't crash the application if OneNote check fails\n return false;\n }\n }\n\n // SetExecutionPolicy is now handled by PowerShellFactory\n\n /// \n /// Clears the installation status cache, forcing fresh checks on next query.\n /// Call this after installing or removing items.\n /// \n public void ClearInstallationStatusCache()\n {\n lock (_cacheLock)\n {\n _installationStatusCache.Clear();\n }\n }\n\n /// \n /// Executes a PowerShell command with a timeout.\n /// \n /// The type of result to return.\n /// The PowerShell instance.\n /// The timeout in seconds.\n /// The result of the PowerShell command.\n private async Task> ExecuteWithTimeoutAsync(\n PowerShell powerShell,\n int timeoutSeconds\n )\n {\n // Create a cancellation token source for the timeout\n using var cancellationTokenSource = new CancellationTokenSource();\n\n try\n {\n // Set up the timeout\n cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(timeoutSeconds));\n\n // Run the PowerShell command with cancellation support\n var task = Task.Run(\n () =>\n {\n try\n {\n // Check if cancellation was requested before starting\n if (cancellationTokenSource.Token.IsCancellationRequested)\n {\n _logService.LogWarning(\n \"PowerShell execution cancelled before starting\"\n );\n return new System.Collections.ObjectModel.Collection();\n }\n\n // Execute the PowerShell command\n return powerShell.Invoke();\n }\n catch (Exception innerEx)\n {\n _logService.LogError(\n $\"Error in PowerShell execution thread: {innerEx.Message}\",\n innerEx\n );\n return new System.Collections.ObjectModel.Collection();\n }\n },\n cancellationTokenSource.Token\n );\n\n // Wait for completion or timeout\n if (\n await Task.WhenAny(\n task,\n Task.Delay(TimeSpan.FromSeconds(timeoutSeconds), cancellationTokenSource.Token)\n ) == task\n )\n {\n // Task completed within timeout\n if (task.IsCompletedSuccessfully)\n {\n return await task;\n }\n else if (task.IsFaulted)\n {\n _logService.LogError(\n $\"PowerShell task faulted: {task.Exception?.Message}\",\n task.Exception\n );\n }\n else if (task.IsCanceled)\n {\n _logService.LogWarning(\"PowerShell task was cancelled\");\n }\n }\n else\n {\n // Task timed out, attempt to cancel it\n _logService.LogWarning(\n $\"PowerShell execution timed out after {timeoutSeconds} seconds\"\n );\n cancellationTokenSource.Cancel();\n\n // Try to stop the PowerShell pipeline if it's still running\n try\n {\n powerShell.Stop();\n }\n catch (Exception stopEx)\n {\n _logService.LogWarning($\"Error stopping PowerShell pipeline: {stopEx.Message}\");\n }\n }\n\n // Return empty collection if we reached here (timeout or error)\n return new System.Collections.ObjectModel.Collection();\n }\n catch (OperationCanceledException)\n {\n _logService.LogWarning(\n $\"PowerShell execution cancelled after {timeoutSeconds} seconds\"\n );\n return new System.Collections.ObjectModel.Collection();\n }\n catch (Exception ex)\n {\n _logService.LogError(\n $\"Error executing PowerShell command with timeout: {ex.Message}\",\n ex\n );\n return new System.Collections.ObjectModel.Collection();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/FeatureRemovalService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service for removing Windows optional features from the system.\n/// \npublic class FeatureRemovalService : IFeatureRemovalService\n{\n private readonly ILogService _logService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IScheduledTaskService _scheduledTaskService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The app discovery service.\n /// The scheduled task service.\n public FeatureRemovalService(\n ILogService logService,\n IAppDiscoveryService appDiscoveryService,\n IScheduledTaskService scheduledTaskService)\n {\n _logService = logService;\n _appDiscoveryService = appDiscoveryService;\n _scheduledTaskService = scheduledTaskService;\n }\n\n /// \n public async Task RemoveFeatureAsync(\n FeatureInfo featureInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (featureInfo == null)\n {\n throw new ArgumentNullException(nameof(featureInfo));\n }\n // Call the other overload and return its result\n return await RemoveFeatureAsync(featureInfo.PackageName, progress, cancellationToken);\n }\n\n /// \n public async Task RemoveFeatureAsync(\n string featureName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n try\n {\n progress?.Report(new TaskProgressDetail { Progress = 0, StatusText = $\"Starting removal of {featureName}...\" });\n _logService.LogInformation($\"Removing optional feature: {featureName}\");\n \n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n \n // First, attempt to disable the feature\n powerShell.AddScript(@\"\n param($featureName)\n try {\n # Check if the feature exists and is enabled\n $feature = Get-WindowsOptionalFeature -Online | Where-Object { $_.FeatureName -eq $featureName -and $_.State -eq 'Enabled' }\n \n if ($feature) {\n # Get the full feature name\n $fullFeatureName = $feature.FeatureName\n \n # Disable the feature\n $result = Disable-WindowsOptionalFeature -Online -FeatureName $featureName -NoRestart\n \n return @{\n FullFeatureName = $fullFeatureName\n }\n } else {\n # Feature not found or already disabled\n return @{\n Error = \"\"Feature not found or already disabled\"\"\n FullFeatureName = $null\n }\n }\n }\n catch {\n return @{\n Error = $_.Exception.Message\n FullFeatureName = $null\n }\n }\n \");\n powerShell.AddParameter(\"featureName\", featureName);\n \n var result = await Task.Run(() => powerShell.Invoke());\n \n // Extract any error or the full feature name from the first command\n string? error = null;\n string fullFeatureName = featureName;\n \n if (result != null && result.Count > 0)\n {\n var resultObj = result[0];\n \n // Get any error\n if (resultObj.Properties.Any(p => p.Name == \"Error\"))\n {\n error = resultObj.Properties[\"Error\"]?.Value as string;\n }\n \n // Get the full feature name if available\n if (resultObj.Properties.Any(p => p.Name == \"FullFeatureName\") && \n resultObj.Properties[\"FullFeatureName\"]?.Value != null)\n {\n fullFeatureName = resultObj.Properties[\"FullFeatureName\"].Value.ToString();\n }\n }\n \n // Now check if the feature is still enabled to determine success\n powerShell.Commands.Clear();\n powerShell.AddScript(@\"\n param($featureName)\n $feature = Get-WindowsOptionalFeature -Online | Where-Object { $_.FeatureName -eq $featureName }\n \n if ($feature -ne $null) {\n return @{\n IsEnabled = ($feature.State -eq 'Enabled')\n RebootRequired = $feature.RestartNeeded\n }\n } else {\n return @{\n IsEnabled = $false\n RebootRequired = $false\n }\n }\n \");\n powerShell.AddParameter(\"featureName\", featureName);\n \n var statusResult = await Task.Run(() => powerShell.Invoke());\n \n bool isStillEnabled = false;\n bool rebootRequired = false;\n \n if (statusResult != null && statusResult.Count > 0)\n {\n var statusObj = statusResult[0];\n \n // Check if the feature is still enabled\n if (statusObj.Properties.Any(p => p.Name == \"IsEnabled\") && \n statusObj.Properties[\"IsEnabled\"]?.Value != null)\n {\n isStillEnabled = Convert.ToBoolean(statusObj.Properties[\"IsEnabled\"].Value);\n }\n \n // Check if a reboot is required\n if (statusObj.Properties.Any(p => p.Name == \"RebootRequired\") && \n statusObj.Properties[\"RebootRequired\"]?.Value != null)\n {\n rebootRequired = Convert.ToBoolean(statusObj.Properties[\"RebootRequired\"].Value);\n }\n }\n \n // Success is determined by whether the feature is no longer enabled\n bool success = !isStillEnabled;\n bool overallSuccess = false;\n \n if (success)\n {\n progress?.Report(new TaskProgressDetail { Progress = 100, StatusText = $\"Successfully removed {featureName}\" });\n _logService.LogSuccess($\"Successfully removed optional feature: {featureName}\");\n \n if (rebootRequired)\n {\n progress?.Report(new TaskProgressDetail { StatusText = \"Restart required\", LogLevel = LogLevel.Warning });\n _logService.LogWarning($\"A system restart is required to complete the removal of {featureName}\");\n }\n \n _logService.LogInformation($\"Full feature name: {fullFeatureName}\");\n \n // Update BloatRemoval.ps1 script after successful removal\n try\n {\n var script = await UpdateBloatRemovalScriptAsync(fullFeatureName);\n _logService.LogInformation($\"BloatRemoval.ps1 script updated for feature: {featureName}\");\n \n // Register the scheduled task to run the script at startup\n try\n {\n bool taskRegistered = await RegisterBloatRemovalTaskAsync(script);\n if (taskRegistered)\n {\n _logService.LogSuccess($\"Scheduled task registered for BloatRemoval.ps1\");\n }\n else\n {\n _logService.LogWarning($\"Failed to register scheduled task for BloatRemoval.ps1, but continuing operation\");\n }\n }\n catch (Exception taskEx)\n {\n _logService.LogError($\"Error registering scheduled task: {taskEx.Message}\");\n // Don't fail the removal if task registration fails\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for feature: {featureName}\", ex);\n // Don't fail the removal if script update fails\n }\n \n overallSuccess = true;\n }\n else\n {\n progress?.Report(new TaskProgressDetail { Progress = 0, StatusText = $\"Failed to remove {featureName}: {error}\", LogLevel = LogLevel.Error });\n _logService.LogError($\"Failed to remove optional feature: {featureName}. {error}\");\n }\n \n return overallSuccess; // Return success status\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing optional feature: {featureName}\", ex);\n progress?.Report(new TaskProgressDetail { Progress = 0, StatusText = $\"Error removing {featureName}: {ex.Message}\", LogLevel = LogLevel.Error });\n return false; // Return false on exception\n }\n }\n\n /// \n public Task CanRemoveFeatureAsync(FeatureInfo featureInfo)\n {\n // Basic implementation: Assume all found features can be removed.\n // TODO: Add actual checks if needed (e.g., dependencies, system protection)\n return Task.FromResult(true);\n }\n\n /// \n public async Task> RemoveFeaturesInBatchAsync(\n List features)\n {\n if (features == null)\n {\n throw new ArgumentNullException(nameof(features));\n }\n\n return await RemoveFeaturesInBatchAsync(features.Select(f => f.PackageName).ToList());\n }\n\n /// \n public async Task> RemoveFeaturesInBatchAsync(\n List featureNames)\n {\n var results = new List<(string Name, bool Success, string? Error)>();\n \n try\n {\n _logService.LogInformation($\"Removing {featureNames.Count} Windows optional features\");\n \n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n \n foreach (var feature in featureNames)\n {\n try\n {\n _logService.LogInformation($\"Removing optional feature: {feature}\");\n \n // First, attempt to disable the feature\n powerShell.Commands.Clear();\n powerShell.AddScript(@\"\n param($featureName)\n try {\n # Check if the feature exists and is enabled\n $feature = Get-WindowsOptionalFeature -Online | Where-Object { $_.FeatureName -eq $featureName -and $_.State -eq 'Enabled' }\n \n if ($feature) {\n # Get the full feature name\n $fullFeatureName = $feature.FeatureName\n \n # Disable the feature\n $result = Disable-WindowsOptionalFeature -Online -FeatureName $featureName -NoRestart\n \n return @{\n FullFeatureName = $fullFeatureName\n }\n } else {\n # Feature not found or already disabled\n return @{\n Error = \"\"Feature not found or already disabled\"\"\n FullFeatureName = $null\n }\n }\n }\n catch {\n return @{\n Error = $_.Exception.Message\n FullFeatureName = $null\n }\n }\n \");\n powerShell.AddParameter(\"featureName\", feature);\n \n var result = await Task.Run(() => powerShell.Invoke());\n \n // Extract any error or the full feature name from the first command\n string? error = null;\n string featureFullName = feature;\n \n if (result != null && result.Count > 0)\n {\n var resultObj = result[0];\n \n // Get any error\n if (resultObj.Properties.Any(p => p.Name == \"Error\"))\n {\n error = resultObj.Properties[\"Error\"]?.Value as string;\n }\n \n // Get the full feature name if available\n if (resultObj.Properties.Any(p => p.Name == \"FullFeatureName\") && \n resultObj.Properties[\"FullFeatureName\"]?.Value != null)\n {\n featureFullName = resultObj.Properties[\"FullFeatureName\"].Value.ToString();\n }\n }\n \n // Now check if the feature is still enabled to determine success\n powerShell.Commands.Clear();\n powerShell.AddScript(@\"\n param($featureName)\n $feature = Get-WindowsOptionalFeature -Online | Where-Object { $_.FeatureName -eq $featureName }\n \n if ($feature -ne $null) {\n return @{\n IsEnabled = ($feature.State -eq 'Enabled')\n RebootRequired = $feature.RestartNeeded\n }\n } else {\n return @{\n IsEnabled = $false\n RebootRequired = $false\n }\n }\n \");\n powerShell.AddParameter(\"featureName\", feature);\n \n var statusResult = await Task.Run(() => powerShell.Invoke());\n \n bool isStillEnabled = false;\n bool rebootRequired = false;\n \n if (statusResult != null && statusResult.Count > 0)\n {\n var statusObj = statusResult[0];\n \n // Check if the feature is still enabled\n if (statusObj.Properties.Any(p => p.Name == \"IsEnabled\") && \n statusObj.Properties[\"IsEnabled\"]?.Value != null)\n {\n isStillEnabled = Convert.ToBoolean(statusObj.Properties[\"IsEnabled\"].Value);\n }\n \n // Check if a reboot is required\n if (statusObj.Properties.Any(p => p.Name == \"RebootRequired\") && \n statusObj.Properties[\"RebootRequired\"]?.Value != null)\n {\n rebootRequired = Convert.ToBoolean(statusObj.Properties[\"RebootRequired\"].Value);\n }\n }\n \n // Success is determined by whether the feature is no longer enabled\n bool success = !isStillEnabled;\n \n if (success)\n {\n _logService.LogInformation($\"Full feature name for batch operation: {featureFullName}\");\n \n // Update BloatRemoval.ps1 script for batch operations too\n try\n {\n var script = await UpdateBloatRemovalScriptAsync(featureFullName);\n _logService.LogInformation($\"BloatRemoval.ps1 script updated for feature in batch: {feature}\");\n \n // Register the scheduled task to run the script at startup\n try\n {\n bool taskRegistered = await RegisterBloatRemovalTaskAsync(script);\n if (taskRegistered)\n {\n _logService.LogSuccess($\"Scheduled task registered for BloatRemoval.ps1\");\n }\n else\n {\n _logService.LogWarning($\"Failed to register scheduled task for BloatRemoval.ps1, but continuing operation\");\n }\n }\n catch (Exception taskEx)\n {\n _logService.LogError($\"Error registering scheduled task: {taskEx.Message}\");\n // Don't fail the removal if task registration fails\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for feature in batch: {feature}\", ex);\n // Don't fail the removal if script update fails\n }\n }\n \n results.Add((feature, success, error));\n \n if (success)\n {\n _logService.LogSuccess($\"Successfully removed optional feature: {feature}\");\n if (rebootRequired)\n {\n _logService.LogWarning($\"A system restart is required to complete the removal of {feature}\");\n }\n }\n else\n {\n _logService.LogError($\"Failed to remove optional feature: {feature}. {error}\");\n }\n }\n catch (Exception ex)\n {\n results.Add((feature, false, ex.Message));\n _logService.LogError($\"Error removing optional feature: {feature}\", ex);\n }\n }\n \n return results;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error removing optional features\", ex);\n return featureNames.Select(f => (f, false, $\"Error: {ex.Message}\")).ToList();\n }\n }\n\n // SetExecutionPolicy is now handled by PowerShellFactory\n \n /// \n /// Updates the BloatRemoval.ps1 script to add the removed feature to it.\n /// \n /// The feature name.\n /// The updated removal script.\n private async Task UpdateBloatRemovalScriptAsync(string featureName)\n {\n try\n {\n // Get the script update service\n var scriptUpdateService = GetScriptUpdateService();\n if (scriptUpdateService == null)\n {\n _logService.LogWarning(\"Script update service not available\");\n throw new InvalidOperationException(\"Script update service not available\");\n }\n \n // Update the script\n var appNames = new List { featureName };\n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n \n _logService.LogInformation($\"Updating BloatRemoval.ps1 script for feature: {featureName}\");\n \n try\n {\n var script = await scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n false); // false = removal operation, so add to script\n \n _logService.LogInformation($\"Successfully updated BloatRemoval.ps1 script for feature: {featureName}\");\n return script;\n }\n catch (FileNotFoundException)\n {\n _logService.LogInformation($\"BloatRemoval.ps1 script not found. It will be created when needed.\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in script update service for feature: {featureName}\", ex);\n throw; // Rethrow to be caught by the outer try-catch\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for feature: {featureName}\", ex);\n throw; // Rethrow so the caller can handle it\n }\n }\n \n /// \n /// Registers a scheduled task to run the BloatRemoval script at startup.\n /// \n /// The removal script to register.\n /// True if the task was registered successfully, false otherwise.\n private async Task RegisterBloatRemovalTaskAsync(RemovalScript script)\n {\n try\n {\n if (script == null)\n {\n _logService.LogError(\"Cannot register scheduled task: Script is null\");\n return false;\n }\n \n _logService.LogInformation(\"Registering scheduled task for BloatRemoval.ps1\");\n \n // Register the scheduled task\n bool success = await _scheduledTaskService.RegisterScheduledTaskAsync(script);\n \n if (success)\n {\n _logService.LogSuccess(\"Successfully registered scheduled task for BloatRemoval.ps1\");\n }\n else\n {\n _logService.LogError(\"Failed to register scheduled task for BloatRemoval.ps1\");\n }\n \n return success;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error registering scheduled task for BloatRemoval.ps1\", ex);\n return false;\n }\n }\n \n /// \n /// Gets the script update service.\n /// \n /// The script update service or null if not available.\n private IScriptUpdateService? GetScriptUpdateService()\n {\n try\n {\n // Use the existing _appDiscoveryService that was injected into the constructor\n // instead of creating a new instance\n var scriptContentModifier = new ScriptContentModifier(_logService);\n return new ScriptUpdateService(_logService, _appDiscoveryService, scriptContentModifier);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to get script update service\", ex);\n return null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppRemovalService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service for removing standard applications from the system.\n/// \npublic class AppRemovalService : IAppRemovalService\n{\n private readonly ILogService _logService;\n private readonly ISpecialAppHandlerService _specialAppHandlerService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IScriptTemplateProvider _scriptTemplateProvider;\n private readonly ISystemServices _systemServices;\n private readonly IRegistryService _registryService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The special app handler service.\n /// The app discovery service.\n /// The script template provider.\n /// The system services.\n public AppRemovalService(\n ILogService logService,\n ISpecialAppHandlerService specialAppHandlerService,\n IAppDiscoveryService appDiscoveryService,\n IScriptTemplateProvider scriptTemplateProvider,\n ISystemServices systemServices,\n IRegistryService registryService)\n {\n _logService = logService;\n _specialAppHandlerService = specialAppHandlerService;\n _appDiscoveryService = appDiscoveryService;\n _scriptTemplateProvider = scriptTemplateProvider;\n _systemServices = systemServices;\n _registryService = registryService;\n }\n\n /// \n public async Task> RemoveAppAsync(\n AppInfo appInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (appInfo == null)\n {\n throw new ArgumentNullException(nameof(appInfo));\n }\n // Call the other overload and return its result\n return await RemoveAppAsync(appInfo.PackageName, progress, cancellationToken);\n }\n\n /// \n /// Removes an application by package name.\n /// \n /// The package name of the application to remove.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n public async Task> RemoveAppAsync(\n string packageName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n try\n {\n _logService.LogInformation($\"Removing app: {packageName}\");\n \n // Get all standard apps to find the app definition\n var allRemovableApps = (await _appDiscoveryService.GetStandardAppsAsync()).ToList();\n \n // Find the app definition that matches the current app\n var appDefinition = allRemovableApps.FirstOrDefault(a =>\n a.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase));\n \n // Get subpackages if any\n string[]? subPackages = appDefinition?.SubPackages;\n if (subPackages != null && subPackages.Length > 0)\n {\n _logService.LogInformation($\"App {packageName} has {subPackages.Length} subpackages that will also be removed\");\n }\n \n // Handle standard app removal\n using var powerShell = PowerShellFactory.CreateForAppxCommands(_logService, _systemServices);\n // No need to set execution policy as it's already done in the factory\n \n powerShell.AddScript(@\"\n param($packageName, $subPackages)\n try {\n $success = $true\n \n # Remove the main app package\n $packagesToRemove = Get-AppxPackage | Where-Object { $_.Name -eq $packageName }\n \n if ($packagesToRemove -ne $null -and $packagesToRemove.Count -gt 0) {\n $packagesToRemove | ForEach-Object {\n Write-Output \"\"Removing package: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }\n }\n \n # Also remove the provisioned package\n $provPackages = Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq $packageName }\n \n if ($provPackages -ne $null -and $provPackages.Count -gt 0) {\n $provPackages | ForEach-Object {\n Write-Output \"\"Removing provisioned package: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }\n }\n \n # If we have subpackages, remove those too\n if ($subPackages -ne $null) {\n foreach ($subPackage in $subPackages) {\n Write-Output \"\"Processing subpackage: $subPackage\"\"\n \n # Remove the subpackage\n $subPackagesToRemove = Get-AppxPackage | Where-Object { $_.Name -eq $subPackage }\n \n if ($subPackagesToRemove -ne $null -and $subPackagesToRemove.Count -gt 0) {\n $subPackagesToRemove | ForEach-Object {\n Write-Output \"\"Removing subpackage: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }\n }\n \n # Also remove the provisioned subpackage\n $subProvPackages = Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq $subPackage }\n \n if ($subProvPackages -ne $null -and $subProvPackages.Count -gt 0) {\n $subProvPackages | ForEach-Object {\n Write-Output \"\"Removing provisioned subpackage: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }\n }\n }\n }\n \n # Check if the main package is still installed\n $stillInstalled = Get-AppxPackage | Where-Object { $_.Name -eq $packageName }\n $mainPackageRemoved = ($stillInstalled -eq $null -or $stillInstalled.Count -eq 0)\n \n # Check if any subpackages are still installed\n $subPackagesRemoved = $true\n if ($subPackages -ne $null) {\n foreach ($subPackage in $subPackages) {\n $stillInstalledSub = Get-AppxPackage | Where-Object { $_.Name -eq $subPackage }\n if ($stillInstalledSub -ne $null -and $stillInstalledSub.Count -gt 0) {\n $subPackagesRemoved = $false\n Write-Output \"\"Subpackage $subPackage is still installed\"\"\n break\n }\n }\n }\n \n # Return true only if both main package and all subpackages are removed\n return $mainPackageRemoved -and $subPackagesRemoved\n }\n catch {\n Write-Error \"\"Error removing package: $_\"\"\n return $false\n }\n \");\n powerShell.AddParameter(\"packageName\", packageName);\n powerShell.AddParameter(\"subPackages\", subPackages);\n \n var result = await Task.Run(() => powerShell.Invoke());\n var success = result.FirstOrDefault();\n \n if (!success)\n {\n _logService.LogError($\"Failed to remove app: {packageName}\");\n }\n else\n {\n _logService.LogSuccess($\"Successfully removed app: {packageName}\");\n \n // Apply registry settings for this app if it has any\n try\n {\n // If we found the app definition and it has registry settings, apply them\n if (appDefinition?.RegistrySettings != null && appDefinition.RegistrySettings.Length > 0)\n {\n _logService.LogInformation($\"Found {appDefinition.RegistrySettings.Length} registry settings for {packageName}\");\n var registrySettings = appDefinition.RegistrySettings.ToList();\n \n // Apply the registry settings\n var settingsApplied = await ApplyRegistrySettingsAsync(registrySettings);\n if (settingsApplied)\n {\n _logService.LogSuccess($\"Successfully applied registry settings for {packageName}\");\n }\n else\n {\n _logService.LogWarning($\"Some registry settings for {packageName} could not be applied\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error applying registry settings for {packageName}\", ex);\n }\n }\n // Return success status after handling registry settings\n return success\n ? OperationResult.Succeeded(true)\n : OperationResult.Failed($\"Failed to remove app: {packageName}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing app: {packageName}\", ex);\n // Return failure with exception details\n return OperationResult.Failed($\"Error removing app: {packageName}\", ex);\n }\n }\n\n /// \n public Task> GenerateRemovalScriptAsync(AppInfo appInfo)\n {\n if (appInfo == null)\n {\n throw new ArgumentNullException(nameof(appInfo));\n }\n\n try\n {\n // Generate a script for removing the app using the pipeline approach\n string script = $@\"\n# Script to remove {appInfo.Name} ({appInfo.PackageName})\n# Generated by Winhance on {DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\")}\n\ntry {{\n # Remove the main app package\n $packagesToRemove = Get-AppxPackage | Where-Object {{ $_.Name -eq '{appInfo.PackageName}' }}\n \n if ($packagesToRemove -ne $null -and $packagesToRemove.Count -gt 0) {{\n $packagesToRemove | ForEach-Object {{\n Write-Output \"\"Removing package: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }}\n }}\n \n # Also remove the provisioned package\n $provPackages = Get-AppxProvisionedPackage -Online | Where-Object {{ $_.DisplayName -eq '{appInfo.PackageName}' }}\n \n if ($provPackages -ne $null -and $provPackages.Count -gt 0) {{\n $provPackages | ForEach-Object {{\n Write-Output \"\"Removing provisioned package: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }}\n }}\";\n\n // Add subpackage removal if the app has subpackages\n if (appInfo.SubPackages != null && appInfo.SubPackages.Length > 0)\n {\n script += $@\"\n \n # Remove subpackages\";\n\n foreach (var subPackage in appInfo.SubPackages)\n {\n script += $@\"\n Write-Output \"\"Processing subpackage: {subPackage}\"\"\n \n # Remove the subpackage\n $subPackagesToRemove = Get-AppxPackage | Where-Object {{ $_.Name -eq '{subPackage}' }}\n \n if ($subPackagesToRemove -ne $null -and $subPackagesToRemove.Count -gt 0) {{\n $subPackagesToRemove | ForEach-Object {{\n Write-Output \"\"Removing subpackage: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }}\n }}\n \n # Also remove the provisioned subpackage\n $subProvPackages = Get-AppxProvisionedPackage -Online | Where-Object {{ $_.DisplayName -eq '{subPackage}' }}\n \n if ($subProvPackages -ne $null -and $subProvPackages.Count -gt 0) {{\n $subProvPackages | ForEach-Object {{\n Write-Output \"\"Removing provisioned subpackage: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }}\n }}\";\n }\n }\n\n // Close the try-catch block\n script += $@\"\n}} catch {{\n # Error handling without output\n}}\n\";\n return Task.FromResult(OperationResult.Succeeded(script));\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error generating removal script for {appInfo.PackageName}\", ex);\n return Task.FromResult(OperationResult.Failed($\"Error generating removal script: {ex.Message}\", ex));\n }\n }\n\n\n /// \n public async Task> RemoveAppsInBatchAsync(\n List apps)\n {\n if (apps == null)\n {\n throw new ArgumentNullException(nameof(apps));\n }\n\n return await RemoveAppsInBatchAsync(apps.Select(a => a.PackageName).ToList());\n }\n\n /// \n public async Task> RemoveAppsInBatchAsync(\n List packageNames)\n {\n var results = new List<(string Name, bool Success, string? Error)>();\n \n try\n {\n _logService.LogInformation($\"Starting batch removal of {packageNames.Count} apps\");\n \n using var powerShell = PowerShellFactory.CreateForAppxCommands(_logService, _systemServices);\n // No need to set execution policy as it's already done in the factory\n \n // Get all standard apps to find app definitions (do this once for the batch)\n var allApps = (await _appDiscoveryService.GetStandardAppsAsync()).ToList();\n \n foreach (var packageName in packageNames)\n {\n try\n {\n _logService.LogInformation($\"Removing app: {packageName}\");\n \n // Find the app definition that matches the current app\n var appDefinition = allApps.FirstOrDefault(a =>\n a.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase));\n \n // Get subpackages if any\n string[]? subPackages = appDefinition?.SubPackages;\n if (subPackages != null && subPackages.Length > 0)\n {\n _logService.LogInformation($\"App {packageName} has {subPackages.Length} subpackages that will also be removed\");\n }\n \n powerShell.Commands.Clear();\n \n powerShell.AddScript(@\"\n param($packageName, $subPackages)\n try {\n $success = $true\n \n # Remove the main app package\n $packagesToRemove = Get-AppxPackage | Where-Object { $_.Name -eq $packageName }\n \n if ($packagesToRemove -ne $null -and $packagesToRemove.Count -gt 0) {\n $packagesToRemove | ForEach-Object {\n Write-Output \"\"Removing package: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }\n }\n \n # Also remove the provisioned package\n $provPackages = Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq $packageName }\n \n if ($provPackages -ne $null -and $provPackages.Count -gt 0) {\n $provPackages | ForEach-Object {\n Write-Output \"\"Removing provisioned package: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }\n }\n \n # If we have subpackages, remove those too\n if ($subPackages -ne $null) {\n foreach ($subPackage in $subPackages) {\n Write-Output \"\"Processing subpackage: $subPackage\"\"\n \n # Remove the subpackage\n $subPackagesToRemove = Get-AppxPackage | Where-Object { $_.Name -eq $subPackage }\n \n if ($subPackagesToRemove -ne $null -and $subPackagesToRemove.Count -gt 0) {\n $subPackagesToRemove | ForEach-Object {\n Write-Output \"\"Removing subpackage: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }\n }\n \n # Also remove the provisioned subpackage\n $subProvPackages = Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq $subPackage }\n \n if ($subProvPackages -ne $null -and $subProvPackages.Count -gt 0) {\n $subProvPackages | ForEach-Object {\n Write-Output \"\"Removing provisioned subpackage: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }\n }\n }\n }\n \n # Check if the main package is still installed\n $stillInstalled = Get-AppxPackage | Where-Object { $_.Name -eq $packageName }\n $mainPackageRemoved = ($stillInstalled -eq $null -or $stillInstalled.Count -eq 0)\n \n # Check if any subpackages are still installed\n $subPackagesRemoved = $true\n if ($subPackages -ne $null) {\n foreach ($subPackage in $subPackages) {\n $stillInstalledSub = Get-AppxPackage | Where-Object { $_.Name -eq $subPackage }\n if ($stillInstalledSub -ne $null -and $stillInstalledSub.Count -gt 0) {\n $subPackagesRemoved = $false\n Write-Output \"\"Subpackage $subPackage is still installed\"\"\n break\n }\n }\n }\n \n # Return true only if both main package and all subpackages are removed\n return $mainPackageRemoved -and $subPackagesRemoved\n }\n catch {\n Write-Error \"\"Error removing package: $_\"\"\n return $false\n }\n \");\n powerShell.AddParameter(\"packageName\", packageName);\n powerShell.AddParameter(\"subPackages\", subPackages);\n \n var result = await Task.Run(() => powerShell.Invoke());\n var success = result.FirstOrDefault();\n results.Add((packageName, success, success ? null : \"Failed to remove app\"));\n _logService.LogInformation($\"Removal of {packageName} {(success ? \"succeeded\" : \"failed\")}\");\n \n // Apply registry settings for this app if it has any and removal was successful\n if (success)\n {\n try\n {\n // If we found the app definition and it has registry settings, apply them\n if (appDefinition?.RegistrySettings != null && appDefinition.RegistrySettings.Length > 0)\n {\n _logService.LogInformation($\"Found {appDefinition.RegistrySettings.Length} registry settings for {packageName}\");\n var registrySettings = appDefinition.RegistrySettings.ToList();\n \n // Apply the registry settings\n var settingsApplied = await ApplyRegistrySettingsAsync(registrySettings);\n if (settingsApplied)\n {\n _logService.LogSuccess($\"Successfully applied registry settings for {packageName}\");\n }\n else\n {\n _logService.LogWarning($\"Some registry settings for {packageName} could not be applied\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error applying registry settings for {packageName}\", ex);\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing app {packageName}\", ex);\n results.Add((packageName, false, $\"Error: {ex.Message}\"));\n }\n }\n \n return results;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error removing standard apps\", ex);\n return packageNames.Select(p => (p, false, $\"Error: {ex.Message}\")).ToList();\n }\n }\n\n /// \n public async Task ApplyRegistrySettingsAsync(List settings)\n {\n try\n {\n _logService.LogInformation($\"Applying {settings.Count} registry settings\");\n \n bool allSucceeded = true;\n \n foreach (var setting in settings)\n {\n try\n {\n _logService.LogInformation($\"Applying registry setting: {setting.Path}\\\\{setting.Name}\");\n \n bool success;\n if (setting.Value == null)\n {\n // If value is null, delete the registry value\n _logService.LogInformation($\"Deleting registry value: {setting.Path}\\\\{setting.Name}\");\n success = _registryService.DeleteValue(setting.Path, setting.Name);\n }\n else\n {\n // If value is not null, set the registry value\n // First ensure the key exists\n if (!_registryService.KeyExists(setting.Path))\n {\n _registryService.CreateKey(setting.Path);\n }\n \n // Set the registry value\n success = _registryService.SetValue(setting.Path, setting.Name, setting.Value, setting.ValueKind);\n }\n \n if (!success)\n {\n _logService.LogError($\"Failed to apply registry setting: {setting.Path}\\\\{setting.Name}\");\n allSucceeded = false;\n }\n else\n {\n _logService.LogSuccess($\"Successfully applied registry setting: {setting.Path}\\\\{setting.Name}\");\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error applying registry setting: {setting.Path}\\\\{setting.Name}\", ex);\n allSucceeded = false;\n }\n }\n \n return allSucceeded;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error applying registry settings\", ex);\n return false;\n }\n }\n\n // SetExecutionPolicy is now handled by PowerShellFactory\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/BaseInstallationService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Base class for installation services that provides common functionality.\n /// \n /// The type of item to install, which must implement IInstallableItem.\n public abstract class BaseInstallationService : IInstallationService where T : IInstallableItem\n {\n protected readonly ILogService _logService;\n protected readonly IPowerShellExecutionService _powerShellService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The PowerShell execution service.\n protected BaseInstallationService(\n ILogService logService,\n IPowerShellExecutionService powerShellService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _powerShellService = powerShellService ?? throw new ArgumentNullException(nameof(powerShellService));\n }\n\n /// \n public Task> InstallAsync(\n T item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n return InstallItemAsync(item, progress, cancellationToken);\n }\n\n /// \n public Task> CanInstallAsync(T item)\n {\n return CanInstallItemAsync(item);\n }\n\n /// \n /// Internal method to install an item.\n /// \n /// The item to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n protected async Task> InstallItemAsync(\n T item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (item == null)\n {\n throw new ArgumentNullException(nameof(item));\n }\n\n try\n {\n // Report initial progress\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Starting installation of {item.DisplayName}...\",\n DetailedMessage = $\"Preparing to install {item.DisplayName}\",\n }\n );\n\n _logService.LogInformation($\"Attempting to install {item.DisplayName} ({item.PackageId})\");\n\n // Perform the actual installation\n var result = await PerformInstallationAsync(item, progress, cancellationToken);\n\n if (result.Success)\n {\n // Report completion\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = $\"{item.DisplayName} installed successfully!\",\n DetailedMessage = $\"Successfully installed {item.DisplayName}\",\n }\n );\n\n if (item.RequiresRestart)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n StatusText = \"A system restart is required to complete the installation\",\n DetailedMessage = \"Please restart your computer to complete the installation\",\n LogLevel = LogLevel.Warning,\n }\n );\n _logService.LogWarning($\"A system restart is required for {item.DisplayName}\");\n }\n\n _logService.LogSuccess($\"Successfully installed {item.DisplayName}\");\n }\n\n return result;\n }\n catch (OperationCanceledException)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Installation of {item.DisplayName} was cancelled\",\n DetailedMessage = \"The installation was cancelled by the user\",\n LogLevel = LogLevel.Warning,\n }\n );\n \n _logService.LogWarning($\"Operation cancelled when installing {item.DisplayName}\");\n return OperationResult.Failed(\"The installation was cancelled by the user\");\n }\n catch (Exception ex)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Error installing {item.DisplayName}: {ex.Message}\",\n DetailedMessage = $\"Exception during installation: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n _logService.LogError($\"Error installing {item.DisplayName}\", ex);\n return OperationResult.Failed($\"Error installing {item.DisplayName}: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Checks if an item can be installed.\n /// \n /// The item to check.\n /// An operation result indicating if the item can be installed, with error details if not.\n protected Task> CanInstallItemAsync(T item)\n {\n if (item == null)\n {\n return Task.FromResult(OperationResult.Failed(\"Item information cannot be null\"));\n }\n\n // Basic implementation: Assume all items can be installed for now.\n // Derived classes can override this method to provide specific checks.\n return Task.FromResult(OperationResult.Succeeded(true));\n }\n\n /// \n /// Performs the actual installation of the item.\n /// \n /// The item to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n protected abstract Task> PerformInstallationAsync(\n T item,\n IProgress? progress,\n CancellationToken cancellationToken);\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScriptGenerationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Service for generating and managing removal scripts.\n /// \n public class ScriptGenerationService : IScriptGenerationService\n {\n private readonly ILogService _logService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IAppRemovalService _appRemovalService;\n private readonly IScriptContentModifier _scriptContentModifier;\n private readonly IScriptUpdateService _scriptUpdateService;\n private readonly IScheduledTaskService _scheduledTaskService;\n private readonly IScriptFactory _scriptFactory;\n private readonly IScriptBuilderService _scriptBuilderService;\n private readonly string _scriptsPath;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The app discovery service.\n /// The app removal service.\n /// The script content modifier.\n /// The script update service.\n /// The scheduled task service.\n /// The script factory.\n /// The script builder service.\n public ScriptGenerationService(\n ILogService logService,\n IAppDiscoveryService appDiscoveryService,\n IAppRemovalService appRemovalService,\n IScriptContentModifier scriptContentModifier,\n IScriptUpdateService scriptUpdateService,\n IScheduledTaskService scheduledTaskService,\n IScriptFactory scriptFactory,\n IScriptBuilderService scriptBuilderService\n )\n {\n _logService = logService;\n _appDiscoveryService = appDiscoveryService;\n _appRemovalService = appRemovalService;\n _scriptContentModifier = scriptContentModifier;\n _scriptUpdateService = scriptUpdateService;\n _scheduledTaskService = scheduledTaskService;\n _scriptFactory = scriptFactory;\n _scriptBuilderService = scriptBuilderService;\n\n _scriptsPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n \"Winhance\",\n \"Scripts\"\n );\n Directory.CreateDirectory(_scriptsPath);\n }\n\n /// \n public async Task CreateBatchRemovalScriptAsync(\n List appNames,\n Dictionary> appsWithRegistry\n )\n {\n try\n {\n _logService.LogInformation(\n $\"Creating batch removal script for {appNames.Count} apps\"\n );\n\n // Get all standard apps to check for subpackages\n var allRemovableApps = (await _appDiscoveryService.GetStandardAppsAsync()).ToList();\n\n // Create a dictionary to store subpackages for each app\n var appSubPackages = new Dictionary();\n\n // Find subpackages for each app in the list\n foreach (var appName in appNames)\n {\n var appInfo = allRemovableApps.FirstOrDefault(a => a.PackageName == appName);\n\n // Explicitly handle Copilot and Xbox packages to ensure subpackages are added\n bool isCopilotOrXbox =\n appName.Contains(\"Copilot\", StringComparison.OrdinalIgnoreCase)\n || appName.Contains(\"Xbox\", StringComparison.OrdinalIgnoreCase);\n\n if (\n appInfo?.SubPackages != null\n && (appInfo.SubPackages.Length > 0 || isCopilotOrXbox)\n )\n {\n appSubPackages[appName] = appInfo.SubPackages ?? new string[0];\n }\n\n // If the app has registry settings but they're not in the appsWithRegistry dictionary,\n // add them now\n if (appInfo?.RegistrySettings != null && appInfo.RegistrySettings.Length > 0)\n {\n if (!appsWithRegistry.ContainsKey(appName))\n {\n appsWithRegistry[appName] = appInfo.RegistrySettings.ToList();\n }\n }\n }\n\n // Check if the BloatRemoval.ps1 file already exists\n string bloatRemovalScriptPath = Path.Combine(_scriptsPath, \"BloatRemoval.ps1\");\n if (File.Exists(bloatRemovalScriptPath))\n {\n _logService.LogInformation(\n \"BloatRemoval.ps1 already exists, updating it with new entries\"\n );\n return await _scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n false // false = removal operation, so add to script\n );\n }\n\n // If the file doesn't exist, create a new one using the script factory\n return _scriptFactory.CreateBatchRemovalScript(\n appNames,\n appsWithRegistry,\n appSubPackages\n );\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error creating batch removal script\", ex);\n throw;\n }\n }\n\n /// \n public async Task CreateBatchRemovalScriptAsync(string scriptPath, AppInfo app)\n {\n try\n {\n _logService.LogInformation(\n $\"Creating removal script for {app.PackageName} at {scriptPath}\"\n );\n\n // Use the script builder service to create the script content\n string content = _scriptBuilderService.BuildSingleAppRemovalScript(app);\n\n await File.WriteAllTextAsync(scriptPath, content);\n _logService.LogSuccess(\n $\"Created removal script for {app.PackageName} at {scriptPath}\"\n );\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error creating removal script for {app.PackageName}\", ex);\n return false;\n }\n }\n\n /// \n public async Task RegisterRemovalTaskAsync(RemovalScript script)\n {\n try\n {\n if (script == null)\n {\n _logService.LogError(\"Cannot register removal task: Script is null\");\n return;\n }\n\n _logService.LogInformation($\"Registering removal task for script: {script.Name}\");\n\n // Ensure the script has been saved\n if (string.IsNullOrEmpty(script.Content))\n {\n _logService.LogWarning($\"Script content is empty for: {script.Name}\");\n }\n\n // Register the scheduled task\n bool success = await _scheduledTaskService.RegisterScheduledTaskAsync(script);\n\n if (success)\n {\n _logService.LogSuccess(\n $\"Successfully registered scheduled task for script: {script.Name}\"\n );\n }\n else\n {\n _logService.LogWarning(\n $\"Failed to register scheduled task for script: {script.Name}, but continuing operation\"\n );\n // Don't throw an exception here, just log a warning and continue\n }\n }\n catch (Exception ex)\n {\n _logService.LogError(\n $\"Error registering removal task for script: {script.Name}\",\n ex\n );\n // Don't rethrow the exception, just log it and continue\n }\n }\n\n /// \n public async Task RegisterRemovalTaskAsync(string taskName, string scriptPath)\n {\n try\n {\n if (string.IsNullOrEmpty(taskName) || string.IsNullOrEmpty(scriptPath))\n {\n _logService.LogError(\n $\"Invalid parameters for task registration. TaskName: {taskName}, ScriptPath: {scriptPath}\"\n );\n return false;\n }\n\n _logService.LogInformation(\n $\"Registering removal task: {taskName} for script: {scriptPath}\"\n );\n\n // Check if the script file exists\n if (!File.Exists(scriptPath))\n {\n _logService.LogError($\"Script file not found at: {scriptPath}\");\n return false;\n }\n\n // Create a RemovalScript object to pass to the scheduled task service\n var script = new RemovalScript\n {\n Name = Path.GetFileNameWithoutExtension(scriptPath),\n Content = await File.ReadAllTextAsync(scriptPath),\n TargetScheduledTaskName = taskName,\n RunOnStartup = true,\n };\n\n // Register the scheduled task\n return await _scheduledTaskService.RegisterScheduledTaskAsync(script);\n }\n catch (Exception ex)\n {\n _logService.LogError(\n $\"Error registering removal task: {taskName} for script: {scriptPath}\",\n ex\n );\n return false;\n }\n }\n\n /// \n public async Task SaveScriptAsync(RemovalScript script)\n {\n try\n {\n string scriptPath = Path.Combine(_scriptsPath, $\"{script.Name}.ps1\");\n await File.WriteAllTextAsync(scriptPath, script.Content);\n _logService.LogInformation($\"Saved script to {scriptPath}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error saving script: {script.Name}\", ex);\n throw;\n }\n }\n\n /// \n public async Task SaveScriptAsync(string scriptPath, string scriptContent)\n {\n try\n {\n await File.WriteAllTextAsync(scriptPath, scriptContent);\n _logService.LogInformation($\"Saved script to {scriptPath}\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error saving script to {scriptPath}\", ex);\n return false;\n }\n }\n\n /// \n public async Task UpdateBloatRemovalScriptForInstalledAppAsync(AppInfo app)\n {\n try\n {\n _logService.LogInformation(\n $\"Updating BloatRemoval script for installed app: {app.PackageName}\"\n );\n\n string bloatRemovalScriptPath = Path.Combine(_scriptsPath, \"BloatRemoval.ps1\");\n if (!File.Exists(bloatRemovalScriptPath))\n {\n _logService.LogWarning(\n $\"BloatRemoval.ps1 not found at {bloatRemovalScriptPath}\"\n );\n return false;\n }\n\n string scriptContent = await File.ReadAllTextAsync(bloatRemovalScriptPath);\n bool scriptModified = false;\n\n // Handle different types of apps\n if (\n app.Type == AppType.OptionalFeature\n || app.PackageName.Equals(\"Recall\", StringComparison.OrdinalIgnoreCase)\n || app.Type == AppType.Capability\n )\n {\n // Handle OptionalFeatures and Capabilities using the ScriptUpdateService\n // This ensures proper handling of install operations (removing from script)\n _logService.LogInformation(\n $\"Using ScriptUpdateService to update BloatRemoval script for {app.Type} {app.PackageName}\"\n );\n\n // Create a list with just this app\n var appNames = new List { app.PackageName };\n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n\n // Get app registry settings if available\n var allRemovableApps = (\n await _appDiscoveryService.GetStandardAppsAsync()\n ).ToList();\n var appDefinition = allRemovableApps.FirstOrDefault(a =>\n a.PackageName.Equals(app.PackageName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (\n appDefinition?.RegistrySettings != null\n && appDefinition.RegistrySettings.Length > 0\n )\n {\n appsWithRegistry[app.PackageName] = appDefinition.RegistrySettings.ToList();\n }\n\n // Update the script with isInstallOperation = true to remove the entry\n await _scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n true // true = install operation, so remove from script\n );\n\n return true;\n }\n else\n {\n // Handle standard package\n scriptContent = _scriptContentModifier.RemovePackageFromScript(\n scriptContent,\n app.PackageName\n );\n\n // Create a list of subpackages to remove\n List subPackagesToRemove = new List();\n\n // Get all standard apps to find the app definition and its subpackages\n var allRemovableApps = (\n await _appDiscoveryService.GetStandardAppsAsync()\n ).ToList();\n\n // Find the app definition that matches the current app\n var appDefinition = allRemovableApps.FirstOrDefault(a =>\n a.PackageName.Equals(app.PackageName, StringComparison.OrdinalIgnoreCase)\n );\n\n // If we found the app definition and it has subpackages, add them to the removal list\n if (appDefinition?.SubPackages != null && appDefinition.SubPackages.Length > 0)\n {\n _logService.LogInformation(\n $\"Found {appDefinition.SubPackages.Length} subpackages for {app.PackageName} in WindowsAppCatalog\"\n );\n subPackagesToRemove.AddRange(appDefinition.SubPackages);\n }\n\n // Remove registry settings for this app from the script\n scriptContent = _scriptContentModifier.RemoveAppRegistrySettingsFromScript(\n scriptContent,\n app.PackageName\n );\n\n // Apply registry settings to delete registry keys from the system\n if (\n appDefinition?.RegistrySettings != null\n && appDefinition.RegistrySettings.Length > 0\n )\n {\n _logService.LogInformation(\n $\"Found {appDefinition.RegistrySettings.Length} registry settings for {app.PackageName}\"\n );\n\n // Create a list of registry settings that delete the keys\n var deleteRegistrySettings = new List();\n\n foreach (var setting in appDefinition.RegistrySettings)\n {\n // Create a new registry setting that deletes the key\n var deleteSetting = new AppRegistrySetting\n {\n Path = setting.Path,\n Name = setting.Name,\n Value = null, // null value means delete the key\n ValueKind = setting.ValueKind,\n };\n\n deleteRegistrySettings.Add(deleteSetting);\n }\n\n // Apply the registry settings to delete the keys\n // TODO: ApplyRegistrySettingsAsync is not on IAppRemovalService.\n // Need to inject IRegistryService or move this logic. Commenting out for now.\n _logService.LogInformation(\n $\"Applying {deleteRegistrySettings.Count} registry settings to delete keys for {app.PackageName}\"\n );\n // var success = await _appRemovalService.ApplyRegistrySettingsAsync(\n // deleteRegistrySettings\n // );\n var success = false; // Assume failure for now as the call is removed\n _logService.LogWarning(\n $\"Skipping registry key deletion for {app.PackageName} as ApplyRegistrySettingsAsync is not available on the interface.\"\n );\n\n if (success) // This block will likely not be hit now\n {\n _logService.LogSuccess(\n $\"Successfully deleted registry keys for {app.PackageName}\"\n );\n }\n else\n {\n _logService.LogWarning(\n $\"Failed to delete some registry keys for {app.PackageName}\"\n );\n }\n }\n\n // Remove all subpackages from the script\n foreach (var subPackage in subPackagesToRemove)\n {\n _logService.LogInformation(\n $\"Removing subpackage: {subPackage} for app: {app.PackageName}\"\n );\n scriptContent = _scriptContentModifier.RemovePackageFromScript(\n scriptContent,\n subPackage\n );\n }\n\n scriptModified = true;\n }\n\n // Save the updated script if it was modified\n if (scriptModified)\n {\n await File.WriteAllTextAsync(bloatRemovalScriptPath, scriptContent);\n _logService.LogSuccess(\n $\"Successfully updated BloatRemoval script for app: {app.PackageName}\"\n );\n }\n else\n {\n _logService.LogInformation(\n $\"No changes needed to BloatRemoval script for app: {app.PackageName}\"\n );\n }\n\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError(\n $\"Error updating BloatRemoval script for app: {app.PackageName}\",\n ex\n );\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/ViewModels/CustomizeViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Optimize.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.Common.Messages;\n\nnamespace Winhance.WPF.Features.Customize.ViewModels\n{\n /// \n /// ViewModel for the Customize view.\n /// \n public partial class CustomizeViewModel : SearchableViewModel\n {\n // Store a backup of all items for state recovery\n private List _allItemsBackup = new List();\n private bool _isInitialSearchDone = false;\n\n // Tracks if search has any results\n [ObservableProperty]\n private bool _hasSearchResults = true;\n private readonly ISystemServices _windowsService;\n private readonly IDialogService _dialogService;\n private readonly IThemeManager _themeManager;\n private readonly IConfigurationService _configurationService;\n private readonly IMessengerService _messengerService;\n private readonly ILogService _logService;\n\n /// \n /// Gets the messenger service.\n /// \n public IMessengerService MessengerService => _messengerService;\n\n // Flag to prevent cascading checkbox updates\n private bool _updatingCheckboxes = false;\n /// \n /// Gets or sets a value indicating whether dark mode is enabled.\n /// \n [ObservableProperty]\n private bool _isDarkModeEnabled;\n\n /// \n /// Gets or sets a value indicating whether all settings are selected.\n /// \n [ObservableProperty]\n private bool _isSelectAllSelected;\n\n /// \n /// Gets or sets a value indicating whether settings are being loaded.\n /// \n [ObservableProperty]\n private bool _isLoading;\n\n /// \n /// Gets or sets the status text.\n /// \n [ObservableProperty]\n private string _statusText = \"Customize Your Windows Appearance and Behaviour\";\n \n // Override the SearchText property to add explicit notification and direct control over the search flow\n private string _searchTextOverride = string.Empty;\n public override string SearchText\n {\n get => _searchTextOverride;\n set\n {\n if (_searchTextOverride != value)\n {\n _searchTextOverride = value;\n OnPropertyChanged(nameof(SearchText));\n LogInfo($\"CustomizeViewModel: SearchText changed to: '{value}'\");\n \n // Explicitly update IsSearchActive and call ApplySearch\n IsSearchActive = !string.IsNullOrWhiteSpace(value);\n ApplySearch();\n \n // Update status text based on search results\n if (IsSearchActive)\n {\n StatusText = $\"Found {Items.Count} settings matching '{value}'\";\n }\n else\n {\n StatusText = \"Customize Your Windows Appearance and Behaviour\";\n }\n }\n }\n }\n \n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n\n /// \n /// Gets the collection of customization items.\n /// \n public ObservableCollection CustomizationItems { get; } = new();\n\n /// \n /// Gets or sets the taskbar settings view model.\n /// \n [ObservableProperty]\n private TaskbarCustomizationsViewModel _taskbarSettings;\n\n /// \n /// Gets or sets the start menu settings view model.\n /// \n [ObservableProperty]\n private StartMenuCustomizationsViewModel _startMenuSettings;\n\n /// \n /// Gets or sets the explorer customizations view model.\n /// \n [ObservableProperty]\n private ExplorerCustomizationsViewModel _explorerSettings;\n\n /// \n /// Gets or sets the Windows theme customizations view model.\n /// \n [ObservableProperty]\n private WindowsThemeCustomizationsViewModel _windowsThemeSettings;\n\n /// \n /// Gets a value indicating whether the view model is initialized.\n /// \n public bool IsInitialized { get; private set; }\n\n /// \n /// Gets the initialize command.\n /// \n public AsyncRelayCommand InitializeCommand { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The Windows service.\n /// The log service.\n /// The dialog service.\n /// The theme manager.\n /// The search service.\n /// The configuration service.\n /// The taskbar customizations view model.\n /// The start menu customizations view model.\n /// The explorer settings view model.\n /// The Windows theme customizations view model.\n /// The messenger service.\n public CustomizeViewModel(\n ITaskProgressService progressService,\n ISystemServices windowsService,\n ILogService logService,\n IDialogService dialogService,\n IThemeManager themeManager,\n ISearchService searchService,\n IConfigurationService configurationService,\n TaskbarCustomizationsViewModel taskbarSettings,\n StartMenuCustomizationsViewModel startMenuSettings,\n ExplorerCustomizationsViewModel explorerSettings,\n WindowsThemeCustomizationsViewModel windowsThemeSettings,\n IMessengerService messengerService)\n : base(progressService, searchService, null)\n {\n _windowsService = windowsService ?? throw new ArgumentNullException(nameof(windowsService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));\n _messengerService = messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n\n TaskbarSettings = taskbarSettings ?? throw new ArgumentNullException(nameof(taskbarSettings));\n StartMenuSettings = startMenuSettings ?? throw new ArgumentNullException(nameof(startMenuSettings));\n ExplorerSettings = explorerSettings ?? throw new ArgumentNullException(nameof(explorerSettings));\n WindowsThemeSettings = windowsThemeSettings ?? throw new ArgumentNullException(nameof(windowsThemeSettings));\n\n InitializeCustomizationItems();\n \n // Sync with WindowsThemeSettings\n IsDarkModeEnabled = WindowsThemeSettings.IsDarkModeEnabled;\n \n // Subscribe to WindowsThemeSettings property changes\n WindowsThemeSettings.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(WindowsThemeSettings.IsDarkModeEnabled))\n {\n // Sync dark mode state with WindowsThemeSettings\n IsDarkModeEnabled = WindowsThemeSettings.IsDarkModeEnabled;\n }\n };\n\n // Create initialize command\n InitializeCommand = new AsyncRelayCommand(InitializeAsync);\n \n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n }\n\n /// \n /// Initializes a new instance of the class for design-time use.\n /// \n public CustomizeViewModel()\n : base(\n new Winhance.Infrastructure.Features.Common.Services.TaskProgressService(new Core.Features.Common.Services.LogService()),\n new Winhance.Infrastructure.Features.Common.Services.SearchService())\n {\n // Default constructor for design-time use\n CustomizationItems = new ObservableCollection();\n InitializeCustomizationItems();\n IsDarkModeEnabled = true; // Default to dark mode for design-time\n }\n\n /// \n /// Called when the view model is navigated to.\n /// \n /// The navigation parameter.\n public override void OnNavigatedTo(object parameter)\n {\n LogInfo(\"CustomizeViewModel.OnNavigatedTo called\");\n \n // Ensure the status text is set to the default value\n StatusText = \"Customize Your Windows Appearance and Behaviour\";\n\n // If not already initialized, initialize now\n if (!IsInitialized)\n {\n InitializeCommand.Execute(null);\n }\n }\n\n /// \n /// Initializes the view model asynchronously.\n /// \n /// The cancellation token.\n /// A task representing the asynchronous operation.\n private async Task InitializeAsync(CancellationToken cancellationToken)\n {\n if (IsInitialized)\n return;\n\n try\n {\n IsLoading = true;\n LogInfo(\"Initializing CustomizeViewModel\");\n\n // Report progress\n ProgressService.UpdateProgress(0, \"Loading customization settings...\");\n\n // Load settings for each category\n LogInfo(\"CustomizeViewModel.InitializeAsync: Loading Taskbar settings\");\n ProgressService.UpdateProgress(10, \"Loading taskbar settings...\");\n await TaskbarSettings.LoadSettingsAsync();\n await TaskbarSettings.CheckSettingStatusesAsync();\n\n LogInfo(\"CustomizeViewModel.InitializeAsync: Loading Start Menu settings\");\n ProgressService.UpdateProgress(30, \"Loading Start Menu settings...\");\n await StartMenuSettings.LoadSettingsAsync();\n await StartMenuSettings.CheckSettingStatusesAsync();\n\n LogInfo(\"CustomizeViewModel.InitializeAsync: Loading Explorer settings\");\n ProgressService.UpdateProgress(50, \"Loading Explorer settings...\");\n await ExplorerSettings.LoadSettingsAsync();\n await ExplorerSettings.CheckSettingStatusesAsync();\n\n // Load Windows Theme settings if available\n if (WindowsThemeSettings != null)\n {\n LogInfo(\"CustomizeViewModel.InitializeAsync: Loading Windows Theme settings\");\n ProgressService.UpdateProgress(70, \"Loading Windows Theme settings...\");\n await WindowsThemeSettings.LoadSettingsAsync();\n await WindowsThemeSettings.CheckSettingStatusesAsync();\n }\n\n // Progress is now complete\n ProgressService.UpdateProgress(90, \"Finalizing...\");\n\n LogInfo(\"CustomizeViewModel.InitializeAsync: All settings loaded\");\n ProgressService.UpdateProgress(100, \"Initialization complete\");\n\n // Set up property change handlers\n SetupPropertyChangeHandlers();\n\n // Update selection states\n UpdateSelectAllState();\n\n // Load all settings for search functionality\n await LoadItemsAsync();\n \n // Ensure Windows Theme settings are properly loaded for search\n if (WindowsThemeSettings != null && WindowsThemeSettings.Settings.Count == 0)\n {\n LogInfo(\"CustomizeViewModel: Reloading Windows Theme settings for search\");\n await WindowsThemeSettings.LoadSettingsAsync();\n }\n \n // Mark as initialized\n IsInitialized = true;\n\n LogInfo(\"CustomizeViewModel initialized successfully\");\n }\n catch (Exception ex)\n {\n LogError($\"Error initializing customization settings: {ex.Message}\");\n throw; // Rethrow to ensure the caller knows initialization failed\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Initializes the customization items.\n /// \n private void InitializeCustomizationItems()\n {\n CustomizationItems.Clear();\n\n // Taskbar customization\n var taskbarItem = new ApplicationSettingGroup\n {\n Name = \"Taskbar\",\n Description = \"Customize taskbar appearance and behavior\",\n IsSelected = false\n };\n CustomizationItems.Add(taskbarItem);\n\n // Start Menu customization\n var startMenuItem = new ApplicationSettingGroup\n {\n Name = \"Start Menu\",\n Description = \"Modify Start Menu layout and settings\",\n IsSelected = false\n };\n CustomizationItems.Add(startMenuItem);\n\n // Explorer customization\n var explorerItem = new ApplicationSettingGroup\n {\n Name = \"Explorer\",\n Description = \"Adjust File Explorer settings and appearance\",\n IsSelected = false\n };\n CustomizationItems.Add(explorerItem);\n\n // Windows Theme customization\n var windowsThemeItem = new ApplicationSettingGroup\n {\n Name = \"Windows Theme\",\n Description = \"Customize Windows appearance themes\",\n IsSelected = false\n };\n CustomizationItems.Add(windowsThemeItem);\n }\n\n /// \n /// Sets up property change handlers.\n /// \n private void SetupPropertyChangeHandlers()\n {\n // Set up property change handlers for all settings\n foreach (var item in CustomizationItems)\n {\n // Add property changed handler for the category itself\n item.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingGroup.IsSelected) && !_updatingCheckboxes)\n {\n _updatingCheckboxes = true;\n try\n {\n // Update all settings in this category\n UpdateCategorySettings(item);\n\n // Update the global state\n UpdateSelectAllState();\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n };\n }\n }\n\n /// \n /// Updates the settings for a category.\n /// \n /// The category.\n private void UpdateCategorySettings(ApplicationSettingGroup category)\n {\n if (category == null) return;\n\n // Get the IsSelected property from ISettingItem interface\n PropertyInfo isSelectedProp = typeof(ISettingItem).GetProperty(\"IsSelected\");\n if (isSelectedProp == null) return;\n\n switch (category.Name)\n {\n case \"Taskbar\":\n foreach (var setting in TaskbarSettings.Settings)\n {\n isSelectedProp.SetValue(setting, category.IsSelected);\n }\n break;\n case \"Start Menu\":\n foreach (var setting in StartMenuSettings.Settings)\n {\n isSelectedProp.SetValue(setting, category.IsSelected);\n }\n break;\n case \"Explorer\":\n foreach (var setting in ExplorerSettings.Settings)\n {\n isSelectedProp.SetValue(setting, category.IsSelected);\n }\n break;\n case \"Windows Theme\":\n if (WindowsThemeSettings != null && WindowsThemeSettings.Settings.Count > 0)\n {\n foreach (var setting in WindowsThemeSettings.Settings)\n {\n isSelectedProp.SetValue(setting, category.IsSelected);\n }\n }\n break;\n }\n }\n\n /// \n /// Updates the category selection state.\n /// \n /// The category name.\n private void UpdateCategorySelectionState(string categoryName)\n {\n // Skip if we're already in an update operation\n if (_updatingCheckboxes)\n return;\n\n _updatingCheckboxes = true;\n\n try\n {\n var category = CustomizationItems.FirstOrDefault(c => c.Name == categoryName);\n if (category == null) return;\n\n bool allSelected = false;\n\n // Get the IsSelected property from ISettingItem interface\n PropertyInfo isSelectedProp = typeof(ISettingItem).GetProperty(\"IsSelected\");\n if (isSelectedProp == null) return;\n\n switch (categoryName)\n {\n case \"Taskbar\":\n allSelected = TaskbarSettings.Settings.Count > 0 &&\n TaskbarSettings.Settings.All(s => (bool)isSelectedProp.GetValue(s));\n break;\n case \"Start Menu\":\n allSelected = StartMenuSettings.Settings.Count > 0 &&\n StartMenuSettings.Settings.All(s => (bool)isSelectedProp.GetValue(s));\n break;\n case \"Explorer\":\n allSelected = ExplorerSettings.Settings.Count > 0 &&\n ExplorerSettings.Settings.All(s => (bool)isSelectedProp.GetValue(s));\n break;\n case \"Windows Theme\":\n allSelected = WindowsThemeSettings != null && \n WindowsThemeSettings.Settings.Count > 0 &&\n WindowsThemeSettings.Settings.All(s => (bool)isSelectedProp.GetValue(s));\n break;\n // Removed Notifications and Sound cases\n }\n\n category.IsSelected = allSelected;\n\n // Update global state\n UpdateSelectAllState();\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Updates the select all state.\n /// \n private void UpdateSelectAllState()\n {\n // Skip if we're already in an update operation\n if (_updatingCheckboxes)\n return;\n\n _updatingCheckboxes = true;\n\n try\n {\n // Skip if no customization items\n if (CustomizationItems.Count == 0)\n return;\n\n // Update global \"Select All\" checkbox based on all categories\n IsSelectAllSelected = CustomizationItems.All(c => c.IsSelected);\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n\n /// \n /// Refreshes the Windows GUI.\n /// \n /// A task representing the asynchronous operation.\n private async Task RefreshWindowsGUI()\n {\n try\n {\n // Use the Windows service to refresh the GUI without restarting explorer\n await _windowsService.RefreshWindowsGUI(false);\n\n LogInfo(\"Windows GUI refresh completed\");\n }\n catch (Exception ex)\n {\n LogError($\"Error refreshing Windows GUI: {ex.Message}\");\n }\n }\n\n /// \n /// Toggles the select all state.\n /// \n [RelayCommand]\n private void ToggleSelectAll()\n {\n bool newState = !IsSelectAllSelected;\n IsSelectAllSelected = newState;\n\n _updatingCheckboxes = true;\n\n try\n {\n foreach (var item in CustomizationItems)\n {\n item.IsSelected = newState;\n UpdateCategorySettings(item);\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n // Note: ApplyCustomizationsCommand has been removed as settings are now applied immediately when toggled\n // Note: RestoreDefaultsCommand has been removed as settings are now applied immediately when toggled\n\n /// \n /// Executes a customization action.\n /// \n /// The action to execute.\n [RelayCommand]\n private async Task ExecuteAction(ApplicationAction? action)\n {\n if (action == null) return;\n\n try\n {\n IsLoading = true;\n StatusText = $\"Executing action: {action.Name}...\";\n\n // Execute the action through the appropriate view model\n if (action.GroupName == \"Taskbar\" && TaskbarSettings != null)\n {\n await TaskbarSettings.ExecuteActionAsync(action);\n }\n else if (action.GroupName == \"Start Menu\" && StartMenuSettings != null)\n {\n await StartMenuSettings.ExecuteActionAsync(action);\n }\n else if (action.GroupName == \"Explorer\" && ExplorerSettings != null)\n {\n await ExplorerSettings.ExecuteActionAsync(action);\n }\n else if (action.GroupName == \"Windows Theme\" && WindowsThemeSettings != null)\n {\n await WindowsThemeSettings.ExecuteActionAsync(action);\n }\n\n StatusText = $\"Action '{action.Name}' executed successfully\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Error executing action: {ex.Message}\";\n LogError($\"Error executing action '{action?.Name}': {ex.Message}\");\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Toggles a category.\n /// \n /// The category to toggle.\n [RelayCommand]\n private void ToggleCategory(ApplicationSettingGroup? category)\n {\n if (category == null) return;\n\n // Skip if we're already in an update operation\n if (_updatingCheckboxes)\n return;\n\n _updatingCheckboxes = true;\n\n try\n {\n switch (category.Name)\n {\n case \"Taskbar\":\n foreach (var setting in TaskbarSettings.Settings)\n {\n setting.IsSelected = category.IsSelected;\n }\n break;\n case \"Start Menu\":\n foreach (var setting in StartMenuSettings.Settings)\n {\n setting.IsSelected = category.IsSelected;\n }\n break;\n case \"Explorer\":\n foreach (var setting in ExplorerSettings.Settings)\n {\n setting.IsSelected = category.IsSelected;\n }\n break;\n case \"Windows Theme\":\n if (WindowsThemeSettings != null && WindowsThemeSettings.Settings.Count > 0)\n {\n foreach (var setting in WindowsThemeSettings.Settings)\n {\n setting.IsSelected = category.IsSelected;\n }\n }\n break;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n \n /// \n /// Loads items asynchronously.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadItemsAsync()\n {\n try\n {\n IsLoading = true;\n StatusText = \"Loading customization settings...\";\n\n // Clear the items collection\n Items.Clear();\n\n // Collect all settings from the various view models\n var allSettings = new List();\n\n // Add settings from each category\n if (TaskbarSettings != null && TaskbarSettings.Settings != null)\n {\n foreach (var setting in TaskbarSettings.Settings)\n {\n if (setting is ApplicationSettingItem applicationSetting)\n {\n allSettings.Add(applicationSetting);\n }\n }\n }\n\n if (StartMenuSettings != null && StartMenuSettings.Settings != null)\n {\n foreach (var setting in StartMenuSettings.Settings)\n {\n if (setting is ApplicationSettingItem applicationSetting)\n {\n allSettings.Add(applicationSetting);\n }\n }\n }\n\n if (ExplorerSettings != null && ExplorerSettings.Settings != null)\n {\n foreach (var setting in ExplorerSettings.Settings)\n {\n if (setting is ApplicationSettingItem applicationSetting)\n {\n allSettings.Add(applicationSetting);\n }\n }\n }\n\n if (WindowsThemeSettings != null && WindowsThemeSettings.Settings != null)\n {\n foreach (var setting in WindowsThemeSettings.Settings)\n {\n if (setting is ApplicationSettingItem applicationSetting)\n {\n allSettings.Add(applicationSetting);\n }\n }\n }\n\n // Add all settings to the Items collection\n foreach (var setting in allSettings)\n {\n Items.Add(setting);\n }\n\n // Create a backup of all items for state recovery\n _allItemsBackup = new List(Items);\n\n // Only update StatusText if it's currently showing a loading message\n if (StatusText.Contains(\"Loading\"))\n {\n StatusText = \"Customize Your Windows Appearance and Behaviour\";\n }\n }\n catch (Exception ex)\n {\n StatusText = $\"Error loading customization settings: {ex.Message}\";\n LogError($\"Error loading customization settings: {ex.Message}\", ex);\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the installation status of items asynchronously.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckInstallationStatusAsync()\n {\n // This method is not applicable for customization settings\n // but we need to implement it to satisfy the interface\n await Task.CompletedTask;\n }\n\n /// \n /// Restores all items visibility to their original state.\n /// \n private void RestoreAllItemsVisibility()\n {\n // Make all settings visible in each category\n if (TaskbarSettings?.Settings != null)\n {\n foreach (var setting in TaskbarSettings.Settings)\n {\n setting.IsVisible = true;\n }\n TaskbarSettings.HasVisibleSettings = TaskbarSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Restored visibility for {TaskbarSettings.Settings.Count} Taskbar settings\");\n }\n \n if (StartMenuSettings?.Settings != null)\n {\n foreach (var setting in StartMenuSettings.Settings)\n {\n setting.IsVisible = true;\n }\n StartMenuSettings.HasVisibleSettings = StartMenuSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Restored visibility for {StartMenuSettings.Settings.Count} Start Menu settings\");\n }\n \n if (ExplorerSettings?.Settings != null)\n {\n foreach (var setting in ExplorerSettings.Settings)\n {\n setting.IsVisible = true;\n }\n ExplorerSettings.HasVisibleSettings = ExplorerSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Restored visibility for {ExplorerSettings.Settings.Count} Explorer settings\");\n }\n \n if (WindowsThemeSettings?.Settings != null)\n {\n foreach (var setting in WindowsThemeSettings.Settings)\n {\n setting.IsVisible = true;\n }\n WindowsThemeSettings.HasVisibleSettings = WindowsThemeSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Restored visibility for {WindowsThemeSettings.Settings.Count} Windows Theme settings, HasVisibleSettings={WindowsThemeSettings.HasVisibleSettings}\");\n }\n \n // Make all customization items visible\n foreach (var item in CustomizationItems)\n {\n item.IsVisible = true;\n LogInfo($\"CustomizeViewModel: Restored visibility for CustomizationItem '{item.Name}'\");\n }\n \n // Always ensure HasSearchResults is true when restoring visibility\n HasSearchResults = true;\n \n // Send a message to notify the view to reset section expansion states\n _messengerService.Send(new ResetExpansionStateMessage());\n \n LogInfo(\"CustomizeViewModel: RestoreAllItemsVisibility has reset all UI elements to visible state\");\n }\n \n /// \n /// Applies the current search text to filter items.\n /// \n protected override void ApplySearch()\n {\n LogInfo($\"CustomizeViewModel: ApplySearch called with SearchText: '{SearchText}'\");\n \n // If we have no items yet, there's nothing to filter\n if (Items == null)\n return;\n \n // If this is our first time running a search and the backup isn't created yet, create it\n if (!_isInitialSearchDone && Items.Count > 0)\n {\n _allItemsBackup = new List(Items);\n _isInitialSearchDone = true;\n LogInfo($\"CustomizeViewModel: Created backup of all items ({_allItemsBackup.Count} items)\");\n }\n\n // If search is empty, restore all items visibility and the original items collection\n if (string.IsNullOrWhiteSpace(SearchText))\n {\n LogInfo(\"CustomizeViewModel: Empty search, restoring all items visibility\");\n \n // Restore visibility of UI elements first\n RestoreAllItemsVisibility();\n \n // Use the backup to restore all items\n if (_allItemsBackup.Count > 0)\n {\n LogInfo($\"CustomizeViewModel: Restoring {_allItemsBackup.Count} items from backup\");\n Items.Clear();\n foreach (var item in _allItemsBackup)\n {\n Items.Add(item);\n }\n }\n else if (Items.Count == 0)\n {\n // If we don't have a backup and Items is empty (which could happen after a no-results search),\n // try to reload items\n LogInfo(\"CustomizeViewModel: No backup available and Items is empty, attempting to reload\");\n _ = LoadItemsAsync();\n }\n \n // Always set HasSearchResults to true when search is cleared - critical to fix the bug\n HasSearchResults = true;\n \n // Make sure all CustomizationItems are visible\n foreach (var item in CustomizationItems)\n {\n item.IsVisible = true;\n LogInfo($\"CustomizeViewModel: Setting CustomizationItem '{item.Name}' visibility to true\");\n }\n \n // Ensure all sub-view models have HasVisibleSettings set to true\n if (TaskbarSettings != null)\n {\n TaskbarSettings.HasVisibleSettings = TaskbarSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Setting TaskbarSettings.HasVisibleSettings to {TaskbarSettings.HasVisibleSettings}\");\n }\n \n if (StartMenuSettings != null)\n {\n StartMenuSettings.HasVisibleSettings = StartMenuSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Setting StartMenuSettings.HasVisibleSettings to {StartMenuSettings.HasVisibleSettings}\");\n }\n \n if (ExplorerSettings != null)\n {\n ExplorerSettings.HasVisibleSettings = ExplorerSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Setting ExplorerSettings.HasVisibleSettings to {ExplorerSettings.HasVisibleSettings}\");\n }\n \n if (WindowsThemeSettings != null)\n {\n WindowsThemeSettings.HasVisibleSettings = WindowsThemeSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Setting WindowsThemeSettings.HasVisibleSettings to {WindowsThemeSettings.HasVisibleSettings}\");\n }\n \n // Update status text\n StatusText = \"Customize Your Windows Appearance and Behaviour\";\n LogInfo($\"CustomizeViewModel: Restored items, count={Items.Count}\");\n return;\n }\n\n // We're doing an active search, use the backup for filtering if available\n var itemsToFilter = _allItemsBackup.Count > 0 \n ? new ObservableCollection(_allItemsBackup) \n : Items;\n \n // Normalize and clean the search text\n string normalizedSearchText = SearchText.Trim().ToLowerInvariant();\n LogInfo($\"CustomizeViewModel: Normalized search text: '{normalizedSearchText}'\");\n \n // Handle edge case: if search is all whitespace after trimming, treat it as empty\n if (string.IsNullOrEmpty(normalizedSearchText))\n {\n // Same handling as empty search\n RestoreAllItemsVisibility();\n if (_allItemsBackup.Count > 0)\n {\n Items.Clear();\n foreach (var item in _allItemsBackup)\n {\n Items.Add(item);\n }\n }\n HasSearchResults = true;\n StatusText = \"Customize Your Windows Appearance and Behaviour\";\n return;\n }\n \n // Filter items based on search text - ensure we pass normalized text\n var filteredItems = FilterItems(itemsToFilter)\n .Where(item => \n item.Name?.IndexOf(normalizedSearchText, StringComparison.OrdinalIgnoreCase) >= 0 || \n item.Description?.IndexOf(normalizedSearchText, StringComparison.OrdinalIgnoreCase) >= 0)\n .ToList();\n \n // Log the number of filtered items\n int filteredCount = filteredItems.Count;\n LogInfo($\"CustomizeViewModel: Found {filteredCount} matching items\");\n \n // Update HasSearchResults based on filtered count\n HasSearchResults = filteredCount > 0;\n LogInfo($\"CustomizeViewModel: Setting HasSearchResults to {HasSearchResults} based on filtered count {filteredCount}\");\n \n // Create a HashSet of filtered item IDs for efficient lookup\n var filteredItemIds = new HashSet(filteredItems.Select(item => item.Id));\n\n // Update each sub-view model's Settings collection\n UpdateSubViewSettings(TaskbarSettings, filteredItemIds);\n UpdateSubViewSettings(StartMenuSettings, filteredItemIds);\n UpdateSubViewSettings(ExplorerSettings, filteredItemIds);\n UpdateSubViewSettings(WindowsThemeSettings, filteredItemIds);\n\n // Count the actual visible items after filtering\n int visibleItemsCount = 0;\n \n // Count visible items in each category\n if (TaskbarSettings?.Settings != null)\n visibleItemsCount += TaskbarSettings.Settings.Count(s => s is ApplicationSettingItem csItem && csItem.IsVisible);\n \n if (StartMenuSettings?.Settings != null)\n visibleItemsCount += StartMenuSettings.Settings.Count(s => s is ApplicationSettingItem csItem && csItem.IsVisible);\n \n if (ExplorerSettings?.Settings != null)\n visibleItemsCount += ExplorerSettings.Settings.Count(s => s is ApplicationSettingItem csItem && csItem.IsVisible);\n \n if (WindowsThemeSettings?.Settings != null)\n visibleItemsCount += WindowsThemeSettings.Settings.Count(s => s is ApplicationSettingItem csItem && csItem.IsVisible);\n\n // Update the Items collection to match visible items\n Items.Clear();\n foreach (var setting in filteredItems)\n {\n if (setting.IsVisible)\n {\n Items.Add(setting);\n }\n }\n\n // Update status text with correct count\n if (IsSearchActive)\n {\n StatusText = $\"Found {visibleItemsCount} settings matching '{SearchText}'\";\n LogInfo($\"CustomizeViewModel: StatusText updated to: '{StatusText}' with {visibleItemsCount} visible items\");\n }\n else\n {\n StatusText = $\"Showing all {Items.Count} customization settings\";\n LogInfo($\"CustomizeViewModel: StatusText updated to: '{StatusText}'\");\n }\n }\n\n /// \n /// Updates a sub-view model's Settings collection based on filtered items.\n /// \n /// The sub-view model to update.\n /// HashSet of IDs of items that match the search criteria.\n private void UpdateSubViewSettings(BaseSettingsViewModel viewModel, HashSet filteredItemIds)\n {\n if (viewModel == null || viewModel.Settings == null)\n return;\n\n // If not searching, show all settings\n if (!IsSearchActive)\n {\n foreach (var setting in viewModel.Settings)\n {\n setting.IsVisible = true;\n }\n \n // Update the view model's visibility\n viewModel.HasVisibleSettings = viewModel.Settings.Count > 0;\n \n // Update the corresponding CustomizationItem\n var item = CustomizationItems.FirstOrDefault(i => i.Name == viewModel.CategoryName);\n if (item != null)\n {\n item.IsVisible = true;\n }\n \n LogInfo($\"CustomizeViewModel: Set all settings visible in {viewModel.CategoryName}\");\n return;\n }\n\n // When searching, only show settings that match the search criteria\n bool hasVisibleSettings = false;\n int visibleCount = 0;\n \n foreach (var setting in viewModel.Settings)\n {\n // Check if this setting is in the filtered items\n setting.IsVisible = filteredItemIds.Contains(setting.Id);\n \n if (setting.IsVisible)\n {\n hasVisibleSettings = true;\n visibleCount++;\n }\n }\n \n // Update the view model's visibility\n viewModel.HasVisibleSettings = hasVisibleSettings;\n \n // Update the corresponding CustomizationItem - this is critical for proper UI behavior\n var categoryItem = CustomizationItems.FirstOrDefault(i => i.Name == viewModel.CategoryName);\n if (categoryItem != null)\n {\n categoryItem.IsVisible = hasVisibleSettings;\n LogInfo($\"CustomizeViewModel: Setting CustomizationItem '{categoryItem.Name}' visibility to {hasVisibleSettings}\");\n }\n \n LogInfo($\"CustomizeViewModel: {viewModel.CategoryName} has {visibleCount} visible settings, HasVisibleSettings={hasVisibleSettings}\");\n }\n\n // SaveConfig and ImportConfig methods removed as part of unified configuration cleanup\n\n /// \n /// Logs an informational message.\n /// \n /// The message to log.\n private void LogInfo(string message)\n {\n StatusText = message;\n _logService?.Log(LogLevel.Info, message);\n }\n\n /// \n /// Logs an error message.\n /// \n /// The message to log.\n private void LogError(string message)\n {\n StatusText = message;\n _logService?.Log(LogLevel.Error, message);\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/PowerOptimizationsViewModel.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Reflection;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Interfaces;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Infrastructure.Features.Common.Registry;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for power optimizations.\n /// \n public partial class PowerOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IPowerPlanService _powerPlanService;\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n [ObservableProperty]\n private int _powerPlanValue;\n\n [ObservableProperty]\n private bool _isApplyingPowerPlan;\n\n [ObservableProperty]\n private string _statusText = \"Power settings\";\n\n [ObservableProperty]\n private ObservableCollection _powerPlanLabels = new()\n {\n \"Balanced\",\n \"High Performance\",\n \"Ultimate Performance\"\n };\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The power plan service.\n /// The view model locator.\n /// The settings registry.\n public PowerOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IPowerPlanService powerPlanService,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService));\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n }\n\n /// \n /// Loads the power settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, \"Loading power settings\");\n\n // Initialize Power settings from PowerOptimizations.GetPowerOptimizations()\n Settings.Clear();\n\n // The Power Plan ComboBox is already defined in the XAML, so we don't need to add it to the Settings collection\n _logService.Log(LogLevel.Info, \"Power Plan ComboBox is defined in XAML\");\n\n // Get power optimizations from the new method\n var powerOptimizations = PowerOptimizations.GetPowerOptimizations();\n \n // Add items for each optimization setting\n foreach (var setting in powerOptimizations.Settings)\n {\n // Skip settings that use PowerCfg commands\n if (setting.CustomProperties != null &&\n setting.CustomProperties.ContainsKey(\"PowerCfgSettings\"))\n {\n _logService.Log(LogLevel.Info, $\"Skipping PowerCfg setting: {setting.Name} - hiding from UI\");\n continue; // Skip this setting\n }\n \n // Create a view model for each setting\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsUpdatingFromCode = true, // Set this to true to allow RefreshStatus to set the correct state\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = setting.ControlType\n };\n \n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Register the setting in the settings registry if available\n if (_settingsRegistry != null && !string.IsNullOrEmpty(settingItem.Id))\n {\n _settingsRegistry.RegisterSetting(settingItem);\n _logService.Log(LogLevel.Info, $\"Registered setting {settingItem.Id} in settings registry during creation\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Refresh status for all settings to populate LinkedRegistrySettingsWithValues\n foreach (var setting in Settings)\n {\n await setting.RefreshStatus();\n }\n\n // Set up power plan ComboBox\n await LoadCurrentPowerPlanAsync();\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading power settings: {ex.Message}\");\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Loads the current power plan and sets the ComboBox value accordingly.\n /// \n private async Task LoadCurrentPowerPlanAsync()\n {\n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));\n var cancellationToken = cancellationTokenSource.Token;\n \n try\n {\n _logService.Log(LogLevel.Info, \"Starting to load current power plan\");\n \n // Get the current active power plan GUID using the service with timeout\n var getPlanTask = _powerPlanService.GetActivePowerPlanGuidAsync();\n await Task.WhenAny(getPlanTask, Task.Delay(5000, cancellationToken));\n \n string activePlanGuid;\n if (getPlanTask.IsCompleted)\n {\n activePlanGuid = await getPlanTask;\n _logService.Log(LogLevel.Info, $\"Active power plan GUID: {activePlanGuid}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"GetActivePowerPlanGuidAsync timed out, defaulting to Balanced\");\n activePlanGuid = PowerOptimizations.PowerPlans.Balanced.Guid;\n cancellationTokenSource.Cancel();\n }\n \n // Get the Ultimate Performance GUID from the service\n string ultimatePerformanceGuid;\n var field = typeof(Winhance.Infrastructure.Features.Optimize.Services.PowerPlanService)\n .GetField(\"ULTIMATE_PERFORMANCE_PLAN_GUID\", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);\n \n if (field != null)\n {\n ultimatePerformanceGuid = (string)field.GetValue(null);\n _logService.Log(LogLevel.Info, $\"Ultimate Performance GUID from service: {ultimatePerformanceGuid}\");\n }\n else\n {\n ultimatePerformanceGuid = PowerOptimizations.PowerPlans.UltimatePerformance.Guid;\n _logService.Log(LogLevel.Warning, $\"Could not get Ultimate Performance GUID from service, using value from PowerOptimizations: {ultimatePerformanceGuid}\");\n }\n \n // Set the slider value based on the active plan\n if (activePlanGuid == PowerOptimizations.PowerPlans.Balanced.Guid)\n {\n // Use IsApplyingPowerPlan to prevent triggering ApplyPowerPlanAsync\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 0; // Balanced\n IsApplyingPowerPlan = wasApplying;\n _logService.Log(LogLevel.Info, \"Detected Balanced power plan\");\n }\n else if (activePlanGuid == PowerOptimizations.PowerPlans.HighPerformance.Guid)\n {\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 1; // High Performance\n IsApplyingPowerPlan = wasApplying;\n _logService.Log(LogLevel.Info, \"Detected High Performance power plan\");\n }\n else if (activePlanGuid == ultimatePerformanceGuid)\n {\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 2; // Ultimate Performance\n IsApplyingPowerPlan = wasApplying;\n _logService.Log(LogLevel.Info, \"Detected Ultimate Performance power plan\");\n }\n else\n {\n // Check if the active plan name contains \"Ultimate Performance\"\n var getPlansTask = _powerPlanService.GetAvailablePowerPlansAsync();\n await Task.WhenAny(getPlansTask, Task.Delay(5000, cancellationToken));\n \n if (getPlansTask.IsCompleted)\n {\n var allPlans = await getPlansTask;\n var activePlan = allPlans.FirstOrDefault(p => p.Guid == activePlanGuid);\n \n if (activePlan != null && activePlan.Name.Contains(\"Ultimate Performance\", StringComparison.OrdinalIgnoreCase))\n {\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 2; // Ultimate Performance\n IsApplyingPowerPlan = wasApplying;\n _logService.Log(LogLevel.Info, $\"Detected Ultimate Performance power plan by name: {activePlan.Name}\");\n \n // Update the static GUID for future reference\n if (field != null)\n {\n field.SetValue(null, activePlanGuid);\n _logService.Log(LogLevel.Info, $\"Updated Ultimate Performance GUID to: {activePlanGuid}\");\n }\n }\n else\n {\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 0; // Default to Balanced if unknown\n IsApplyingPowerPlan = wasApplying;\n _logService.Log(LogLevel.Warning, $\"Unknown power plan GUID: {activePlanGuid}, defaulting to Balanced\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"GetAvailablePowerPlansAsync timed out, defaulting to Balanced\");\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 0; // Default to Balanced\n IsApplyingPowerPlan = wasApplying;\n cancellationTokenSource.Cancel();\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Current power plan: {PowerPlanLabels[PowerPlanValue]} (Value: {PowerPlanValue})\");\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"Power plan loading was canceled due to timeout\");\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 0; // Default to Balanced on timeout\n IsApplyingPowerPlan = wasApplying;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading current power plan: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 0; // Default to Balanced on error\n IsApplyingPowerPlan = wasApplying;\n }\n }\n\n /// \n /// Called when the PowerPlanValue property changes.\n /// \n /// The new value.\n partial void OnPowerPlanValueChanged(int value)\n {\n // Only apply the power plan when not in the middle of applying a power plan\n // This prevents recursive calls and allows for importing without applying\n if (!IsApplyingPowerPlan)\n {\n _logService.Log(LogLevel.Info, $\"PowerPlanValue changed to {value}, applying power plan\");\n try\n {\n // Use ConfigureAwait(false) to avoid deadlocks\n ApplyPowerPlanAsync(value).ConfigureAwait(false);\n _logService.Log(LogLevel.Info, $\"Successfully initiated power plan change to {value}\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error initiating power plan change: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Info, $\"PowerPlanValue changed to {value}, but not applying because IsApplyingPowerPlan is true\");\n _logService.Log(LogLevel.Debug, $\"Stack trace at PowerPlanValue change: {Environment.StackTrace}\");\n }\n }\n\n /// \n /// Applies the selected power plan.\n /// \n /// The power plan index (0=Balanced, 1=High Performance, 2=Ultimate Performance).\n /// A task representing the asynchronous operation.\n [RelayCommand]\n private async Task ApplyPowerPlanAsync(int planIndex)\n {\n // Double-check to prevent recursive calls\n if (IsApplyingPowerPlan)\n {\n _logService.Log(LogLevel.Warning, $\"ApplyPowerPlanAsync called while IsApplyingPowerPlan is true, ignoring\");\n return;\n }\n \n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(15));\n var cancellationToken = cancellationTokenSource.Token;\n \n try\n {\n IsApplyingPowerPlan = true;\n StatusText = $\"Applying {PowerPlanLabels[planIndex]} power plan...\";\n \n // Get the appropriate GUID based on the selected plan\n string planGuid;\n \n // Special handling for Ultimate Performance plan\n if (planIndex == 2) // Ultimate Performance\n {\n // Get the GUID from the service directly\n // This ensures we're using the most up-to-date GUID that might have been created dynamically\n var field = typeof(Winhance.Infrastructure.Features.Optimize.Services.PowerPlanService)\n .GetField(\"ULTIMATE_PERFORMANCE_PLAN_GUID\", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);\n \n if (field != null)\n {\n planGuid = (string)field.GetValue(null);\n _logService.Log(LogLevel.Info, $\"Using Ultimate Performance GUID from service: {planGuid}\");\n }\n else\n {\n // Fallback to the value from PowerOptimizations\n planGuid = PowerOptimizations.PowerPlans.UltimatePerformance.Guid;\n _logService.Log(LogLevel.Warning, $\"Could not get GUID from service, using value from PowerOptimizations: {planGuid}\");\n }\n }\n else\n {\n // For other plans, use the standard GUIDs\n planGuid = planIndex switch\n {\n 0 => PowerOptimizations.PowerPlans.Balanced.Guid,\n 1 => PowerOptimizations.PowerPlans.HighPerformance.Guid,\n _ => PowerOptimizations.PowerPlans.Balanced.Guid // Default to Balanced\n };\n }\n \n _logService.Log(LogLevel.Info, $\"Applying power plan: {PowerPlanLabels[planIndex]} with GUID: {planGuid}\");\n \n // Use the service to set the power plan with timeout\n var setPlanTask = _powerPlanService.SetPowerPlanAsync(planGuid);\n var timeoutTask = Task.Delay(10000, cancellationToken); // 10 second timeout\n \n await Task.WhenAny(setPlanTask, timeoutTask);\n \n if (setPlanTask.IsCompleted)\n {\n bool success = await setPlanTask;\n \n if (success)\n {\n _logService.Log(LogLevel.Info, $\"Power plan set to {PowerPlanLabels[planIndex]} ({planGuid})\");\n StatusText = $\"{PowerPlanLabels[planIndex]} power plan applied\";\n \n // Refresh the current power plan to ensure the UI is updated correctly\n var loadTask = LoadCurrentPowerPlanAsync();\n await Task.WhenAny(loadTask, Task.Delay(5000, cancellationToken));\n \n if (!loadTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"LoadCurrentPowerPlanAsync timed out, continuing anyway\");\n }\n \n // Refresh all PowerCfg settings to reflect the new power plan\n _logService.Log(LogLevel.Info, \"Refreshing PowerCfg settings after power plan change\");\n var checkTask = CheckSettingStatusesAsync();\n await Task.WhenAny(checkTask, Task.Delay(5000, cancellationToken));\n \n if (!checkTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"CheckSettingStatusesAsync timed out, continuing anyway\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Failed to set power plan to {PowerPlanLabels[planIndex]} ({planGuid})\");\n StatusText = $\"Failed to apply {PowerPlanLabels[planIndex]} power plan\";\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Setting power plan timed out after 10 seconds\");\n StatusText = $\"Timeout while applying {PowerPlanLabels[planIndex]} power plan\";\n \n // Cancel the operation\n cancellationTokenSource.Cancel();\n }\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"Power plan application was canceled due to timeout\");\n StatusText = \"Power plan application timed out\";\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying power plan: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n StatusText = $\"Error applying power plan: {ex.Message}\";\n }\n finally\n {\n // Make sure we always reset IsApplyingPowerPlan to false when done\n IsApplyingPowerPlan = false;\n _logService.Log(LogLevel.Info, \"Reset IsApplyingPowerPlan to false in ApplyPowerPlanAsync\");\n }\n }\n\n /// \n /// Checks the status of all power settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, $\"Checking status for {Settings.Count} power settings\");\n\n foreach (var setting in Settings)\n {\n try\n {\n // Check if this is a command-based setting with PowerCfg settings\n bool isCommandBasedSetting = setting.CustomProperties != null &&\n setting.CustomProperties.ContainsKey(\"PowerCfgSettings\") &&\n setting.CustomProperties[\"PowerCfgSettings\"] is List;\n\n if (isCommandBasedSetting)\n {\n _logService.Log(LogLevel.Info, $\"Checking command-based setting status for: {setting.Name}\");\n \n // Get PowerCfg settings from CustomProperties\n var powerCfgSettings = setting.CustomProperties[\"PowerCfgSettings\"] as List;\n \n try\n {\n // Special handling for Desktop Slideshow setting\n bool isDesktopSlideshowSetting = setting.Name.Contains(\"Desktop Slideshow\", StringComparison.OrdinalIgnoreCase);\n \n // Check if all PowerCfg settings are applied\n bool allApplied = await _powerPlanService.AreAllPowerCfgSettingsAppliedAsync(powerCfgSettings);\n \n // Update setting status based on PowerCfg settings\n setting.Status = allApplied ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n \n // Set a more descriptive current value\n if (isDesktopSlideshowSetting)\n {\n // For Desktop Slideshow, the value is counter-intuitive\n // When enabled (IsSelected=true), the slideshow is \"Available\" (value=0)\n // When disabled (IsSelected=false), the slideshow is \"Paused\" (value=1)\n setting.CurrentValue = allApplied ? \"Available\" : \"Paused\";\n }\n else\n {\n setting.CurrentValue = allApplied ? \"Enabled\" : \"Disabled\";\n }\n \n // Set status message with more detailed information\n setting.StatusMessage = allApplied\n ? \"This setting is currently applied.\"\n : \"This setting is not currently applied.\";\n \n _logService.Log(LogLevel.Info, $\"Command-based setting {setting.Name} status: {setting.Status}, isApplied={allApplied}, currentValue={setting.CurrentValue}\");\n \n // Update IsSelected to match the detected state\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = allApplied;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking PowerCfg setting status for {setting.Name}: {ex.Message}\");\n \n // On error, assume the setting is in its default state\n setting.Status = RegistrySettingStatus.NotApplied;\n setting.CurrentValue = \"Unknown\";\n setting.StatusMessage = \"Could not determine the current status of this setting.\";\n }\n }\n else if (setting.RegistrySetting != null)\n {\n _logService.Log(LogLevel.Info, $\"Checking registry-based setting status for: {setting.Name}\");\n\n // Get the status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // Get the current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name}: {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n setting.LinkedRegistrySettingsWithValues.Clear();\n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Checking linked registry settings status for: {setting.Name} with {setting.LinkedRegistrySettings.Settings.Count} registry entries\");\n\n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(regSetting.Hive);\n string fullPath = $\"{hiveString}\\\\{regSetting.SubKey}\";\n _logService.Log(LogLevel.Info, $\"Registry entry: {fullPath}\\\\{regSetting.Name}, EnabledValue={regSetting.EnabledValue}, DisabledValue={regSetting.DisabledValue}\");\n\n // Check if the key exists\n bool keyExists = _registryService.KeyExists(fullPath);\n _logService.Log(LogLevel.Info, $\"Key exists: {keyExists}\");\n\n if (keyExists)\n {\n // Check if the value exists and get its current value\n var currentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value: {currentValue ?? \"null\"}\");\n }\n }\n\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n _logService.Log(LogLevel.Info, $\"Combined status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name} (first entry): {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value for linked setting {regSetting.Name}: {regCurrentValue ?? \"null\"}\");\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry setting or command-based setting found for {setting.Name}\");\n setting.Status = RegistrySettingStatus.Unknown;\n setting.StatusMessage = \"Setting information is missing\";\n }\n\n // If this is a grouped setting, update child settings too\n if (setting.IsGroupedSetting && setting.ChildSettings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Updating {setting.ChildSettings.Count} child settings for {setting.Name}\");\n foreach (var childSetting in setting.ChildSettings)\n {\n // Check if this is a command-based child setting\n bool isCommandBasedChildSetting = childSetting.CustomProperties != null &&\n childSetting.CustomProperties.ContainsKey(\"PowerCfgSettings\") &&\n childSetting.CustomProperties[\"PowerCfgSettings\"] is List;\n\n if (isCommandBasedChildSetting)\n {\n try\n {\n var powerCfgSettings = childSetting.CustomProperties[\"PowerCfgSettings\"] as List;\n \n // Special handling for Desktop Slideshow setting\n bool isDesktopSlideshowSetting = childSetting.Name.Contains(\"Desktop Slideshow\", StringComparison.OrdinalIgnoreCase);\n \n bool allApplied = await _powerPlanService.AreAllPowerCfgSettingsAppliedAsync(powerCfgSettings);\n \n childSetting.Status = allApplied ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n \n // Set a more descriptive current value\n if (isDesktopSlideshowSetting)\n {\n childSetting.CurrentValue = allApplied ? \"Available\" : \"Paused\";\n }\n else\n {\n childSetting.CurrentValue = allApplied ? \"Enabled\" : \"Disabled\";\n }\n \n childSetting.StatusMessage = allApplied\n ? \"This setting is currently applied.\"\n : \"This setting is not currently applied.\";\n \n // Update IsSelected based on status\n childSetting.IsUpdatingFromCode = true;\n try\n {\n childSetting.IsSelected = allApplied;\n }\n finally\n {\n childSetting.IsUpdatingFromCode = false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking PowerCfg setting status for child setting {childSetting.Name}: {ex.Message}\");\n \n // On error, assume the setting is in its default state\n childSetting.Status = RegistrySettingStatus.NotApplied;\n childSetting.CurrentValue = \"Unknown\";\n childSetting.StatusMessage = \"Could not determine the current status of this setting.\";\n }\n }\n else if (childSetting.RegistrySetting != null)\n {\n var status = await _registryService.GetSettingStatusAsync(childSetting.RegistrySetting);\n childSetting.Status = status;\n\n var currentValue = await _registryService.GetCurrentValueAsync(childSetting.RegistrySetting);\n childSetting.CurrentValue = currentValue;\n\n childSetting.StatusMessage = GetStatusMessage(childSetting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Child setting {childSetting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n childSetting.IsUpdatingFromCode = true;\n try\n {\n childSetting.IsSelected = shouldBeSelected;\n }\n finally\n {\n childSetting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating status for setting {setting.Name}: {ex.Message}\");\n setting.Status = RegistrySettingStatus.Error;\n setting.StatusMessage = $\"Error: {ex.Message}\";\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking power setting statuses: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0)\n return;\n\n var selectedCount = Settings.Count(setting => setting.IsSelected);\n IsSelected = selectedCount == Settings.Count;\n }\n\n /// \n /// Applies a registry setting with the specified value.\n /// \n /// The registry setting to apply.\n /// The value to set.\n /// A task representing the asynchronous operation.\n private async Task ApplyRegistrySetting(RegistrySetting registrySetting, object value)\n {\n string hiveString = registrySetting.Hive.ToString();\n if (hiveString == \"LocalMachine\") hiveString = \"HKLM\";\n else if (hiveString == \"CurrentUser\") hiveString = \"HKCU\";\n else if (hiveString == \"ClassesRoot\") hiveString = \"HKCR\";\n else if (hiveString == \"Users\") hiveString = \"HKU\";\n else if (hiveString == \"CurrentConfig\") hiveString = \"HKCC\";\n\n string fullPath = $\"{hiveString}\\\\{registrySetting.SubKey}\";\n \n if (value == null)\n {\n await _registryService.DeleteValue(registrySetting.Hive, registrySetting.SubKey, registrySetting.Name);\n }\n else\n {\n _registryService.SetValue(fullPath, registrySetting.Name, value, registrySetting.ValueType);\n }\n }\n\n /// \n /// Gets a user-friendly status message for a setting.\n /// \n /// The setting to get the status message for.\n /// A user-friendly status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied =>\n \"This setting is already applied with the recommended value.\",\n\n RegistrySettingStatus.NotApplied =>\n setting.CurrentValue == null\n ? \"This setting is not applied (registry value does not exist).\"\n : \"This setting is using the default value.\",\n\n RegistrySettingStatus.Modified =>\n \"This setting has a custom value that differs from the recommended value.\",\n\n RegistrySettingStatus.Error =>\n \"An error occurred while checking this setting's status.\",\n\n _ => \"The status of this setting is unknown.\"\n };\n }\n\n /// \n /// Converts a tuple to a RegistrySetting object.\n /// \n /// The key for the setting.\n /// The tuple containing the setting information.\n /// A RegistrySetting object.\n private RegistrySetting ConvertToRegistrySetting(string key, (string Path, string Name, object Value, Microsoft.Win32.RegistryValueKind ValueKind) settingTuple)\n {\n // Determine the registry hive from the path\n RegistryHive hive = RegistryHive.LocalMachine; // Default to HKLM\n if (settingTuple.Path.StartsWith(\"HKEY_CURRENT_USER\") || settingTuple.Path.StartsWith(\"HKCU\") || settingTuple.Path.StartsWith(\"Software\\\\\"))\n {\n hive = RegistryHive.CurrentUser;\n }\n else if (settingTuple.Path.StartsWith(\"HKEY_LOCAL_MACHINE\") || settingTuple.Path.StartsWith(\"HKLM\"))\n {\n hive = RegistryHive.LocalMachine;\n }\n else if (settingTuple.Path.StartsWith(\"HKEY_CLASSES_ROOT\") || settingTuple.Path.StartsWith(\"HKCR\"))\n {\n hive = RegistryHive.ClassesRoot;\n }\n else if (settingTuple.Path.StartsWith(\"HKEY_USERS\") || settingTuple.Path.StartsWith(\"HKU\"))\n {\n hive = RegistryHive.Users;\n }\n else if (settingTuple.Path.StartsWith(\"HKEY_CURRENT_CONFIG\") || settingTuple.Path.StartsWith(\"HKCC\"))\n {\n hive = RegistryHive.CurrentConfig;\n }\n\n // Clean up the path to remove any hive prefix\n string subKey = settingTuple.Path;\n if (subKey.StartsWith(\"HKEY_CURRENT_USER\\\\\") || subKey.StartsWith(\"HKCU\\\\\"))\n {\n subKey = subKey.Replace(\"HKEY_CURRENT_USER\\\\\", \"\").Replace(\"HKCU\\\\\", \"\");\n }\n else if (subKey.StartsWith(\"HKEY_LOCAL_MACHINE\\\\\") || subKey.StartsWith(\"HKLM\\\\\"))\n {\n subKey = subKey.Replace(\"HKEY_LOCAL_MACHINE\\\\\", \"\").Replace(\"HKLM\\\\\", \"\");\n }\n else if (subKey.StartsWith(\"HKEY_CLASSES_ROOT\\\\\") || subKey.StartsWith(\"HKCR\\\\\"))\n {\n subKey = subKey.Replace(\"HKEY_CLASSES_ROOT\\\\\", \"\").Replace(\"HKCR\\\\\", \"\");\n }\n else if (subKey.StartsWith(\"HKEY_USERS\\\\\") || subKey.StartsWith(\"HKU\\\\\"))\n {\n subKey = subKey.Replace(\"HKEY_USERS\\\\\", \"\").Replace(\"HKU\\\\\", \"\");\n }\n else if (subKey.StartsWith(\"HKEY_CURRENT_CONFIG\\\\\") || subKey.StartsWith(\"HKCC\\\\\"))\n {\n subKey = subKey.Replace(\"HKEY_CURRENT_CONFIG\\\\\", \"\").Replace(\"HKCC\\\\\", \"\");\n }\n\n // Create and return the RegistrySetting object\n var registrySetting = new RegistrySetting\n {\n Category = \"Power\",\n Hive = hive,\n SubKey = subKey,\n Name = settingTuple.Name,\n EnabledValue = settingTuple.Value, // Recommended value becomes EnabledValue\n DisabledValue = settingTuple.Value,\n ValueType = settingTuple.ValueKind,\n // Keep these for backward compatibility\n RecommendedValue = settingTuple.Value,\n DefaultValue = settingTuple.Value,\n Description = $\"Power setting: {key}\"\n };\n\n return registrySetting;\n }\n\n /// \n /// Gets a friendly name for a power setting.\n /// \n /// The power setting key.\n /// A user-friendly name for the power setting.\n private string GetFriendlyNameForPowerSetting(string key)\n {\n return key switch\n {\n \"HibernateEnabled\" => \"Disable Hibernate\",\n \"HibernateEnabledDefault\" => \"Disable Hibernate by Default\",\n \"VideoQuality\" => \"High Video Quality on Battery\",\n \"LockOption\" => \"Hide Lock Option\",\n \"FastBoot\" => \"Disable Fast Boot\",\n \"CpuUnpark\" => \"CPU Core Unparking\",\n \"PowerThrottling\" => \"Disable Power Throttling\",\n _ => key\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IInternetConnectivityService.cs", "using System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for services that check and monitor internet connectivity.\n /// \n public interface IInternetConnectivityService\n {\n /// \n /// Checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// True if internet is connected, false otherwise.\n bool IsInternetConnected(bool forceCheck = false);\n\n /// \n /// Asynchronously checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// Cancellation token for the operation.\n /// True if internet is connected, false otherwise.\n Task IsInternetConnectedAsync(bool forceCheck = false, CancellationToken cancellationToken = default, bool userInitiatedCancellation = false);\n \n /// \n /// Event that is raised when the internet connectivity status changes.\n /// \n event EventHandler ConnectivityChanged;\n \n /// \n /// Starts monitoring internet connectivity at the specified interval.\n /// \n /// The interval in seconds between connectivity checks.\n /// Cancellation token to stop monitoring.\n /// A task representing the monitoring operation.\n Task StartMonitoringAsync(int intervalSeconds = 5, CancellationToken cancellationToken = default);\n \n /// \n /// Stops monitoring internet connectivity.\n /// \n void StopMonitoring();\n }\n \n /// \n /// Event arguments for connectivity change events.\n /// \n public class ConnectivityChangedEventArgs : EventArgs\n {\n /// \n /// Gets a value indicating whether the internet is connected.\n /// \n public bool IsConnected { get; }\n \n /// \n /// Gets a value indicating whether the connectivity change was due to user cancellation.\n /// \n public bool IsUserCancelled { get; }\n \n /// \n /// Gets the timestamp when the connectivity status changed.\n /// \n public DateTime Timestamp { get; }\n \n /// \n /// Initializes a new instance of the class.\n /// \n /// Whether the internet is connected.\n /// Whether the connectivity change was due to user cancellation.\n public ConnectivityChangedEventArgs(bool isConnected, bool isUserCancelled = false)\n {\n IsConnected = isConnected;\n IsUserCancelled = isUserCancelled;\n Timestamp = DateTime.Now;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/CapabilityRemovalService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service for removing Windows capabilities from the system.\n/// \npublic class CapabilityRemovalService : ICapabilityRemovalService\n{\n private readonly ILogService _logService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IScheduledTaskService _scheduledTaskService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The app discovery service.\n /// The scheduled task service.\n public CapabilityRemovalService(\n ILogService logService,\n IAppDiscoveryService appDiscoveryService,\n IScheduledTaskService scheduledTaskService)\n {\n _logService = logService;\n _appDiscoveryService = appDiscoveryService;\n _scheduledTaskService = scheduledTaskService;\n }\n\n /// \n public async Task RemoveCapabilityAsync(\n CapabilityInfo capabilityInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (capabilityInfo == null)\n {\n throw new ArgumentNullException(nameof(capabilityInfo));\n }\n // Call the other overload and return its result\n return await RemoveCapabilityAsync(capabilityInfo.PackageName, progress, cancellationToken);\n }\n\n /// \n public async Task RemoveCapabilityAsync(\n string capabilityName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n try\n {\n progress?.Report(new TaskProgressDetail { Progress = 0, StatusText = $\"Starting removal of {capabilityName}...\" });\n _logService.LogInformation($\"Removing capability: {capabilityName}\");\n \n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n \n // Step 1: Get a list of all installed capabilities that match the pattern\n List capabilityNames = new List();\n try\n {\n powerShell.Commands.Clear();\n powerShell.AddScript($@\"\n Get-WindowsCapability -Online |\n Where-Object {{ $_.Name -like '{capabilityName}*' }} |\n Select-Object -ExpandProperty Name\n \");\n\n capabilityNames = (await Task.Run(() => powerShell.Invoke())).ToList();\n _logService.LogInformation($\"Found {capabilityNames.Count} capabilities matching '{capabilityName}*'\");\n \n // Log the found capabilities\n foreach (var capName in capabilityNames)\n {\n _logService.LogInformation($\"Found installed capability: {capName}\");\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error retrieving Windows capabilities for '{capabilityName}': {ex.Message}. Will proceed with empty capability list.\");\n // Continue with empty capability list\n }\n\n // If no capabilities found with exact name, try with a more flexible pattern\n if (capabilityNames == null || !capabilityNames.Any())\n {\n try\n {\n // Try with a more flexible pattern that might include tildes\n powerShell.Commands.Clear();\n powerShell.AddScript($@\"\n Get-WindowsCapability -Online |\n Where-Object {{ $_.Name -match '{capabilityName}' }} |\n Select-Object -ExpandProperty Name\n \");\n\n capabilityNames = (await Task.Run(() => powerShell.Invoke())).ToList();\n _logService.LogInformation($\"Found {capabilityNames.Count} capabilities with flexible pattern matching '{capabilityName}'\");\n \n // Log the found capabilities\n foreach (var capName in capabilityNames)\n {\n _logService.LogInformation($\"Found installed capability with flexible pattern: {capName}\");\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error retrieving capabilities with flexible pattern: {ex.Message}\");\n }\n }\n\n bool overallSuccess = true;\n \n if (capabilityNames != null && capabilityNames.Any())\n {\n int totalCapabilities = capabilityNames.Count;\n int currentCapability = 0;\n \n foreach (var capName in capabilityNames)\n {\n currentCapability++;\n progress?.Report(new TaskProgressDetail {\n Progress = (currentCapability * 100) / totalCapabilities,\n StatusText = $\"Removing capability {currentCapability} of {totalCapabilities}: {capName}\"\n });\n \n _logService.LogInformation($\"Removing installed capability: {capName}\");\n\n // Step 2: Remove the capability\n bool success = false;\n try\n {\n powerShell.Commands.Clear();\n powerShell.AddScript($@\"\n Remove-WindowsCapability -Name '{capName}' -Online -ErrorAction SilentlyContinue\n return $?\n \");\n\n var result = await Task.Run(() => powerShell.Invoke());\n success = result.FirstOrDefault();\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing capability '{capName}': {ex.Message}\");\n success = false;\n }\n\n if (success)\n {\n _logService.LogSuccess($\"Successfully removed capability: {capName}\");\n }\n else\n {\n _logService.LogError($\"Failed to remove capability: {capName}\");\n overallSuccess = false;\n }\n }\n \n // Update BloatRemoval.ps1 script and register scheduled task\n if (overallSuccess)\n {\n try\n {\n // Pass the full capability names (with version numbers) to the script update service\n var script = await UpdateBloatRemovalScriptAsync(capabilityNames);\n \n // Register the scheduled task to run the script at startup\n try\n {\n bool taskRegistered = await RegisterBloatRemovalTaskAsync(script);\n if (taskRegistered)\n {\n _logService.LogSuccess($\"Scheduled task registered for BloatRemoval.ps1\");\n }\n else\n {\n _logService.LogWarning($\"Failed to register scheduled task for BloatRemoval.ps1, but continuing operation\");\n }\n }\n catch (Exception taskEx)\n {\n _logService.LogError($\"Error registering scheduled task: {taskEx.Message}\");\n // Don't fail the removal if task registration fails\n }\n }\n catch (Exception scriptEx)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script: {scriptEx.Message}\");\n // Don't fail the removal if script update fails\n }\n }\n \n progress?.Report(new TaskProgressDetail {\n Progress = 100,\n StatusText = overallSuccess ? $\"Successfully removed all capabilities\" : $\"Some capabilities could not be removed\",\n DetailedMessage = $\"Removed {capabilityNames.Count} capabilities matching {capabilityName}\",\n LogLevel = overallSuccess ? LogLevel.Success : LogLevel.Warning\n });\n \n return overallSuccess;\n }\n else\n {\n _logService.LogInformation($\"No installed capabilities found matching: {capabilityName}*\");\n progress?.Report(new TaskProgressDetail {\n Progress = 100,\n StatusText = $\"No installed capabilities found matching: {capabilityName}*\",\n LogLevel = LogLevel.Warning\n });\n \n // Consider it a success if nothing needs to be removed\n return true;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing capability: {capabilityName}\", ex);\n progress?.Report(new TaskProgressDetail {\n Progress = 0,\n StatusText = $\"Error removing {capabilityName}: {ex.Message}\",\n LogLevel = LogLevel.Error\n });\n return false;\n }\n }\n\n // Add missing CanRemoveCapabilityAsync method\n /// \n public Task CanRemoveCapabilityAsync(CapabilityInfo capabilityInfo)\n {\n // Basic implementation: Assume all found capabilities can be removed.\n // TODO: Add actual checks if needed (e.g., dependencies)\n return Task.FromResult(true);\n }\n\n\n /// \n public async Task> RemoveCapabilitiesInBatchAsync(\n List capabilities)\n {\n if (capabilities == null)\n {\n throw new ArgumentNullException(nameof(capabilities));\n }\n\n return await RemoveCapabilitiesInBatchAsync(capabilities.Select(c => c.PackageName).ToList());\n }\n\n /// \n public async Task> RemoveCapabilitiesInBatchAsync(\n List capabilityNames)\n {\n var results = new List<(string Name, bool Success, string? Error)>();\n \n try\n {\n _logService.LogInformation($\"Removing {capabilityNames.Count} Windows capabilities\");\n \n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n \n foreach (var capability in capabilityNames)\n {\n try\n {\n _logService.LogInformation($\"Removing capability: {capability}\");\n \n // Step 1: Get a list of all installed capabilities that match the pattern\n List matchingCapabilities = new List();\n try\n {\n powerShell.Commands.Clear();\n powerShell.AddScript($@\"\n Get-WindowsCapability -Online |\n Where-Object {{ $_.Name -like '{capability}*' -and $_.State -eq 'Installed' }} |\n Select-Object -ExpandProperty Name\n \");\n\n matchingCapabilities = (await Task.Run(() => powerShell.Invoke())).ToList();\n _logService.LogInformation($\"Found {matchingCapabilities.Count} capabilities matching '{capability}*' for batch removal\");\n \n // Log the found capabilities\n foreach (var capName in matchingCapabilities)\n {\n _logService.LogInformation($\"Found installed capability for batch removal: {capName}\");\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error retrieving Windows capabilities for batch removal '{capability}': {ex.Message}. Will proceed with empty capability list.\");\n // Continue with empty capability list\n }\n\n bool success = true;\n string? error = null;\n \n if (matchingCapabilities != null && matchingCapabilities.Any())\n {\n foreach (var capName in matchingCapabilities)\n {\n _logService.LogInformation($\"Removing installed capability in batch: {capName}\");\n\n // Step 2: Remove the capability\n bool capSuccess = false;\n try\n {\n powerShell.Commands.Clear();\n powerShell.AddScript($@\"\n Remove-WindowsCapability -Name '{capName}' -Online -ErrorAction SilentlyContinue\n return $?\n \");\n\n var capResult = await Task.Run(() => powerShell.Invoke());\n capSuccess = capResult.FirstOrDefault();\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing capability in batch '{capName}': {ex.Message}\");\n capSuccess = false;\n }\n\n if (capSuccess)\n {\n _logService.LogSuccess($\"Successfully removed capability in batch: {capName}\");\n }\n else\n {\n _logService.LogError($\"Failed to remove capability in batch: {capName}\");\n success = false;\n error = $\"Failed to remove one or more capabilities\";\n }\n }\n }\n else\n {\n _logService.LogInformation($\"No installed capabilities found matching for batch removal: {capability}*\");\n // Consider it a success if nothing needs to be removed\n success = true;\n }\n \n // If successful, update the BloatRemoval.ps1 script with the full capability names\n if (success && matchingCapabilities.Any())\n {\n try\n {\n await UpdateBloatRemovalScriptAsync(matchingCapabilities);\n _logService.LogInformation($\"Updated BloatRemoval.ps1 script with full capability names for batch removal\");\n }\n catch (Exception scriptEx)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for batch capability removal: {scriptEx.Message}\");\n // Don't fail the removal if script update fails\n }\n }\n \n results.Add((capability, success, error));\n }\n catch (Exception ex)\n {\n results.Add((capability, false, ex.Message));\n _logService.LogError($\"Error removing capability: {capability}\", ex);\n }\n }\n \n return results;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error removing capabilities\", ex);\n return capabilityNames.Select(c => (c, false, $\"Error: {ex.Message}\")).ToList();\n }\n }\n\n // SetExecutionPolicy is now handled by PowerShellFactory\n /// \n /// Updates the BloatRemoval.ps1 script to add the removed capabilities to it.\n /// \n /// The list of capability names with version numbers.\n /// The updated removal script.\n private async Task UpdateBloatRemovalScriptAsync(List capabilityNames)\n {\n try\n {\n // Get the script update service\n var scriptUpdateService = GetScriptUpdateService();\n if (scriptUpdateService == null)\n {\n _logService.LogWarning(\"Script update service not available\");\n throw new InvalidOperationException(\"Script update service not available\");\n }\n \n // Update the script with the full capability names (including version numbers)\n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n \n _logService.LogInformation($\"Updating BloatRemoval.ps1 script for {capabilityNames.Count} capabilities\");\n \n try\n {\n var script = await scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n capabilityNames,\n appsWithRegistry,\n appSubPackages,\n false); // false = removal operation, so add to script\n \n _logService.LogInformation($\"Successfully updated BloatRemoval.ps1 script for capabilities\");\n return script;\n }\n catch (FileNotFoundException)\n {\n _logService.LogInformation($\"BloatRemoval.ps1 script not found. It will be created when needed.\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in script update service for capabilities: {ex.Message}\", ex);\n throw;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for capabilities: {ex.Message}\", ex);\n throw;\n }\n }\n\n /// \n /// Updates the BloatRemoval.ps1 script to add the removed capability to it.\n /// \n /// The capability name.\n /// The updated removal script.\n private async Task UpdateBloatRemovalScriptAsync(string capabilityName)\n {\n try\n {\n // Get the script update service\n var scriptUpdateService = GetScriptUpdateService();\n if (scriptUpdateService == null)\n {\n _logService.LogWarning(\"Script update service not available\");\n throw new InvalidOperationException(\"Script update service not available\");\n }\n \n // Update the script\n var appNames = new List { capabilityName };\n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n \n _logService.LogInformation($\"Updating BloatRemoval.ps1 script for capability: {capabilityName}\");\n \n try\n {\n var script = await scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n false); // false = removal operation, so add to script\n \n _logService.LogInformation($\"Successfully updated BloatRemoval.ps1 script for capability: {capabilityName}\");\n return script;\n }\n catch (FileNotFoundException)\n {\n _logService.LogInformation($\"BloatRemoval.ps1 script not found. It will be created when needed.\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in script update service for capability: {capabilityName}\", ex);\n throw;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for capability: {capabilityName}\", ex);\n throw;\n }\n }\n /// \n /// Registers a scheduled task to run the BloatRemoval script at startup.\n /// \n /// The removal script to register.\n /// True if the task was registered successfully, false otherwise.\n private async Task RegisterBloatRemovalTaskAsync(RemovalScript script)\n {\n try\n {\n if (script == null)\n {\n _logService.LogError(\"Cannot register scheduled task: Script is null\");\n return false;\n }\n \n _logService.LogInformation(\"Registering scheduled task for BloatRemoval.ps1\");\n \n \n // Register the scheduled task\n bool success = await _scheduledTaskService.RegisterScheduledTaskAsync(script);\n \n if (success)\n {\n _logService.LogSuccess(\"Successfully registered scheduled task for BloatRemoval.ps1\");\n }\n else\n {\n _logService.LogError(\"Failed to register scheduled task for BloatRemoval.ps1\");\n }\n \n return success;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error registering scheduled task for BloatRemoval.ps1\", ex);\n return false;\n }\n }\n \n /// \n /// Gets the script update service.\n /// \n /// The script update service or null if not available.\n private IScriptUpdateService? GetScriptUpdateService()\n {\n try\n {\n // This is a simplified implementation. In a real application, you would use dependency injection.\n // For now, we'll create a new instance directly.\n // Use the injected _appDiscoveryService instead of creating a new instance\n var scriptContentModifier = new ScriptContentModifier(_logService);\n return new ScriptUpdateService(_logService, _appDiscoveryService, scriptContentModifier);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to get script update service\", ex);\n return null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/OptimizeViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Linq;\nusing System.Windows.Controls;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.Customize.Enums;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.Common.Messages;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for the OptimizeView that manages system optimization settings.\n /// \n public partial class OptimizeViewModel : SearchableViewModel\n {\n private readonly IRegistryService _registryService;\n private readonly IDialogService _dialogService;\n private readonly ILogService _logService;\n private readonly IConfigurationService _configurationService;\n private readonly IMessengerService _messengerService;\n private List _allItemsBackup = new List();\n private bool _updatingCheckboxes;\n private bool _isInitialSearchDone = false;\n \n /// \n /// Gets or sets a value indicating whether the view model is initialized.\n /// \n [ObservableProperty]\n private bool _isInitialized;\n \n /// \n /// Gets or sets a value indicating whether search has any results.\n /// \n [ObservableProperty]\n private bool _hasSearchResults = true;\n \n /// \n /// Gets or sets the status text.\n /// \n [ObservableProperty]\n private string _statusText = \"Optimize Your Windows Settings and Performance\";\n \n // Override the SearchText property to add explicit notification and direct control over the search flow\n private string _searchTextOverride = string.Empty;\n public override string SearchText\n {\n get => _searchTextOverride;\n set\n {\n if (_searchTextOverride != value)\n {\n _searchTextOverride = value;\n OnPropertyChanged(nameof(SearchText));\n LogInfo($\"OptimizeViewModel: SearchText changed to: '{value}'\");\n \n // Explicitly update IsSearchActive and call ApplySearch\n IsSearchActive = !string.IsNullOrWhiteSpace(value);\n ApplySearch();\n \n // Update status text based on search results\n if (IsSearchActive)\n {\n StatusText = $\"Found {Items.Count} settings matching '{value}'\";\n }\n else\n {\n StatusText = \"Optimize Your Windows Settings and Performance\";\n }\n }\n }\n }\n\n /// \n /// Gets the messenger service.\n /// \n public IMessengerService MessengerService => _messengerService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The registry service for interacting with the Windows Registry.\n /// The dialog service for showing dialogs.\n /// The logging service.\n /// The progress service.\n /// The search service.\n /// The configuration service.\n /// The gaming settings view model.\n /// The privacy optimizations view model.\n /// The update optimizations view model.\n /// The power settings view model.\n /// The Windows security optimizations view model.\n /// The explorer optimizations view model.\n /// The notification optimizations view model.\n /// The sound optimizations view model.\n /// The messenger service.\n\n public OptimizeViewModel(\n IRegistryService registryService,\n IDialogService dialogService,\n ILogService logService,\n ITaskProgressService progressService,\n ISearchService searchService,\n IConfigurationService configurationService,\n GamingandPerformanceOptimizationsViewModel gamingSettings,\n PrivacyOptimizationsViewModel privacySettings,\n UpdateOptimizationsViewModel updateSettings,\n PowerOptimizationsViewModel powerSettings,\n WindowsSecurityOptimizationsViewModel windowsSecuritySettings,\n ExplorerOptimizationsViewModel explorerSettings,\n NotificationOptimizationsViewModel notificationSettings,\n SoundOptimizationsViewModel soundSettings,\n IMessengerService messengerService)\n : base(progressService, searchService, null)\n {\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _messengerService = messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n\n // Set specialized view models\n GamingandPerformanceOptimizationsViewModel = gamingSettings ?? throw new ArgumentNullException(nameof(gamingSettings));\n PrivacyOptimizationsViewModel = privacySettings ?? throw new ArgumentNullException(nameof(privacySettings));\n UpdateOptimizationsViewModel = updateSettings ?? throw new ArgumentNullException(nameof(updateSettings));\n PowerSettingsViewModel = powerSettings ?? throw new ArgumentNullException(nameof(powerSettings));\n WindowsSecuritySettingsViewModel = windowsSecuritySettings ?? throw new ArgumentNullException(nameof(windowsSecuritySettings));\n ExplorerOptimizationsViewModel = explorerSettings ?? throw new ArgumentNullException(nameof(explorerSettings));\n NotificationOptimizationsViewModel = notificationSettings ?? throw new ArgumentNullException(nameof(notificationSettings));\n SoundOptimizationsViewModel = soundSettings ?? throw new ArgumentNullException(nameof(soundSettings));\n\n // Store the configuration service\n _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));\n\n // Create initialize command\n InitializeCommand = new AsyncRelayCommand(InitializeAsync);\n\n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n\n // We'll initialize when explicitly called, not automatically\n // This ensures the loading screen stays visible until initialization is complete\n\n }\n\n /// \n /// Gets the command to initialize the view model.\n /// \n public IAsyncRelayCommand InitializeCommand { get; }\n\n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n\n /// \n /// Gets the gaming settings view model.\n /// \n public GamingandPerformanceOptimizationsViewModel GamingandPerformanceOptimizationsViewModel { get; }\n\n /// \n /// Gets the privacy optimizations view model.\n /// \n public PrivacyOptimizationsViewModel PrivacyOptimizationsViewModel { get; }\n\n /// \n /// Gets the updates optimizations view model.\n /// \n public UpdateOptimizationsViewModel UpdateOptimizationsViewModel { get; }\n\n /// \n /// Gets the power settings view model.\n /// \n public PowerOptimizationsViewModel PowerSettingsViewModel { get; }\n\n /// \n /// Gets the Windows security optimizations view model.\n /// \n public WindowsSecurityOptimizationsViewModel WindowsSecuritySettingsViewModel { get; }\n\n /// \n /// Gets the explorer optimizations view model.\n /// \n public ExplorerOptimizationsViewModel ExplorerOptimizationsViewModel { get; }\n\n /// \n /// Gets the notification optimizations view model.\n /// \n public NotificationOptimizationsViewModel NotificationOptimizationsViewModel { get; }\n\n /// \n /// Gets the sound optimizations view model.\n /// \n public SoundOptimizationsViewModel SoundOptimizationsViewModel { get; }\n\n /// \n /// Toggles the selection state of all gaming settings.\n /// \n [RelayCommand]\n private void ToggleGaming()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n GamingandPerformanceOptimizationsViewModel.IsSelected = !GamingandPerformanceOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in GamingandPerformanceOptimizationsViewModel.Settings)\n {\n setting.IsSelected = GamingandPerformanceOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all privacy settings.\n /// \n [RelayCommand]\n private void TogglePrivacy()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n PrivacyOptimizationsViewModel.IsSelected = !PrivacyOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in PrivacyOptimizationsViewModel.Settings)\n {\n setting.IsSelected = PrivacyOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all update settings.\n /// \n [RelayCommand]\n private void ToggleUpdates()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n UpdateOptimizationsViewModel.IsSelected = !UpdateOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in UpdateOptimizationsViewModel.Settings)\n {\n setting.IsSelected = UpdateOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all power settings.\n /// \n [RelayCommand]\n private void TogglePowerSettings()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n PowerSettingsViewModel.IsSelected = !PowerSettingsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in PowerSettingsViewModel.Settings)\n {\n setting.IsSelected = PowerSettingsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of Windows Security settings.\n /// \n [RelayCommand]\n private void ToggleWindowsSecurity()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n WindowsSecuritySettingsViewModel.IsSelected = !WindowsSecuritySettingsViewModel.IsSelected;\n\n // Windows Security only has the UAC notification level, no individual settings to update\n // This is primarily for UI consistency with other sections\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all explorer settings.\n /// \n [RelayCommand]\n private void ToggleExplorer()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n ExplorerOptimizationsViewModel.IsSelected = !ExplorerOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in ExplorerOptimizationsViewModel.Settings)\n {\n setting.IsSelected = ExplorerOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all notification settings.\n /// \n [RelayCommand]\n private void ToggleNotifications()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n NotificationOptimizationsViewModel.IsSelected = !NotificationOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in NotificationOptimizationsViewModel.Settings)\n {\n setting.IsSelected = NotificationOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all sound settings.\n /// \n [RelayCommand]\n private void ToggleSound()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n SoundOptimizationsViewModel.IsSelected = !SoundOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in SoundOptimizationsViewModel.Settings)\n {\n setting.IsSelected = SoundOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Loads items asynchronously.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadItemsAsync()\n {\n try\n {\n IsLoading = true;\n StatusText = \"Loading optimization settings...\";\n\n // Clear the items collection\n Items.Clear();\n\n // Collect all settings from the various view models\n var allSettings = new List();\n \n // Ensure all child view models are initialized and have loaded their settings\n await EnsureChildViewModelsInitialized();\n\n // Add settings from each category - convert from OptimizationSettingViewModel to OptimizationSettingItem\n if (WindowsSecuritySettingsViewModel != null && WindowsSecuritySettingsViewModel.Settings != null)\n {\n _logService.Log(LogLevel.Debug, $\"Loading {WindowsSecuritySettingsViewModel.Settings.Count} settings from WindowsSecuritySettingsViewModel\");\n foreach (var setting in WindowsSecuritySettingsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n \n // For UAC slider, add the slider labels\n if (item.Id == \"UACSlider\" && item.ControlType == ControlType.ThreeStateSlider)\n {\n item.SliderLabels.Clear();\n item.SliderLabels.Add(\"Low\");\n item.SliderLabels.Add(\"Moderate\");\n item.SliderLabels.Add(\"High\");\n }\n \n allSettings.Add(item);\n }\n }\n\n if (GamingandPerformanceOptimizationsViewModel != null && GamingandPerformanceOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in GamingandPerformanceOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n if (PrivacyOptimizationsViewModel != null && PrivacyOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in PrivacyOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n if (UpdateOptimizationsViewModel != null && UpdateOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in UpdateOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n if (PowerSettingsViewModel != null && PowerSettingsViewModel.Settings != null)\n {\n foreach (var setting in PowerSettingsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n \n // For Power Plan ComboBox, add the ComboBox labels\n if (item.Id == \"PowerPlanComboBox\" && item.ControlType == ControlType.ComboBox)\n {\n item.SliderLabels.Clear();\n // Copy labels from PowerSettingsViewModel\n if (PowerSettingsViewModel.PowerPlanLabels != null)\n {\n foreach (var label in PowerSettingsViewModel.PowerPlanLabels)\n {\n item.SliderLabels.Add(label);\n }\n \n // Set the SliderValue based on the current PowerPlanValue\n if (PowerSettingsViewModel.PowerPlanValue >= 0 &&\n PowerSettingsViewModel.PowerPlanValue < PowerSettingsViewModel.PowerPlanLabels.Count)\n {\n item.SliderValue = PowerSettingsViewModel.PowerPlanValue;\n _logService.Log(LogLevel.Info, $\"Set SliderValue for Power Plan to {item.SliderValue} (label: {PowerSettingsViewModel.PowerPlanLabels[PowerSettingsViewModel.PowerPlanValue]})\");\n }\n }\n else\n {\n // Fallback labels if PowerPlanLabels is null\n item.SliderLabels.Add(\"Balanced\");\n item.SliderLabels.Add(\"High Performance\");\n item.SliderLabels.Add(\"Ultimate Performance\");\n \n // Set the SliderValue based on the current PowerPlanValue\n if (PowerSettingsViewModel.PowerPlanValue >= 0 && PowerSettingsViewModel.PowerPlanValue < 3)\n {\n item.SliderValue = PowerSettingsViewModel.PowerPlanValue;\n string[] defaultLabels = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n _logService.Log(LogLevel.Info, $\"Set SliderValue for Power Plan to {item.SliderValue} (label: {defaultLabels[PowerSettingsViewModel.PowerPlanValue]})\");\n }\n }\n }\n \n allSettings.Add(item);\n }\n }\n\n if (ExplorerOptimizationsViewModel != null && ExplorerOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in ExplorerOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n if (NotificationOptimizationsViewModel != null && NotificationOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in NotificationOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n if (SoundOptimizationsViewModel != null && SoundOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in SoundOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n // Add all settings to the Items collection\n foreach (var setting in allSettings)\n {\n Items.Add(setting);\n }\n\n // Create a backup of all items for state recovery\n _allItemsBackup = new List(Items);\n\n // Only update StatusText if it's currently showing a loading message\n if (StatusText.Contains(\"Loading\"))\n {\n StatusText = \"Optimize Your Windows Settings and Performance\";\n }\n _logService.Log(LogLevel.Info, $\"OptimizeViewModel.LoadItemsAsync completed with {Items.Count} items\");\n }\n catch (Exception ex)\n {\n StatusText = $\"Error loading optimization settings: {ex.Message}\";\n LogError($\"Error loading optimization settings: {ex.Message}\", ex);\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the installation status of items asynchronously.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckInstallationStatusAsync()\n {\n // This method is not applicable for optimization settings\n // but we need to implement it to satisfy the interface\n await Task.CompletedTask;\n }\n\n \n /// \n /// Restores all items visibility to their original state.\n /// \n private void RestoreAllItemsVisibility()\n {\n // Make all settings visible in each category\n if (GamingandPerformanceOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in GamingandPerformanceOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n GamingandPerformanceOptimizationsViewModel.HasVisibleSettings = GamingandPerformanceOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (PrivacyOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in PrivacyOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n PrivacyOptimizationsViewModel.HasVisibleSettings = PrivacyOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (UpdateOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in UpdateOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n UpdateOptimizationsViewModel.HasVisibleSettings = UpdateOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (PowerSettingsViewModel?.Settings != null)\n {\n foreach (var setting in PowerSettingsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n PowerSettingsViewModel.HasVisibleSettings = PowerSettingsViewModel.Settings.Count > 0;\n }\n \n if (ExplorerOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in ExplorerOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n ExplorerOptimizationsViewModel.HasVisibleSettings = ExplorerOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (NotificationOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in NotificationOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n NotificationOptimizationsViewModel.HasVisibleSettings = NotificationOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (SoundOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in SoundOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n SoundOptimizationsViewModel.HasVisibleSettings = SoundOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (WindowsSecuritySettingsViewModel?.Settings != null)\n {\n foreach (var setting in WindowsSecuritySettingsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n WindowsSecuritySettingsViewModel.HasVisibleSettings = WindowsSecuritySettingsViewModel.Settings.Count > 0;\n }\n \n // Always ensure HasSearchResults is true when restoring visibility\n HasSearchResults = true;\n \n // Send a message to notify the view to reset section expansion states\n _messengerService.Send(new ResetExpansionStateMessage());\n \n LogInfo(\"OptimizeViewModel: RestoreAllItemsVisibility has reset all UI elements to visible state\");\n }\n \n /// \n /// Applies the current search text to filter items.\n /// \n protected override void ApplySearch()\n {\n LogInfo($\"OptimizeViewModel: ApplySearch called with SearchText: '{SearchText}'\");\n \n // If we have no items yet, there's nothing to filter\n if (Items == null)\n return;\n \n // If this is our first time running a search and the backup isn't created yet, create it\n if (!_isInitialSearchDone && Items.Count > 0)\n {\n _allItemsBackup = new List(Items);\n _isInitialSearchDone = true;\n LogInfo($\"OptimizeViewModel: Created backup of all items ({_allItemsBackup.Count} items)\");\n }\n\n // If search is empty, restore all items visibility and the original items collection\n if (string.IsNullOrWhiteSpace(SearchText))\n {\n LogInfo(\"OptimizeViewModel: Empty search, restoring all items visibility\");\n \n // Restore visibility of UI elements first\n RestoreAllItemsVisibility();\n \n // Use the backup to restore all items\n if (_allItemsBackup.Count > 0)\n {\n LogInfo($\"OptimizeViewModel: Restoring {_allItemsBackup.Count} items from backup\");\n Items.Clear();\n foreach (var item in _allItemsBackup)\n {\n Items.Add(item);\n }\n }\n else if (Items.Count == 0)\n {\n // If we don't have a backup and Items is empty (which could happen after a no-results search),\n // try to reload items\n LogInfo(\"OptimizeViewModel: No backup available and Items is empty, attempting to reload\");\n _ = LoadItemsAsync();\n }\n \n // Always set HasSearchResults to true when search is cleared\n HasSearchResults = true;\n \n // Update status text\n StatusText = \"Optimize Your Windows Settings and Performance\";\n LogInfo($\"OptimizeViewModel: Restored items, count={Items.Count}\");\n return;\n }\n\n // We're doing an active search, use the backup for filtering if available\n var itemsToFilter = _allItemsBackup.Count > 0\n ? new ObservableCollection(_allItemsBackup)\n : Items;\n \n // Normalize and clean the search text - convert to lowercase for consistent case-insensitive matching\n string normalizedSearchText = SearchText.Trim().ToLowerInvariant();\n LogInfo($\"OptimizeViewModel: Normalized search text: '{normalizedSearchText}'\");\n \n // Handle edge case: if search is empty after normalization, treat it as empty\n if (string.IsNullOrEmpty(normalizedSearchText))\n {\n // Same handling as empty search\n RestoreAllItemsVisibility();\n if (_allItemsBackup.Count > 0)\n {\n Items.Clear();\n foreach (var item in _allItemsBackup)\n {\n Items.Add(item);\n }\n }\n HasSearchResults = true;\n StatusText = \"Optimize Your Windows Settings and Performance\";\n return;\n }\n \n // Add additional logging to help diagnose search issues\n LogInfo($\"OptimizeViewModel: Starting search with term '{normalizedSearchText}'\");\n \n // Filter items based on search text - ensure we pass normalized text\n // Don't convert to lowercase here - we'll handle case insensitivity in the MatchesSearch method\n var filteredItems = FilterItems(itemsToFilter).ToList();\n \n // Log each filtered item for debugging\n foreach (var item in filteredItems)\n {\n LogInfo($\"OptimizeViewModel: Filtered item: '{item.Name}' (ID: {item.Id})\");\n }\n \n // Log the number of filtered items\n int filteredCount = filteredItems.Count;\n LogInfo($\"OptimizeViewModel: Found {filteredCount} matching items\");\n \n // Log the filtered count for debugging\n LogInfo($\"OptimizeViewModel: Initial filtered count: {filteredCount}\");\n \n // We'll update HasSearchResults after counting the actual visible items\n // This is just an initial value\n bool initialHasResults = filteredCount > 0;\n LogInfo($\"OptimizeViewModel: Initial HasSearchResults: {initialHasResults}\");\n \n // Log the filtered items for debugging\n LogInfo($\"OptimizeViewModel: Filtered items: {string.Join(\", \", filteredItems.Select(item => item.Name))}\");\n\n // Update each sub-view model's Settings collection with the normalized search text\n UpdateSubViewSettings(GamingandPerformanceOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(PrivacyOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(UpdateOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(PowerSettingsViewModel, normalizedSearchText);\n UpdateSubViewSettings(ExplorerOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(NotificationOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(SoundOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(WindowsSecuritySettingsViewModel, normalizedSearchText);\n\n // Count the actual visible items after filtering\n int visibleItemsCount = 0;\n \n // Count visible items in each category\n if (GamingandPerformanceOptimizationsViewModel?.Settings != null)\n visibleItemsCount += GamingandPerformanceOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (PrivacyOptimizationsViewModel?.Settings != null)\n visibleItemsCount += PrivacyOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (UpdateOptimizationsViewModel?.Settings != null)\n visibleItemsCount += UpdateOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (PowerSettingsViewModel?.Settings != null)\n visibleItemsCount += PowerSettingsViewModel.Settings.Count(s => s.IsVisible);\n \n if (ExplorerOptimizationsViewModel?.Settings != null)\n visibleItemsCount += ExplorerOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (NotificationOptimizationsViewModel?.Settings != null)\n visibleItemsCount += NotificationOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (SoundOptimizationsViewModel?.Settings != null)\n visibleItemsCount += SoundOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (WindowsSecuritySettingsViewModel?.Settings != null)\n visibleItemsCount += WindowsSecuritySettingsViewModel.Settings.Count(s => s.IsVisible);\n\n // Update the Items collection to match visible items\n Items.Clear();\n foreach (var setting in filteredItems)\n {\n if (setting.IsVisible)\n {\n Items.Add(setting);\n }\n }\n \n // Now update HasSearchResults based on the ACTUAL visible items count\n // This is more accurate than using the filtered count\n HasSearchResults = visibleItemsCount > 0;\n LogInfo($\"OptimizeViewModel: Final HasSearchResults: {HasSearchResults} (visibleItemsCount: {visibleItemsCount})\");\n\n // Update status text with correct count\n if (IsSearchActive)\n {\n StatusText = $\"Found {visibleItemsCount} settings matching '{SearchText}'\";\n LogInfo($\"OptimizeViewModel: StatusText updated to: '{StatusText}' with {visibleItemsCount} visible items\");\n }\n else\n {\n StatusText = $\"Showing all {Items.Count} optimization settings\";\n LogInfo($\"OptimizeViewModel: StatusText updated to: '{StatusText}'\");\n }\n }\n\n /// \n /// Updates a sub-view model's Settings collection based on search text.\n /// \n /// The sub-view model to update.\n /// The normalized search text to match against.\n private void UpdateSubViewSettings(object viewModel, string searchText)\n {\n if (viewModel == null)\n return;\n\n // Use dynamic to access properties without knowing the exact type\n dynamic dynamicViewModel = viewModel;\n \n if (dynamicViewModel.Settings == null)\n return;\n\n // If not searching, show all settings\n if (!IsSearchActive)\n {\n foreach (var setting in dynamicViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n \n // Update the view model's visibility\n dynamicViewModel.HasVisibleSettings = dynamicViewModel.Settings.Count > 0;\n \n LogInfo($\"OptimizeViewModel: Set all settings visible in {dynamicViewModel.GetType().Name}\");\n return;\n }\n\n // When searching, only show settings that match the search criteria\n bool hasVisibleSettings = false;\n int visibleCount = 0;\n \n foreach (var setting in dynamicViewModel.Settings)\n {\n // Use partial matching instead of exact name matching\n // This matches the same logic used in OptimizationSettingItem.MatchesSearch()\n bool matchesName = setting.Name != null &&\n setting.Name.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0;\n bool matchesDescription = setting.Description != null &&\n setting.Description.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0;\n bool matchesGroupName = setting.GroupName != null &&\n setting.GroupName.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0;\n \n // Set visibility based on any match\n setting.IsVisible = matchesName || matchesDescription || matchesGroupName;\n \n // Log when we find a match for debugging\n if (setting.IsVisible)\n {\n LogInfo($\"OptimizeViewModel: Setting '{setting.Name}' is visible in {viewModel.GetType().Name}\");\n }\n \n if (setting.IsVisible)\n {\n hasVisibleSettings = true;\n visibleCount++;\n }\n }\n \n // Update the view model's visibility\n dynamicViewModel.HasVisibleSettings = hasVisibleSettings;\n \n LogInfo($\"OptimizeViewModel: {dynamicViewModel.GetType().Name} has {visibleCount} visible settings, HasVisibleSettings={hasVisibleSettings}\");\n }\n\n // SaveConfig and ImportConfig methods removed as part of unified configuration cleanup\n\n /// \n /// Gets the name of the UAC level.\n /// \n /// The UAC level (0=Low, 1=Moderate, 2=High).\n /// The name of the UAC level.\n private string GetUacLevelName(int level)\n {\n return level switch\n {\n 0 => \"Low\",\n 1 => \"Moderate\",\n 2 => \"High\",\n _ => \"Unknown\"\n };\n }\n\n /// \n /// Called when the view model is navigated to.\n /// \n /// The navigation parameter.\n public override async void OnNavigatedTo(object parameter)\n {\n LogInfo(\"OptimizeViewModel.OnNavigatedTo called\");\n\n try\n {\n // If not already initialized, initialize now\n if (!IsInitialized)\n {\n await InitializeAsync(CancellationToken.None);\n }\n else\n {\n // Just refresh the settings status\n await RefreshSettingsStatusAsync();\n }\n }\n catch (Exception ex)\n {\n LogError($\"Error in OptimizeViewModel.OnNavigatedTo: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Initializes the view model asynchronously.\n /// \n /// A cancellation token that can be used to cancel the operation.\n /// A task representing the asynchronous operation.\n private async Task InitializeAsync(CancellationToken cancellationToken)\n {\n if (IsInitialized)\n return;\n\n try\n {\n IsLoading = true;\n LogInfo(\"Initializing OptimizeViewModel\");\n\n // Create a progress reporter\n var progress = new Progress(detail => {\n // Report progress through the task progress service\n int progress = detail.Progress.HasValue ? (int)detail.Progress.Value : 0;\n ProgressService.UpdateProgress(progress, detail.StatusText);\n });\n\n // Initialize settings sequentially to provide better progress reporting\n ProgressService.UpdateProgress(0, \"Loading Windows security settings...\");\n await WindowsSecuritySettingsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(10, \"Loading gaming settings...\");\n await GamingandPerformanceOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(25, \"Loading privacy settings...\");\n await PrivacyOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(40, \"Loading update settings...\");\n await UpdateOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(55, \"Loading power settings...\");\n await PowerSettingsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(70, \"Loading explorer settings...\");\n await ExplorerOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(80, \"Loading notification settings...\");\n await NotificationOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(90, \"Loading sound settings...\");\n await SoundOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(100, \"Initialization complete\");\n\n // Mark as initialized\n IsInitialized = true;\n\n LogInfo(\"OptimizeViewModel initialized successfully\");\n }\n catch (Exception ex)\n {\n LogError($\"Error initializing OptimizeViewModel: {ex.Message}\", ex);\n throw; // Rethrow to ensure the caller knows initialization failed\n }\n finally\n {\n IsLoading = false;\n }\n }\n \n /// \n /// Ensures all child view models are initialized and have loaded their settings.\n /// \n private async Task EnsureChildViewModelsInitialized()\n {\n _logService.Log(LogLevel.Debug, \"Ensuring all child view models are initialized\");\n \n // Create a list of tasks to initialize all child view models\n var initializationTasks = new List();\n \n // Windows Security Settings\n if (WindowsSecuritySettingsViewModel != null && WindowsSecuritySettingsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading WindowsSecuritySettingsViewModel settings\");\n initializationTasks.Add(WindowsSecuritySettingsViewModel.LoadSettingsAsync());\n }\n \n // Gaming and Performance Settings\n if (GamingandPerformanceOptimizationsViewModel != null && GamingandPerformanceOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading GamingandPerformanceOptimizationsViewModel settings\");\n initializationTasks.Add(GamingandPerformanceOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Privacy Settings\n if (PrivacyOptimizationsViewModel != null && PrivacyOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading PrivacyOptimizationsViewModel settings\");\n initializationTasks.Add(PrivacyOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Update Settings\n if (UpdateOptimizationsViewModel != null && UpdateOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading UpdateOptimizationsViewModel settings\");\n initializationTasks.Add(UpdateOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Power Settings\n if (PowerSettingsViewModel != null && PowerSettingsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading PowerSettingsViewModel settings\");\n initializationTasks.Add(PowerSettingsViewModel.LoadSettingsAsync());\n }\n \n // Explorer Settings\n if (ExplorerOptimizationsViewModel != null && ExplorerOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading ExplorerOptimizationsViewModel settings\");\n initializationTasks.Add(ExplorerOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Notification Settings\n if (NotificationOptimizationsViewModel != null && NotificationOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading NotificationOptimizationsViewModel settings\");\n initializationTasks.Add(NotificationOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Sound Settings\n if (SoundOptimizationsViewModel != null && SoundOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading SoundOptimizationsViewModel settings\");\n initializationTasks.Add(SoundOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Wait for all initialization tasks to complete\n if (initializationTasks.Count > 0)\n {\n _logService.Log(LogLevel.Debug, $\"Waiting for {initializationTasks.Count} child view models to initialize\");\n await Task.WhenAll(initializationTasks);\n _logService.Log(LogLevel.Debug, \"All child view models initialized\");\n }\n else\n {\n _logService.Log(LogLevel.Debug, \"All child view models were already initialized\");\n }\n }\n\n /// \n /// Refreshes the status of all settings.\n /// \n /// A task representing the asynchronous operation.\n private async Task RefreshSettingsStatusAsync()\n {\n try\n {\n IsLoading = true;\n LogInfo(\"Refreshing settings status\");\n\n // Refresh all settings view models\n var refreshTasks = new List\n {\n WindowsSecuritySettingsViewModel.CheckSettingStatusesAsync(),\n GamingandPerformanceOptimizationsViewModel.CheckSettingStatusesAsync(),\n PrivacyOptimizationsViewModel.CheckSettingStatusesAsync(),\n UpdateOptimizationsViewModel.CheckSettingStatusesAsync(),\n PowerSettingsViewModel.CheckSettingStatusesAsync(),\n ExplorerOptimizationsViewModel.CheckSettingStatusesAsync(),\n NotificationOptimizationsViewModel.CheckSettingStatusesAsync(),\n SoundOptimizationsViewModel.CheckSettingStatusesAsync()\n };\n\n // Wait for all refresh tasks to complete\n await Task.WhenAll(refreshTasks);\n\n LogInfo(\"Settings status refreshed successfully\");\n }\n catch (Exception ex)\n {\n LogError($\"Error refreshing settings status: {ex.Message}\", ex);\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Handles the checkbox state changed event for optimization settings.\n /// \n /// The setting that was changed.\n [RelayCommand]\n private void SettingChanged(Winhance.WPF.Features.Common.Models.ApplicationSettingItem setting)\n {\n if (_updatingCheckboxes)\n return;\n\n try\n {\n _updatingCheckboxes = true;\n\n if (setting.RegistrySetting?.Category == \"PowerPlan\")\n {\n // Handle power plan changes separately\n // This would call a method to change the power plan\n LogInfo($\"Power plan setting changed: {setting.Name} to {setting.IsSelected}\");\n }\n else\n {\n // Apply registry change\n if (setting.RegistrySetting != null)\n {\n // Use EnabledValue/DisabledValue if available, otherwise fall back to RecommendedValue/DefaultValue\n string valueToSet;\n if (setting.IsSelected)\n {\n var enabledValue = setting.RegistrySetting.EnabledValue ?? setting.RegistrySetting.RecommendedValue;\n valueToSet = enabledValue.ToString();\n }\n else\n {\n var disabledValue = setting.RegistrySetting.DisabledValue ?? setting.RegistrySetting.DefaultValue;\n valueToSet = disabledValue?.ToString() ?? \"\";\n }\n\n var result = _registryService.SetValue(\n setting.RegistrySetting.Hive + \"\\\\\" + setting.RegistrySetting.SubKey,\n setting.RegistrySetting.Name,\n valueToSet,\n setting.RegistrySetting.ValueType);\n\n if (result)\n {\n LogInfo($\"Setting applied: {setting.Name}\");\n\n // Check if restart is required based on setting category or name\n bool requiresRestart = setting.Name.Contains(\"restart\", StringComparison.OrdinalIgnoreCase);\n\n if (requiresRestart)\n {\n _dialogService.ShowMessage(\n \"Some changes require a system restart to take effect.\",\n \"Restart Required\");\n }\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Failed to apply setting: {setting.Name}\");\n\n // Revert the checkbox state\n setting.IsSelected = !setting.IsSelected;\n\n _dialogService.ShowMessage(\n $\"Failed to apply the setting: {setting.Name}. This may require administrator privileges.\",\n \"Error\");\n }\n }\n }\n catch (Exception ex)\n {\n LogError($\"Error applying setting: {ex.Message}\", ex);\n\n // Revert the checkbox state\n setting.IsSelected = !setting.IsSelected;\n\n _dialogService.ShowMessage(\n $\"An error occurred: {ex.Message}\",\n \"Error\");\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n // Note: ApplyOptimizationsCommand has been removed as settings are now applied immediately when toggled\n \n // The CreateOptimizationSettingItem method has been removed as it's no longer needed\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGetInstallationServiceAdapter.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Infrastructure.Features.Common.Services;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Adapter that implements the legacy IWinGetInstallationService using the new IWinGetInstaller.\n /// \n public class WinGetInstallationServiceAdapter : IWinGetInstallationService, IDisposable\n {\n private readonly IWinGetInstaller _winGetInstaller;\n private readonly ITaskProgressService _taskProgressService;\n private bool _disposed;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The WinGet installer service.\n /// The task progress service.\n public WinGetInstallationServiceAdapter(\n IWinGetInstaller winGetInstaller,\n ITaskProgressService taskProgressService)\n {\n _winGetInstaller = winGetInstaller ?? throw new ArgumentNullException(nameof(winGetInstaller));\n _taskProgressService = taskProgressService ?? throw new ArgumentNullException(nameof(taskProgressService));\n }\n\n /// \n public async Task InstallWithWingetAsync(\n string packageName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default,\n string? displayName = null)\n {\n if (string.IsNullOrWhiteSpace(packageName))\n throw new ArgumentException(\"Package name cannot be null or empty\", nameof(packageName));\n\n var displayNameToUse = displayName ?? packageName;\n var progressWrapper = new ProgressAdapter(progress);\n \n try\n {\n // Report initial progress\n progressWrapper.Report(0, $\"Starting installation of {displayNameToUse}...\");\n\n // Check if WinGet is installed first\n bool wingetInstalled = await IsWinGetInstalledAsync().ConfigureAwait(false);\n if (!wingetInstalled)\n {\n progressWrapper.Report(10, \"WinGet is not installed. Installing WinGet first...\");\n \n // Install WinGet\n await InstallWinGetAsync(progress).ConfigureAwait(false);\n \n // Verify WinGet installation was successful\n wingetInstalled = await IsWinGetInstalledAsync().ConfigureAwait(false);\n if (!wingetInstalled)\n {\n progressWrapper.Report(0, \"Failed to install WinGet. Cannot proceed with application installation.\");\n return false;\n }\n \n progressWrapper.Report(30, $\"WinGet installed successfully. Continuing with {displayNameToUse} installation...\");\n }\n\n // Now use the WinGet installer to install the package\n var result = await _winGetInstaller.InstallPackageAsync(\n packageName,\n new InstallationOptions\n {\n // Configure installation options as needed\n Silent = true\n },\n displayNameToUse, // Pass the display name to use in progress reporting\n cancellationToken)\n .ConfigureAwait(false);\n\n if (result.Success)\n {\n progressWrapper.Report(100, $\"Successfully installed {displayNameToUse}\");\n return true;\n }\n \n progressWrapper.Report(0, $\"Failed to install {displayNameToUse}: {result.Message}\");\n return false;\n }\n catch (Exception ex)\n {\n progressWrapper.Report(0, $\"Error installing {displayNameToUse}: {ex.Message}\");\n throw;\n }\n }\n\n /// \n public async Task InstallWinGetAsync(IProgress? progress = null)\n {\n // Check if WinGet is already installed\n if (await IsWinGetInstalledAsync().ConfigureAwait(false))\n {\n progress?.Report(new TaskProgressDetail { StatusText = \"WinGet is already installed\" });\n return;\n }\n\n var progressWrapper = new ProgressAdapter(progress);\n \n try\n {\n progressWrapper.Report(0, \"Downloading WinGet installer...\");\n \n // Force a search operation which will trigger WinGet installation if it's not found\n // This leverages the WinGetInstaller's built-in mechanism to install WinGet when needed\n try \n {\n // We use a simple search operation to trigger the WinGet installation process\n // The dot (.) is a simple search term that will match everything\n progressWrapper.Report(20, \"Installing WinGet...\");\n \n var searchResult = await _winGetInstaller.SearchPackagesAsync(\n \".\", // Simple search term\n null, // No search options\n CancellationToken.None)\n .ConfigureAwait(false);\n \n progressWrapper.Report(80, \"WinGet installation in progress...\");\n \n // If we get here, WinGet should be installed\n progressWrapper.Report(100, \"WinGet installed successfully\");\n }\n catch (Exception ex)\n {\n progressWrapper.Report(0, $\"Error installing WinGet: {ex.Message}\");\n throw;\n }\n \n // Verify WinGet installation\n bool isInstalled = await IsWinGetInstalledAsync().ConfigureAwait(false);\n if (!isInstalled)\n {\n progressWrapper.Report(0, \"WinGet installation verification failed\");\n throw new InvalidOperationException(\"WinGet installation could not be verified\");\n }\n }\n catch (Exception ex)\n {\n progressWrapper.Report(0, $\"Error installing WinGet: {ex.Message}\");\n throw;\n }\n }\n\n /// \n public async Task IsWinGetInstalledAsync()\n {\n try\n {\n // Try to list packages to check if WinGet is working\n var result = await _winGetInstaller.SearchPackagesAsync(\".\").ConfigureAwait(false);\n return result != null;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n /// \n /// Releases the unmanaged resources used by the \n /// and optionally releases the managed resources.\n /// \n /// True to release both managed and unmanaged resources; false to release only unmanaged resources.\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n // Dispose managed resources here if needed\n }\n\n _disposed = true;\n }\n }\n\n /// \n /// Adapter to convert between IProgress and IProgress\n /// \n private class ProgressAdapter\n {\n private readonly IProgress? _progress;\n\n public ProgressAdapter(IProgress? progress)\n {\n _progress = progress;\n }\n\n public void Report(int progress, string status)\n {\n _progress?.Report(new TaskProgressDetail\n {\n Progress = progress,\n StatusText = status,\n LogLevel = progress == 100 ? LogLevel.Info : LogLevel.Debug\n });\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/ApplicationSettingViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.WPF.Features.Common.Extensions;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// Base view model for application settings.\n /// \n public partial class ApplicationSettingViewModel : ObservableObject, ISettingItem\n {\n protected readonly IRegistryService? _registryService;\n protected readonly IDialogService? _dialogService;\n protected readonly ILogService? _logService;\n protected readonly IDependencyManager? _dependencyManager;\n protected readonly Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService? _powerPlanService;\n protected bool _isUpdatingFromCode;\n\n /// \n /// Gets or sets a value indicating whether the IsSelected property is being updated from code.\n /// This is used to prevent automatic application of settings when loading.\n /// \n public bool IsUpdatingFromCode\n {\n get => _isUpdatingFromCode;\n set => _isUpdatingFromCode = value;\n }\n\n [ObservableProperty]\n private string _id = string.Empty;\n\n [ObservableProperty]\n private string _name = string.Empty;\n\n [ObservableProperty]\n private string _description = string.Empty;\n\n [ObservableProperty]\n private bool _isSelected;\n\n [ObservableProperty]\n private string _groupName = string.Empty;\n\n [ObservableProperty]\n private bool _isGroupHeader;\n\n [ObservableProperty]\n private bool _isGroupedSetting;\n\n [ObservableProperty]\n private bool _isVisible = true;\n\n [ObservableProperty]\n private ObservableCollection _childSettings = new();\n\n [ObservableProperty]\n private ControlType _controlType = ControlType.BinaryToggle;\n\n [ObservableProperty]\n private int? _sliderSteps;\n\n [ObservableProperty]\n private int _sliderValue;\n\n [ObservableProperty]\n private ObservableCollection _sliderLabels = new();\n\n [ObservableProperty]\n private RegistrySettingStatus _status = RegistrySettingStatus.Unknown;\n\n [ObservableProperty]\n private object? _currentValue;\n\n /// \n /// Gets a value indicating whether this setting is command-based rather than registry-based.\n /// \n public bool IsCommandBasedSetting\n {\n get\n {\n // Check if this setting has PowerCfg commands in its CustomProperties\n return CustomProperties != null &&\n CustomProperties.ContainsKey(\"PowerCfgSettings\") &&\n CustomProperties[\"PowerCfgSettings\"] is List powerCfgSettings &&\n powerCfgSettings.Count > 0;\n }\n }\n \n /// \n /// Gets a list of PowerCfg commands for display in tooltips.\n /// \n public ObservableCollection PowerCfgCommands\n {\n get\n {\n var commands = new ObservableCollection();\n \n if (IsCommandBasedSetting &&\n CustomProperties.ContainsKey(\"PowerCfgSettings\") &&\n CustomProperties[\"PowerCfgSettings\"] is List powerCfgSettings)\n {\n foreach (var setting in powerCfgSettings)\n {\n commands.Add(setting.Command);\n }\n }\n \n return commands;\n }\n }\n\n /// \n /// Gets a value indicating whether the registry value is null.\n /// \n public bool IsRegistryValueNull\n {\n get\n {\n // Don't show warning for command-based settings\n if (IsCommandBasedSetting)\n {\n return false;\n }\n \n // Don't show warning for settings with ActionType = Remove\n if (RegistrySetting != null && RegistrySetting.ActionType == RegistryActionType.Remove)\n {\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Returning false because ActionType is Remove\");\n return false;\n }\n \n // Also check linked registry settings for ActionType = Remove\n if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n // If all linked settings have ActionType = Remove, don't show warning\n bool allRemove = LinkedRegistrySettings.Settings.All(s => s.ActionType == RegistryActionType.Remove);\n if (allRemove)\n {\n // For Remove actions, we don't want to show the warning if all values are null (which means keys don't exist)\n bool allNull = LinkedRegistrySettingsWithValues.All(lv => lv.CurrentValue == null);\n if (allNull)\n {\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Returning false because all Remove settings have null values (keys don't exist)\");\n return false;\n }\n \n // If any key exists when it shouldn't, we might want to show a warning\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Continuing because some Remove settings have non-null values (keys exist)\");\n }\n }\n \n // Add debug logging to help diagnose the issue\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': CurrentValue = {(CurrentValue == null ? \"null\" : CurrentValue.ToString())}\");\n \n // Check if the registry value is null or a special value that indicates it doesn't exist\n if (CurrentValue == null)\n {\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Returning true because CurrentValue is null\");\n return true;\n }\n \n // Check if the registry setting exists\n if (RegistrySetting != null)\n {\n // If we have a registry setting but no current value, it might be null\n if (Status == RegistrySettingStatus.Unknown)\n {\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Returning true because Status is Unknown\");\n return true;\n }\n }\n \n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Returning false\");\n return false;\n }\n }\n\n [ObservableProperty]\n private string _statusMessage = string.Empty;\n\n [ObservableProperty]\n private bool _isApplying;\n\n /// \n /// Gets or sets the registry setting associated with this view model.\n /// \n public RegistrySetting? RegistrySetting { get; set; }\n\n /// \n /// Gets or sets the linked registry settings associated with this view model.\n /// \n public LinkedRegistrySettings LinkedRegistrySettings { get; set; } = new LinkedRegistrySettings();\n\n /// \n /// Gets or sets the linked registry settings with their current values for display in tooltips.\n /// \n [ObservableProperty]\n private ObservableCollection _linkedRegistrySettingsWithValues = new();\n\n /// \n /// Gets or sets the dependencies between settings.\n /// \n public List Dependencies { get; set; } = new List();\n\n /// \n /// Gets or sets custom properties for this setting.\n /// This can be used to store additional data specific to certain optimization types,\n /// such as PowerCfg settings.\n /// \n public Dictionary CustomProperties { get; set; } = new Dictionary();\n\n /// \n /// Gets or sets the command to apply the setting.\n /// \n public ICommand ApplySettingCommand { get; set; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n public ApplicationSettingViewModel()\n {\n // Default constructor for design-time use\n ApplySettingCommand = new RelayCommand(async () => await ApplySetting());\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The registry service.\n /// The dialog service.\n /// The log service.\n /// The dependency manager.\n public ApplicationSettingViewModel(\n IRegistryService registryService,\n IDialogService? dialogService,\n ILogService logService,\n IDependencyManager? dependencyManager = null,\n Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService? powerPlanService = null)\n {\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n _dialogService = dialogService; // Allow null for dialogService\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _dependencyManager = dependencyManager; // Allow null for backward compatibility\n _powerPlanService = powerPlanService; // Allow null for backward compatibility\n \n // Initialize the ApplySettingCommand\n ApplySettingCommand = new RelayCommand(async () => await ApplySetting());\n\n // Set up property changed handlers for immediate application\n this.PropertyChanged += (s, e) => {\n if ((e.PropertyName == nameof(IsSelected) || e.PropertyName == nameof(SliderValue)) && !IsUpdatingFromCode)\n {\n _logService?.Log(LogLevel.Info, $\"Property {e.PropertyName} changed for {Name}, applying setting\");\n\n // Check dependencies when enabling a setting\n if (e.PropertyName == nameof(IsSelected))\n {\n if (IsSelected)\n {\n // Check if this setting can be enabled based on its dependencies\n var allSettings = GetAllSettings();\n if (allSettings != null && _dependencyManager != null)\n {\n if (!_dependencyManager.CanEnableSetting(Id, allSettings))\n {\n _logService?.Log(LogLevel.Info, $\"Setting {Name} has unsatisfied dependencies, attempting to enable them\");\n \n // Find the dependencies that need to be enabled\n var unsatisfiedDependencies = new List();\n foreach (var dependency in Dependencies)\n {\n if (dependency.DependencyType == SettingDependencyType.RequiresEnabled)\n {\n var requiredSetting = allSettings.FirstOrDefault(s => s.Id == dependency.RequiredSettingId);\n if (requiredSetting != null && !requiredSetting.IsSelected)\n {\n unsatisfiedDependencies.Add(requiredSetting);\n }\n }\n }\n \n if (unsatisfiedDependencies.Count > 0)\n {\n // Automatically enable the dependencies without asking\n bool enableDependencies = true;\n \n // Log what we're doing\n var dependencyNames = string.Join(\", \", unsatisfiedDependencies.Select(d => $\"'{d.Name}'\"));\n _logService?.Log(LogLevel.Info, $\"'{Name}' requires {dependencyNames} to be enabled. Automatically enabling dependencies.\");\n \n if (enableDependencies)\n {\n // Enable all dependencies\n foreach (var dependency in unsatisfiedDependencies)\n {\n _logService?.Log(LogLevel.Info, $\"Automatically enabling dependency: {dependency.Name}\");\n \n // Enable the dependency\n if (dependency is ApplicationSettingViewModel depViewModel)\n {\n depViewModel.IsUpdatingFromCode = true;\n try\n {\n depViewModel.IsSelected = true;\n }\n finally\n {\n depViewModel.IsUpdatingFromCode = false;\n }\n \n // Apply the setting\n depViewModel.ApplySettingCommand.Execute(null);\n }\n }\n }\n else\n {\n // User chose not to enable dependencies, so don't enable this setting\n IsUpdatingFromCode = true;\n try\n {\n IsSelected = false;\n }\n finally\n {\n IsUpdatingFromCode = false;\n }\n return;\n }\n }\n else\n {\n // No dependencies found, show a generic message\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"'{Name}' cannot be enabled because one of its dependencies is not satisfied.\",\n \"Setting Dependency\");\n }\n \n // Prevent enabling this setting\n IsUpdatingFromCode = true;\n try\n {\n IsSelected = false;\n }\n finally\n {\n IsUpdatingFromCode = false;\n }\n return;\n }\n }\n \n // Automatically enable any required settings\n _dependencyManager.HandleSettingEnabled(Id, allSettings);\n }\n }\n else\n {\n // Handle disabling a setting\n var allSettings = GetAllSettings();\n if (allSettings != null && _dependencyManager != null)\n {\n _dependencyManager.HandleSettingDisabled(Id, allSettings);\n }\n }\n }\n\n ApplySettingCommand.Execute(null);\n }\n else if ((e.PropertyName == nameof(IsSelected) || e.PropertyName == nameof(SliderValue)) && IsUpdatingFromCode)\n {\n _logService?.Log(LogLevel.Info, $\"Property {e.PropertyName} changed for {Name}, but not applying setting because IsUpdatingFromCode is true\");\n }\n };\n }\n\n /// \n /// Called when the IsSelected property changes.\n /// \n /// The new value.\n partial void OnIsSelectedChanged(bool value)\n {\n // If this is a grouped setting, update all child settings\n if (IsGroupedSetting && ChildSettings.Count > 0)\n {\n _isUpdatingFromCode = true;\n try\n {\n foreach (var child in ChildSettings)\n {\n child.IsSelected = value;\n }\n }\n finally\n {\n _isUpdatingFromCode = false;\n }\n }\n }\n\n /// \n /// Applies the setting immediately.\n /// \n protected virtual async Task ApplySetting()\n {\n if (IsApplying || _registryService == null || _logService == null)\n return;\n\n try\n {\n IsApplying = true;\n\n // Check if this is a command-based setting (PowerCfg commands)\n if (IsCommandBasedSetting)\n {\n _logService.Log(LogLevel.Info, $\"Applying command-based setting: {Name}, IsSelected={IsSelected}\");\n \n // Get the PowerPlanService from the application services\n var powerPlanService = GetPowerPlanService();\n if (powerPlanService == null)\n {\n _logService.Log(LogLevel.Error, $\"Cannot apply command-based setting: {Name} - PowerPlanService not found\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = \"Failed to apply setting: PowerPlanService not found\";\n return;\n }\n \n // Get the PowerCfg settings from CustomProperties\n var powerCfgSettings = CustomProperties[\"PowerCfgSettings\"] as List;\n if (powerCfgSettings == null || powerCfgSettings.Count == 0)\n {\n _logService.Log(LogLevel.Error, $\"Cannot apply command-based setting: {Name} - PowerCfgSettings is null or empty\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = \"Failed to apply setting: PowerCfgSettings is null or empty\";\n return;\n }\n \n bool success;\n \n if (IsSelected)\n {\n // Apply the PowerCfg settings when enabling\n _logService.Log(LogLevel.Info, $\"Enabling command-based setting: {Name}\");\n success = await powerPlanService.ApplyPowerCfgSettingsAsync(powerCfgSettings);\n }\n else\n {\n // Apply the disabled values when disabling\n _logService.Log(LogLevel.Info, $\"Disabling command-based setting: {Name}\");\n \n // Create a list of PowerCfgSetting objects with disabled values\n var disabledSettings = new List();\n foreach (var powerCfgSetting in powerCfgSettings)\n {\n if (!string.IsNullOrEmpty(powerCfgSetting.DisabledValue))\n {\n disabledSettings.Add(new Winhance.Core.Features.Optimize.Models.PowerCfgSetting\n {\n Command = powerCfgSetting.DisabledValue.StartsWith(\"powercfg \")\n ? powerCfgSetting.DisabledValue\n : \"powercfg \" + powerCfgSetting.DisabledValue,\n Description = \"Restore default: \" + powerCfgSetting.Description,\n EnabledValue = powerCfgSetting.DisabledValue,\n DisabledValue = powerCfgSetting.EnabledValue\n });\n }\n }\n \n // Apply the disabled settings\n if (disabledSettings.Count > 0)\n {\n success = await powerPlanService.ApplyPowerCfgSettingsAsync(disabledSettings);\n }\n else\n {\n // If no disabled settings are defined, consider it a success\n _logService.Log(LogLevel.Warning, $\"No disabled values defined for command-based setting: {Name}\");\n success = true;\n }\n }\n \n if (success)\n {\n _logService.Log(LogLevel.Info, $\"Successfully applied command-based setting: {Name}\");\n Status = IsSelected ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n StatusMessage = IsSelected ? \"Setting applied successfully\" : \"Setting disabled successfully\";\n \n // Set a dummy current value to prevent warning icon\n CurrentValue = IsSelected ? \"Enabled\" : \"Disabled\";\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to apply command-based setting: {Name}\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = \"Failed to apply setting\";\n }\n \n return;\n }\n\n // Check if we have linked registry settings\n if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Applying linked registry settings for {Name}\");\n var linkedResult = await _registryService.ApplyLinkedSettingsAsync(LinkedRegistrySettings, IsSelected);\n\n if (linkedResult)\n {\n _logService.Log(LogLevel.Info, $\"Successfully applied linked settings for {Name}\");\n Status = RegistrySettingStatus.Applied;\n StatusMessage = \"Settings applied successfully\";\n\n // Update tooltip data for linked settings\n if (_registryService != null && LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n // Update the tooltip data\n LinkedRegistrySettingsWithValues.Clear();\n\n // For linked settings, get fresh values from registry\n foreach (var regSetting in LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = _registryService.GetValue(\n RegistryExtensions.GetRegistryHiveString(regSetting.Hive) + \"\\\\\" + regSetting.SubKey,\n regSetting.Name);\n LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n\n // Update the main current value display with the primary or first setting\n var primarySetting = LinkedRegistrySettings.Settings.FirstOrDefault(s => s.IsPrimary) ??\n LinkedRegistrySettings.Settings.FirstOrDefault();\n if (primarySetting != null)\n {\n var primaryValue = _registryService.GetValue(\n RegistryExtensions.GetRegistryHiveString(primarySetting.Hive) + \"\\\\\" + primarySetting.SubKey,\n primarySetting.Name);\n CurrentValue = primaryValue;\n }\n }\n\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to apply linked settings for {Name}\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = \"Failed to apply settings\";\n }\n return;\n }\n\n // Fall back to single registry setting if no linked settings\n if (RegistrySetting == null)\n {\n _logService.Log(LogLevel.Error, $\"Cannot apply setting: {Name} - Registry setting is null\");\n return;\n }\n\n string valueToSet = string.Empty;\n object valueObject;\n\n // Determine value to set based on control type\n switch (ControlType)\n {\n case ControlType.BinaryToggle:\n if (IsSelected)\n {\n // When toggle is ON, use EnabledValue if available, otherwise fall back to RecommendedValue\n valueObject = RegistrySetting.EnabledValue ?? RegistrySetting.RecommendedValue;\n }\n else\n {\n // When toggle is OFF, use DisabledValue if available, otherwise fall back to DefaultValue\n valueObject = RegistrySetting.DisabledValue ?? RegistrySetting.DefaultValue;\n }\n break;\n\n case ControlType.ThreeStateSlider:\n // Map slider value to appropriate setting value\n valueObject = SliderValue;\n break;\n\n case ControlType.Custom:\n default:\n // Custom handling would go here\n valueObject = IsSelected ?\n (RegistrySetting.EnabledValue ?? RegistrySetting.RecommendedValue) :\n (RegistrySetting.DisabledValue ?? RegistrySetting.DefaultValue);\n break;\n }\n\n // Check if this registry setting requires special handling\n if (RegistrySetting.RequiresSpecialHandling() && \n RegistrySetting.ApplySpecialHandling(_registryService, IsSelected))\n {\n // Special handling was applied successfully\n _logService.Log(LogLevel.Info, $\"Special handling applied for {RegistrySetting.Name}\");\n Status = RegistrySettingStatus.Applied;\n StatusMessage = \"Setting applied successfully\";\n \n // Update current value for tooltip display\n if (_registryService != null)\n {\n // Get the current value after special handling\n var currentValue = _registryService.GetValue(\n RegistryExtensions.GetRegistryHiveString(RegistrySetting.Hive) + \"\\\\\" + RegistrySetting.SubKey,\n RegistrySetting.Name);\n \n CurrentValue = currentValue;\n \n // Update the tooltip data\n LinkedRegistrySettingsWithValues.Clear();\n LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(RegistrySetting, currentValue));\n }\n \n return;\n }\n else\n {\n // Apply the registry change normally\n var result = _registryService.SetValue(\n RegistryExtensions.GetRegistryHiveString(RegistrySetting.Hive) + \"\\\\\" + RegistrySetting.SubKey,\n RegistrySetting.Name,\n valueObject,\n RegistrySetting.ValueType);\n\n if (result)\n {\n _logService.Log(LogLevel.Info, $\"Setting applied: {Name}\");\n Status = RegistrySettingStatus.Applied;\n StatusMessage = \"Setting applied successfully\";\n\n // Update current value for tooltip display\n if (_registryService != null)\n {\n // Update the current value\n CurrentValue = valueObject;\n\n // Update the tooltip data\n LinkedRegistrySettingsWithValues.Clear();\n if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n // For linked settings\n foreach (var regSetting in LinkedRegistrySettings.Settings)\n {\n // For the setting that was just changed, use the new value\n if (regSetting.SubKey == RegistrySetting.SubKey &&\n regSetting.Name == RegistrySetting.Name &&\n regSetting.Hive == RegistrySetting.Hive)\n {\n LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, valueObject));\n }\n else\n {\n // For other linked settings, get the current value from registry\n var regCurrentValue = _registryService.GetValue(\n RegistryExtensions.GetRegistryHiveString(regSetting.Hive) + \"\\\\\" + regSetting.SubKey,\n regSetting.Name);\n LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n }\n }\n else if (RegistrySetting != null)\n {\n // For single setting\n LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(RegistrySetting, valueObject));\n }\n }\n\n // Check if restart is required\n bool requiresRestart = Name.Contains(\"restart\", StringComparison.OrdinalIgnoreCase);\n if (requiresRestart && _dialogService != null)\n {\n _dialogService.ShowMessage(\n \"This change requires a system restart to take effect.\",\n \"Restart Required\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to apply setting: {Name}\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = \"Failed to apply setting\";\n\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"Failed to apply {Name}. This may require administrator privileges.\",\n \"Error\");\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying setting: {ex.Message}\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = $\"Error: {ex.Message}\";\n\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"An error occurred: {ex.Message}\",\n \"Error\");\n }\n }\n finally\n {\n IsApplying = false;\n }\n }\n\n /// \n /// Gets all settings from all view models in the application.\n /// \n /// A list of all settings, or null if none found.\n protected virtual List? GetAllSettings()\n {\n try\n {\n _logService?.Log(LogLevel.Info, $\"Getting all settings for dependency check\");\n \n // Check if we have a dependency manager with a settings registry\n if (_dependencyManager is IDependencyManager dependencyManager && \n dependencyManager.GetType().GetProperty(\"SettingsRegistry\")?.GetValue(dependencyManager) is ISettingsRegistry settingsRegistry)\n {\n var settings = settingsRegistry.GetAllSettings();\n if (settings.Count > 0)\n {\n _logService?.Log(LogLevel.Info, $\"Found {settings.Count} settings in settings registry via dependency manager\");\n return settings;\n }\n }\n \n // If no settings registry is available or it's empty, fall back to the original implementation\n var result = new List();\n var app = System.Windows.Application.Current;\n if (app == null) return null;\n\n // Try to find all settings view models\n foreach (System.Windows.Window window in app.Windows)\n {\n if (window.DataContext != null)\n {\n // Look for view models that have a Settings property\n var settingsProperties = window.DataContext.GetType().GetProperties()\n .Where(p => p.Name == \"Settings\" || p.Name.EndsWith(\"Settings\"));\n\n foreach (var prop in settingsProperties)\n {\n var value = prop.GetValue(window.DataContext);\n if (value is IEnumerable settings)\n {\n result.AddRange(settings);\n _logService?.Log(LogLevel.Info, $\"Found {settings.Count()} settings in {prop.Name}\");\n }\n }\n\n // Also look for view models that might contain other view models with settings\n var viewModelProperties = window.DataContext.GetType().GetProperties()\n .Where(p => p.Name.EndsWith(\"ViewModel\") && p.Name != \"DataContext\");\n\n foreach (var prop in viewModelProperties)\n {\n var viewModel = prop.GetValue(window.DataContext);\n if (viewModel != null)\n {\n var nestedSettingsProps = viewModel.GetType().GetProperties()\n .Where(p => p.Name == \"Settings\" || p.Name.EndsWith(\"Settings\"));\n\n foreach (var nestedProp in nestedSettingsProps)\n {\n var value = nestedProp.GetValue(viewModel);\n if (value is IEnumerable settings)\n {\n result.AddRange(settings);\n _logService?.Log(LogLevel.Info, $\"Found {settings.Count()} settings in {prop.Name}.{nestedProp.Name}\");\n }\n }\n }\n }\n }\n }\n\n // If we found settings, return them\n if (result.Count > 0)\n {\n _logService?.Log(LogLevel.Info, $\"Found a total of {result.Count} settings through property scanning\");\n \n // Log the settings we found\n foreach (var setting in result)\n {\n _logService?.Log(LogLevel.Info, $\"Found setting: {setting.Id} - {setting.Name}\");\n }\n \n // If we found a settings registry earlier, register these settings for future use\n if (_dependencyManager is IDependencyManager dependencyManager2 && \n dependencyManager2.GetType().GetProperty(\"SettingsRegistry\")?.GetValue(dependencyManager2) is ISettingsRegistry settingsRegistry2)\n {\n foreach (var setting in result)\n {\n settingsRegistry2.RegisterSetting(setting);\n }\n _logService?.Log(LogLevel.Info, $\"Registered {result.Count} settings in settings registry for future use\");\n }\n \n return result;\n }\n\n _logService?.Log(LogLevel.Warning, \"Could not find any settings for dependency check\");\n return null;\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Error getting all settings: {ex.Message}\");\n return null;\n }\n }\n \n /// \n /// Gets the PowerPlanService from the application services.\n /// \n /// The PowerPlanService, or null if not found.\n protected Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService? GetPowerPlanService()\n {\n // If we already have a PowerPlanService, return it\n if (_powerPlanService != null)\n {\n return _powerPlanService;\n }\n \n try\n {\n // Try to get the PowerPlanService from the application services\n var app = System.Windows.Application.Current;\n if (app == null) return null;\n \n // Check if the application has a GetService method\n var getServiceMethod = app.GetType().GetMethod(\"GetService\", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);\n if (getServiceMethod != null)\n {\n // Call the GetService method to get the PowerPlanService\n var powerPlanService = getServiceMethod.Invoke(app, new object[] { typeof(Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService) });\n return powerPlanService as Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService;\n }\n \n // If the application doesn't have a GetService method, try to find the PowerPlanService in the application resources\n foreach (System.Windows.Window window in app.Windows)\n {\n if (window.DataContext != null)\n {\n // Look for view models that might have a PowerPlanService property\n var powerPlanServiceProperty = window.DataContext.GetType().GetProperty(\"PowerPlanService\");\n if (powerPlanServiceProperty != null)\n {\n var powerPlanService = powerPlanServiceProperty.GetValue(window.DataContext);\n if (powerPlanService is Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService)\n {\n return powerPlanService as Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService;\n }\n }\n \n // Look for view models that might contain other view models with a PowerPlanService property\n var viewModelProperties = window.DataContext.GetType().GetProperties()\n .Where(p => p.Name.EndsWith(\"ViewModel\") && p.Name != \"DataContext\");\n \n foreach (var prop in viewModelProperties)\n {\n var viewModel = prop.GetValue(window.DataContext);\n if (viewModel != null)\n {\n var nestedPowerPlanServiceProperty = viewModel.GetType().GetProperty(\"PowerPlanService\");\n if (nestedPowerPlanServiceProperty != null)\n {\n var powerPlanService = nestedPowerPlanServiceProperty.GetValue(viewModel);\n if (powerPlanService is Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService)\n {\n return powerPlanService as Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService;\n }\n }\n \n // Check if this view model has a _powerPlanService field\n var powerPlanServiceField = viewModel.GetType().GetField(\"_powerPlanService\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (powerPlanServiceField != null)\n {\n var powerPlanService = powerPlanServiceField.GetValue(viewModel);\n if (powerPlanService is Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService)\n {\n return powerPlanService as Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService;\n }\n }\n }\n }\n }\n }\n \n return null;\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Error getting PowerPlanService: {ex.Message}\");\n return null;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppLoadingService.cs", "using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Helpers;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n public class AppLoadingService : IAppLoadingService\n {\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IPackageManager _packageManager;\n private readonly ILogService _logService;\n private readonly ConcurrentDictionary _statusCache = new();\n\n public AppLoadingService(\n IAppDiscoveryService appDiscoveryService,\n IPackageManager packageManager,\n ILogService logService)\n {\n _appDiscoveryService = appDiscoveryService;\n _packageManager = packageManager;\n _logService = logService;\n }\n\n /// \n public async Task>> LoadAppsAsync()\n {\n try\n {\n var apps = await _appDiscoveryService.GetStandardAppsAsync();\n return OperationResult>.Succeeded(apps);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to load standard apps\", ex);\n return OperationResult>.Failed(\"Failed to load standard apps\", ex);\n }\n }\n\n // Removed LoadInstallableAppsAsync as it's not in the interface\n\n public async Task> LoadCapabilitiesAsync()\n {\n try\n {\n // This is a placeholder implementation\n // In a real implementation, this would query the system for available capabilities\n _logService.LogInformation(\"Loading Windows capabilities\");\n \n // Return an empty list for now\n return Enumerable.Empty();\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to load capabilities\", ex);\n return Enumerable.Empty();\n }\n }\n\n public async Task GetItemInstallStatusAsync(IInstallableItem item)\n {\n ValidationHelper.NotNull(item, nameof(item));\n ValidationHelper.NotNullOrEmpty(item.PackageId, nameof(item.PackageId));\n\n if (_statusCache.TryGetValue(item.PackageId, out var cachedStatus))\n {\n return cachedStatus;\n }\n\n var isInstalled = await _packageManager.IsAppInstalledAsync(item.PackageId);\n _statusCache[item.PackageId] = isInstalled;\n return isInstalled;\n }\n\n // Added missing GetInstallStatusAsync method\n /// \n public async Task> GetInstallStatusAsync(string appId)\n {\n try\n {\n ValidationHelper.NotNullOrEmpty(appId, nameof(appId));\n\n // Use the existing cache logic, assuming 'true' maps to Success\n if (_statusCache.TryGetValue(appId, out var cachedStatus))\n {\n return OperationResult.Succeeded(\n cachedStatus ? InstallStatus.Success : InstallStatus.NotFound\n );\n }\n\n var isInstalled = await _packageManager.IsAppInstalledAsync(appId);\n _statusCache[appId] = isInstalled;\n return OperationResult.Succeeded(\n isInstalled ? InstallStatus.Success : InstallStatus.NotFound\n );\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to get installation status for app {appId}\", ex);\n return OperationResult.Failed($\"Failed to get installation status: {ex.Message}\", ex);\n }\n }\n\n // Added missing SetInstallStatusAsync method\n /// \n public Task> SetInstallStatusAsync(string appId, InstallStatus status)\n {\n try\n {\n ValidationHelper.NotNullOrEmpty(appId, nameof(appId));\n // This service primarily reads status; setting might not be its responsibility\n // or might require interaction with the package manager.\n // For now, just update the cache.\n _logService.LogWarning($\"Attempting to set install status for {appId} to {status} (cache only).\");\n _statusCache[appId] = (status == InstallStatus.Success); // Corrected enum member\n return Task.FromResult(OperationResult.Succeeded(true)); // Assume cache update is always successful\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to set installation status for app {appId}\", ex);\n return Task.FromResult(OperationResult.Failed($\"Failed to set installation status: {ex.Message}\", ex));\n }\n }\n\n\n public async Task> GetBatchInstallStatusAsync(IEnumerable packageIds)\n {\n ValidationHelper.NotNull(packageIds, nameof(packageIds));\n \n var distinctIds = packageIds\n .Where(id => !string.IsNullOrWhiteSpace(id))\n .Distinct()\n .ToList();\n\n if (distinctIds.Count == 0)\n throw new ArgumentException(\"Must provide at least one valid package ID\", nameof(packageIds));\n var results = new Dictionary();\n\n foreach (var id in distinctIds)\n {\n if (_statusCache.TryGetValue(id, out var cachedStatus))\n {\n results[id] = cachedStatus;\n }\n else\n {\n var isInstalled = await _packageManager.IsAppInstalledAsync(id);\n _statusCache[id] = isInstalled;\n results[id] = isInstalled;\n }\n }\n\n return results;\n } // Removed extra closing brace here\n\n\n /// \n public async Task> RefreshInstallationStatusAsync(IEnumerable apps)\n {\n try\n {\n ValidationHelper.NotNull(apps, nameof(apps));\n\n var packageIds = apps\n .Where(app => app != null && !string.IsNullOrWhiteSpace(app.PackageID)) // Use PackageID from AppInfo\n .Select(app => app.PackageID)\n .Distinct();\n \n if (!packageIds.Any())\n {\n return OperationResult.Succeeded(true); // No apps to refresh\n }\n \n var statuses = await GetBatchInstallStatusAsync(packageIds);\n\n foreach (var app in apps) // Iterate through AppInfo\n {\n if (app != null && statuses.TryGetValue(app.PackageID, out var isInstalled)) // Use PackageID\n {\n _statusCache[app.PackageID] = isInstalled; // Use PackageID\n // Optionally update the IsInstalled property on the AppInfo object itself\n // app.IsInstalled = isInstalled; // This depends if AppInfo is mutable and if this side-effect is desired\n }\n }\n \n return OperationResult.Succeeded(true);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to refresh installation status\", ex);\n return OperationResult.Failed(\"Failed to refresh installation status\", ex);\n }\n }\n\n public void ClearStatusCache()\n {\n _statusCache.Clear();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ConfigurationApplierService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for applying configuration settings to different view models.\n /// \n public class ConfigurationApplierService : IConfigurationApplierService\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n private readonly IEnumerable _sectionAppliers;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n /// The section-specific configuration appliers.\n public ConfigurationApplierService(\n IServiceProvider serviceProvider,\n ILogService logService,\n IEnumerable sectionAppliers)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _sectionAppliers = sectionAppliers ?? throw new ArgumentNullException(nameof(sectionAppliers));\n }\n\n /// \n /// Applies configuration settings to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A dictionary of section names and their application result.\n public async Task> ApplySectionsAsync(UnifiedConfigurationFile config, IEnumerable selectedSections)\n {\n var sectionResults = new Dictionary();\n \n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120)); // Increased timeout\n var cancellationToken = cancellationTokenSource.Token;\n \n // Track execution time\n var startTime = DateTime.Now;\n _logService.Log(LogLevel.Info, $\"Starting ApplySectionsAsync at {startTime}\");\n \n foreach (var section in selectedSections)\n {\n var sectionStartTime = DateTime.Now;\n _logService.Log(LogLevel.Info, $\"Processing section: {section} at {sectionStartTime}\");\n \n // Check for cancellation\n if (cancellationToken.IsCancellationRequested)\n {\n _logService.Log(LogLevel.Warning, $\"Skipping section {section} due to timeout\");\n sectionResults[section] = false;\n continue;\n }\n \n // Extract the section from the unified configuration\n var configFile = ExtractSectionFromUnifiedConfiguration(config, section);\n \n if (configFile == null)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to extract section {section} from unified configuration\");\n sectionResults[section] = false;\n continue;\n }\n \n if (configFile.Items == null || !configFile.Items.Any())\n {\n _logService.Log(LogLevel.Warning, $\"Section {section} is empty or not included in the unified configuration\");\n sectionResults[section] = false;\n continue;\n }\n \n _logService.Log(LogLevel.Info, $\"Extracted section {section} with {configFile.Items.Count} items\");\n \n // Apply the configuration to the appropriate view model\n bool sectionResult = false;\n \n try\n {\n // Find the appropriate section applier\n var sectionApplier = _sectionAppliers.FirstOrDefault(a => a.SectionName.Equals(section, StringComparison.OrdinalIgnoreCase));\n \n if (sectionApplier != null)\n {\n _logService.Log(LogLevel.Info, $\"Starting to apply configuration for section {section}\");\n \n // Apply with timeout protection\n var applyTask = sectionApplier.ApplyConfigAsync(configFile);\n \n // Set a section-specific timeout (longer for Optimize section which has power plan operations)\n int timeoutMs = section.Equals(\"Optimize\", StringComparison.OrdinalIgnoreCase) ? 60000 : 30000; // Increased timeouts\n \n _logService.Log(LogLevel.Info, $\"Setting timeout of {timeoutMs}ms for section {section}\");\n \n // Create a separate cancellation token source for this section\n using var sectionCts = new CancellationTokenSource(timeoutMs);\n var sectionCancellationToken = sectionCts.Token;\n \n try\n {\n // Wait for the task to complete or timeout\n var delayTask = Task.Delay(timeoutMs, sectionCancellationToken);\n var completedTask = await Task.WhenAny(applyTask, delayTask);\n \n if (completedTask == applyTask)\n {\n sectionResult = await applyTask;\n _logService.Log(LogLevel.Info, $\"Section {section} applied with result: {sectionResult}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Applying section {section} timed out after {timeoutMs}ms\");\n \n // Try to cancel the operation if possible\n sectionCts.Cancel();\n \n // Log detailed information about the section\n _logService.Log(LogLevel.Warning, $\"Section {section} details: {configFile.Items?.Count ?? 0} items\");\n \n sectionResult = false;\n }\n }\n catch (OperationCanceledException)\n {\n _logService.Log(LogLevel.Warning, $\"Section {section} application was canceled\");\n sectionResult = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No applier found for section: {section}\");\n sectionResult = false;\n }\n \n // If we have items but didn't update any, consider it a success\n // This handles the case where all items are already in the desired state\n if (!sectionResult && configFile.Items != null && configFile.Items.Any())\n {\n _logService.Log(LogLevel.Info, $\"No items were updated in section {section}, but considering it a success since configuration was applied\");\n sectionResult = true;\n }\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, $\"Applying section {section} was canceled due to timeout\");\n sectionResult = false;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying configuration to section {section}: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n sectionResult = false;\n }\n \n sectionResults[section] = sectionResult;\n }\n \n // Calculate and log execution time\n var endTime = DateTime.Now;\n var executionTime = endTime - startTime;\n _logService.Log(LogLevel.Info, $\"Completed ApplySectionsAsync in {executionTime.TotalSeconds:F2} seconds\");\n \n // Log summary of results\n foreach (var result in sectionResults)\n {\n _logService.Log(LogLevel.Info, $\"Section {result.Key}: {(result.Value ? \"Success\" : \"Failed\")}\");\n }\n \n return sectionResults;\n }\n\n private ConfigurationFile ExtractSectionFromUnifiedConfiguration(UnifiedConfigurationFile unifiedConfig, string section)\n {\n try\n {\n var configFile = new ConfigurationFile\n {\n ConfigType = section,\n Items = new List()\n };\n\n switch (section)\n {\n case \"WindowsApps\":\n configFile.Items = unifiedConfig.WindowsApps.Items;\n break;\n case \"ExternalApps\":\n configFile.Items = unifiedConfig.ExternalApps.Items;\n break;\n case \"Customize\":\n configFile.Items = unifiedConfig.Customize.Items;\n break;\n case \"Optimize\":\n configFile.Items = unifiedConfig.Optimize.Items;\n break;\n default:\n _logService.Log(LogLevel.Warning, $\"Unknown section: {section}\");\n return null;\n }\n\n return configFile;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error extracting section {section}: {ex.Message}\");\n return null;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/App.xaml.cs", "using System;\nusing System.IO;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Services;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\nusing Winhance.Infrastructure.Features.Common.Services;\nusing Winhance.Infrastructure.Features.Customize.Services;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Implementations;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.Common.Services.Configuration;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.Customize.ViewModels;\nusing Winhance.WPF.Features.Customize.Views;\nusing Winhance.WPF.Features.Optimize.ViewModels;\nusing Winhance.WPF.Features.Optimize.Views;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\nusing Winhance.WPF.Features.SoftwareApps.Views;\n\nnamespace Winhance.WPF\n{\n public partial class App : Application\n {\n private readonly IHost _host;\n\n public App()\n {\n // Add global unhandled exception handlers\n AppDomain.CurrentDomain.UnhandledException += (sender, args) =>\n {\n var ex = args.ExceptionObject as Exception;\n LogStartupError($\"Unhandled AppDomain exception: {ex?.Message}\", ex);\n };\n\n Current.DispatcherUnhandledException += (sender, args) =>\n {\n LogStartupError(\n $\"Unhandled Dispatcher exception: {args.Exception.Message}\",\n args.Exception\n );\n args.Handled = true; // Prevent the application from crashing\n };\n\n TaskScheduler.UnobservedTaskException += (sender, args) =>\n {\n LogStartupError(\n $\"Unobserved Task exception: {args.Exception.Message}\",\n args.Exception\n );\n args.SetObserved(); // Prevent the application from crashing\n };\n\n _host = Host.CreateDefaultBuilder()\n .ConfigureServices(\n (context, services) =>\n {\n ConfigureServices(services);\n }\n )\n .Build();\n\n LogStartupError(\"Application constructor completed\");\n }\n\n protected override async void OnStartup(StartupEventArgs e)\n {\n LogStartupError(\"OnStartup method beginning\");\n LoadingWindow? loadingWindow = null;\n\n // Ensure the application has administrator privileges\n try\n {\n LogStartupError(\"Checking for administrator privileges\");\n var systemServices = _host.Services.GetService();\n if (systemServices != null)\n {\n bool isAdmin = systemServices.RequireAdministrator();\n LogStartupError($\"Administrator privileges check result: {isAdmin}\");\n }\n else\n {\n LogStartupError(\"ISystemServices not available for admin check\");\n }\n }\n catch (Exception adminEx)\n {\n LogStartupError(\n \"Error checking administrator privileges: \" + adminEx.Message,\n adminEx\n );\n }\n\n // Set the application icon for all windows\n try\n {\n // We'll continue to use the original icon for the application icon (taskbar, shortcuts, etc.)\n var iconUri = new Uri(\"/Resources/AppIcons/winhance-rocket.ico\", UriKind.Relative);\n Current.Resources[\"ApplicationIcon\"] = new System.Windows.Media.Imaging.BitmapImage(\n iconUri\n );\n LogStartupError(\"Application icon set successfully\");\n }\n catch (Exception iconEx)\n {\n LogStartupError(\"Failed to set application icon: \" + iconEx.Message, iconEx);\n }\n\n try\n {\n // Create and show loading window first\n LogStartupError(\"Attempting to get theme manager\");\n var themeManager = _host.Services.GetRequiredService();\n LogStartupError(\"Got theme manager\");\n\n // Ensure the IsDarkTheme resource is set in the application resources\n Application.Current.Resources[\"IsDarkTheme\"] = themeManager.IsDarkTheme;\n LogStartupError($\"Set IsDarkTheme resource to {themeManager.IsDarkTheme}\");\n\n LogStartupError(\"Attempting to get task progress service\");\n var initialProgressService =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got task progress service\");\n\n LogStartupError(\"Creating loading window\");\n loadingWindow = new LoadingWindow(themeManager, initialProgressService);\n LogStartupError(\"Loading window created\");\n\n LogStartupError(\"Showing loading window\");\n loadingWindow.Show();\n LogStartupError(\"Loading window shown\");\n\n // Start the host and initialize services\n LogStartupError(\"Starting host\");\n await _host.StartAsync();\n LogStartupError(\"Host started\");\n\n // Get required services\n LogStartupError(\"Getting main window\");\n var mainWindow = _host.Services.GetRequiredService();\n LogStartupError(\"Got main window\");\n\n LogStartupError(\"Getting main view model\");\n var mainViewModel = _host.Services.GetRequiredService();\n LogStartupError(\"Got main view model\");\n\n LogStartupError(\"Getting software apps view model\");\n var windowsAppsViewModel =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got Windows apps view model\");\n\n // Set the DataContext\n LogStartupError(\"Setting main window DataContext\");\n mainWindow.DataContext = mainViewModel;\n LogStartupError(\"Main window DataContext set\");\n\n // Preload the SoftwareAppsViewModel data\n LogStartupError(\"Loading apps and checking installation status...\");\n\n // Create a progress handler to update the loading window\n var progressHandler = new EventHandler(\n (sender, args) =>\n {\n if (\n loadingWindow != null\n && loadingWindow.DataContext is LoadingWindowViewModel vm\n )\n {\n vm.Progress = args.Progress * 100;\n vm.StatusMessage = args.StatusText;\n vm.IsIndeterminate = args.IsIndeterminate;\n vm.ShowProgressText = !args.IsIndeterminate && args.IsTaskRunning;\n\n // Update detail message based on the current operation\n if (args.StatusText.Contains(\"Loading installable apps\"))\n {\n vm.DetailMessage = \"Discovering available applications...\";\n }\n else if (args.StatusText.Contains(\"Loading removable apps\"))\n {\n vm.DetailMessage = \"Identifying Windows applications...\";\n }\n else if (args.StatusText.Contains(\"Checking installation status\"))\n {\n vm.DetailMessage = \"Verifying which applications are installed...\";\n }\n else if (args.StatusText.Contains(\"Organizing apps\"))\n {\n vm.DetailMessage = \"Sorting applications for display...\";\n }\n }\n }\n );\n\n // Subscribe to progress events\n LogStartupError(\"Getting task progress service\");\n var taskProgressService = _host.Services.GetRequiredService();\n LogStartupError(\"Got task progress service\");\n\n LogStartupError(\"Subscribing to progress events\");\n taskProgressService.ProgressChanged += progressHandler;\n LogStartupError(\"Subscribed to progress events\");\n\n try\n {\n // Load apps and check installation status while showing the loading screen\n LogStartupError(\n \"Starting LoadAppsAndCheckInstallationStatusAsync for WindowsAppsViewModel\"\n );\n await windowsAppsViewModel.LoadAppsAndCheckInstallationStatusAsync();\n LogStartupError(\"WindowsApps loaded and installation status checked\");\n\n // Also preload the SoftwareAppsViewModel data\n LogStartupError(\"Getting SoftwareAppsViewModel\");\n var softwareAppsViewModel =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got SoftwareAppsViewModel\");\n\n LogStartupError(\"Starting Initialize for SoftwareAppsViewModel\");\n await softwareAppsViewModel.InitializeCommand.ExecuteAsync(null);\n LogStartupError(\"SoftwareAppsViewModel initialized\");\n\n // Preload the OptimizeViewModel to ensure all registry settings are loaded\n LogStartupError(\"Getting OptimizeViewModel\");\n var optimizeViewModel = _host.Services.GetRequiredService();\n LogStartupError(\"Got OptimizeViewModel\");\n\n // Initialize the OptimizeViewModel and wait for it to complete\n LogStartupError(\"Starting Initialize for OptimizeViewModel\");\n if (loadingWindow?.DataContext is LoadingWindowViewModel loadingVM)\n {\n loadingVM.StatusMessage = \"Loading system settings...\";\n loadingVM.DetailMessage = \"Checking registry settings...\";\n }\n await optimizeViewModel.InitializeCommand.ExecuteAsync(null);\n LogStartupError(\"OptimizeViewModel initialized\");\n\n // Preload the CustomizeViewModel to ensure all customization settings are loaded\n LogStartupError(\"Getting CustomizeViewModel\");\n var customizeViewModel =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got CustomizeViewModel\");\n\n // Initialize the CustomizeViewModel and wait for it to complete\n LogStartupError(\"Starting Initialize for CustomizeViewModel\");\n if (loadingWindow?.DataContext is LoadingWindowViewModel loadingVMCustomize)\n {\n loadingVMCustomize.StatusMessage = \"Loading customization settings...\";\n loadingVMCustomize.DetailMessage = \"Checking customization options...\";\n }\n await customizeViewModel.InitializeCommand.ExecuteAsync(null);\n LogStartupError(\"CustomizeViewModel initialized\");\n }\n finally\n {\n // Unsubscribe from progress events\n LogStartupError(\"Unsubscribing from progress events\");\n taskProgressService.ProgressChanged -= progressHandler;\n LogStartupError(\"Unsubscribed from progress events\");\n }\n\n // Show the main window\n LogStartupError(\"Showing main window\");\n mainWindow.Show();\n LogStartupError(\"Main window shown\");\n\n // Close the loading window\n LogStartupError(\"Closing loading window\");\n loadingWindow.Close();\n loadingWindow = null;\n LogStartupError(\"Loading window closed\");\n\n // Check for updates\n await CheckForUpdatesAsync(mainWindow);\n\n LogStartupError(\"Calling base.OnStartup\");\n base.OnStartup(e);\n LogStartupError(\"OnStartup method completed successfully\");\n }\n catch (Exception ex)\n {\n LogStartupError(\"Error during startup\", ex);\n MessageBox.Show(\n $\"Error during startup: {ex.Message}\\n\\nStack Trace:\\n{ex.StackTrace}\",\n \"Startup Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error\n );\n\n // Ensure loading window is closed if there was an error\n if (loadingWindow != null)\n {\n loadingWindow.Close();\n }\n\n Current.Shutdown();\n }\n }\n\n private async Task CheckForUpdatesAsync(Window ownerWindow)\n {\n try\n {\n LogStartupError(\"Checking for updates...\");\n var versionService = _host.Services.GetRequiredService();\n var latestVersion = await versionService.CheckForUpdateAsync();\n\n if (latestVersion.IsUpdateAvailable)\n {\n LogStartupError($\"Update available: {latestVersion.Version}\");\n\n // Get current version\n var currentVersion = versionService.GetCurrentVersion();\n\n // Show the styled update dialog\n string message = \"Good News! A New Version of Winhance is available.\";\n\n // Create a download and install action\n Func downloadAndInstallAction = async () =>\n {\n await versionService.DownloadAndInstallUpdateAsync();\n\n // Close the application without showing a message\n System.Windows.Application.Current.Shutdown();\n };\n\n // Show the update dialog\n bool installNow = await UpdateDialog.ShowAsync(\n \"Update Available\",\n message,\n currentVersion,\n latestVersion,\n downloadAndInstallAction\n );\n\n if (installNow)\n {\n LogStartupError(\"User chose to download and install the update\");\n }\n else\n {\n LogStartupError(\"User chose to be reminded later\");\n }\n }\n else\n {\n LogStartupError(\"No updates available\");\n }\n }\n catch (Exception ex)\n {\n LogStartupError($\"Error checking for updates: {ex.Message}\", ex);\n // Don't show error to user, just log it\n }\n }\n\n protected override async void OnExit(ExitEventArgs e)\n {\n try\n {\n // Material Design resources are automatically unloaded\n\n // Dispose of the ThemeManager to clean up event subscriptions\n try\n {\n var themeManager = _host.Services.GetService();\n themeManager?.Dispose();\n }\n catch (Exception disposeEx)\n {\n LogStartupError(\"Error disposing ThemeManager\", disposeEx);\n }\n\n using (_host)\n {\n await _host.StopAsync();\n }\n }\n catch (Exception ex)\n {\n LogStartupError(\"Error during shutdown\", ex);\n }\n finally\n {\n base.OnExit(e);\n }\n }\n\n private void LogStartupError(string message, Exception? ex = null)\n {\n string fullMessage = $\"[{DateTime.Now}] {message}\";\n if (ex != null)\n {\n fullMessage += $\"\\nException: {ex.Message}\\nStack Trace: {ex.StackTrace}\";\n if (ex.InnerException != null)\n {\n fullMessage += $\"\\nInner Exception: {ex.InnerException.Message}\";\n }\n }\n\n try\n {\n string logPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\",\n \"WinhanceStartupLog.txt\"\n );\n\n // Ensure directory exists\n Directory.CreateDirectory(Path.GetDirectoryName(logPath));\n File.AppendAllText(logPath, $\"{fullMessage}\\n\");\n }\n catch\n {\n MessageBox.Show(\n fullMessage,\n \"Startup Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error\n );\n }\n }\n\n private void ConfigureServices(IServiceCollection services)\n {\n try\n {\n LogStartupError(\"Beginning service configuration...\");\n\n // Core Services\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton<\n Winhance.Core.Interfaces.Services.IFileSystemService,\n Winhance.Infrastructure.FileSystem.FileSystemService\n >();\n\n // Register the base services\n services.AddSingleton();\n services.AddSingleton(provider =>\n provider.GetRequiredService()\n );\n services.AddSingleton();\n services.AddSingleton(\n provider => new SpecialAppHandlerService(\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton<\n ISearchService,\n Winhance.Infrastructure.Features.Common.Services.SearchService\n >();\n services.AddSingleton<\n IConfigurationService,\n Winhance.Infrastructure.Features.Common.Services.ConfigurationService\n >();\n // Register UserPreferencesService as a singleton to ensure the same instance is used throughout the app\n services.AddSingleton(provider =>\n {\n var logService = provider.GetRequiredService();\n var userPreferencesService =\n new Features.Common.Services.UserPreferencesService(logService);\n\n // Log that the UserPreferencesService has been registered\n logService.Log(LogLevel.Info, \"UserPreferencesService registered as singleton\");\n\n return userPreferencesService;\n });\n services.AddSingleton(\n provider => new Winhance.WPF.Features.Common.Services.UnifiedConfigurationService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // Register configuration services\n services.AddConfigurationServices();\n\n // Keep the old service for backward compatibility during transition\n services.AddSingleton(\n provider => new Winhance.WPF.Features.Common.Services.ConfigurationCoordinatorService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton();\n\n // Register script generation services\n services.AddScriptGenerationServices();\n\n services.AddSingleton(\n provider => new PowerShellExecutionService(\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // Register power plan service\n services.AddSingleton<\n Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService,\n Winhance.Infrastructure.Features.Optimize.Services.PowerPlanService\n >();\n\n // Register the installation and removal services\n // Register WinGet verification methods\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n\n // Register the composite verifier\n services.AddSingleton();\n\n // Register the WinGet installer\n services.AddSingleton();\n\n // Register the adapter for backward compatibility\n services.AddSingleton<\n IWinGetInstallationService,\n WinGetInstallationServiceAdapter\n >();\n\n // Register the main installation service\n services.AddSingleton(\n provider => new AppInstallationService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton(provider => new AppRemovalService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n services.AddSingleton<\n ICapabilityInstallationService,\n CapabilityInstallationService\n >();\n services.AddSingleton(\n provider => new CapabilityRemovalService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton();\n services.AddSingleton(provider => new FeatureRemovalService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n // Register the orchestrator\n services.AddSingleton();\n\n // Register the PackageManager with its dependencies\n services.AddSingleton(provider => new PackageManager(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetService()\n ));\n\n // Register the InternetConnectivityService\n services.AddSingleton(\n provider => new Winhance.Infrastructure.Features.Common.Services.InternetConnectivityService(\n provider.GetRequiredService()\n )\n );\n\n // Register the AppInstallationCoordinatorService\n services.AddSingleton(\n provider => new Winhance.Infrastructure.Features.SoftwareApps.Services.AppInstallationCoordinatorService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetService(),\n provider.GetService()\n )\n );\n\n // Use fully qualified type name to resolve ambiguity between Winhance.Core.Models.WindowsService\n // and Winhance.Infrastructure.Features.Common.Services.WindowsSystemService\n services.AddSingleton(\n provider => new Winhance.Infrastructure.Features.Common.Services.WindowsSystemService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n null, // Intentionally not passing IThemeService to break circular dependency\n provider.GetRequiredService()\n )\n );\n\n // Register theme and wallpaper services\n services.AddSingleton();\n services.AddSingleton(provider => new ThemeService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton<\n Core.Features.Common.Interfaces.IDialogService,\n Features.Common.Services.DialogService\n >();\n services.AddSingleton();\n services.AddSingleton();\n\n // Register the notification service\n services.AddSingleton<\n Core.Features.UI.Interfaces.INotificationService,\n Winhance.Infrastructure.Features.UI.Services.NotificationService\n >();\n\n // Register the messenger service\n services.AddSingleton<\n Core.Features.Common.Interfaces.IMessengerService,\n Features.Common.Services.MessengerService\n >();\n\n // Register navigation service\n services.AddSingleton(\n provider =>\n {\n var navigationService = new FrameNavigationService(\n provider,\n provider.GetRequiredService()\n );\n\n // Register view mappings\n navigationService.RegisterViewMapping(\n \"SoftwareApps\",\n typeof(Features.SoftwareApps.Views.SoftwareAppsView),\n typeof(Features.SoftwareApps.ViewModels.SoftwareAppsViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"WindowsApps\",\n typeof(Features.SoftwareApps.Views.WindowsAppsView),\n typeof(Features.SoftwareApps.ViewModels.WindowsAppsViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"ExternalApps\",\n typeof(Features.SoftwareApps.Views.ExternalAppsView),\n typeof(Features.SoftwareApps.ViewModels.ExternalAppsViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"Optimize\",\n typeof(Features.Optimize.Views.OptimizeView),\n typeof(Features.Optimize.ViewModels.OptimizeViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"Customize\",\n typeof(Features.Customize.Views.CustomizeView),\n typeof(Features.Customize.ViewModels.CustomizeViewModel)\n );\n\n return navigationService;\n }\n );\n\n services.AddSingleton<\n IParameterSerializer,\n Winhance.Infrastructure.Features.Common.Services.JsonParameterSerializer\n >();\n\n // Register ThemeManager with navigation service dependency\n services.AddSingleton(\n provider => new Features.Common.Resources.Theme.ThemeManager(\n provider.GetRequiredService()\n )\n );\n\n // Register design-time data service\n services.AddSingleton<\n Features.Common.Services.IDesignTimeDataService,\n Features.Common.Services.DesignTimeDataService\n >();\n\n // Register ViewModels with explicit factory methods for all view models\n services.AddSingleton(provider => new MainViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton(provider => new WindowsAppsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton(provider => new ExternalAppsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n // Register UacSettingsService\n services.AddSingleton(\n provider => new UacSettingsService(\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // Register child ViewModels for OptimizeViewModel\n services.AddSingleton(\n provider => new WindowsSecurityOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new PrivacyOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new GamingandPerformanceOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new UpdateOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new PowerOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // ViewModels are registered above\n\n services.AddSingleton(provider => new OptimizeViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n // Register child ViewModels for CustomizeViewModel\n services.AddSingleton(\n provider => new TaskbarCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new StartMenuCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new ExplorerCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new ExplorerOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new NotificationOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new SoundOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new WindowsThemeCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(provider => new CustomizeViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton(provider => new SoftwareAppsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider\n ));\n\n // Register Views\n services.AddTransient(provider => new MainWindow(\n provider.GetRequiredService(),\n provider,\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n\n // Register version service\n services.AddSingleton();\n services.AddSingleton();\n\n // Register ApplicationCloseService\n services.AddSingleton();\n\n // Register logging service\n services.AddHostedService();\n\n LogStartupError(\"Service configuration complete\");\n }\n catch (Exception ex)\n {\n LogStartupError(\"Error during service configuration\", ex);\n throw;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/TaskProgressService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Threading;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service that manages task progress reporting across the application.\n /// \n public class TaskProgressService : ITaskProgressService\n {\n private readonly ILogService _logService;\n private int _currentProgress;\n private string _currentStatusText;\n private bool _isTaskRunning;\n private bool _isIndeterminate;\n private List _logMessages = new List();\n private CancellationTokenSource _cancellationSource;\n\n /// \n /// Gets whether a task is currently running.\n /// \n public bool IsTaskRunning => _isTaskRunning;\n\n /// \n /// Gets the current progress value (0-100).\n /// \n public int CurrentProgress => _currentProgress;\n\n /// \n /// Gets the current status text.\n /// \n public string CurrentStatusText => _currentStatusText;\n\n /// \n /// Gets whether the current task is in indeterminate mode.\n /// \n public bool IsIndeterminate => _isIndeterminate;\n\n /// \n /// Gets the cancellation token source for the current task.\n /// \n public CancellationTokenSource? CurrentTaskCancellationSource => _cancellationSource;\n\n /// \n /// Event raised when progress changes.\n /// \n public event EventHandler? ProgressUpdated;\n\n /// \n /// Event raised when progress changes (compatibility with App.xaml.cs).\n /// \n public event EventHandler? ProgressChanged;\n\n /// \n /// Event raised when a log message is added.\n /// \n public event EventHandler? LogMessageAdded;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public TaskProgressService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _currentProgress = 0;\n _currentStatusText = string.Empty;\n _isTaskRunning = false;\n _isIndeterminate = false;\n }\n\n /// \n /// Starts a new task with the specified name.\n /// \n /// The name of the task.\n /// Whether the task progress is indeterminate.\n /// A cancellation token source for the task.\n public CancellationTokenSource StartTask(string taskName, bool isIndeterminate = false)\n {\n // Cancel any existing task\n CancelCurrentTask();\n\n if (string.IsNullOrEmpty(taskName))\n {\n throw new ArgumentException(\"Task name cannot be null or empty.\", nameof(taskName));\n }\n\n _cancellationSource = new CancellationTokenSource();\n _currentProgress = 0;\n _currentStatusText = taskName;\n _isTaskRunning = true;\n _isIndeterminate = isIndeterminate;\n _logMessages.Clear();\n\n _logService.Log(LogLevel.Info, $\"Task started: {taskName}\"); // Corrected Log call\n AddLogMessage($\"Task started: {taskName}\");\n OnProgressChanged(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = taskName,\n IsIndeterminate = isIndeterminate,\n }\n );\n\n return _cancellationSource;\n }\n\n /// \n /// Updates the progress of the current task.\n /// \n /// The progress percentage (0-100).\n /// The status text.\n public void UpdateProgress(int progressPercentage, string? statusText = null)\n {\n if (!_isTaskRunning)\n {\n Debug.WriteLine(\"Warning: Attempting to update progress when no task is running.\");\n return;\n }\n\n if (progressPercentage < 0 || progressPercentage > 100)\n {\n throw new ArgumentOutOfRangeException(\n nameof(progressPercentage),\n \"Progress must be between 0 and 100.\"\n );\n }\n\n _currentProgress = progressPercentage;\n if (!string.IsNullOrEmpty(statusText))\n {\n _currentStatusText = statusText;\n _logService.Log(\n LogLevel.Info,\n $\"Task progress ({progressPercentage}%): {statusText}\"\n ); // Corrected Log call\n AddLogMessage($\"Task progress ({progressPercentage}%): {statusText}\");\n }\n else\n {\n _logService.Log(LogLevel.Info, $\"Task progress: {progressPercentage}%\"); // Corrected Log call\n AddLogMessage($\"Task progress: {progressPercentage}%\");\n }\n OnProgressChanged(\n new TaskProgressDetail\n {\n Progress = progressPercentage,\n StatusText = _currentStatusText,\n }\n );\n }\n\n /// \n /// Updates the progress with detailed information.\n /// \n /// The detailed progress information.\n public void UpdateDetailedProgress(TaskProgressDetail detail)\n {\n if (!_isTaskRunning)\n {\n Debug.WriteLine(\n \"Warning: Attempting to update detailed progress when no task is running.\"\n );\n return;\n }\n\n if (detail.Progress.HasValue)\n {\n if (detail.Progress.Value < 0 || detail.Progress.Value > 100)\n {\n throw new ArgumentOutOfRangeException(\n nameof(detail.Progress),\n \"Progress must be between 0 and 100.\"\n );\n }\n\n _currentProgress = (int)detail.Progress.Value;\n }\n\n if (!string.IsNullOrEmpty(detail.StatusText))\n {\n _currentStatusText = detail.StatusText;\n }\n\n _isIndeterminate = detail.IsIndeterminate;\n if (!string.IsNullOrEmpty(detail.DetailedMessage))\n {\n _logService.Log(detail.LogLevel, detail.DetailedMessage); // Corrected Log call\n AddLogMessage(detail.DetailedMessage);\n }\n OnProgressChanged(detail);\n }\n\n /// \n /// Completes the current task.\n /// \n public void CompleteTask()\n {\n if (!_isTaskRunning)\n {\n Debug.WriteLine(\"Warning: Attempting to complete a task when no task is running.\");\n return;\n }\n\n _currentProgress = 100;\n\n _isTaskRunning = false;\n _isIndeterminate = false;\n\n _logService.Log(LogLevel.Info, $\"Task completed: {_currentStatusText}\"); // Corrected Log call\n AddLogMessage($\"Task completed: {_currentStatusText}\");\n\n OnProgressChanged(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = _currentStatusText,\n DetailedMessage = \"Task completed\",\n }\n );\n\n // Dispose cancellation token source\n _cancellationSource?.Dispose();\n _cancellationSource = null;\n }\n\n /// \n /// Adds a log message.\n /// \n /// The message content.\n public void AddLogMessage(string message)\n {\n if (string.IsNullOrEmpty(message))\n return;\n\n _logMessages.Add(message);\n LogMessageAdded?.Invoke(this, message);\n }\n\n /// \n /// Cancels the current task.\n /// \n public void CancelCurrentTask()\n {\n if (_cancellationSource != null && !_cancellationSource.IsCancellationRequested)\n {\n _cancellationSource.Cancel();\n AddLogMessage(\"Task cancelled by user\");\n\n // Don't dispose here, as the task might still be using it\n // It will be disposed in CompleteTask or when a new task starts\n }\n }\n\n /// \n /// Creates a progress reporter for detailed progress.\n /// \n /// The progress reporter.\n public IProgress CreateDetailedProgress()\n {\n return new Progress(UpdateDetailedProgress);\n }\n\n /// \n /// Creates a progress reporter for PowerShell progress.\n /// \n /// The progress reporter.\n public IProgress CreatePowerShellProgress()\n {\n return new Progress(UpdateDetailedProgress);\n }\n\n /// \n /// Creates a progress adapter for PowerShell progress data.\n /// \n /// A progress adapter for PowerShell progress data.\n public IProgress CreatePowerShellProgressAdapter()\n {\n return new Progress(data =>\n {\n var detail = new TaskProgressDetail();\n\n // Map PowerShell progress data to task progress detail\n if (data.PercentComplete.HasValue)\n {\n detail.Progress = data.PercentComplete.Value;\n }\n\n if (!string.IsNullOrEmpty(data.Activity))\n {\n detail.StatusText = data.Activity;\n if (!string.IsNullOrEmpty(data.StatusDescription))\n {\n detail.StatusText += $\": {data.StatusDescription}\";\n }\n }\n\n detail.DetailedMessage = data.Message ?? data.CurrentOperation;\n\n // Map stream type to log level\n switch (data.StreamType)\n {\n case PowerShellStreamType.Error:\n detail.LogLevel = LogLevel.Error;\n break;\n case PowerShellStreamType.Warning:\n detail.LogLevel = LogLevel.Warning;\n break;\n case PowerShellStreamType.Verbose:\n case PowerShellStreamType.Debug:\n detail.LogLevel = LogLevel.Debug;\n break;\n default:\n detail.LogLevel = LogLevel.Info;\n break;\n }\n\n UpdateDetailedProgress(detail);\n });\n }\n\n /// \n /// Raises the ProgressUpdated event.\n /// \n protected virtual void OnProgressChanged(TaskProgressDetail detail)\n {\n ProgressUpdated?.Invoke(this, detail);\n ProgressChanged?.Invoke(\n this,\n TaskProgressEventArgs.FromTaskProgressDetail(detail, _isTaskRunning)\n );\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/ConfigurationCoordinatorService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows.Input;\nusing Microsoft.Extensions.DependencyInjection;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Customize.ViewModels;\nusing Winhance.WPF.Features.Optimize.ViewModels;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\nusing Winhance.WPF.Features.SoftwareApps.Models;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for coordinating configuration operations across multiple view models.\n /// \n public class ConfigurationCoordinatorService : IConfigurationCoordinatorService\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly IConfigurationService _configurationService;\n private readonly ILogService _logService;\n private readonly IDialogService _dialogService;\n private readonly IRegistryService _registryService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The configuration service.\n /// The log service.\n /// The dialog service.\n public ConfigurationCoordinatorService(\n IServiceProvider serviceProvider,\n IConfigurationService configurationService,\n ILogService logService,\n IDialogService dialogService,\n IRegistryService registryService)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n }\n\n /// \n /// Creates a unified configuration file containing settings from all view models.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file.\n public async Task CreateUnifiedConfigurationAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Creating unified configuration from all view models\");\n \n // Create a dictionary to hold settings from all sections\n var sectionSettings = new Dictionary>();\n\n // Get all view models from the service provider\n var windowsAppsViewModel = _serviceProvider.GetService();\n var externalAppsViewModel = _serviceProvider.GetService();\n var customizeViewModel = _serviceProvider.GetService();\n var optimizeViewModel = _serviceProvider.GetService();\n\n // Add settings from each view model to the dictionary\n if (windowsAppsViewModel != null)\n {\n _logService.Log(LogLevel.Debug, \"Processing WindowsAppsViewModel\");\n \n // Ensure the view model is initialized\n if (!windowsAppsViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"WindowsAppsViewModel not initialized, loading items\");\n await windowsAppsViewModel.LoadItemsAsync();\n }\n \n // Log the number of items in the view model\n var itemsProperty = windowsAppsViewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(windowsAppsViewModel) as System.Collections.ICollection;\n if (items != null)\n {\n _logService.Log(LogLevel.Debug, $\"WindowsAppsViewModel has {items.Count} items\");\n \n // Log the type of the first item\n if (items.Count > 0)\n {\n var enumerator = items.GetEnumerator();\n enumerator.MoveNext();\n var firstItem = enumerator.Current;\n if (firstItem != null)\n {\n _logService.Log(LogLevel.Debug, $\"First item type: {firstItem.GetType().FullName}\");\n }\n }\n }\n }\n \n // For WindowsAppsViewModel, we need to use SaveConfig to get the settings\n // This is because the Items property is not of type ISettingItem\n // We'll use reflection to call the SaveConfig method\n var saveConfigMethod = windowsAppsViewModel.GetType().GetMethod(\"SaveConfig\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);\n \n // Instead of trying to call SaveConfig, directly access the Items collection\n // and convert them to WindowsAppSettingItems\n var windowsAppsItemsProperty = windowsAppsViewModel.GetType().GetProperty(\"Items\");\n if (windowsAppsItemsProperty != null)\n {\n var items = windowsAppsItemsProperty.GetValue(windowsAppsViewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n _logService.Log(LogLevel.Info, \"Directly accessing Items collection from WindowsAppsViewModel\");\n \n // Convert each WindowsApp to WindowsAppSettingItem\n var windowsAppSettingItems = new List();\n \n foreach (var item in items)\n {\n if (item is Winhance.WPF.Features.SoftwareApps.Models.WindowsApp windowsApp)\n {\n windowsAppSettingItems.Add(new WindowsAppSettingItem(windowsApp));\n _logService.Log(LogLevel.Debug, $\"Added WindowsAppSettingItem for {windowsApp.Name}\");\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Created {windowsAppSettingItems.Count} WindowsAppSettingItems\");\n \n // Always add WindowsApps to sectionSettings, even if empty\n sectionSettings[\"WindowsApps\"] = windowsAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added WindowsApps section with {windowsAppSettingItems.Count} items\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Items collection is null\");\n \n // Create some default WindowsApps\n var defaultApps = new[]\n {\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Microsoft Edge\",\n PackageName = \"Microsoft.MicrosoftEdge\",\n IsSelected = true,\n Description = \"Microsoft Edge browser\"\n },\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Calculator\",\n PackageName = \"Microsoft.WindowsCalculator\",\n IsSelected = true,\n Description = \"Windows Calculator app\"\n },\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Photos\",\n PackageName = \"Microsoft.Windows.Photos\",\n IsSelected = true,\n Description = \"Windows Photos app\"\n }\n };\n \n var defaultWindowsAppSettingItems = new List();\n foreach (var app in defaultApps)\n {\n defaultWindowsAppSettingItems.Add(new WindowsAppSettingItem(app));\n }\n \n // Always add WindowsApps to sectionSettings, even if using defaults\n sectionSettings[\"WindowsApps\"] = defaultWindowsAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added WindowsApps section with {defaultWindowsAppSettingItems.Count} default items\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Error, \"Could not find Items property in WindowsAppsViewModel\");\n \n // Create some default WindowsApps\n var defaultApps = new[]\n {\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Microsoft Edge\",\n PackageName = \"Microsoft.MicrosoftEdge\",\n IsSelected = true,\n Description = \"Microsoft Edge browser\"\n },\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Calculator\",\n PackageName = \"Microsoft.WindowsCalculator\",\n IsSelected = true,\n Description = \"Windows Calculator app\"\n },\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Photos\",\n PackageName = \"Microsoft.Windows.Photos\",\n IsSelected = true,\n Description = \"Windows Photos app\"\n }\n };\n \n var defaultWindowsAppSettingItems = new List();\n foreach (var app in defaultApps)\n {\n defaultWindowsAppSettingItems.Add(new WindowsAppSettingItem(app));\n }\n \n // Always add WindowsApps to sectionSettings, even if using defaults\n sectionSettings[\"WindowsApps\"] = defaultWindowsAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added WindowsApps section with {defaultWindowsAppSettingItems.Count} default items\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"WindowsAppsViewModel is null\");\n }\n\n if (externalAppsViewModel != null)\n {\n // Ensure the view model is initialized\n if (!externalAppsViewModel.IsInitialized)\n {\n await externalAppsViewModel.LoadItemsAsync();\n }\n \n // For ExternalAppsViewModel, we need to get the settings directly\n // This is because the Items property is not of type ISettingItem\n var externalAppsItems = new List();\n \n // Get the Items property\n var itemsProperty = externalAppsViewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(externalAppsViewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n foreach (var item in items)\n {\n if (item is Winhance.WPF.Features.SoftwareApps.Models.ExternalApp externalApp)\n {\n externalAppsItems.Add(new ExternalAppSettingItem(externalApp));\n }\n }\n }\n }\n \n // Add the settings to the dictionary\n sectionSettings[\"ExternalApps\"] = externalAppsItems;\n _logService.Log(LogLevel.Info, $\"Added ExternalApps section with {externalAppsItems.Count} items\");\n }\n\n if (customizeViewModel != null)\n {\n // Ensure the view model is initialized\n if (!customizeViewModel.IsInitialized)\n {\n await customizeViewModel.LoadItemsAsync();\n }\n \n // For CustomizeViewModel, we need to get the settings directly\n var customizeItems = new List();\n \n // Get the Items property\n var itemsProperty = customizeViewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(customizeViewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n foreach (var item in items)\n {\n if (item is ISettingItem settingItem)\n {\n customizeItems.Add(settingItem);\n }\n }\n }\n }\n \n // Add the settings to the dictionary\n sectionSettings[\"Customize\"] = customizeItems;\n _logService.Log(LogLevel.Info, $\"Added Customize section with {customizeItems.Count} items\");\n }\n\n if (optimizeViewModel != null)\n {\n _logService.Log(LogLevel.Debug, \"Processing OptimizeViewModel\");\n \n // Ensure the view model is initialized\n if (!optimizeViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"OptimizeViewModel not initialized, initializing now\");\n await optimizeViewModel.InitializeCommand.ExecuteAsync(null);\n \n // After initialization, ensure items are loaded\n await optimizeViewModel.LoadItemsAsync();\n _logService.Log(LogLevel.Debug, $\"OptimizeViewModel initialized and loaded with {optimizeViewModel.Items?.Count ?? 0} items\");\n }\n else\n {\n _logService.Log(LogLevel.Debug, \"OptimizeViewModel already initialized\");\n \n // Even if initialized, make sure items are loaded\n if (optimizeViewModel.Items == null || optimizeViewModel.Items.Count == 0)\n {\n _logService.Log(LogLevel.Debug, \"OptimizeViewModel items not loaded, loading now\");\n await optimizeViewModel.LoadItemsAsync();\n _logService.Log(LogLevel.Debug, $\"OptimizeViewModel items loaded, count: {optimizeViewModel.Items?.Count ?? 0}\");\n }\n }\n \n // For OptimizeViewModel, we need to get the settings directly\n var optimizeItems = new List();\n \n // Get the Items property\n var itemsProperty = optimizeViewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(optimizeViewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n _logService.Log(LogLevel.Debug, $\"OptimizeViewModel has items collection, enumerating\");\n \n // Log the type of the first item\n var enumerator = items.GetEnumerator();\n if (enumerator.MoveNext() && enumerator.Current != null)\n {\n _logService.Log(LogLevel.Debug, $\"First item type: {enumerator.Current.GetType().FullName}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"OptimizeViewModel items collection is empty or first item is null\");\n }\n \n // Reset the enumerator\n items = itemsProperty.GetValue(optimizeViewModel) as System.Collections.IEnumerable;\n \n foreach (var item in items)\n {\n if (item is Winhance.WPF.Features.Common.Models.ApplicationSettingItem applicationItem)\n {\n optimizeItems.Add(applicationItem);\n _logService.Log(LogLevel.Debug, $\"Added ApplicationSettingItem for {applicationItem.Name}\");\n }\n else if (item is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added generic ISettingItem for {settingItem.Name}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Item of type {item?.GetType().FullName ?? \"null\"} is not an ISettingItem\");\n }\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"OptimizeViewModel items collection is null\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Error, \"Could not find Items property in OptimizeViewModel\");\n }\n \n // If we still don't have any items, collect them directly from the child view models\n // This avoids showing the Optimizations Custom Dialog before the Save Dialog\n if (optimizeItems.Count == 0)\n {\n _logService.Log(LogLevel.Warning, \"No items found in OptimizeViewModel, collecting from child view models\");\n \n // Get all the child view models using reflection\n var childViewModels = new List();\n var properties = optimizeViewModel.GetType().GetProperties();\n \n foreach (var property in properties)\n {\n if (property.Name.EndsWith(\"ViewModel\") &&\n property.Name != \"OptimizeViewModel\" &&\n property.PropertyType.Name.Contains(\"Optimizations\"))\n {\n var childViewModel = property.GetValue(optimizeViewModel);\n if (childViewModel != null)\n {\n childViewModels.Add(childViewModel);\n _logService.Log(LogLevel.Debug, $\"Found child view model: {property.Name}\");\n }\n }\n }\n \n // Collect settings from each child view model\n foreach (var childViewModel in childViewModels)\n {\n var settingsProperty = childViewModel.GetType().GetProperty(\"Settings\");\n if (settingsProperty != null)\n {\n var settings = settingsProperty.GetValue(childViewModel) as System.Collections.IEnumerable;\n if (settings != null)\n {\n foreach (var setting in settings)\n {\n // Use dynamic to avoid type issues\n dynamic settingViewModel = setting;\n try\n {\n // Convert setting to ApplicationSettingItem using dynamic\n var item = new Winhance.WPF.Features.Common.Models.ApplicationSettingItem(_registryService, _dialogService, _logService);\n \n // Copy properties using reflection to avoid type issues\n try { item.Id = settingViewModel.Id; } catch { }\n try { item.Name = settingViewModel.Name; } catch { }\n try { item.Description = settingViewModel.Description; } catch { }\n try { item.IsSelected = settingViewModel.IsSelected; } catch { }\n try { item.GroupName = settingViewModel.GroupName; } catch { }\n try { item.IsVisible = settingViewModel.IsVisible; } catch { }\n try { item.ControlType = settingViewModel.ControlType; } catch { }\n try { item.SliderValue = settingViewModel.SliderValue; } catch { }\n try { item.SliderSteps = settingViewModel.SliderSteps; } catch { }\n try { item.Status = settingViewModel.Status; } catch { }\n try { item.StatusMessage = settingViewModel.StatusMessage; } catch { }\n try { item.RegistrySetting = settingViewModel.RegistrySetting; } catch { }\n \n // Skip LinkedRegistrySettings for now as it's causing issues\n \n optimizeItems.Add(item);\n _logService.Log(LogLevel.Debug, $\"Added setting from {childViewModel.GetType().Name}: {item.Name}\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error converting setting: {ex.Message}\");\n \n // Try to add as generic ISettingItem if possible\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added generic setting from {childViewModel.GetType().Name}: {settingItem.Name}\");\n }\n }\n }\n }\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Collected {optimizeItems.Count} items from child view models\");\n \n // If we still don't have any items, add a placeholder as a last resort\n if (optimizeItems.Count == 0)\n {\n _logService.Log(LogLevel.Warning, \"No items found in child view models, adding placeholder\");\n \n var placeholderItem = new Winhance.WPF.Features.Common.Models.ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = \"OptimizePlaceholder\",\n Name = \"Optimization Settings\",\n Description = \"Default optimization settings\",\n IsSelected = true,\n GroupName = \"Optimizations\"\n };\n \n optimizeItems.Add(placeholderItem);\n _logService.Log(LogLevel.Info, \"Added placeholder item to Optimize section\");\n }\n }\n \n // Add the settings to the dictionary\n sectionSettings[\"Optimize\"] = optimizeItems;\n _logService.Log(LogLevel.Info, $\"Added Optimize section with {optimizeItems.Count} items\");\n }\n\n // Create a list of all available sections - include all sections by default\n var availableSections = new List { \"WindowsApps\", \"ExternalApps\", \"Customize\", \"Optimize\" };\n\n // Create and return the unified configuration\n var unifiedConfig = _configurationService.CreateUnifiedConfiguration(sectionSettings, availableSections);\n \n _logService.Log(LogLevel.Info, \"Successfully created unified configuration from all view models\");\n \n return unifiedConfig;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating unified configuration: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Applies a unified configuration to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n public async Task ApplyUnifiedConfigurationAsync(UnifiedConfigurationFile config, IEnumerable selectedSections)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Applying unified configuration to selected sections: {string.Join(\", \", selectedSections)}\");\n \n // Log the contents of the unified configuration\n _logService.Log(LogLevel.Debug, $\"Unified configuration contains: \" +\n $\"WindowsApps: {config.WindowsApps?.Items?.Count ?? 0} items, \" +\n $\"ExternalApps: {config.ExternalApps?.Items?.Count ?? 0} items, \" +\n $\"Customize: {config.Customize?.Items?.Count ?? 0} items, \" +\n $\"Optimize: {config.Optimize?.Items?.Count ?? 0} items\");\n \n // Validate the configuration\n if (config == null)\n {\n _logService.Log(LogLevel.Error, \"Unified configuration is null\");\n return false;\n }\n \n // Validate the selected sections\n if (selectedSections == null || !selectedSections.Any())\n {\n _logService.Log(LogLevel.Error, \"No sections selected for import\");\n return false;\n }\n \n bool result = true;\n var sectionResults = new Dictionary();\n\n foreach (var section in selectedSections)\n {\n _logService.Log(LogLevel.Info, $\"Processing section: {section}\");\n \n // Extract the section from the unified configuration\n var configFile = _configurationService.ExtractSectionFromUnifiedConfiguration(config, section);\n \n if (configFile == null)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to extract section {section} from unified configuration\");\n sectionResults[section] = false;\n result = false;\n continue;\n }\n \n if (configFile.Items == null || !configFile.Items.Any())\n {\n _logService.Log(LogLevel.Warning, $\"Section {section} is empty or not included in the unified configuration\");\n sectionResults[section] = false;\n continue;\n }\n\n _logService.Log(LogLevel.Info, $\"Extracted section {section} with {configFile.Items.Count} items\");\n \n // Log all items for debugging\n foreach (var item in configFile.Items)\n {\n _logService.Log(LogLevel.Debug, $\"Item in {section}: {item.Name}, IsSelected: {item.IsSelected}, ControlType: {item.ControlType}\");\n }\n\n // Apply the configuration to the appropriate view model\n bool sectionResult = false;\n \n switch (section)\n {\n case \"WindowsApps\":\n _logService.Log(LogLevel.Info, $\"Getting WindowsAppsViewModel from service provider\");\n var windowsAppsViewModel = _serviceProvider.GetService();\n if (windowsAppsViewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"WindowsAppsViewModel found, importing configuration\");\n \n // Ensure the view model is initialized\n if (!windowsAppsViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, $\"WindowsAppsViewModel not initialized, initializing now\");\n await windowsAppsViewModel.LoadItemsAsync();\n }\n \n // Use the view model's own import method\n sectionResult = await ImportWindowsAppsConfig(windowsAppsViewModel, configFile);\n _logService.Log(LogLevel.Info, $\"WindowsApps import result: {sectionResult}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"WindowsAppsViewModel not available\");\n sectionResult = false;\n }\n break;\n\n case \"ExternalApps\":\n _logService.Log(LogLevel.Info, $\"Getting ExternalAppsViewModel from service provider\");\n var externalAppsViewModel = _serviceProvider.GetService();\n if (externalAppsViewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"ExternalAppsViewModel found, importing configuration\");\n \n // Ensure the view model is initialized\n if (!externalAppsViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, $\"ExternalAppsViewModel not initialized, initializing now\");\n await externalAppsViewModel.LoadItemsAsync();\n }\n \n // Use the view model's own import method\n sectionResult = await ImportExternalAppsConfig(externalAppsViewModel, configFile);\n _logService.Log(LogLevel.Info, $\"ExternalApps import result: {sectionResult}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"ExternalAppsViewModel not available\");\n sectionResult = false;\n }\n break;\n\n case \"Customize\":\n _logService.Log(LogLevel.Info, $\"Getting CustomizeViewModel from service provider\");\n var customizeViewModel = _serviceProvider.GetService();\n if (customizeViewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"CustomizeViewModel found, importing configuration\");\n \n // Ensure the view model is initialized\n if (!customizeViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, $\"CustomizeViewModel not initialized, initializing now\");\n await customizeViewModel.InitializeCommand.ExecuteAsync(null);\n }\n \n // Use the view model's own import method\n sectionResult = await ImportCustomizeConfig(customizeViewModel, configFile);\n _logService.Log(LogLevel.Info, $\"Customize import result: {sectionResult}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"CustomizeViewModel not available\");\n sectionResult = false;\n }\n break;\n\n case \"Optimize\":\n _logService.Log(LogLevel.Info, $\"Getting OptimizeViewModel from service provider\");\n var optimizeViewModel = _serviceProvider.GetService();\n if (optimizeViewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"OptimizeViewModel found, importing configuration\");\n \n // Ensure the view model is initialized\n if (!optimizeViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, $\"OptimizeViewModel not initialized, initializing now\");\n await optimizeViewModel.InitializeCommand.ExecuteAsync(null);\n }\n \n // Use the view model's own import method\n sectionResult = await ImportOptimizeConfig(optimizeViewModel, configFile);\n _logService.Log(LogLevel.Info, $\"Optimize import result: {sectionResult}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"OptimizeViewModel not available\");\n sectionResult = false;\n }\n break;\n\n default:\n _logService.Log(LogLevel.Warning, $\"Unknown section: {section}\");\n sectionResult = false;\n break;\n }\n \n sectionResults[section] = sectionResult;\n if (!sectionResult)\n {\n result = false;\n }\n }\n\n // Log the results for each section\n _logService.Log(LogLevel.Info, \"Import results by section:\");\n foreach (var sectionResult in sectionResults)\n {\n _logService.Log(LogLevel.Info, $\" {sectionResult.Key}: {(sectionResult.Value ? \"Success\" : \"Failed\")}\");\n }\n\n _logService.Log(LogLevel.Info, $\"Finished applying unified configuration to selected sections. Overall result: {(result ? \"Success\" : \"Partial failure\")}\");\n return result;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying unified configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false; // Return false instead of throwing to prevent crashing the application\n }\n }\n\n /// \n /// Imports a configuration to a view model using reflection to call its ImportConfig method.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n private async Task ImportConfigToViewModel(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n string viewModelTypeName = viewModel.GetType().Name;\n _logService.Log(LogLevel.Info, $\"Starting to import configuration to {viewModelTypeName}\");\n _logService.Log(LogLevel.Debug, $\"Configuration file has {configFile.Items?.Count ?? 0} items\");\n \n // Log the first few items for debugging\n if (configFile.Items != null && configFile.Items.Any())\n {\n foreach (var item in configFile.Items.Take(5))\n {\n _logService.Log(LogLevel.Debug, $\"Item: {item.Name}, IsSelected: {item.IsSelected}, ControlType: {item.ControlType}\");\n }\n }\n\n // Store the original configuration file\n var originalConfigFile = configFile;\n\n // Create a wrapper for the configuration service\n var configServiceWrapper = new ConfigurationServiceWrapper(_configurationService, originalConfigFile);\n _logService.Log(LogLevel.Debug, \"Created configuration service wrapper\");\n\n // Replace the configuration service in the view model\n var configServiceField = viewModel.GetType().GetField(\"_configurationService\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n\n if (configServiceField != null)\n {\n _logService.Log(LogLevel.Debug, \"Found _configurationService field in view model\");\n \n // Store the original service\n var originalService = configServiceField.GetValue(viewModel);\n _logService.Log(LogLevel.Debug, $\"Original service type: {originalService?.GetType().Name ?? \"null\"}\");\n\n try\n {\n // Replace with our wrapper\n configServiceField.SetValue(viewModel, configServiceWrapper);\n _logService.Log(LogLevel.Debug, \"Replaced configuration service with wrapper\");\n\n // Special handling for different view model types\n bool importResult = false;\n \n if (viewModelTypeName.Contains(\"WindowsApps\"))\n {\n importResult = await ImportWindowsAppsConfig(viewModel, configFile);\n }\n else if (viewModelTypeName.Contains(\"ExternalApps\"))\n {\n importResult = await ImportExternalAppsConfig(viewModel, configFile);\n }\n else if (viewModelTypeName.Contains(\"Customize\"))\n {\n importResult = await ImportCustomizeConfig(viewModel, configFile);\n }\n else if (viewModelTypeName.Contains(\"Optimize\"))\n {\n importResult = await ImportOptimizeConfig(viewModel, configFile);\n }\n else\n {\n // Generic import for other view model types\n importResult = await ImportGenericConfig(viewModel, configFile);\n }\n \n if (importResult)\n {\n _logService.Log(LogLevel.Info, $\"Successfully imported configuration to {viewModelTypeName}\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Failed to import configuration to {viewModelTypeName}\");\n return false;\n }\n }\n finally\n {\n // Restore the original service\n configServiceField.SetValue(viewModel, originalService);\n _logService.Log(LogLevel.Debug, \"Restored original configuration service\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Could not find _configurationService field in {viewModelTypeName}\");\n \n // Try direct application as a fallback\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, $\"Successfully applied configuration directly to {viewModelTypeName}\");\n return true;\n }\n \n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing configuration to {viewModel.GetType().Name}: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Imports configuration to WindowsAppsViewModel.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// True if successful, false otherwise.\n private async Task ImportWindowsAppsConfig(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Importing configuration to WindowsAppsViewModel\");\n \n // First try using the ImportConfigCommand\n var importCommand = viewModel.GetType().GetProperty(\"ImportConfigCommand\")?.GetValue(viewModel) as IAsyncRelayCommand;\n if (importCommand != null)\n {\n _logService.Log(LogLevel.Debug, \"Found ImportConfigCommand, executing...\");\n await importCommand.ExecuteAsync(null);\n \n // Verify that the configuration was applied\n bool configApplied = await VerifyConfigurationApplied(viewModel, configFile);\n \n if (configApplied)\n {\n _logService.Log(LogLevel.Info, \"Successfully imported configuration using ImportConfigCommand\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Configuration may not have been properly applied using ImportConfigCommand\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"ImportConfigCommand not found\");\n }\n \n // If we get here, try direct application\n _logService.Log(LogLevel.Info, \"Falling back to direct application\");\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n \n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, \"Successfully applied configuration directly\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Failed to apply configuration directly\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing WindowsApps configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Imports configuration to ExternalAppsViewModel.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// True if successful, false otherwise.\n private async Task ImportExternalAppsConfig(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Importing configuration to ExternalAppsViewModel\");\n \n // First try using the ImportConfigCommand\n var importCommand = viewModel.GetType().GetProperty(\"ImportConfigCommand\")?.GetValue(viewModel) as IAsyncRelayCommand;\n if (importCommand != null)\n {\n _logService.Log(LogLevel.Debug, \"Found ImportConfigCommand, executing...\");\n await importCommand.ExecuteAsync(null);\n \n // Verify that the configuration was applied\n bool configApplied = await VerifyConfigurationApplied(viewModel, configFile);\n \n if (configApplied)\n {\n _logService.Log(LogLevel.Info, \"Successfully imported configuration using ImportConfigCommand\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Configuration may not have been properly applied using ImportConfigCommand\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"ImportConfigCommand not found\");\n }\n \n // If we get here, try direct application\n _logService.Log(LogLevel.Info, \"Falling back to direct application\");\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n \n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, \"Successfully applied configuration directly\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Failed to apply configuration directly\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing ExternalApps configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Imports configuration to CustomizeViewModel.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// True if successful, false otherwise.\n private async Task ImportCustomizeConfig(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Importing configuration to CustomizeViewModel\");\n \n // First try using the ImportConfigCommand\n var importCommand = viewModel.GetType().GetProperty(\"ImportConfigCommand\")?.GetValue(viewModel) as IAsyncRelayCommand;\n if (importCommand != null)\n {\n _logService.Log(LogLevel.Debug, \"Found ImportConfigCommand, executing...\");\n await importCommand.ExecuteAsync(null);\n \n // Verify that the configuration was applied\n bool configApplied = await VerifyConfigurationApplied(viewModel, configFile);\n \n if (configApplied)\n {\n _logService.Log(LogLevel.Info, \"Successfully imported configuration using ImportConfigCommand\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Configuration may not have been properly applied using ImportConfigCommand\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"ImportConfigCommand not found\");\n }\n \n // If we get here, try direct application\n _logService.Log(LogLevel.Info, \"Falling back to direct application\");\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n \n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, \"Successfully applied configuration directly\");\n \n // For CustomizeViewModel, try to call ApplyCustomizations if available\n var applyCustomizationsMethod = viewModel.GetType().GetMethod(\"ApplyCustomizations\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (applyCustomizationsMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling ApplyCustomizations method\");\n \n // Check if the method takes parameters\n var parameters = applyCustomizationsMethod.GetParameters();\n if (parameters.Length == 0)\n {\n applyCustomizationsMethod.Invoke(viewModel, null);\n }\n else if (parameters.Length == 1 && parameters[0].ParameterType == typeof(bool))\n {\n // If it takes a boolean parameter, pass true to force application\n applyCustomizationsMethod.Invoke(viewModel, new object[] { true });\n }\n }\n \n // Additionally, iterate through all items and ensure their registry settings are applied\n var itemsProperty = viewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(viewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n _logService.Log(LogLevel.Debug, \"Iterating through items to ensure registry settings are applied\");\n foreach (var item in items)\n {\n var applySettingCommand = item.GetType().GetProperty(\"ApplySettingCommand\")?.GetValue(item) as ICommand;\n if (applySettingCommand != null && applySettingCommand.CanExecute(null))\n {\n var nameProperty = item.GetType().GetProperty(\"Name\");\n var name = nameProperty?.GetValue(item)?.ToString() ?? \"unknown\";\n _logService.Log(LogLevel.Debug, $\"Executing ApplySettingCommand for {name}\");\n applySettingCommand.Execute(null);\n }\n }\n }\n }\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Failed to apply configuration directly\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing Customize configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Imports configuration to OptimizeViewModel.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// True if successful, false otherwise.\n private async Task ImportOptimizeConfig(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Importing configuration to OptimizeViewModel\");\n \n // First try using the ImportConfigCommand\n var importCommand = viewModel.GetType().GetProperty(\"ImportConfigCommand\")?.GetValue(viewModel) as IAsyncRelayCommand;\n if (importCommand != null)\n {\n _logService.Log(LogLevel.Debug, \"Found ImportConfigCommand, executing...\");\n await importCommand.ExecuteAsync(null);\n \n // Verify that the configuration was applied\n bool configApplied = await VerifyConfigurationApplied(viewModel, configFile);\n \n if (configApplied)\n {\n _logService.Log(LogLevel.Info, \"Successfully imported configuration using ImportConfigCommand\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Configuration may not have been properly applied using ImportConfigCommand\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"ImportConfigCommand not found\");\n }\n \n // If we get here, try direct application\n _logService.Log(LogLevel.Info, \"Falling back to direct application\");\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n \n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, \"Successfully applied configuration directly\");\n \n // For OptimizeViewModel, try to call ApplyOptimizations if available\n var applyOptimizationsMethod = viewModel.GetType().GetMethod(\"ApplyOptimizations\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (applyOptimizationsMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling ApplyOptimizations method\");\n \n // Check if the method takes parameters\n var parameters = applyOptimizationsMethod.GetParameters();\n if (parameters.Length == 0)\n {\n applyOptimizationsMethod.Invoke(viewModel, null);\n }\n else if (parameters.Length == 1 && parameters[0].ParameterType == typeof(bool))\n {\n // If it takes a boolean parameter, pass true to force application\n applyOptimizationsMethod.Invoke(viewModel, new object[] { true });\n }\n }\n \n // Additionally, iterate through all items and ensure their registry settings are applied\n var itemsProperty = viewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(viewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n _logService.Log(LogLevel.Debug, \"Iterating through items to ensure registry settings are applied\");\n foreach (var item in items)\n {\n var applySettingCommand = item.GetType().GetProperty(\"ApplySettingCommand\")?.GetValue(item) as ICommand;\n if (applySettingCommand != null && applySettingCommand.CanExecute(null))\n {\n var nameProperty = item.GetType().GetProperty(\"Name\");\n var name = nameProperty?.GetValue(item)?.ToString() ?? \"unknown\";\n _logService.Log(LogLevel.Debug, $\"Executing ApplySettingCommand for {name}\");\n applySettingCommand.Execute(null);\n }\n }\n }\n }\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Failed to apply configuration directly\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing Optimize configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Imports configuration to a generic view model.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// True if successful, false otherwise.\n private async Task ImportGenericConfig(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Importing configuration to generic view model\");\n \n // First try using the ImportConfigCommand\n var importCommand = viewModel.GetType().GetProperty(\"ImportConfigCommand\")?.GetValue(viewModel) as IAsyncRelayCommand;\n if (importCommand != null)\n {\n _logService.Log(LogLevel.Debug, \"Found ImportConfigCommand, executing...\");\n await importCommand.ExecuteAsync(null);\n \n // Verify that the configuration was applied\n bool configApplied = await VerifyConfigurationApplied(viewModel, configFile);\n \n if (configApplied)\n {\n _logService.Log(LogLevel.Info, \"Successfully imported configuration using ImportConfigCommand\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Configuration may not have been properly applied using ImportConfigCommand\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"ImportConfigCommand not found\");\n }\n \n // If we get here, try direct application\n _logService.Log(LogLevel.Info, \"Falling back to direct application\");\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n \n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, \"Successfully applied configuration directly\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Failed to apply configuration directly\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing generic configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Verifies that the configuration was properly applied to the view model.\n /// \n /// The view model to verify.\n /// The configuration file that was applied.\n /// True if the configuration was applied, false otherwise.\n private async Task VerifyConfigurationApplied(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Debug, $\"Verifying configuration was applied to {viewModel.GetType().Name}\");\n \n // Get the Items property from the view model\n var itemsProperty = viewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty == null)\n {\n _logService.Log(LogLevel.Warning, $\"Could not find Items property in {viewModel.GetType().Name}\");\n return false;\n }\n \n var items = itemsProperty.GetValue(viewModel) as System.Collections.IEnumerable;\n if (items == null)\n {\n _logService.Log(LogLevel.Warning, $\"Items collection is null in {viewModel.GetType().Name}\");\n return false;\n }\n \n // Check if at least some items have the expected IsSelected state\n int matchCount = 0;\n int totalChecked = 0;\n \n // Create dictionaries of config items by name and ID for faster lookup\n var configItemsByName = new Dictionary(StringComparer.OrdinalIgnoreCase);\n var configItemsById = new Dictionary(StringComparer.OrdinalIgnoreCase);\n \n if (configFile.Items != null)\n {\n foreach (var item in configFile.Items)\n {\n if (!string.IsNullOrEmpty(item.Name) && !configItemsByName.ContainsKey(item.Name))\n {\n configItemsByName.Add(item.Name, item);\n }\n \n if (item.CustomProperties.TryGetValue(\"Id\", out var id) && id != null &&\n !string.IsNullOrEmpty(id.ToString()) && !configItemsById.ContainsKey(id.ToString()))\n {\n configItemsById.Add(id.ToString(), item);\n }\n }\n }\n \n // Get the view model type to determine special handling\n string viewModelTypeName = viewModel.GetType().Name;\n _logService.Log(LogLevel.Debug, $\"Verifying view model of type: {viewModelTypeName}\");\n \n // Check up to 15 items\n foreach (var item in items)\n {\n if (totalChecked >= 15) break;\n \n var nameProperty = item.GetType().GetProperty(\"Name\");\n var idProperty = item.GetType().GetProperty(\"Id\");\n var isSelectedProperty = item.GetType().GetProperty(\"IsSelected\");\n \n if (nameProperty != null && isSelectedProperty != null)\n {\n var name = nameProperty.GetValue(item)?.ToString();\n var id = idProperty?.GetValue(item)?.ToString();\n \n _logService.Log(LogLevel.Debug, $\"Processing item: {name}, Id: {id}\");\n \n ConfigurationItem configItem = null;\n \n // Try to match by ID first\n if (!string.IsNullOrEmpty(id) && configItemsById.TryGetValue(id, out var itemById))\n {\n configItem = itemById;\n }\n // Then try to match by name\n else if (!string.IsNullOrEmpty(name) && configItemsByName.TryGetValue(name, out var itemByName))\n {\n configItem = itemByName;\n }\n \n if (configItem != null)\n {\n totalChecked++;\n bool itemMatches = true;\n \n // Check IsSelected property\n if (isSelectedProperty.GetValue(item) is bool isSelected && isSelected != configItem.IsSelected)\n {\n _logService.Log(LogLevel.Debug, $\"Item {name} has IsSelected={isSelected}, expected {configItem.IsSelected}\");\n itemMatches = false;\n }\n \n // For controls with additional properties, check those too\n if (configItem.ControlType == ControlType.ThreeStateSlider || configItem.ControlType == ControlType.ComboBox)\n {\n var sliderValueProperty = item.GetType().GetProperty(\"SliderValue\");\n if (sliderValueProperty != null && configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int expectedValue = Convert.ToInt32(sliderValue);\n int actualValue = (int)(sliderValueProperty.GetValue(item) ?? 0);\n \n if (actualValue != expectedValue)\n {\n _logService.Log(LogLevel.Debug, $\"Item {name} has SliderValue={actualValue}, expected {expectedValue}\");\n itemMatches = false;\n }\n }\n }\n \n // For ComboBox, check SelectedValue\n if (configItem.ControlType == ControlType.ComboBox)\n {\n var selectedValueProperty = item.GetType().GetProperty(\"SelectedValue\");\n if (selectedValueProperty != null && !string.IsNullOrEmpty(configItem.SelectedValue))\n {\n string expectedValue = configItem.SelectedValue;\n string actualValue = selectedValueProperty.GetValue(item)?.ToString();\n \n if (actualValue != expectedValue)\n {\n _logService.Log(LogLevel.Debug, $\"Item {name} has SelectedValue={actualValue}, expected {expectedValue}\");\n itemMatches = false;\n }\n }\n }\n \n if (itemMatches)\n {\n matchCount++;\n }\n }\n }\n }\n \n _logService.Log(LogLevel.Debug, $\"Verification result: {matchCount} matches out of {totalChecked} checked items\");\n \n // If we checked at least 3 items and at least 50% match, consider it successful\n if (totalChecked >= 3 && (double)matchCount / totalChecked >= 0.5)\n {\n _logService.Log(LogLevel.Info, $\"Configuration verification passed: {matchCount}/{totalChecked} items match\");\n return true;\n }\n else if (totalChecked > 0)\n {\n _logService.Log(LogLevel.Warning, $\"Configuration verification failed: only {matchCount}/{totalChecked} items match\");\n \n // Even if verification fails, we'll try to directly apply the configuration\n _logService.Log(LogLevel.Info, \"Will attempt direct application as fallback\");\n return false;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"No items could be checked for verification\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error verifying configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Directly applies the configuration to the view model without using the ImportConfigCommand.\n /// \n /// The view model to apply the configuration to.\n /// The configuration file to apply.\n /// True if successful, false otherwise.\n private async Task DirectlyApplyConfiguration(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Attempting to directly apply configuration to {viewModel.GetType().Name}\");\n \n // Get the Items property from the view model\n var itemsProperty = viewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty == null)\n {\n _logService.Log(LogLevel.Warning, $\"Could not find Items property in {viewModel.GetType().Name}\");\n return false;\n }\n \n var items = itemsProperty.GetValue(viewModel) as System.Collections.IEnumerable;\n if (items == null)\n {\n _logService.Log(LogLevel.Warning, $\"Items collection is null in {viewModel.GetType().Name}\");\n return false;\n }\n \n // Create dictionaries of config items by name and ID for faster lookup\n var configItemsByName = new Dictionary(StringComparer.OrdinalIgnoreCase);\n var configItemsById = new Dictionary(StringComparer.OrdinalIgnoreCase);\n \n if (configFile.Items != null)\n {\n foreach (var item in configFile.Items)\n {\n if (!string.IsNullOrEmpty(item.Name) && !configItemsByName.ContainsKey(item.Name))\n {\n configItemsByName.Add(item.Name, item);\n }\n \n if (item.CustomProperties.TryGetValue(\"Id\", out var id) && id != null &&\n !string.IsNullOrEmpty(id.ToString()) && !configItemsById.ContainsKey(id.ToString()))\n {\n configItemsById.Add(id.ToString(), item);\n }\n }\n }\n \n // Update the items in the view model\n int updatedCount = 0;\n \n // Determine if we're dealing with a collection that implements INotifyCollectionChanged\n bool isObservableCollection = false;\n var itemsType = items.GetType();\n if (typeof(System.Collections.Specialized.INotifyCollectionChanged).IsAssignableFrom(itemsType))\n {\n isObservableCollection = true;\n _logService.Log(LogLevel.Debug, $\"Items collection is an observable collection\");\n }\n \n // Get the view model type to determine special handling\n string viewModelTypeName = viewModel.GetType().Name;\n _logService.Log(LogLevel.Debug, $\"Processing view model of type: {viewModelTypeName}\");\n \n foreach (var item in items)\n {\n var nameProperty = item.GetType().GetProperty(\"Name\");\n var idProperty = item.GetType().GetProperty(\"Id\");\n var isSelectedProperty = item.GetType().GetProperty(\"IsSelected\");\n var isUpdatingFromCodeProperty = item.GetType().GetProperty(\"IsUpdatingFromCode\");\n \n if (nameProperty != null && isSelectedProperty != null)\n {\n var name = nameProperty.GetValue(item)?.ToString();\n var id = idProperty?.GetValue(item)?.ToString();\n \n _logService.Log(LogLevel.Debug, $\"Processing item: {name}, Id: {id}\");\n \n ConfigurationItem configItem = null;\n \n // Try to match by ID first\n if (!string.IsNullOrEmpty(id) && configItemsById.TryGetValue(id, out var itemById))\n {\n configItem = itemById;\n }\n // Then try to match by name\n else if (!string.IsNullOrEmpty(name) && configItemsByName.TryGetValue(name, out var itemByName))\n {\n configItem = itemByName;\n }\n \n if (configItem != null)\n {\n // Get the current IsSelected value before changing it\n bool currentIsSelected = (bool)(isSelectedProperty.GetValue(item) ?? false);\n \n // Set IsUpdatingFromCode to true before making changes\n if (isUpdatingFromCodeProperty != null)\n {\n isUpdatingFromCodeProperty.SetValue(item, true);\n }\n \n // Update IsSelected\n if (currentIsSelected != configItem.IsSelected)\n {\n _logService.Log(LogLevel.Debug, $\"Updating IsSelected for {name} from {currentIsSelected} to {configItem.IsSelected}\");\n isSelectedProperty.SetValue(item, configItem.IsSelected);\n }\n \n // Update other properties if available\n bool propertiesUpdated = UpdateAdditionalProperties(item, configItem);\n \n // If any property was updated, count it\n if (currentIsSelected != configItem.IsSelected || propertiesUpdated)\n {\n updatedCount++;\n }\n \n // Set IsUpdatingFromCode back to false to allow property change events to trigger\n if (isUpdatingFromCodeProperty != null)\n {\n isUpdatingFromCodeProperty.SetValue(item, false);\n }\n \n // Ensure UI state is properly updated\n TriggerPropertyChangedIfPossible(item);\n \n // Always explicitly call ApplySetting method to ensure registry changes are applied\n // regardless of view model type or IsSelected state\n var applySettingCommand = item.GetType().GetProperty(\"ApplySettingCommand\")?.GetValue(item) as ICommand;\n if (applySettingCommand != null && applySettingCommand.CanExecute(null))\n {\n _logService.Log(LogLevel.Debug, $\"Explicitly executing ApplySettingCommand for {name}\");\n applySettingCommand.Execute(null);\n }\n }\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Directly updated {updatedCount} items in {viewModel.GetType().Name}\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return updatedCount > 0;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error directly applying configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Attempts to trigger property changed notifications on an item if it implements INotifyPropertyChanged.\n /// \n /// The item to trigger property changed on.\n private void TriggerPropertyChangedIfPossible(object item)\n {\n try\n {\n // Check if the item implements INotifyPropertyChanged\n if (item is System.ComponentModel.INotifyPropertyChanged notifyPropertyChanged)\n {\n try\n {\n // Try to find the OnPropertyChanged method with a string parameter\n var onPropertyChangedMethod = item.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(string) },\n null);\n \n if (onPropertyChangedMethod != null)\n {\n // Invoke the method with null string to refresh all properties\n onPropertyChangedMethod.Invoke(item, new object[] { null });\n _logService.Log(LogLevel.Debug, $\"Triggered OnPropertyChanged(string) for {item.GetType().Name}\");\n }\n else\n {\n // Try to find the OnPropertyChanged method with no parameters\n var onPropertyChangedNoParamsMethod = item.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n Type.EmptyTypes,\n null);\n \n if (onPropertyChangedNoParamsMethod != null)\n {\n // Invoke the method with no parameters\n onPropertyChangedNoParamsMethod.Invoke(item, null);\n _logService.Log(LogLevel.Debug, $\"Triggered OnPropertyChanged() for {item.GetType().Name}\");\n }\n else\n {\n // Try to find the RaisePropertyChanged method as an alternative\n var raisePropertyChangedMethod = item.GetType().GetMethod(\"RaisePropertyChanged\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (raisePropertyChangedMethod != null)\n {\n // Invoke with null to refresh all properties\n raisePropertyChangedMethod.Invoke(item, new object[] { null });\n _logService.Log(LogLevel.Debug, $\"Triggered RaisePropertyChanged for {item.GetType().Name}\");\n }\n }\n }\n }\n catch (System.Reflection.AmbiguousMatchException)\n {\n _logService.Log(LogLevel.Debug, $\"Ambiguous match for OnPropertyChanged in {item.GetType().Name}, trying alternative approach\");\n \n // Try to get all methods named OnPropertyChanged\n var methods = item.GetType().GetMethods(System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance)\n .Where(m => m.Name == \"OnPropertyChanged\").ToList();\n \n if (methods.Any())\n {\n // Try to find one that takes a string parameter\n var stringParamMethod = methods.FirstOrDefault(m =>\n {\n var parameters = m.GetParameters();\n return parameters.Length == 1 && parameters[0].ParameterType == typeof(string);\n });\n \n if (stringParamMethod != null)\n {\n stringParamMethod.Invoke(item, new object[] { null });\n _logService.Log(LogLevel.Debug, $\"Triggered OnPropertyChanged using specific method for {item.GetType().Name}\");\n }\n }\n }\n \n // Try to find a method that might trigger property changed\n var refreshMethod = item.GetType().GetMethod(\"Refresh\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);\n \n if (refreshMethod != null)\n {\n refreshMethod.Invoke(item, null);\n _logService.Log(LogLevel.Debug, $\"Called Refresh method for {item.GetType().Name}\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error triggering property changed: {ex.Message}\");\n }\n }\n \n /// \n /// Updates additional properties of an item based on the configuration item.\n /// \n /// The item to update.\n /// The configuration item containing the values to apply.\n /// True if any property was updated, false otherwise.\n private bool UpdateAdditionalProperties(object item, ConfigurationItem configItem)\n {\n try\n {\n bool anyPropertyUpdated = false;\n \n // Get the item type to access its properties\n var itemType = item.GetType();\n \n // Log the control type for debugging\n _logService.Log(LogLevel.Debug, $\"Updating additional properties for {configItem.Name}, ControlType: {configItem.ControlType}\");\n \n // Update SliderValue for ThreeStateSlider or ComboBox\n if (configItem.ControlType == ControlType.ThreeStateSlider || configItem.ControlType == ControlType.ComboBox)\n {\n var sliderValueProperty = itemType.GetProperty(\"SliderValue\");\n if (sliderValueProperty != null && configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int newSliderValue = Convert.ToInt32(sliderValue);\n int currentSliderValue = (int)(sliderValueProperty.GetValue(item) ?? 0);\n \n if (currentSliderValue != newSliderValue)\n {\n _logService.Log(LogLevel.Debug, $\"Updating SliderValue for {configItem.Name} from {currentSliderValue} to {newSliderValue}\");\n sliderValueProperty.SetValue(item, newSliderValue);\n anyPropertyUpdated = true;\n }\n }\n }\n \n // Update SelectedValue for ComboBox\n if (configItem.ControlType == ControlType.ComboBox)\n {\n var selectedValueProperty = itemType.GetProperty(\"SelectedValue\");\n if (selectedValueProperty != null && !string.IsNullOrEmpty(configItem.SelectedValue))\n {\n string currentSelectedValue = selectedValueProperty.GetValue(item)?.ToString();\n \n if (currentSelectedValue != configItem.SelectedValue)\n {\n _logService.Log(LogLevel.Debug, $\"Updating SelectedValue for {configItem.Name} from '{currentSelectedValue}' to '{configItem.SelectedValue}'\");\n selectedValueProperty.SetValue(item, configItem.SelectedValue);\n anyPropertyUpdated = true;\n }\n }\n }\n \n // Update SelectedTheme for theme selector\n if (configItem.Name.Contains(\"Theme\") && configItem.CustomProperties.TryGetValue(\"SelectedTheme\", out var selectedTheme))\n {\n var selectedThemeProperty = itemType.GetProperty(\"SelectedTheme\");\n if (selectedThemeProperty != null && selectedTheme != null)\n {\n string currentSelectedTheme = selectedThemeProperty.GetValue(item)?.ToString();\n string newSelectedTheme = selectedTheme.ToString();\n \n if (currentSelectedTheme != newSelectedTheme)\n {\n _logService.Log(LogLevel.Debug, $\"Updating SelectedTheme for {configItem.Name} from '{currentSelectedTheme}' to '{newSelectedTheme}'\");\n selectedThemeProperty.SetValue(item, newSelectedTheme);\n anyPropertyUpdated = true;\n }\n }\n }\n \n // Update Status for items that have a status property\n var statusProperty = itemType.GetProperty(\"Status\");\n if (statusProperty != null && configItem.CustomProperties.TryGetValue(\"Status\", out var status))\n {\n statusProperty.SetValue(item, status);\n anyPropertyUpdated = true;\n }\n \n // Update StatusMessage for items that have a status message property\n var statusMessageProperty = itemType.GetProperty(\"StatusMessage\");\n if (statusMessageProperty != null && configItem.CustomProperties.TryGetValue(\"StatusMessage\", out var statusMessage))\n {\n statusMessageProperty.SetValue(item, statusMessage?.ToString());\n anyPropertyUpdated = true;\n }\n \n // For toggle switches, ensure IsChecked is synchronized with IsSelected\n var isCheckedProperty = itemType.GetProperty(\"IsChecked\");\n if (isCheckedProperty != null)\n {\n bool currentIsChecked = (bool)(isCheckedProperty.GetValue(item) ?? false);\n \n if (currentIsChecked != configItem.IsSelected)\n {\n _logService.Log(LogLevel.Debug, $\"Updating IsChecked for {configItem.Name} from {currentIsChecked} to {configItem.IsSelected}\");\n isCheckedProperty.SetValue(item, configItem.IsSelected);\n anyPropertyUpdated = true;\n }\n }\n \n // Update CurrentValue property if it exists\n var currentValueProperty = itemType.GetProperty(\"CurrentValue\");\n if (currentValueProperty != null)\n {\n // For toggle buttons, set the current value based on IsSelected\n if (configItem.ControlType == ControlType.BinaryToggle)\n {\n object valueToSet = configItem.IsSelected ? 1 : 0;\n currentValueProperty.SetValue(item, valueToSet);\n _logService.Log(LogLevel.Debug, $\"Setting CurrentValue for {configItem.Name} to {valueToSet}\");\n anyPropertyUpdated = true;\n }\n // For other control types, use the appropriate value\n else if (configItem.ControlType == ControlType.ThreeStateSlider || configItem.ControlType == ControlType.ComboBox)\n {\n if (configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n currentValueProperty.SetValue(item, sliderValue);\n _logService.Log(LogLevel.Debug, $\"Setting CurrentValue for {configItem.Name} to {sliderValue}\");\n anyPropertyUpdated = true;\n }\n }\n }\n \n // Update RegistrySetting property if it exists\n var registrySettingProperty = itemType.GetProperty(\"RegistrySetting\");\n if (registrySettingProperty != null && configItem.CustomProperties.TryGetValue(\"RegistrySetting\", out var registrySetting))\n {\n registrySettingProperty.SetValue(item, registrySetting);\n _logService.Log(LogLevel.Debug, $\"Updated RegistrySetting for {configItem.Name}\");\n anyPropertyUpdated = true;\n }\n \n // Update LinkedRegistrySettings property if it exists\n var linkedRegistrySettingsProperty = itemType.GetProperty(\"LinkedRegistrySettings\");\n if (linkedRegistrySettingsProperty != null && configItem.CustomProperties.TryGetValue(\"LinkedRegistrySettings\", out var linkedRegistrySettings))\n {\n linkedRegistrySettingsProperty.SetValue(item, linkedRegistrySettings);\n _logService.Log(LogLevel.Debug, $\"Updated LinkedRegistrySettings for {configItem.Name}\");\n anyPropertyUpdated = true;\n }\n \n return anyPropertyUpdated;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating additional properties: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Forces a UI refresh if needed for the view model.\n /// \n /// The view model to refresh.\n private async Task RefreshUIIfNeeded(object viewModel)\n {\n try\n {\n _logService.Log(LogLevel.Debug, $\"Refreshing UI for {viewModel.GetType().Name}\");\n bool refreshed = false;\n \n // Get the view model type to determine special handling\n string viewModelTypeName = viewModel.GetType().Name;\n \n // Try multiple refresh methods in order of preference\n \n // 1. First try RefreshCommand if available\n var refreshCommandProperty = viewModel.GetType().GetProperty(\"RefreshCommand\");\n if (refreshCommandProperty != null)\n {\n var refreshCommand = refreshCommandProperty.GetValue(viewModel) as IAsyncRelayCommand;\n if (refreshCommand != null && refreshCommand.CanExecute(null))\n {\n _logService.Log(LogLevel.Debug, \"Executing RefreshCommand\");\n await refreshCommand.ExecuteAsync(null);\n refreshed = true;\n }\n }\n \n // 2. Try RaisePropertyChanged for the Items property if the view model implements INotifyPropertyChanged\n if (!refreshed && viewModel is System.ComponentModel.INotifyPropertyChanged)\n {\n try\n {\n // Try to find the OnPropertyChanged method with a string parameter\n var onPropertyChangedMethod = viewModel.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(string) },\n null);\n \n if (onPropertyChangedMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling OnPropertyChanged(string) for Items property\");\n onPropertyChangedMethod.Invoke(viewModel, new object[] { \"Items\" });\n refreshed = true;\n }\n else\n {\n // Try to find the RaisePropertyChanged method as an alternative\n var raisePropertyChangedMethod = viewModel.GetType().GetMethod(\"RaisePropertyChanged\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (raisePropertyChangedMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling RaisePropertyChanged for Items property\");\n raisePropertyChangedMethod.Invoke(viewModel, new object[] { \"Items\" });\n refreshed = true;\n }\n else\n {\n // Try to find the NotifyPropertyChanged method as another alternative\n var notifyPropertyChangedMethod = viewModel.GetType().GetMethod(\"NotifyPropertyChanged\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (notifyPropertyChangedMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling NotifyPropertyChanged for Items property\");\n notifyPropertyChangedMethod.Invoke(viewModel, new object[] { \"Items\" });\n refreshed = true;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Warning, $\"Error calling property changed method: {ex.Message}\");\n // Continue with other refresh methods\n }\n }\n \n // 3. Try LoadItemsAsync method\n if (!refreshed)\n {\n var loadItemsMethod = viewModel.GetType().GetMethod(\"LoadItemsAsync\");\n if (loadItemsMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling LoadItemsAsync method\");\n await (Task)loadItemsMethod.Invoke(viewModel, null);\n refreshed = true;\n }\n }\n \n // 4. Try ApplySearch method\n if (!refreshed)\n {\n var applySearchMethod = viewModel.GetType().GetMethod(\"ApplySearch\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (applySearchMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling ApplySearch method\");\n applySearchMethod.Invoke(viewModel, null);\n refreshed = true;\n }\n }\n \n // 5. For specific view model types, try additional refresh methods\n if (!refreshed)\n {\n if (viewModelTypeName.Contains(\"Customize\"))\n {\n // Try to refresh the CustomizeViewModel specifically\n var refreshCustomizationsMethod = viewModel.GetType().GetMethod(\"RefreshCustomizations\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (refreshCustomizationsMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling RefreshCustomizations method\");\n refreshCustomizationsMethod.Invoke(viewModel, null);\n refreshed = true;\n }\n }\n else if (viewModelTypeName.Contains(\"Optimize\"))\n {\n // Try to refresh the OptimizeViewModel specifically\n var refreshOptimizationsMethod = viewModel.GetType().GetMethod(\"RefreshOptimizations\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (refreshOptimizationsMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling RefreshOptimizations method\");\n refreshOptimizationsMethod.Invoke(viewModel, null);\n refreshed = true;\n }\n }\n }\n \n // 6. If we still haven't refreshed, try to force a collection refresh\n if (!refreshed)\n {\n // Get the Items property\n var itemsProperty = viewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(viewModel);\n \n // Check if it's an ObservableCollection\n if (items != null && items.GetType().Name.Contains(\"ObservableCollection\"))\n {\n // Try to call a refresh method on the collection\n var refreshMethod = items.GetType().GetMethod(\"Refresh\");\n if (refreshMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling Refresh on ObservableCollection\");\n refreshMethod.Invoke(items, null);\n refreshed = true;\n }\n }\n }\n }\n \n if (!refreshed)\n {\n _logService.Log(LogLevel.Warning, \"Could not find a suitable method to refresh the UI\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error refreshing UI: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n }\n\n /// \n /// A wrapper for the configuration service that returns a specific configuration file.\n /// \n private class ConfigurationServiceWrapper : IConfigurationService\n {\n private readonly IConfigurationService _innerService;\n private readonly ConfigurationFile _configFile;\n private readonly ILogService _logService;\n\n public ConfigurationServiceWrapper(IConfigurationService innerService, ConfigurationFile configFile)\n {\n _innerService = innerService;\n _configFile = configFile;\n \n // Try to get the log service from the inner service using reflection\n try\n {\n var logServiceField = _innerService.GetType().GetField(\"_logService\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (logServiceField != null)\n {\n _logService = logServiceField.GetValue(_innerService) as ILogService;\n }\n }\n catch\n {\n // Ignore any errors, we'll just operate without logging\n }\n }\n\n public Task LoadConfigurationAsync(string configType)\n {\n // Log the operation if possible\n _logService?.Log(LogLevel.Debug, $\"ConfigurationServiceWrapper.LoadConfigurationAsync called with configType: {configType}\");\n _logService?.Log(LogLevel.Debug, $\"Returning config file with {_configFile.Items?.Count ?? 0} items\");\n \n // Always return our config file, but ensure it has the correct configType\n var configFileCopy = new ConfigurationFile\n {\n ConfigType = configType,\n CreatedAt = _configFile.CreatedAt,\n Items = _configFile.Items\n };\n \n return Task.FromResult(configFileCopy);\n }\n\n public Task SaveConfigurationAsync(IEnumerable items, string configType)\n {\n // Log the operation if possible\n _logService?.Log(LogLevel.Debug, $\"ConfigurationServiceWrapper.SaveConfigurationAsync called with configType: {configType}\");\n \n // Delegate to the inner service\n return _innerService.SaveConfigurationAsync(items, configType);\n }\n\n public Task LoadUnifiedConfigurationAsync()\n {\n // Log the operation if possible\n _logService?.Log(LogLevel.Debug, \"ConfigurationServiceWrapper.LoadUnifiedConfigurationAsync called\");\n \n // Delegate to the inner service\n return _innerService.LoadUnifiedConfigurationAsync();\n }\n\n public Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile unifiedConfig)\n {\n return Task.FromResult(true);\n }\n\n public UnifiedConfigurationFile CreateUnifiedConfiguration(Dictionary> sections, IEnumerable includedSections)\n {\n // Log the operation if possible\n _logService?.Log(LogLevel.Debug, \"ConfigurationServiceWrapper.CreateUnifiedConfiguration called\");\n \n // Delegate to the inner service\n return _innerService.CreateUnifiedConfiguration(sections, includedSections);\n }\n\n public ConfigurationFile ExtractSectionFromUnifiedConfiguration(UnifiedConfigurationFile unifiedConfig, string sectionName)\n {\n // Log the operation if possible\n _logService?.Log(LogLevel.Debug, $\"ConfigurationServiceWrapper.ExtractSectionFromUnifiedConfiguration called with sectionName: {sectionName}\");\n \n // Delegate to the inner service\n return _innerService.ExtractSectionFromUnifiedConfiguration(unifiedConfig, sectionName);\n }\n }\n\n /// \n /// A mock configuration service that captures the settings passed to SaveConfigurationAsync.\n /// \n private class MockConfigurationService : IConfigurationService\n {\n // Flag to indicate this is being used for unified configuration\n public bool IsUnifiedConfigurationMode { get; set; } = true;\n \n // Flag to suppress dialogs\n public bool SuppressDialogs { get; set; } = true;\n \n // Captured settings\n public List CapturedSettings { get; } = new List();\n \n // Dialog service for showing messages\n private readonly IDialogService _dialogService;\n \n public MockConfigurationService(IDialogService dialogService = null)\n {\n _dialogService = dialogService;\n }\n\n public Task LoadConfigurationAsync(string configType)\n {\n // Return an empty configuration file\n return Task.FromResult(new ConfigurationFile\n {\n ConfigType = configType,\n CreatedAt = DateTime.UtcNow,\n Items = new List()\n });\n }\n\n public Task SaveConfigurationAsync(IEnumerable items, string configType)\n {\n System.Diagnostics.Debug.WriteLine($\"MockConfigurationService.SaveConfigurationAsync called with configType: {configType}\");\n System.Diagnostics.Debug.WriteLine($\"Generic type T: {typeof(T).FullName}\");\n System.Diagnostics.Debug.WriteLine($\"SuppressDialogs: {SuppressDialogs}, IsUnifiedConfigurationMode: {IsUnifiedConfigurationMode}\");\n \n // Check if items is null or empty\n if (items == null)\n {\n System.Diagnostics.Debug.WriteLine(\"Items collection is null\");\n return Task.FromResult(true);\n }\n \n if (!items.Any())\n {\n System.Diagnostics.Debug.WriteLine(\"Items collection is empty\");\n return Task.FromResult(true);\n }\n \n // Log the count of items\n System.Diagnostics.Debug.WriteLine($\"Items count: {items.Count()}\");\n \n try\n {\n // We no longer need special handling for WindowsApps since we're directly accessing the Items collection\n // Special handling for ExternalApps\n if (configType == \"ExternalApps\")\n {\n System.Diagnostics.Debug.WriteLine(\"Processing ExternalApps configuration\");\n \n // Convert each ExternalApp to ExternalAppSettingItem\n var externalApps = new List();\n \n foreach (var item in items)\n {\n if (item is Winhance.WPF.Features.SoftwareApps.Models.ExternalApp externalApp)\n {\n externalApps.Add(new ExternalAppSettingItem(externalApp));\n System.Diagnostics.Debug.WriteLine($\"Added ExternalAppSettingItem for {externalApp.Name}\");\n }\n }\n \n System.Diagnostics.Debug.WriteLine($\"Created {externalApps.Count} ExternalAppSettingItems\");\n CapturedSettings.AddRange(externalApps);\n System.Diagnostics.Debug.WriteLine($\"Added {externalApps.Count} ExternalAppSettingItems to CapturedSettings\");\n }\n else\n {\n // For other types, try to cast directly to ISettingItem\n try\n {\n var settingItems = items.Cast().ToList();\n System.Diagnostics.Debug.WriteLine($\"Successfully cast to ISettingItem, count: {settingItems.Count}\");\n \n CapturedSettings.AddRange(settingItems);\n System.Diagnostics.Debug.WriteLine($\"Added {settingItems.Count} ISettingItems to CapturedSettings\");\n }\n catch (InvalidCastException ex)\n {\n // Log the error but don't throw it to avoid breaking the configuration process\n System.Diagnostics.Debug.WriteLine($\"Error casting items to ISettingItem: {ex.Message}\");\n \n // Try to convert each item individually\n int convertedCount = 0;\n foreach (var item in items)\n {\n try\n {\n if (item is Winhance.WPF.Features.SoftwareApps.Models.WindowsApp windowsApp)\n {\n CapturedSettings.Add(new WindowsAppSettingItem(windowsApp));\n System.Diagnostics.Debug.WriteLine($\"Added WindowsAppSettingItem for {windowsApp.Name}\");\n convertedCount++;\n }\n else if (item is Winhance.WPF.Features.SoftwareApps.Models.ExternalApp externalApp)\n {\n CapturedSettings.Add(new ExternalAppSettingItem(externalApp));\n System.Diagnostics.Debug.WriteLine($\"Added ExternalAppSettingItem for {externalApp.Name}\");\n convertedCount++;\n }\n else\n {\n System.Diagnostics.Debug.WriteLine($\"Unknown item type: {item?.GetType().FullName ?? \"null\"}\");\n }\n }\n catch (Exception itemEx)\n {\n System.Diagnostics.Debug.WriteLine($\"Error processing individual item: {itemEx.Message}\");\n }\n }\n System.Diagnostics.Debug.WriteLine($\"Converted {convertedCount} items individually\");\n }\n }\n }\n catch (Exception ex)\n {\n System.Diagnostics.Debug.WriteLine($\"Unexpected error in SaveConfigurationAsync: {ex.Message}\");\n }\n \n System.Diagnostics.Debug.WriteLine($\"CapturedSettings count after SaveConfigurationAsync: {CapturedSettings.Count}\");\n \n // Return true without showing any dialogs when in unified configuration mode\n if (SuppressDialogs || IsUnifiedConfigurationMode)\n {\n System.Diagnostics.Debug.WriteLine(\"Suppressing dialogs in unified configuration mode\");\n return Task.FromResult(true);\n }\n \n // Show a success dialog if not in unified configuration mode\n if (_dialogService != null)\n {\n _dialogService.ShowMessage($\"Configuration saved successfully.\", \"Configuration Saved\");\n }\n \n return Task.FromResult(true);\n }\n\n public Task LoadUnifiedConfigurationAsync()\n {\n // Return an empty unified configuration file\n return Task.FromResult(new UnifiedConfigurationFile\n {\n CreatedAt = DateTime.UtcNow,\n WindowsApps = new ConfigSection(),\n ExternalApps = new ConfigSection(),\n Customize = new ConfigSection(),\n Optimize = new ConfigSection()\n });\n }\n\n public Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile unifiedConfig)\n {\n return Task.FromResult(true);\n }\n\n public UnifiedConfigurationFile CreateUnifiedConfiguration(Dictionary> sections, IEnumerable includedSections)\n {\n // Create a unified configuration file with all sections included\n var unifiedConfig = new UnifiedConfigurationFile\n {\n CreatedAt = DateTime.UtcNow,\n WindowsApps = new ConfigSection(),\n ExternalApps = new ConfigSection(),\n Customize = new ConfigSection(),\n Optimize = new ConfigSection()\n };\n\n // Set the IsIncluded flag for each section based on whether it's in the includedSections list\n // and whether it has any items\n if (sections.TryGetValue(\"WindowsApps\", out var windowsApps) && windowsApps.Any())\n {\n unifiedConfig.WindowsApps.IsIncluded = true;\n unifiedConfig.WindowsApps.Items = ConvertToConfigurationItems(windowsApps);\n }\n\n if (sections.TryGetValue(\"ExternalApps\", out var externalApps) && externalApps.Any())\n {\n unifiedConfig.ExternalApps.IsIncluded = true;\n unifiedConfig.ExternalApps.Items = ConvertToConfigurationItems(externalApps);\n }\n\n if (sections.TryGetValue(\"Customize\", out var customize) && customize.Any())\n {\n unifiedConfig.Customize.IsIncluded = true;\n unifiedConfig.Customize.Items = ConvertToConfigurationItems(customize);\n }\n\n if (sections.TryGetValue(\"Optimize\", out var optimize) && optimize.Any())\n {\n unifiedConfig.Optimize.IsIncluded = true;\n unifiedConfig.Optimize.Items = ConvertToConfigurationItems(optimize);\n }\n\n return unifiedConfig;\n }\n\n // Helper method to convert ISettingItem objects to ConfigurationItem objects\n private List ConvertToConfigurationItems(IEnumerable items)\n {\n var result = new List();\n \n foreach (var item in items)\n {\n var configItem = new ConfigurationItem\n {\n Name = item.Name,\n IsSelected = item.IsSelected,\n ControlType = item.ControlType\n };\n \n // Add Id to custom properties\n if (!string.IsNullOrEmpty(item.Id))\n {\n configItem.CustomProperties[\"Id\"] = item.Id;\n }\n \n // Add GroupName to custom properties\n if (!string.IsNullOrEmpty(item.GroupName))\n {\n configItem.CustomProperties[\"GroupName\"] = item.GroupName;\n }\n \n // Add Description to custom properties\n if (!string.IsNullOrEmpty(item.Description))\n {\n configItem.CustomProperties[\"Description\"] = item.Description;\n }\n \n // Ensure SelectedValue is set for ComboBox controls\n configItem.EnsureSelectedValueIsSet();\n \n result.Add(configItem);\n }\n \n return result;\n }\n\n public ConfigurationFile ExtractSectionFromUnifiedConfiguration(UnifiedConfigurationFile unifiedConfig, string sectionName)\n {\n // Return an empty configuration file\n return new ConfigurationFile\n {\n ConfigType = sectionName,\n CreatedAt = DateTime.UtcNow,\n Items = new List()\n };\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Customize/ViewModels/StartMenuCustomizationsViewModel.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Extensions;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Customize.ViewModels\n{\n /// \n /// ViewModel for Start Menu customizations.\n /// \n public partial class StartMenuCustomizationsViewModel : BaseSettingsViewModel\n {\n private readonly ISystemServices _systemServices;\n private bool _isWindows11;\n\n /// \n /// Gets the command to clean the Start Menu.\n /// \n [RelayCommand]\n public async Task CleanStartMenu()\n {\n try\n {\n // Start task with progress\n _progressService.StartTask(\"Cleaning Start Menu...\");\n \n // Update initial progress\n _progressService.UpdateDetailedProgress(new TaskProgressDetail\n {\n StatusText = \"Cleaning Start Menu...\",\n Progress = 0\n });\n\n // Determine Windows version\n _isWindows11 = _systemServices.IsWindows11();\n\n // Clean Start Menu\n await Task.Run(() =>\n {\n StartMenuCustomizations.CleanStartMenu(_isWindows11, _systemServices);\n });\n\n // Log success\n _logService.Log(LogLevel.Info, \"Start Menu cleaned successfully\");\n\n // Update completion progress\n _progressService.UpdateDetailedProgress(new TaskProgressDetail\n {\n StatusText = \"Start Menu cleaned successfully\",\n Progress = 100\n });\n \n // Complete the task\n _progressService.CompleteTask();\n }\n catch (Exception ex)\n {\n // Log error\n _logService.Log(LogLevel.Error, $\"Error cleaning Start Menu: {ex.Message}\");\n\n // Update error progress\n _progressService.UpdateDetailedProgress(new TaskProgressDetail\n {\n StatusText = $\"Error cleaning Start Menu: {ex.Message}\",\n Progress = 100\n });\n \n // Complete the task\n _progressService.CompleteTask();\n }\n }\n\n /// \n /// Gets the command to execute an action.\n /// \n [RelayCommand]\n public async Task ExecuteAction(ApplicationAction? action)\n {\n if (action == null) return;\n\n try\n {\n // Execute the registry action if present\n if (action.RegistrySetting != null)\n {\n string hiveString = action.RegistrySetting.Hive.ToString();\n if (hiveString == \"LocalMachine\") hiveString = \"HKLM\";\n else if (hiveString == \"CurrentUser\") hiveString = \"HKCU\";\n else if (hiveString == \"ClassesRoot\") hiveString = \"HKCR\";\n else if (hiveString == \"Users\") hiveString = \"HKU\";\n else if (hiveString == \"CurrentConfig\") hiveString = \"HKCC\";\n\n string fullPath = $\"{hiveString}\\\\{action.RegistrySetting.SubKey}\";\n _registryService.SetValue(\n fullPath,\n action.RegistrySetting.Name,\n action.RegistrySetting.RecommendedValue,\n action.RegistrySetting.ValueType);\n }\n\n // Execute custom action if present\n if (action.CustomAction != null)\n {\n await action.CustomAction();\n }\n\n _logService.Log(LogLevel.Info, $\"Action '{action.Name}' executed successfully\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error executing action '{action.Name}': {ex.Message}\");\n }\n }\n\n /// \n /// Gets the collection of Start Menu actions.\n /// \n public ObservableCollection Actions { get; } = new();\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The system services.\n public StartMenuCustomizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n ISystemServices systemServices)\n : base(progressService, registryService, logService)\n {\n _systemServices = systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n _isWindows11 = _systemServices.IsWindows11();\n }\n\n /// \n /// Loads the Start Menu customizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Start Menu customizations\n var startMenuCustomizations = Core.Features.Customize.Models.StartMenuCustomizations.GetStartMenuCustomizations();\n if (startMenuCustomizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in startMenuCustomizations.Settings.OrderBy(s => s.Name))\n {\n // Skip Windows 11 specific settings on Windows 10\n if (!_isWindows11 && setting.IsWindows11Only)\n {\n continue;\n }\n\n // Skip Windows 10 specific settings on Windows 11\n if (_isWindows11 && setting.IsWindows10Only)\n {\n continue;\n }\n\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n ControlType = setting.ControlType,\n IsWindows11Only = setting.IsWindows11Only,\n IsWindows10Only = setting.IsWindows10Only\n };\n\n // Add any actions\n var actionsProperty = setting.GetType().GetProperty(\"Actions\");\n if (actionsProperty != null && \n actionsProperty.GetValue(setting) is IEnumerable actions && \n actions.Any())\n {\n // We need to handle this differently since the Actions property doesn't exist in ApplicationSetting\n // This is a temporary workaround until we refactor the code properly\n }\n\n // Set up the registry settings\n if (setting.RegistrySettings != null && setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings != null && setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n var linkedSettings = new LinkedRegistrySettings();\n foreach (var regSetting in setting.RegistrySettings)\n {\n linkedSettings.Settings.Add(regSetting);\n _logService.Log(LogLevel.Info, $\"Adding linked registry setting for {setting.Name}: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}\");\n }\n settingItem.LinkedRegistrySettings = linkedSettings;\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for settings\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Initializes the Start Menu actions.\n /// \n private void InitializeActions()\n {\n Actions.Clear();\n\n // Add Clean Start Menu action\n Actions.Add(new ApplicationAction\n {\n Id = \"clean-start-menu\",\n Name = \"Clean Start Menu\",\n Description = \"Cleans the Start Menu by removing pinned apps and restoring the default layout\",\n CustomAction = async () =>\n {\n await CleanStartMenu();\n return true;\n }\n });\n }\n\n /// \n /// Checks the status of all Start Menu settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n foreach (var setting in Settings)\n {\n // Get status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n setting.Status = status;\n\n // Get current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n setting.CurrentValue = currentValue;\n\n // Set IsRegistryValueNull property based on current value\n setting.IsRegistryValueNull = currentValue == null;\n\n // Update LinkedRegistrySettingsWithValues for tooltip display\n var linkedRegistrySettingsWithValues = new ObservableCollection();\n \n // Get the LinkedRegistrySettings property\n var linkedRegistrySettings = setting.LinkedRegistrySettings;\n \n if (linkedRegistrySettings != null && linkedRegistrySettings.Settings.Count > 0)\n {\n // For linked settings, get fresh values from registry\n bool anyNull = false;\n foreach (var regSetting in linkedRegistrySettings.Settings)\n {\n string hiveString = regSetting.Hive.ToString();\n if (hiveString == \"LocalMachine\") hiveString = \"HKLM\";\n else if (hiveString == \"CurrentUser\") hiveString = \"HKCU\";\n else if (hiveString == \"ClassesRoot\") hiveString = \"HKCR\";\n else if (hiveString == \"Users\") hiveString = \"HKU\";\n else if (hiveString == \"CurrentConfig\") hiveString = \"HKCC\";\n \n var regCurrentValue = _registryService.GetValue(\n $\"{hiveString}\\\\{regSetting.SubKey}\",\n regSetting.Name);\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n linkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // For linked settings, set IsRegistryValueNull if any value is null\n setting.IsRegistryValueNull = anyNull;\n }\n else if (setting.RegistrySetting != null)\n {\n // For single setting\n linkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n // IsRegistryValueNull is already set above\n }\n \n setting.LinkedRegistrySettingsWithValues = linkedRegistrySettingsWithValues;\n\n // Set status message\n string statusMessage = GetStatusMessage(setting);\n setting.StatusMessage = statusMessage;\n\n // Set the IsUpdatingFromCode flag to prevent automatic application\n setting.IsUpdatingFromCode = true;\n\n try\n {\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n // Reset the flag\n setting.IsUpdatingFromCode = false;\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Start Menu setting statuses: {ex.Message}\");\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n // Get status\n var status = setting.Status;\n string message = status switch\n {\n RegistrySettingStatus.Applied => \"Setting is enabled (toggle is ON)\",\n RegistrySettingStatus.NotApplied => \"Setting is disabled (toggle is OFF)\",\n RegistrySettingStatus.Modified => \"Setting has a custom value different from both enabled and disabled values\",\n RegistrySettingStatus.Error => \"Error checking setting status\",\n _ => \"Unknown status\"\n };\n\n // Add current value if available\n var currentValue = setting.CurrentValue;\n if (currentValue != null)\n {\n message += $\"\\nCurrent value: {currentValue}\";\n }\n\n // Add enabled value if available\n var registrySetting = setting.RegistrySetting;\n object? enabledValue = registrySetting?.EnabledValue ?? registrySetting?.RecommendedValue;\n if (enabledValue != null)\n {\n message += $\"\\nEnabled value (ON): {enabledValue}\";\n }\n\n // Add disabled value if available\n object? disabledValue = registrySetting?.DisabledValue ?? registrySetting?.DefaultValue;\n if (disabledValue != null)\n {\n message += $\"\\nDisabled value (OFF): {disabledValue}\";\n }\n\n return message;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Models/ApplicationSettingItem.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Services;\nusing Microsoft.Win32;\n\nnamespace Winhance.WPF.Features.Common.Models\n{\n /// \n /// Base class for application setting items used in both Optimization and Customization features.\n /// \n public partial class ApplicationSettingItem : ObservableObject, ISettingItem, ISearchable\n {\n private readonly IRegistryService? _registryService;\n private readonly ICommandService? _commandService;\n private readonly IDialogService? _dialogService;\n private readonly ILogService? _logService;\n private bool _isUpdatingFromCode;\n\n /// \n /// Gets or sets a value indicating whether the IsSelected property is being updated from code.\n /// This is used to prevent automatic application of settings when loading.\n /// \n public bool IsUpdatingFromCode\n {\n get => _isUpdatingFromCode;\n set => _isUpdatingFromCode = value;\n }\n\n [ObservableProperty]\n private string _id = string.Empty;\n\n [ObservableProperty]\n private string _name = string.Empty;\n\n [ObservableProperty]\n private string _fullName = string.Empty;\n\n partial void OnNameChanged(string value) => UpdateFullName();\n\n private void UpdateFullName()\n {\n FullName = Name;\n }\n\n [ObservableProperty]\n private string _description = string.Empty;\n\n [ObservableProperty]\n private bool _isSelected;\n\n partial void OnIsSelectedChanged(bool value)\n {\n // Skip if we're updating from code\n if (IsUpdatingFromCode)\n {\n return;\n }\n\n // Store the current selection state to restore after applying\n bool currentSelection = value;\n\n // Apply the setting when IsSelected changes\n ApplySetting();\n \n // Ensure the toggle stays in the state the user selected\n if (IsSelected != currentSelection)\n {\n IsUpdatingFromCode = true;\n try\n {\n IsSelected = currentSelection;\n }\n finally\n {\n IsUpdatingFromCode = false;\n }\n }\n }\n\n [ObservableProperty]\n private bool _isGroupHeader;\n\n [ObservableProperty]\n private bool _isVisible = true;\n\n [ObservableProperty]\n private string _groupName = string.Empty;\n\n [ObservableProperty]\n private RegistrySettingStatus _status = RegistrySettingStatus.Unknown;\n\n [ObservableProperty]\n private string _statusMessage = string.Empty;\n\n [ObservableProperty]\n private object? _currentValue;\n\n [ObservableProperty]\n private object? _selectedValue;\n\n [ObservableProperty]\n private bool _isRegistryValueNull;\n\n [ObservableProperty]\n private ControlType _controlType = ControlType.BinaryToggle;\n\n [ObservableProperty]\n private int? _sliderSteps;\n\n [ObservableProperty]\n private int _sliderValue;\n\n [ObservableProperty]\n private ObservableCollection _sliderLabels = new();\n\n [ObservableProperty]\n private bool _isApplying;\n\n /// \n /// Gets or sets the registry setting.\n /// \n public RegistrySetting? RegistrySetting { get; set; }\n\n private LinkedRegistrySettings? _linkedRegistrySettings;\n\n /// \n /// Gets or sets the linked registry settings.\n /// \n public LinkedRegistrySettings? LinkedRegistrySettings \n { \n get => _linkedRegistrySettings;\n set\n {\n _linkedRegistrySettings = value;\n \n // Populate LinkedRegistrySettingsWithValues when LinkedRegistrySettings is assigned\n if (value != null && value.Settings.Count > 0)\n {\n LinkedRegistrySettingsWithValues.Clear();\n foreach (var setting in value.Settings)\n {\n LinkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(setting, null));\n }\n }\n }\n }\n\n /// \n /// Gets or sets the linked registry settings with values.\n /// \n public ObservableCollection LinkedRegistrySettingsWithValues { get; set; } = new();\n\n /// \n /// Gets or sets the command settings.\n /// \n public List CommandSettings { get; set; } = new List();\n\n /// \n /// Gets or sets the dependencies between settings.\n /// \n public List Dependencies { get; set; } = new List();\n\n /// \n /// Gets or sets the dropdown options.\n /// \n public ObservableCollection DropdownOptions { get; set; } = new();\n\n /// \n /// Gets or sets the selected dropdown option.\n /// \n [ObservableProperty]\n private string _selectedDropdownOption = string.Empty;\n \n /// \n /// Gets a value indicating whether there are no settings to display.\n /// \n public bool HasNoSettings\n {\n get\n {\n // True if there are no registry settings and no command settings\n bool hasRegistrySettings = RegistrySetting != null || (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0);\n bool hasCommandSettings = CommandSettings != null && CommandSettings.Count > 0;\n \n return !hasRegistrySettings && !hasCommandSettings;\n }\n }\n \n /// \n /// Gets a value indicating whether this setting only has command settings (no registry settings).\n /// \n public bool HasCommandSettingsOnly\n {\n get\n {\n // True if there are command settings but no registry settings\n bool hasRegistrySettings = RegistrySetting != null || (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0);\n bool hasCommandSettings = CommandSettings != null && CommandSettings.Count > 0;\n \n return hasCommandSettings && !hasRegistrySettings;\n }\n }\n\n /// \n /// Gets or sets a value indicating whether this is a grouped setting that contains child settings.\n /// \n public bool IsGroupedSetting { get; set; }\n\n /// \n /// Gets or sets the child settings for a grouped setting.\n /// \n public ObservableCollection ChildSettings { get; set; } = new ObservableCollection();\n\n /// \n /// Gets or sets a dictionary of custom properties.\n /// \n public Dictionary CustomProperties { get; set; } = new Dictionary();\n\n /// \n /// Gets the collection of actions associated with this setting.\n /// \n public List Actions { get; } = new List();\n\n /// \n /// Gets or sets the command to apply the setting.\n /// \n public ICommand ApplySettingCommand { get; private set; }\n\n /// \n /// Gets or sets the command to restore the setting to its default value.\n /// \n public ICommand RestoreDefaultCommand { get; private set; }\n\n /// \n /// Gets or sets a value indicating whether this setting is only for Windows 11.\n /// \n public bool IsWindows11Only { get; set; }\n\n /// \n /// Gets or sets a value indicating whether this setting is only for Windows 10.\n /// \n public bool IsWindows10Only { get; set; }\n\n /// \n /// Gets or sets the setting type.\n /// \n public string SettingType { get; set; } = string.Empty;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public ApplicationSettingItem()\n {\n ApplySettingCommand = new RelayCommand(ApplySetting);\n RestoreDefaultCommand = new RelayCommand(RestoreDefault);\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The registry service.\n /// The dialog service.\n /// The log service.\n /// The command service.\n public ApplicationSettingItem(IRegistryService? registryService, IDialogService? dialogService, ILogService? logService, ICommandService? commandService = null)\n : this()\n {\n _registryService = registryService;\n _dialogService = dialogService;\n _logService = logService;\n _commandService = commandService;\n }\n\n /// \n /// Applies the setting.\n /// \n public async void ApplySetting()\n {\n // Skip if we're updating from code\n if (IsUpdatingFromCode)\n {\n return;\n }\n \n // Apply registry settings if available\n if (_registryService != null)\n {\n ApplyRegistrySettings();\n }\n \n // Apply command settings if available\n if (_commandService != null && CommandSettings.Any())\n {\n await ApplyCommandSettingsAsync();\n }\n }\n \n /// \n /// Applies the registry settings.\n /// \n private void ApplyRegistrySettings()\n {\n if (_registryService == null)\n {\n return;\n }\n\n // Apply the setting\n if (RegistrySetting != null)\n {\n try\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(RegistrySetting.Hive);\n\n // Get the appropriate value based on the toggle state\n object valueToApply = IsSelected \n ? (RegistrySetting.EnabledValue ?? RegistrySetting.RecommendedValue) \n : (RegistrySetting.DisabledValue ?? RegistrySetting.DefaultValue);\n\n // Apply the setting\n _registryService.SetValue(\n $\"{hiveString}\\\\{RegistrySetting.SubKey}\",\n RegistrySetting.Name,\n valueToApply,\n RegistrySetting.ValueType);\n\n // Update the current value and linked registry settings with values\n CurrentValue = valueToApply;\n \n // Update the linked registry settings with values collection\n LinkedRegistrySettingsWithValues.Clear();\n LinkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(RegistrySetting, CurrentValue));\n\n // Update status without changing IsSelected\n Status = IsSelected ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n StatusMessage = Status == RegistrySettingStatus.Applied ? \"Applied\" : \"Not Applied\";\n\n // Log the action\n _logService?.Log(LogLevel.Info, $\"Applied setting {Name}: {(IsSelected ? \"Enabled\" : \"Disabled\")}\");\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Error applying setting {Name}: {ex.Message}\");\n }\n }\n else if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n try\n {\n // Clear the existing values\n LinkedRegistrySettingsWithValues.Clear();\n \n // Apply all linked settings\n foreach (var setting in LinkedRegistrySettings.Settings)\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(setting.Hive);\n\n // Get the appropriate value based on the toggle state\n object valueToApply = IsSelected \n ? (setting.EnabledValue ?? setting.RecommendedValue) \n : (setting.DisabledValue ?? setting.DefaultValue);\n \n // Apply the setting\n _registryService.SetValue(\n $\"{hiveString}\\\\{setting.SubKey}\",\n setting.Name,\n valueToApply,\n setting.ValueType);\n \n // Add to the linked registry settings with values collection\n LinkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(setting, valueToApply));\n }\n\n // Update status without changing IsSelected\n Status = IsSelected ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n StatusMessage = Status == RegistrySettingStatus.Applied ? \"Applied\" : \"Not Applied\";\n\n // Log the action\n _logService?.Log(LogLevel.Info, $\"Applied linked settings for {Name}: {(IsSelected ? \"Enabled\" : \"Disabled\")}\");\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Error applying linked settings for {Name}: {ex.Message}\");\n }\n }\n\n // Don't call RefreshStatus() here to avoid triggering additional registry operations\n }\n \n /// \n /// Applies the command settings.\n /// \n private async Task ApplyCommandSettingsAsync()\n {\n if (_commandService == null || !CommandSettings.Any())\n {\n return;\n }\n \n try\n {\n // Apply the command settings based on the toggle state\n var (success, message) = await _commandService.ApplyCommandSettingsAsync(CommandSettings, IsSelected);\n \n if (success)\n {\n // Update status without changing IsSelected\n Status = IsSelected ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n StatusMessage = Status == RegistrySettingStatus.Applied ? \"Applied\" : \"Not Applied\";\n \n // Log the action\n _logService?.Log(LogLevel.Info, $\"Applied command settings for {Name}: {(IsSelected ? \"Enabled\" : \"Disabled\")}\");\n }\n else\n {\n // Log the error\n _logService?.Log(LogLevel.Error, $\"Error applying command settings for {Name}: {message}\");\n }\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Exception applying command settings for {Name}: {ex.Message}\");\n }\n }\n\n /// \n /// Restores the setting to its default value.\n /// \n public void RestoreDefault()\n {\n if (_registryService == null)\n {\n return;\n }\n\n // Skip if we're updating from code\n if (IsUpdatingFromCode)\n {\n return;\n }\n\n // Restore the setting to its default value\n if (RegistrySetting != null)\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(RegistrySetting.Hive);\n\n // Apply the setting\n _registryService.SetValue(\n $\"{hiveString}\\\\{RegistrySetting.SubKey}\",\n RegistrySetting.Name,\n RegistrySetting.DefaultValue,\n RegistrySetting.ValueType);\n\n // Log the action\n _logService?.Log(LogLevel.Info, $\"Restored setting {Name} to default value\");\n }\n else if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n // Apply all linked settings\n foreach (var setting in LinkedRegistrySettings.Settings)\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(setting.Hive);\n\n // Apply the setting\n _registryService.SetValue(\n $\"{hiveString}\\\\{setting.SubKey}\",\n setting.Name,\n setting.DefaultValue,\n setting.ValueType);\n }\n\n // Log the action\n _logService?.Log(LogLevel.Info, $\"Restored linked settings for {Name} to default values\");\n }\n\n // Update IsSelected based on status\n IsUpdatingFromCode = true;\n try\n {\n IsSelected = Status == RegistrySettingStatus.Applied;\n }\n finally\n {\n IsUpdatingFromCode = false;\n }\n\n // Refresh the status\n _ = RefreshStatus();\n }\n \n /// \n /// Refreshes the status of command settings.\n /// \n /// A task representing the asynchronous operation.\n private async Task RefreshCommandSettingsStatusAsync()\n {\n if (_commandService == null || !CommandSettings.Any())\n {\n return;\n }\n \n try\n {\n // For now, we'll assume command settings are not applied by default\n // In the future, this could be enhanced to check the actual system state\n bool isEnabled = false;\n \n // If there are primary command settings, check their status\n var primarySetting = CommandSettings.FirstOrDefault(s => s.IsPrimary);\n if (primarySetting != null)\n {\n isEnabled = await _commandService.IsCommandSettingEnabledAsync(primarySetting);\n }\n \n // Update status\n Status = isEnabled ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n StatusMessage = Status == RegistrySettingStatus.Applied ? \"Applied\" : \"Not Applied\";\n \n // Update IsSelected based on status\n IsUpdatingFromCode = true;\n try\n {\n IsSelected = Status == RegistrySettingStatus.Applied;\n }\n finally\n {\n IsUpdatingFromCode = false;\n }\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Error refreshing command settings status for {Name}: {ex.Message}\");\n }\n }\n\n /// \n /// Refreshes the status of the setting.\n /// \n /// A task representing the asynchronous operation.\n public async Task RefreshStatus()\n {\n // Refresh registry settings status if available\n if (_registryService != null)\n {\n await RefreshRegistrySettingsStatusAsync();\n }\n \n // Refresh command settings status if available\n if (_commandService != null && CommandSettings.Any())\n {\n await RefreshCommandSettingsStatusAsync();\n }\n }\n \n /// \n /// Refreshes the status of registry settings.\n /// \n /// A task representing the asynchronous operation.\n private async Task RefreshRegistrySettingsStatusAsync()\n {\n if (_registryService == null)\n {\n return;\n }\n\n // Get the status\n if (RegistrySetting != null)\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(RegistrySetting.Hive);\n\n // Get the current value\n var currentValue = _registryService.GetValue(\n $\"{hiveString}\\\\{RegistrySetting.SubKey}\",\n RegistrySetting.Name);\n\n // Update the current value\n CurrentValue = currentValue;\n \n // Update the linked registry settings with values collection\n LinkedRegistrySettingsWithValues.Clear();\n LinkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(RegistrySetting, currentValue));\n\n // Determine if the value is null\n IsRegistryValueNull = currentValue == null;\n\n // Determine the status\n if (currentValue == null)\n {\n // The value doesn't exist\n Status = RegistrySetting.DefaultValue == null\n ? RegistrySettingStatus.Applied\n : RegistrySettingStatus.NotApplied;\n }\n else\n {\n // Check if it matches the enabled value first\n if (RegistrySetting.EnabledValue != null && currentValue.Equals(RegistrySetting.EnabledValue))\n {\n Status = RegistrySettingStatus.Applied;\n }\n // Then check if it matches the disabled value\n else if (RegistrySetting.DisabledValue != null && currentValue.Equals(RegistrySetting.DisabledValue))\n {\n Status = RegistrySettingStatus.NotApplied;\n }\n // Finally, fall back to recommended value for backward compatibility\n else if (currentValue.Equals(RegistrySetting.RecommendedValue))\n {\n // If RecommendedValue equals EnabledValue, mark as Applied\n // If RecommendedValue equals DisabledValue, mark as NotApplied\n if (RegistrySetting.EnabledValue != null && RegistrySetting.RecommendedValue.Equals(RegistrySetting.EnabledValue))\n {\n Status = RegistrySettingStatus.Applied;\n }\n else\n {\n Status = RegistrySettingStatus.NotApplied;\n }\n }\n else\n {\n Status = RegistrySettingStatus.NotApplied;\n }\n }\n\n // Update the status message\n StatusMessage = Status == RegistrySettingStatus.Applied\n ? \"Applied\"\n : \"Not Applied\";\n\n // Update the IsSelected property - only during initial load\n if (IsUpdatingFromCode)\n {\n IsSelected = Status == RegistrySettingStatus.Applied;\n }\n }\n else if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n // Clear the existing values\n LinkedRegistrySettingsWithValues.Clear();\n \n // Check all linked settings\n bool allApplied = true;\n bool anyApplied = false;\n bool allNull = true;\n bool anyNull = false;\n\n foreach (var setting in LinkedRegistrySettings.Settings)\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(setting.Hive);\n\n // Special handling for Remove action type\n bool isRemoveAction = setting.ActionType == RegistryActionType.Remove;\n \n // Get the current value\n var currentValue = _registryService.GetValue(\n $\"{hiveString}\\\\{setting.SubKey}\",\n setting.Name);\n \n // Add to the linked registry settings with values collection\n LinkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(setting, currentValue));\n\n // Check if the value is null\n if (currentValue == null)\n {\n anyNull = true;\n }\n else\n {\n allNull = false;\n }\n\n // Determine if the value is applied\n bool isApplied;\n \n // For Remove action type, null means the key/value doesn't exist, which means it's applied\n if (isRemoveAction)\n {\n isApplied = currentValue == null;\n }\n else if (currentValue == null)\n {\n // The value doesn't exist\n isApplied = setting.DefaultValue == null;\n }\n else\n {\n // Check if it matches the enabled value first\n if (setting.EnabledValue != null && currentValue.Equals(setting.EnabledValue))\n {\n isApplied = true;\n }\n // Then check if it matches the disabled value\n else if (setting.DisabledValue != null && currentValue.Equals(setting.DisabledValue))\n {\n isApplied = false;\n }\n // Finally, fall back to recommended value for backward compatibility\n else if (currentValue.Equals(setting.RecommendedValue))\n {\n // If RecommendedValue equals EnabledValue, mark as Applied\n // If RecommendedValue equals DisabledValue, mark as NotApplied\n if (setting.EnabledValue != null && setting.RecommendedValue.Equals(setting.EnabledValue))\n {\n isApplied = true;\n }\n else\n {\n isApplied = false;\n }\n }\n else\n {\n isApplied = false;\n }\n }\n\n // Update the status\n if (isApplied)\n {\n anyApplied = true;\n }\n else\n {\n allApplied = false;\n }\n }\n\n // Determine the status based on the logic\n if (LinkedRegistrySettings.Logic == LinkedSettingsLogic.All)\n {\n // All settings must be applied\n Status = allApplied\n ? RegistrySettingStatus.Applied\n : RegistrySettingStatus.NotApplied;\n \n // For ActionType = Remove settings, we need to invert the IsRegistryValueNull logic\n // because null means the key/value doesn't exist, which is the desired state\n bool allRemoveActions = LinkedRegistrySettings.Settings.All(s => s.ActionType == RegistryActionType.Remove);\n if (allRemoveActions)\n {\n // For Remove actions, we want to show the warning when values exist (not null)\n IsRegistryValueNull = !allNull;\n }\n else\n {\n IsRegistryValueNull = allNull;\n }\n }\n else\n {\n // Any setting must be applied\n Status = anyApplied\n ? RegistrySettingStatus.Applied\n : RegistrySettingStatus.NotApplied;\n \n // For ActionType = Remove settings, we need to invert the IsRegistryValueNull logic\n bool allRemoveActions = LinkedRegistrySettings.Settings.All(s => s.ActionType == RegistryActionType.Remove);\n if (allRemoveActions)\n {\n // For Remove actions, we want to show the warning when values exist (not null)\n IsRegistryValueNull = !anyNull;\n }\n else\n {\n IsRegistryValueNull = anyNull;\n }\n }\n\n // Update the status message\n StatusMessage = Status == RegistrySettingStatus.Applied\n ? \"Applied\"\n : \"Not Applied\";\n\n // Update the IsSelected property - only during initial load\n if (IsUpdatingFromCode)\n {\n IsSelected = Status == RegistrySettingStatus.Applied;\n }\n }\n }\n\n /// \n /// Gets the registry hive string.\n /// \n /// The registry hive.\n /// The registry hive string.\n private string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => throw new ArgumentOutOfRangeException(nameof(hive), hive, null)\n };\n }\n\n /// \n /// Determines if the object matches the given search term.\n /// \n /// The search term to match against.\n /// True if the object matches the search term, false otherwise.\n public virtual bool MatchesSearch(string searchTerm)\n {\n if (string.IsNullOrWhiteSpace(searchTerm))\n {\n return true;\n }\n\n searchTerm = searchTerm.ToLowerInvariant();\n\n foreach (var propertyName in GetSearchableProperties())\n {\n var property = GetType().GetProperty(propertyName);\n if (property != null)\n {\n var value = property.GetValue(this)?.ToString();\n if (!string.IsNullOrWhiteSpace(value) && value.ToLowerInvariant().Contains(searchTerm))\n {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /// \n /// Gets the searchable properties of the object.\n /// \n /// An array of property names that should be searched.\n public virtual string[] GetSearchableProperties()\n {\n return new[] { nameof(Name), nameof(Description), nameof(GroupName) };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/WindowsSecurityOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.Common.ViewModels;\n// Use UacLevel from Core.Models.Enums for the UI\nusing UacLevel = Winhance.Core.Models.Enums.UacLevel;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Windows Security optimizations.\n /// \n public partial class WindowsSecurityOptimizationsViewModel : BaseViewModel\n {\n private readonly IRegistryService _registryService;\n private readonly ILogService _logService;\n private readonly ISystemServices _systemServices;\n private readonly IUacSettingsService _uacSettingsService;\n\n /// \n /// Gets or sets a value indicating whether the view model is selected.\n /// \n [ObservableProperty]\n private bool _isSelected;\n\n /// \n /// Gets or sets the selected UAC level.\n /// \n [ObservableProperty]\n private UacLevel _selectedUacLevel;\n\n /// \n /// Gets or sets a value indicating whether the view model has visible settings.\n /// \n [ObservableProperty]\n private bool _hasVisibleSettings = true;\n\n /// \n /// Gets or sets a value indicating whether the UAC level is being applied.\n /// \n [ObservableProperty]\n private bool _isApplyingUacLevel;\n \n /// \n /// Gets or sets a value indicating whether a custom UAC setting is detected.\n /// \n [ObservableProperty]\n private bool _hasCustomUacSetting;\n\n /// \n /// Gets the collection of available UAC levels with their display names.\n /// \n public ObservableCollection> UacLevelOptions { get; } = new();\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The system services.\n /// The UAC settings service.\n public WindowsSecurityOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n ISystemServices systemServices,\n IUacSettingsService uacSettingsService\n )\n : base(progressService, logService, new Features.Common.Services.MessengerService())\n {\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _systemServices = systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n _uacSettingsService = uacSettingsService ?? throw new ArgumentNullException(nameof(uacSettingsService));\n\n // Initialize UAC level options (excluding Custom initially)\n foreach (var kvp in UacOptimizations.UacLevelNames)\n {\n // Skip the Custom option initially - it will be added dynamically when needed\n if (kvp.Key != UacLevel.Custom)\n {\n UacLevelOptions.Add(new KeyValuePair(kvp.Key, kvp.Value));\n }\n }\n\n // Subscribe to property changes to handle UAC level changes\n this.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(SelectedUacLevel))\n {\n HandleUACLevelChange();\n }\n };\n }\n\n /// \n /// Gets the collection of settings.\n /// \n public ObservableCollection Settings { get; } =\n new ObservableCollection();\n\n /// \n /// Handles changes to the UAC notification level.\n /// \n private void HandleUACLevelChange()\n {\n try\n {\n IsApplyingUacLevel = true;\n \n // Set the UAC level using the system service - no conversion needed\n _systemServices.SetUacLevel(SelectedUacLevel);\n \n string levelName = UacOptimizations.UacLevelNames.TryGetValue(SelectedUacLevel, out string name) ? name : SelectedUacLevel.ToString();\n LogInfo($\"UAC Notification Level set to {levelName}\");\n }\n catch (Exception ex)\n {\n LogError($\"Error setting UAC notification level: {ex.Message}\");\n }\n finally\n {\n IsApplyingUacLevel = false;\n }\n }\n \n // Conversion methods removed as we're now using UacLevel directly\n\n /// \n /// Gets the display name of the UAC level.\n /// \n /// The UAC level.\n /// The display name of the UAC level.\n private string GetUacLevelDisplayName(UacLevel level)\n {\n return UacOptimizations.UacLevelNames.TryGetValue(level, out string name) ? name : level.ToString();\n }\n\n /// \n /// Loads the settings.\n /// \n /// A task representing the asynchronous operation.\n public async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n LogInfo(\"Loading UAC notification level setting\");\n\n // Clear existing settings\n Settings.Clear();\n\n // Add a searchable item for the UAC dropdown\n var uacDropdownItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = \"UACDropdown\",\n Name = \"User Account Control Notification Level\",\n Description = \"Controls when Windows notifies you about changes to your computer\",\n GroupName = \"Windows Security Settings\",\n IsVisible = true,\n ControlType = ControlType.Dropdown,\n };\n Settings.Add(uacDropdownItem);\n LogInfo(\"Added searchable item for UAC dropdown\");\n\n // Load UAC notification level\n try\n {\n // Get the UAC level from the system service (now returns Core UacLevel directly)\n SelectedUacLevel = _systemServices.GetUacLevel();\n \n // Check if we have a custom UAC setting in the registry\n bool hasCustomUacInRegistry = (SelectedUacLevel == UacLevel.Custom);\n \n // Check if we have custom UAC settings saved in preferences (using synchronous method to avoid deadlocks)\n bool hasCustomSettingsInPreferences = _uacSettingsService.TryGetCustomUacValues(out _, out _);\n \n // Set flag if we have custom settings either in registry or preferences\n HasCustomUacSetting = hasCustomUacInRegistry || hasCustomSettingsInPreferences;\n \n // If it's a custom setting, add the Custom option to the dropdown if not already present\n if (HasCustomUacSetting)\n {\n // Check if the Custom option is already in the dropdown\n bool customOptionExists = false;\n foreach (var option in UacLevelOptions)\n {\n if (option.Key == UacLevel.Custom)\n {\n customOptionExists = true;\n break;\n }\n }\n \n // Add the Custom option if it doesn't exist\n if (!customOptionExists)\n {\n UacLevelOptions.Add(new KeyValuePair(\n UacLevel.Custom, \n UacOptimizations.UacLevelNames[UacLevel.Custom]));\n LogInfo(\"Added Custom UAC setting option to dropdown\");\n }\n \n // Log the custom UAC settings values\n if (_uacSettingsService.TryGetCustomUacValues(out int consentPromptValue, out int secureDesktopValue))\n {\n LogInfo($\"Custom UAC setting detected: ConsentPrompt={consentPromptValue}, SecureDesktop={secureDesktopValue}\");\n }\n }\n else\n {\n // If not a custom setting, remove the Custom option if it exists\n for (int i = UacLevelOptions.Count - 1; i >= 0; i--)\n {\n if (UacLevelOptions[i].Key == UacLevel.Custom)\n {\n UacLevelOptions.RemoveAt(i);\n LogInfo(\"Removed Custom UAC setting option from dropdown\");\n break;\n }\n }\n }\n \n string levelName = GetUacLevelDisplayName(SelectedUacLevel);\n LogInfo($\"Loaded UAC Notification Level: {levelName}\");\n }\n catch (Exception ex)\n {\n LogError($\"Error loading UAC notification level: {ex.Message}\");\n SelectedUacLevel = UacLevel.NotifyChangesOnly; // Default to standard notification level if there's an error\n HasCustomUacSetting = false;\n }\n\n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n LogError($\"Error loading Windows security settings: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all settings.\n /// \n /// A task representing the asynchronous operation.\n public async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n LogInfo(\"Checking UAC notification level status\");\n\n // Refresh UAC notification level\n await LoadSettingsAsync();\n\n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n LogError($\"Error checking UAC notification level status: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Applies the selected settings.\n /// \n /// Progress reporter.\n /// A task representing the asynchronous operation.\n public async Task ApplySettingsAsync(\n IProgress progress\n )\n {\n try\n {\n IsLoading = true;\n IsApplyingUacLevel = true;\n \n progress.Report(\n new Winhance.Core.Features.Common.Models.TaskProgressDetail\n {\n StatusText = \"Applying UAC notification level setting...\",\n Progress = 0,\n }\n );\n\n // Apply UAC notification level using the system service directly\n // No conversion needed as we're now using UacLevel directly\n _systemServices.SetUacLevel(SelectedUacLevel);\n \n string levelName = GetUacLevelDisplayName(SelectedUacLevel);\n LogInfo($\"UAC Notification Level set to {levelName}\");\n \n progress.Report(\n new Winhance.Core.Features.Common.Models.TaskProgressDetail\n {\n StatusText = $\"{levelName} UAC notification level applied\",\n Progress = 1.0,\n }\n );\n \n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n LogError($\"Error applying UAC notification level: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n IsApplyingUacLevel = false;\n }\n }\n\n /// \n /// Restores the default settings.\n /// \n /// Progress reporter.\n /// A task representing the asynchronous operation.\n public async Task RestoreDefaultsAsync(\n IProgress progress\n )\n {\n try\n {\n IsLoading = true;\n progress.Report(\n new Winhance.Core.Features.Common.Models.TaskProgressDetail\n {\n StatusText = \"Restoring UAC notification level to default...\",\n Progress = 0,\n }\n );\n\n // Set UAC notification level to default (Notify when apps try to make changes)\n SelectedUacLevel = UacLevel.NotifyChangesOnly;\n progress.Report(\n new Winhance.Core.Features.Common.Models.TaskProgressDetail\n {\n StatusText = \"Applying UAC notification level...\",\n Progress = 0.5,\n }\n );\n\n // Apply the changes\n await ApplySettingsAsync(progress);\n\n progress.Report(\n new Winhance.Core.Features.Common.Models.TaskProgressDetail\n {\n StatusText = \"UAC notification level restored to default\",\n Progress = 1.0,\n }\n );\n }\n catch (Exception ex)\n {\n LogError($\"Error restoring UAC notification level: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/ViewModels/ExplorerCustomizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Customize.Enums;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Customize.ViewModels\n{\n /// \n /// ViewModel for Explorer customizations.\n /// \n public partial class ExplorerCustomizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDialogService _dialogService;\n\n /// \n /// Gets the command to execute an action.\n /// \n [RelayCommand]\n public async Task ExecuteAction(ApplicationAction? action)\n {\n if (action == null) return;\n\n try\n {\n // Execute the registry action if present\n if (action.RegistrySetting != null)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(action.RegistrySetting.Hive);\n string fullPath = $\"{hiveString}\\\\{action.RegistrySetting.SubKey}\";\n _registryService.SetValue(\n fullPath,\n action.RegistrySetting.Name,\n action.RegistrySetting.RecommendedValue,\n action.RegistrySetting.ValueType);\n }\n\n // Execute the command action if present\n if (action.CommandAction != null)\n {\n // Execute the command\n // This would typically be handled by a command execution service\n }\n\n // Refresh the status after applying the action\n await CheckSettingStatusesAsync();\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error executing action: {ex.Message}\");\n }\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dialog service.\n public ExplorerCustomizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDialogService dialogService)\n : base(progressService, registryService, logService)\n {\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n }\n\n /// \n /// Loads the Explorer customizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Explorer customizations from ExplorerCustomizations\n var explorerCustomizations = Core.Features.Customize.Models.ExplorerCustomizations.GetExplorerCustomizations();\n if (explorerCustomizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in explorerCustomizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n ControlType = setting.ControlType\n };\n\n // Add any actions\n var actionsProperty = setting.GetType().GetProperty(\"Actions\");\n if (actionsProperty != null && \n actionsProperty.GetValue(setting) is IEnumerable actions && \n actions.Any())\n {\n // We need to handle this differently since the Actions property doesn't exist in ApplicationSetting\n // This is a temporary workaround until we refactor the code properly\n }\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for settings\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all Explorer customizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n foreach (var setting in Settings)\n {\n // Get status\n if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n // For linked registry settings, use GetLinkedSettingsStatusAsync\n var linkedStatus = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n setting.Status = linkedStatus;\n \n // Update IsSelected based on status - this is crucial for the initial toggle state\n setting.IsUpdatingFromCode = true;\n setting.IsSelected = linkedStatus == RegistrySettingStatus.Applied;\n setting.IsUpdatingFromCode = false;\n }\n else\n {\n // For single registry setting\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n setting.Status = status;\n }\n\n // Get current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n setting.CurrentValue = currentValue;\n\n // Set IsRegistryValueNull property based on current value for single registry setting\n if (setting.LinkedRegistrySettings == null || setting.LinkedRegistrySettings.Settings.Count == 0)\n {\n // Special handling for specific Explorer items that should not show warning icons\n if (setting.Name == \"3D Objects\" || \n setting.Name == \"Gallery in Navigation Pane\" || \n setting.Name == \"Home in Navigation Pane\")\n {\n // Don't show warning icon for these specific items\n setting.IsRegistryValueNull = false;\n }\n else\n {\n setting.IsRegistryValueNull = currentValue == null;\n }\n }\n\n // Update LinkedRegistrySettingsWithValues for tooltip display\n var linkedRegistrySettingsWithValues = new ObservableCollection();\n \n // Get the LinkedRegistrySettings property\n var linkedRegistrySettings = setting.LinkedRegistrySettings;\n \n if (linkedRegistrySettings != null && linkedRegistrySettings.Settings.Count > 0)\n {\n // For linked settings, get fresh values from registry\n bool anyNull = false;\n foreach (var regSetting in linkedRegistrySettings.Settings)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(regSetting.Hive);\n var regCurrentValue = _registryService.GetValue(\n $\"{hiveString}\\\\{regSetting.SubKey}\",\n regSetting.Name);\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n linkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // For linked settings, set IsRegistryValueNull if any value is null\n // Special handling for specific Explorer items that should not show warning icons\n if (setting.Name == \"3D Objects\" || \n setting.Name == \"Gallery in Navigation Pane\" || \n setting.Name == \"Home in Navigation Pane\")\n {\n // Don't show warning icon for these specific items\n setting.IsRegistryValueNull = false;\n }\n else\n {\n setting.IsRegistryValueNull = anyNull;\n }\n }\n else if (setting.RegistrySetting != null)\n {\n // For single setting\n linkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n }\n \n setting.LinkedRegistrySettingsWithValues = linkedRegistrySettingsWithValues;\n\n // Set status message\n string statusMessage = GetStatusMessage(setting);\n setting.StatusMessage = statusMessage;\n\n // Set the IsUpdatingFromCode flag to prevent automatic application\n setting.IsUpdatingFromCode = true;\n\n try\n {\n // Update IsSelected based on status\n bool shouldBeSelected = setting.Status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {setting.Status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n // Reset the flag\n setting.IsUpdatingFromCode = false;\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Explorer customization statuses: {ex.Message}\");\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n var status = setting.Status;\n string message = status switch\n {\n RegistrySettingStatus.Applied => \"Setting is applied with recommended value\",\n RegistrySettingStatus.NotApplied => \"Setting is not applied or using default value\",\n RegistrySettingStatus.Modified => \"Setting has a custom value different from recommended\",\n RegistrySettingStatus.Error => \"Error checking setting status\",\n _ => \"Unknown status\"\n };\n\n // Add current value if available\n var currentValue = setting.CurrentValue;\n if (currentValue != null)\n {\n message += $\"\\nCurrent value: {currentValue}\";\n }\n\n // Add recommended value if available\n var registrySetting = setting.RegistrySetting;\n if (registrySetting?.RecommendedValue != null)\n {\n message += $\"\\nRecommended value: {registrySetting.RecommendedValue}\";\n }\n\n // Add default value if available\n if (registrySetting?.DefaultValue != null)\n {\n message += $\"\\nDefault value: {registrySetting.DefaultValue}\";\n }\n\n return message;\n }\n\n // ApplySelectedSettingsAsync and RestoreDefaultsAsync methods removed as part of the refactoring\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/PowerShellScriptFactory.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Factory for creating PowerShell script objects.\n /// \n public class PowerShellScriptFactory : IScriptFactory\n {\n private readonly IScriptBuilderService _scriptBuilder;\n private readonly ILogService _logService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The script builder service.\n /// The logging service.\n /// The app discovery service.\n public PowerShellScriptFactory(\n IScriptBuilderService scriptBuilder,\n ILogService logService,\n IAppDiscoveryService appDiscoveryService)\n {\n _scriptBuilder = scriptBuilder ?? throw new ArgumentNullException(nameof(scriptBuilder));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _appDiscoveryService = appDiscoveryService ?? throw new ArgumentNullException(nameof(appDiscoveryService));\n }\n\n /// \n public RemovalScript CreateBatchRemovalScript(\n List appNames,\n Dictionary> appsWithRegistry,\n Dictionary appSubPackages = null)\n {\n try\n {\n _logService.LogInformation($\"Creating batch removal script for {appNames.Count} apps\");\n\n // Categorize apps into packages, capabilities, and features\n var (packages, capabilities, features) = CategorizeApps(appNames);\n\n // Build the script content\n string scriptContent = _scriptBuilder.BuildCompleteRemovalScript(\n packages,\n capabilities,\n features,\n appsWithRegistry,\n appSubPackages);\n\n // Return the RemovalScript object\n return new RemovalScript\n {\n Name = \"BloatRemoval\",\n Content = scriptContent,\n TargetScheduledTaskName = \"Winhance\\\\BloatRemoval\",\n RunOnStartup = true\n };\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error creating batch removal script\", ex);\n throw;\n }\n }\n\n /// \n public RemovalScript CreateSingleAppRemovalScript(AppInfo app)\n {\n try\n {\n _logService.LogInformation($\"Creating single app removal script for {app.PackageName}\");\n\n // Build the script content\n string scriptContent = _scriptBuilder.BuildSingleAppRemovalScript(app);\n\n // Return the RemovalScript object\n return new RemovalScript\n {\n Name = $\"Remove_{app.PackageName.Replace(\".\", \"_\")}\",\n Content = scriptContent,\n TargetScheduledTaskName = $\"Winhance\\\\Remove_{app.PackageName.Replace(\".\", \"_\")}\",\n RunOnStartup = false\n };\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error creating single app removal script for {app.PackageName}\", ex);\n throw;\n }\n }\n\n /// \n /// Categorizes apps into packages, capabilities, and features.\n /// \n /// The app names to categorize.\n /// A tuple containing lists of packages, capabilities, and features.\n private (List, List, List) CategorizeApps(List appNames)\n {\n var packages = new List();\n var capabilities = new List();\n var features = new List();\n\n // Get all standard apps to check their types\n var allApps = _appDiscoveryService.GetStandardAppsAsync().GetAwaiter().GetResult();\n var appInfoDict = allApps.ToDictionary(a => a.PackageName, a => a);\n\n foreach (var appName in appNames)\n {\n if (appInfoDict.TryGetValue(appName, out var appInfo))\n {\n switch (appInfo.Type)\n {\n case AppType.StandardApp:\n packages.Add(appName);\n break;\n case AppType.Capability:\n capabilities.Add(appName);\n break;\n case AppType.OptionalFeature:\n features.Add(appName);\n break;\n default:\n // Default to package if type is unknown\n packages.Add(appName);\n break;\n }\n }\n else\n {\n // If app is not found in the dictionary, assume it's a package\n packages.Add(appName);\n }\n }\n\n return (packages, capabilities, features);\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/NotificationOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\n\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Notifications optimizations.\n /// \n public class NotificationOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDialogService _dialogService;\n private readonly IDependencyManager _dependencyManager;\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dialog service.\n /// The dependency manager.\n /// The view model locator.\n /// The settings registry.\n public NotificationOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDialogService dialogService,\n IDependencyManager dependencyManager,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _dependencyManager = dependencyManager ?? throw new ArgumentNullException(nameof(dependencyManager));\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n _logService.Log(LogLevel.Info, \"NotificationOptimizationsViewModel instance created\");\n }\n\n /// \n /// Loads the Notifications settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, \"NotificationOptimizationsViewModel.LoadSettingsAsync: Starting to load notification optimizations\");\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Notification optimizations from NotificationOptimizations\n var notificationOptimizations = Core.Features.Optimize.Models.NotificationOptimizations.GetNotificationOptimizations();\n _logService.Log(LogLevel.Info, $\"NotificationOptimizationsViewModel.LoadSettingsAsync: Got {notificationOptimizations?.Settings?.Count ?? 0} notification optimizations\");\n if (notificationOptimizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in notificationOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = false, // Always initialize as unchecked\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Register the setting in the settings registry if available\n if (_settingsRegistry != null && !string.IsNullOrEmpty(settingItem.Id))\n {\n _settingsRegistry.RegisterSetting(settingItem);\n _logService.Log(LogLevel.Info, $\"Registered setting {settingItem.Id} in settings registry during creation\");\n }\n\n Settings.Add(settingItem);\n _logService.Log(LogLevel.Info, $\"NotificationOptimizationsViewModel.LoadSettingsAsync: Added setting {setting.Name} to collection\");\n }\n\n // Set up property change handlers for checkboxes\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n\n _logService.Log(LogLevel.Info, $\"NotificationOptimizationsViewModel.LoadSettingsAsync: Added {Settings.Count} settings to collection\");\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n\n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading notification settings: {ex.Message}\");\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all Notifications settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"NotificationOptimizationsViewModel.CheckSettingStatusesAsync: Checking status for {Settings.Count} settings\");\n\n foreach (var setting in Settings)\n {\n if (setting.RegistrySetting != null)\n {\n // Get status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n setting.Status = status;\n\n // Get current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n setting.CurrentValue = currentValue;\n \n // Set IsRegistryValueNull property based on current value\n setting.IsRegistryValueNull = currentValue == null;\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking notification setting statuses: {ex.Message}\");\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied => \"Applied\",\n RegistrySettingStatus.NotApplied => \"Not Applied\",\n RegistrySettingStatus.Error => \"Error\",\n RegistrySettingStatus.Unknown => \"Unknown\",\n _ => \"Unknown\"\n };\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0) return;\n\n bool allSelected = Settings.All(s => s.IsSelected);\n bool anySelected = Settings.Any(s => s.IsSelected);\n\n IsSelected = allSelected;\n }\n\n /// \n /// Converts a RegistryHive enum to its string representation (HKCU, HKLM, etc.)\n /// \n /// The registry hive.\n /// The string representation of the registry hive.\n private string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => hive.ToString()\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/BaseViewModel.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Runtime.CompilerServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// Base view model class that implements INotifyPropertyChanged and provides common functionality.\n /// \n public abstract class BaseViewModel : ObservableObject, IDisposable, IViewModel\n {\n private readonly ITaskProgressService _progressService;\n private readonly ILogService _logService;\n private readonly IMessengerService _messengerService;\n private bool _isDisposed;\n private bool _isLoading;\n private string _statusText = string.Empty;\n private double _currentProgress;\n private bool _isIndeterminate;\n private ObservableCollection _logMessages =\n new ObservableCollection();\n private bool _areDetailsExpanded;\n private bool _canCancelTask;\n private bool _isTaskRunning;\n private ICommand _cancelCommand;\n\n /// \n /// Gets or sets whether the view model is loading.\n /// \n public bool IsLoading\n {\n get => _isLoading;\n protected set => SetProperty(ref _isLoading, value);\n }\n\n /// \n /// Gets the command to cancel the current task.\n /// \n public ICommand CancelCommand =>\n _cancelCommand ??= new RelayCommand(CancelCurrentTask, () => CanCancelTask);\n\n /// \n /// Gets or sets the status text.\n /// \n public string StatusText\n {\n get => _statusText;\n protected set => SetProperty(ref _statusText, value);\n }\n\n /// \n /// Gets or sets the current progress value (0-100).\n /// \n public double CurrentProgress\n {\n get => _currentProgress;\n protected set => SetProperty(ref _currentProgress, value);\n }\n\n /// \n /// Gets or sets whether the progress is indeterminate.\n /// \n public bool IsIndeterminate\n {\n get => _isIndeterminate;\n protected set => SetProperty(ref _isIndeterminate, value);\n }\n\n /// \n /// Gets the collection of log messages.\n /// \n public ObservableCollection LogMessages => _logMessages;\n\n /// \n /// Gets or sets whether the details are expanded.\n /// \n public bool AreDetailsExpanded\n {\n get => _areDetailsExpanded;\n set => SetProperty(ref _areDetailsExpanded, value);\n }\n\n /// \n /// Gets or sets whether the task can be cancelled.\n /// \n public bool CanCancelTask\n {\n get => _canCancelTask;\n protected set => SetProperty(ref _canCancelTask, value);\n }\n\n /// \n /// Gets or sets whether a task is running.\n /// \n public bool IsTaskRunning\n {\n get => _isTaskRunning;\n protected set => SetProperty(ref _isTaskRunning, value);\n }\n\n /// \n /// Gets the command to cancel the current task.\n /// \n public ICommand CancelTaskCommand { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The log service.\n /// The messenger service.\n protected BaseViewModel(\n ITaskProgressService progressService,\n ILogService logService,\n IMessengerService messengerService\n )\n {\n _progressService =\n progressService ?? throw new ArgumentNullException(nameof(progressService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _messengerService =\n messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n\n // Subscribe to progress service events\n if (_progressService != null)\n {\n _progressService.ProgressUpdated -= ProgressService_ProgressUpdated;\n _progressService.ProgressUpdated += ProgressService_ProgressUpdated;\n _progressService.LogMessageAdded -= ProgressService_LogMessageAdded;\n _progressService.LogMessageAdded += ProgressService_LogMessageAdded;\n }\n\n CancelTaskCommand = new RelayCommand(\n CancelCurrentTask,\n () => CanCancelTask && IsTaskRunning\n );\n _cancelCommand = CancelTaskCommand; // Ensure both commands point to the same implementation\n }\n\n /// \n /// Initializes a new instance of the class.\n /// This constructor is for backward compatibility.\n /// \n /// The task progress service.\n /// The messenger service.\n protected BaseViewModel(\n ITaskProgressService progressService,\n IMessengerService messengerService\n )\n : this(\n progressService,\n new Core.Features.Common.Services.LogService(),\n messengerService\n ) { }\n\n /// \n /// Initializes a new instance of the class.\n /// This constructor is for backward compatibility.\n /// \n /// The task progress service.\n protected BaseViewModel(ITaskProgressService progressService)\n : this(\n progressService,\n new Core.Features.Common.Services.LogService(),\n new Features.Common.Services.MessengerService()\n ) { }\n\n /// \n /// Disposes of the resources used by the ViewModel\n /// \n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n /// \n /// Disposes of the resources used by the ViewModel\n /// \n /// Whether to dispose of managed resources\n protected virtual void Dispose(bool disposing)\n {\n if (!_isDisposed)\n {\n if (disposing)\n {\n // Unsubscribe from events\n _progressService.ProgressUpdated -= ProgressService_ProgressUpdated;\n _progressService.LogMessageAdded -= ProgressService_LogMessageAdded;\n\n // Unregister from messenger\n if (_messengerService != null)\n {\n _messengerService.Unregister(this);\n }\n }\n\n _isDisposed = true;\n }\n }\n\n /// \n /// Finalizer to ensure resources are released\n /// \n ~BaseViewModel()\n {\n Dispose(false);\n }\n\n /// \n /// Called when the view model is navigated to\n /// \n /// Navigation parameter\n public virtual void OnNavigatedTo(object? parameter = null)\n {\n // Base implementation does nothing\n // Derived classes should override if they need to handle parameters\n }\n\n /// \n /// Handles the ProgressUpdated event of the progress service.\n /// \n /// The source of the event.\n /// The progress detail.\n private void ProgressService_ProgressUpdated(\n object? sender,\n Winhance.Core.Features.Common.Models.TaskProgressDetail detail\n )\n {\n // Update local properties\n IsLoading = _progressService.IsTaskRunning;\n StatusText = detail.StatusText ?? string.Empty;\n CurrentProgress = detail.Progress ?? 0;\n IsIndeterminate = detail.IsIndeterminate;\n IsTaskRunning = _progressService.IsTaskRunning;\n CanCancelTask =\n _progressService.IsTaskRunning\n && _progressService.CurrentTaskCancellationSource != null;\n\n // Send a message for UI updates that may occur in other threads\n _messengerService.Send(\n new TaskProgressMessage\n {\n Progress = detail.Progress ?? 0,\n StatusText = detail.StatusText ?? string.Empty,\n IsIndeterminate = detail.IsIndeterminate,\n IsTaskRunning = _progressService.IsTaskRunning,\n CanCancel =\n _progressService.IsTaskRunning\n && _progressService.CurrentTaskCancellationSource != null,\n }\n );\n }\n\n /// \n /// Handles the LogMessageAdded event of the progress service.\n /// \n /// The source of the event.\n /// The log message.\n private void ProgressService_LogMessageAdded(object? sender, string message)\n {\n if (string.IsNullOrEmpty(message))\n return;\n\n // Add to local collection\n var logMessageViewModel = new LogMessageViewModel\n {\n Message = message,\n Level = LogLevel.Info, // Default to Info since we don't have level information\n Timestamp = DateTime.Now,\n };\n\n LogMessages.Add(logMessageViewModel);\n\n // Auto-expand details on error or warning (we can't determine this from the string message)\n\n // Send a message for UI updates that may occur in other threads\n _messengerService.Send(\n new LogMessage\n {\n Message = message,\n Level = LogLevel.Info, // Default to Info since we don't have level information\n Exception = null,\n }\n );\n }\n\n /// \n /// Cancels the current task.\n /// \n protected void CancelCurrentTask()\n {\n if (_progressService.CurrentTaskCancellationSource != null && CanCancelTask)\n {\n _logService.LogInformation(\"User requested task cancellation\");\n _progressService.CancelCurrentTask();\n }\n }\n\n /// \n /// Executes an operation with progress reporting.\n /// \n /// The operation to execute.\n /// The name of the task.\n /// Whether the progress is indeterminate.\n /// A task representing the asynchronous operation.\n protected async Task ExecuteWithProgressAsync(\n Func operation,\n string taskName,\n bool isIndeterminate = false\n )\n {\n try\n {\n _progressService.StartTask(taskName, isIndeterminate);\n await operation(_progressService);\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in {taskName}: {ex.Message}\", ex);\n _progressService.AddLogMessage($\"Error: {ex.Message}\");\n throw;\n }\n finally\n {\n if (_progressService.IsTaskRunning)\n {\n _progressService.CompleteTask();\n }\n }\n }\n\n /// \n /// Executes an operation with progress reporting and returns a result.\n /// \n /// The type of the result.\n /// The operation to execute.\n /// The name of the task.\n /// Whether the progress is indeterminate.\n /// A task representing the asynchronous operation.\n protected async Task ExecuteWithProgressAsync(\n Func> operation,\n string taskName,\n bool isIndeterminate = false\n )\n {\n try\n {\n _progressService.StartTask(taskName, isIndeterminate);\n return await operation(_progressService);\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in {taskName}: {ex.Message}\", ex);\n _progressService.AddLogMessage($\"Error: {ex.Message}\");\n throw;\n }\n finally\n {\n if (_progressService.IsTaskRunning)\n {\n _progressService.CompleteTask();\n }\n }\n }\n\n /// \n /// Executes an operation with detailed progress reporting.\n /// \n /// The operation to execute.\n /// The name of the task.\n /// Whether the progress is indeterminate.\n /// A task representing the asynchronous operation.\n protected async Task ExecuteWithProgressAsync(\n Func<\n IProgress,\n CancellationToken,\n Task\n > operation,\n string taskName,\n bool isIndeterminate = false\n )\n {\n try\n {\n // Clear previous log messages\n LogMessages.Clear();\n\n _progressService.StartTask(taskName, isIndeterminate);\n var progress = _progressService.CreateDetailedProgress();\n var cancellationToken = _progressService.CurrentTaskCancellationSource.Token;\n\n await operation(progress, cancellationToken);\n }\n catch (OperationCanceledException)\n {\n _progressService.AddLogMessage(\"Operation cancelled by user\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in {taskName}: {ex.Message}\", ex);\n _progressService.AddLogMessage($\"Error: {ex.Message}\");\n throw;\n }\n finally\n {\n if (_progressService.IsTaskRunning)\n {\n _progressService.CompleteTask();\n }\n }\n }\n\n /// \n /// Executes an operation with detailed progress reporting and returns a result.\n /// \n /// The type of the result.\n /// The operation to execute.\n /// The name of the task.\n /// Whether the progress is indeterminate.\n /// A task representing the asynchronous operation.\n protected async Task ExecuteWithProgressAsync(\n Func<\n IProgress,\n CancellationToken,\n Task\n > operation,\n string taskName,\n bool isIndeterminate = false\n )\n {\n try\n {\n // Clear previous log messages\n LogMessages.Clear();\n\n _progressService.StartTask(taskName, isIndeterminate);\n var progress = _progressService.CreateDetailedProgress();\n var cancellationToken = _progressService.CurrentTaskCancellationSource.Token;\n\n return await operation(progress, cancellationToken);\n }\n catch (OperationCanceledException)\n {\n _progressService.AddLogMessage(\"Operation cancelled by user\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in {taskName}: {ex.Message}\", ex);\n _progressService.AddLogMessage($\"Error: {ex.Message}\");\n throw;\n }\n finally\n {\n if (_progressService.IsTaskRunning)\n {\n _progressService.CompleteTask();\n }\n }\n }\n\n /// \n /// Gets the progress service.\n /// \n protected ITaskProgressService ProgressService => _progressService;\n\n /// \n /// Logs an informational message.\n /// \n /// The message to log.\n protected void LogInfo(string message)\n {\n _logService.LogInformation(message);\n }\n\n /// \n /// Logs an error message.\n /// \n /// The message to log.\n /// The exception associated with the error, if any.\n protected void LogError(string message, Exception? exception = null)\n {\n _logService.LogError(message, exception);\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/ViewModels/WindowsThemeCustomizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.Customize.Models;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Customize.ViewModels\n{\n /// \n /// ViewModel for Windows Theme customizations.\n /// \n public partial class WindowsThemeCustomizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDialogService _dialogService;\n private readonly IThemeService _themeService;\n private readonly WindowsThemeSettings _themeSettings;\n private readonly IRegistryService _registryService;\n\n // Flags to prevent triggering dark mode action during property change\n private bool _isHandlingDarkModeChange = false;\n private bool _isShowingDialog = false;\n \n // Store the original state before any changes\n private bool _originalDarkModeState;\n private string _originalTheme = string.Empty;\n \n // Store the requested state for the dialog\n private bool _requestedDarkModeState;\n private string _requestedTheme = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether dark mode is enabled.\n /// \n [ObservableProperty]\n private bool _isDarkModeEnabled;\n \n /// \n /// Gets or sets a value indicating whether to change the wallpaper when changing the theme.\n /// \n [ObservableProperty]\n private bool _changeWallpaper;\n\n /// \n /// Gets a value indicating whether theme options are available.\n /// \n public bool HasThemeOptions => true;\n\n /// \n /// Gets the available theme options.\n /// \n public List ThemeOptions => new List { \"Light Mode\", \"Dark Mode\" };\n\n /// \n /// Gets or sets the selected theme.\n /// \n public string SelectedTheme\n {\n get => IsDarkModeEnabled ? \"Dark Mode\" : \"Light Mode\";\n set\n {\n if (value == \"Dark Mode\" && !IsDarkModeEnabled)\n {\n IsDarkModeEnabled = true;\n }\n else if (value == \"Light Mode\" && IsDarkModeEnabled)\n {\n IsDarkModeEnabled = false;\n }\n OnPropertyChanged();\n }\n }\n\n /// \n /// Gets the category name.\n /// \n public string CategoryName => \"Windows Theme\";\n\n /// \n /// Gets the command to apply the theme.\n /// \n public ICommand ApplyThemeCommand { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dialog service.\n /// The theme service.\n public WindowsThemeCustomizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDialogService dialogService,\n IThemeService themeService)\n : base(progressService, registryService, logService)\n {\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _themeService = themeService ?? throw new ArgumentNullException(nameof(themeService));\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n \n // Initialize the theme settings model\n _themeSettings = new WindowsThemeSettings(themeService);\n \n // Load the current theme state\n LoadDarkModeState();\n \n // Initialize commands\n ApplyThemeCommand = new AsyncRelayCommand(ApplyThemeWithConfirmationAsync);\n\n // Subscribe to property changes to handle dark mode toggle and theme selection\n this.PropertyChanged += (s, e) =>\n {\n // Skip if we're already handling a change or showing a dialog\n if (_isHandlingDarkModeChange || _isShowingDialog)\n return;\n \n if (e.PropertyName == nameof(IsDarkModeEnabled))\n {\n HandleDarkModePropertyChange();\n }\n else if (e.PropertyName == nameof(SelectedTheme))\n {\n HandleThemeSelectionChange();\n }\n };\n }\n\n /// \n /// Handles changes to the IsDarkModeEnabled property.\n /// \n private void HandleDarkModePropertyChange()\n {\n // Store the original state before any changes\n _originalDarkModeState = _themeService.IsDarkModeEnabled();\n _originalTheme = _originalDarkModeState ? \"Dark Mode\" : \"Light Mode\";\n \n // Store the requested state\n _requestedDarkModeState = IsDarkModeEnabled;\n _requestedTheme = IsDarkModeEnabled ? \"Dark Mode\" : \"Light Mode\";\n \n // Log the state change\n _logService.Log(LogLevel.Info, $\"Dark mode check completed. Is Dark Mode: {_originalDarkModeState}\");\n \n // Update the selected theme to match the dark mode state\n _isHandlingDarkModeChange = true;\n try\n {\n SelectedTheme = IsDarkModeEnabled ? \"Dark Mode\" : \"Light Mode\";\n \n // Update the theme settings model\n _themeSettings.IsDarkMode = IsDarkModeEnabled;\n \n // Update the theme selector setting if it exists\n UpdateThemeSelectorSetting();\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n \n // Prompt for confirmation\n PromptForThemeChange();\n }\n\n /// \n /// Handles changes to the SelectedTheme property.\n /// \n private void HandleThemeSelectionChange()\n {\n // Store the original state before any changes\n _originalDarkModeState = _themeService.IsDarkModeEnabled();\n _originalTheme = _originalDarkModeState ? \"Dark Mode\" : \"Light Mode\";\n \n // Store the requested state\n _requestedTheme = SelectedTheme;\n _requestedDarkModeState = SelectedTheme == \"Dark Mode\";\n \n // Log the state change\n _logService.Log(LogLevel.Info, $\"Theme mode changed to {SelectedTheme}\");\n \n // Update the dark mode state based on the selected theme\n _isHandlingDarkModeChange = true;\n try\n {\n IsDarkModeEnabled = SelectedTheme == \"Dark Mode\";\n \n // Update the theme settings model\n _themeSettings.IsDarkMode = IsDarkModeEnabled;\n \n // Update the theme selector setting if it exists\n UpdateThemeSelectorSetting();\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n \n // Prompt for confirmation\n PromptForThemeChange();\n }\n\n /// \n /// Loads the dark mode state.\n /// \n private void LoadDarkModeState()\n {\n try\n {\n // Load the current theme settings\n _themeSettings.LoadCurrentSettings();\n \n // Update the view model properties\n _isHandlingDarkModeChange = true;\n try\n {\n IsDarkModeEnabled = _themeSettings.IsDarkMode;\n SelectedTheme = _themeSettings.ThemeName;\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n\n // Store the original state\n _originalDarkModeState = IsDarkModeEnabled;\n _originalTheme = SelectedTheme;\n\n _logService.Log(LogLevel.Info, $\"Loaded theme settings: {SelectedTheme}\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading dark mode state: {ex.Message}\");\n IsDarkModeEnabled = true; // Default to dark mode if there's an error\n SelectedTheme = \"Dark Mode\"; // Set selected theme to match\n \n // Store the original state\n _originalDarkModeState = IsDarkModeEnabled;\n _originalTheme = SelectedTheme;\n }\n }\n\n /// \n /// Prompts the user for theme change confirmation.\n /// \n private async void PromptForThemeChange()\n {\n // Prevent multiple dialogs from being shown at once\n if (_isShowingDialog)\n {\n _logService.Log(LogLevel.Info, \"Dialog already showing, ignoring request\");\n return;\n }\n \n _isShowingDialog = true;\n \n try\n {\n // Store the current UI state before showing the dialog\n bool currentDarkModeState = IsDarkModeEnabled;\n string currentTheme = SelectedTheme;\n \n // Revert to the original state before showing the dialog\n // This ensures that if the user cancels, we're already in the original state\n _isHandlingDarkModeChange = true;\n try\n {\n IsDarkModeEnabled = _originalDarkModeState;\n SelectedTheme = _originalTheme;\n _themeSettings.IsDarkMode = _originalDarkModeState;\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n \n // Prompt user about wallpaper change\n _logService.Log(LogLevel.Info, \"Showing dialog for theme change confirmation\");\n \n // Use the DialogService to show the confirmation dialog\n var result = await _dialogService.ShowYesNoCancelAsync(\n $\"Would you also like to change to the default {(currentDarkModeState ? \"dark\" : \"light\")} theme wallpaper?\",\n \"Windows Theme Change\"\n );\n\n switch (result)\n {\n case true: // Yes - Change theme AND apply wallpaper\n _logService.Log(LogLevel.Info, \"User selected to apply theme with wallpaper\");\n _isHandlingDarkModeChange = true;\n try\n {\n // Apply the requested theme\n IsDarkModeEnabled = _requestedDarkModeState;\n SelectedTheme = _requestedTheme;\n ChangeWallpaper = true; // Store the user's preference\n \n // Update the theme settings model\n _themeSettings.IsDarkMode = _requestedDarkModeState;\n _themeSettings.ChangeWallpaper = true;\n \n // Apply the theme\n await ApplyThemeAsync(true);\n _logService.Log(LogLevel.Info, $\"Theme changed to {(IsDarkModeEnabled ? \"dark\" : \"light\")} mode with wallpaper\");\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n break;\n\n case false: // No - Change theme but DON'T change wallpaper\n _logService.Log(LogLevel.Info, \"User selected to apply theme without wallpaper\");\n _isHandlingDarkModeChange = true;\n try\n {\n // Apply the requested theme\n IsDarkModeEnabled = _requestedDarkModeState;\n SelectedTheme = _requestedTheme;\n ChangeWallpaper = false; // Store the user's preference\n \n // Update the theme settings model\n _themeSettings.IsDarkMode = _requestedDarkModeState;\n _themeSettings.ChangeWallpaper = false;\n \n // Apply the theme\n await ApplyThemeAsync(false);\n _logService.Log(LogLevel.Info, $\"Theme changed to {(IsDarkModeEnabled ? \"dark\" : \"light\")} mode without wallpaper\");\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n break;\n\n case null: // Cancel - Do NOTHING, just close dialog\n _logService.Log(LogLevel.Info, \"User canceled theme change - keeping original state\");\n break;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error toggling dark mode: {ex.Message}\");\n await _dialogService.ShowErrorAsync(\"Theme Error\", $\"Failed to switch themes: {ex.Message}\");\n\n // Revert the toggle and selected theme on error\n _isHandlingDarkModeChange = true;\n try\n {\n // Revert to the original state\n IsDarkModeEnabled = _originalDarkModeState;\n SelectedTheme = _originalTheme;\n _themeSettings.IsDarkMode = _originalDarkModeState;\n \n _logService.Log(LogLevel.Info, \"Reverted to original state after error\");\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n }\n finally\n {\n // Always reset the dialog flag\n _isShowingDialog = false;\n _logService.Log(LogLevel.Info, \"Dialog handling completed\");\n }\n }\n\n /// \n /// Applies the theme with confirmation dialog.\n /// \n /// Whether to change the wallpaper.\n /// A task representing the asynchronous operation.\n private async Task ApplyThemeWithConfirmationAsync(bool changeWallpaper)\n {\n // Store the current state\n bool currentDarkMode = IsDarkModeEnabled;\n \n // Prompt for confirmation\n var result = await _dialogService.ShowConfirmationAsync(\n \"Apply Theme\",\n $\"Are you sure you want to apply the {(currentDarkMode ? \"dark\" : \"light\")} theme?\"\n );\n \n if (result)\n {\n await ApplyThemeAsync(changeWallpaper);\n }\n }\n\n /// \n /// Applies the dark mode setting.\n /// \n /// Whether to change the wallpaper.\n /// A task representing the asynchronous operation.\n public async Task ApplyThemeAsync(bool changeWallpaper)\n {\n try\n {\n // Update the theme settings model\n _themeSettings.IsDarkMode = IsDarkModeEnabled;\n _themeSettings.ChangeWallpaper = changeWallpaper;\n \n // Apply the theme\n bool success = await _themeSettings.ApplyThemeAsync();\n \n if (success)\n {\n _logService.Log(LogLevel.Info, $\"Windows Dark Mode {(IsDarkModeEnabled ? \"enabled\" : \"disabled\")}\");\n }\n else\n {\n _logService.Log(LogLevel.Error, \"Failed to apply theme\");\n }\n \n return success;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying dark mode: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Loads the settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, \"Loading Windows theme settings\");\n\n // Load dark mode state\n LoadDarkModeState();\n \n // Clear existing settings\n Settings.Clear();\n \n // Add a searchable item for the Theme Selector\n var themeItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = \"ThemeSelector\",\n Name = \"Windows Theme\",\n Description = \"Select between light and dark theme for Windows\",\n GroupName = \"Windows Theme\",\n IsVisible = true,\n IsSelected = true, // Always mark as selected so it appears in the config list\n ControlType = ControlType.ComboBox,\n SelectedValue = SelectedTheme, // Store the selected theme directly\n // Create a registry setting for the theme selector\n RegistrySetting = new RegistrySetting\n {\n Category = \"WindowsTheme\",\n Hive = Microsoft.Win32.RegistryHive.CurrentUser,\n SubKey = WindowsThemeSettings.Registry.ThemesPersonalizeSubKey,\n Name = WindowsThemeSettings.Registry.AppsUseLightThemeName,\n RecommendedValue = SelectedTheme == \"Dark Mode\" ? 0 : 1,\n DefaultValue = 1,\n EnabledValue = SelectedTheme == \"Dark Mode\" ? 0 : 1,\n DisabledValue = SelectedTheme == \"Dark Mode\" ? 1 : 0,\n ValueType = Microsoft.Win32.RegistryValueKind.DWord,\n Description = \"Windows Theme Mode\",\n // Store the selected theme and wallpaper preference\n CustomProperties = new Dictionary\n {\n { \"SelectedTheme\", SelectedTheme },\n { \"ChangeWallpaper\", ChangeWallpaper },\n { \"ThemeOptions\", ThemeOptions } // Store available options\n }\n }\n };\n Settings.Add(themeItem);\n \n _logService.Log(LogLevel.Info, $\"Added {Settings.Count} searchable items for Windows Theme settings\");\n\n // Check the status of all settings\n await CheckSettingStatusesAsync();\n\n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading Windows theme settings: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, \"Checking status for Windows theme settings\");\n\n // Refresh dark mode state\n LoadDarkModeState();\n\n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Windows theme settings status: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n // Get status\n var status = setting.Status;\n string message = status switch\n {\n RegistrySettingStatus.Applied => \"Setting is applied with recommended value\",\n RegistrySettingStatus.NotApplied => \"Setting is not applied or using default value\",\n RegistrySettingStatus.Modified => \"Setting has a custom value different from recommended\",\n RegistrySettingStatus.Error => \"Error checking setting status\",\n _ => \"Unknown status\"\n };\n\n return message;\n }\n\n // ApplySelectedSettingsAsync and RestoreDefaultsAsync methods removed as part of the refactoring\n \n /// \n /// Updates the theme selector setting to match the current selected theme.\n /// \n private void UpdateThemeSelectorSetting()\n {\n // Find the theme selector setting\n var themeSelector = Settings.FirstOrDefault(s => s.Id == \"ThemeSelector\");\n if (themeSelector != null)\n {\n themeSelector.IsUpdatingFromCode = true;\n try\n {\n // Update the SelectedValue directly with the current theme\n themeSelector.SelectedValue = SelectedTheme;\n _logService.Log(LogLevel.Info, $\"Updated theme selector setting to {SelectedTheme}\");\n \n // Store the wallpaper preference and selected theme in the setting's additional properties\n // This will be used when saving/loading configurations\n // Create a new RegistrySetting object with updated values\n var customProperties = new Dictionary();\n customProperties[\"ChangeWallpaper\"] = ChangeWallpaper;\n customProperties[\"SelectedTheme\"] = SelectedTheme;\n customProperties[\"ThemeOptions\"] = ThemeOptions; // Store available options\n \n // Create a new RegistrySetting with the updated values\n var newRegistrySetting = new RegistrySetting\n {\n Category = \"WindowsTheme\",\n Hive = Microsoft.Win32.RegistryHive.CurrentUser,\n SubKey = WindowsThemeSettings.Registry.ThemesPersonalizeSubKey,\n Name = WindowsThemeSettings.Registry.AppsUseLightThemeName,\n RecommendedValue = SelectedTheme == \"Dark Mode\" ? 0 : 1,\n DefaultValue = 1,\n EnabledValue = SelectedTheme == \"Dark Mode\" ? 0 : 1,\n DisabledValue = SelectedTheme == \"Dark Mode\" ? 1 : 0,\n ValueType = Microsoft.Win32.RegistryValueKind.DWord,\n Description = \"Windows Theme Mode\",\n CustomProperties = customProperties\n };\n \n // Assign the new RegistrySetting to the theme selector\n themeSelector.RegistrySetting = newRegistrySetting;\n \n _logService.Log(LogLevel.Info, $\"Stored theme preferences: SelectedTheme={SelectedTheme}, ChangeWallpaper={ChangeWallpaper}\");\n }\n finally\n {\n themeSelector.IsUpdatingFromCode = false;\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/InstallationStatusService.cs", "using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.SoftwareApps.Exceptions;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n public class InstallationStatusService : IInstallationStatusService\n {\n private readonly IPackageManager _packageManager;\n private readonly ConcurrentDictionary _statusCache = new();\n private readonly ILogService _logService;\n\n public InstallationStatusService(IPackageManager packageManager, ILogService logService)\n {\n _packageManager = packageManager;\n _logService = logService;\n }\n\n public Task SetInstallStatusAsync(string appId, InstallStatus status)\n {\n try\n {\n _logService.LogInformation($\"Setting install status for {appId} to {status}\");\n bool isInstalled = status == InstallStatus.Success;\n _statusCache.AddOrUpdate(appId, isInstalled, (k, v) => isInstalled);\n _logService.LogInformation($\"Successfully set status for {appId}\");\n return Task.FromResult(true);\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to set install status for {appId}\", ex);\n return Task.FromResult(false);\n }\n }\n\n public async Task GetInstallStatusAsync(string appId)\n {\n try\n {\n if (_statusCache.TryGetValue(appId, out var cachedStatus))\n {\n _logService.LogInformation($\"Retrieved cached status for {appId}\");\n return cachedStatus ? InstallStatus.Success : InstallStatus.Failed;\n }\n\n _logService.LogInformation($\"Querying package manager for {appId}\");\n var isInstalled = await _packageManager.IsAppInstalledAsync(appId);\n _statusCache.TryAdd(appId, isInstalled);\n \n _logService.LogInformation($\"Install status for {appId}: {isInstalled}\");\n return isInstalled ? InstallStatus.Success : InstallStatus.Failed;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to get install status for {appId}\", ex);\n return InstallStatus.Failed;\n }\n }\n\n public async Task RefreshStatusAsync(IEnumerable appIds)\n {\n var result = new RefreshResult();\n var errors = new Dictionary();\n\n try\n {\n _logService.LogInformation(\"Refreshing installation status for batch of apps\");\n \n foreach (var appId in appIds.Distinct())\n {\n try\n {\n var isInstalled = await _packageManager.IsAppInstalledAsync(appId);\n _statusCache.AddOrUpdate(appId, isInstalled, (k, v) => isInstalled);\n result.SuccessCount++;\n }\n catch (Exception ex)\n {\n errors[appId] = ex.Message;\n result.FailedCount++;\n _logService.LogError($\"Failed to refresh status for {appId}\", ex);\n }\n }\n \n result.Errors = errors;\n _logService.LogSuccess(\"Successfully refreshed installation status\");\n return result;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to refresh installation status\", ex);\n throw new InstallationStatusException(\"Failed to refresh installation status\", ex);\n }\n }\n\n public async Task RefreshInstallationStatusAsync(\n IEnumerable items,\n CancellationToken cancellationToken = default)\n {\n try\n {\n _logService.LogInformation(\"Refreshing installation status for batch of items\");\n \n var packageIds = items.Select(i => i.PackageId).Distinct();\n var statuses = await GetBatchInstallStatusAsync(packageIds, cancellationToken);\n \n foreach (var item in items)\n {\n cancellationToken.ThrowIfCancellationRequested();\n \n if (statuses.TryGetValue(item.PackageId, out var isInstalled))\n {\n _statusCache.TryAdd(item.PackageId, isInstalled);\n }\n }\n \n _logService.LogSuccess(\"Successfully refreshed installation status\");\n }\n catch (OperationCanceledException)\n {\n _logService.LogWarning(\"Installation status refresh was cancelled\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to refresh installation status\", ex);\n throw new InstallationStatusException(\"Failed to refresh installation status\", ex);\n }\n }\n\n public async Task GetItemInstallStatusAsync(\n IInstallableItem item,\n CancellationToken cancellationToken = default)\n {\n try\n {\n if (_statusCache.TryGetValue(item.PackageId, out var cachedStatus))\n {\n _logService.LogInformation($\"Retrieved cached status for {item.PackageId}\");\n return cachedStatus;\n }\n\n _logService.LogInformation($\"Querying package manager for {item.PackageId}\");\n var isInstalled = await _packageManager.IsAppInstalledAsync(item.PackageId, cancellationToken);\n _statusCache.TryAdd(item.PackageId, isInstalled);\n \n _logService.LogInformation($\"Install status for {item.PackageId}: {isInstalled}\");\n return isInstalled;\n }\n catch (OperationCanceledException)\n {\n _logService.LogWarning($\"Install status check for {item.PackageId} was cancelled\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to get install status for {item.PackageId}\", ex);\n throw new InstallationStatusException($\"Failed to get install status for {item.PackageId}\", ex);\n }\n }\n\n public async Task> GetBatchInstallStatusAsync(\n IEnumerable packageIds,\n CancellationToken cancellationToken = default)\n {\n try\n {\n var distinctIds = packageIds.Distinct().ToList();\n var results = new Dictionary();\n _logService.LogInformation($\"Getting batch install status for {distinctIds.Count} packages\");\n\n foreach (var id in distinctIds)\n {\n cancellationToken.ThrowIfCancellationRequested();\n \n if (_statusCache.TryGetValue(id, out var cachedStatus))\n {\n results[id] = cachedStatus;\n _logService.LogInformation($\"Using cached status for {id}\");\n }\n else\n {\n var isInstalled = await _packageManager.IsAppInstalledAsync(id, cancellationToken);\n _statusCache.TryAdd(id, isInstalled);\n results[id] = isInstalled;\n _logService.LogInformation($\"Retrieved fresh status for {id}: {isInstalled}\");\n }\n }\n\n _logService.LogSuccess(\"Completed batch install status check\");\n return results;\n }\n catch (OperationCanceledException)\n {\n _logService.LogWarning(\"Batch install status check was cancelled\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to get batch install status\", ex);\n throw new InstallationStatusException(\"Failed to get batch install status\", ex);\n }\n }\n\n public void ClearStatusCache()\n {\n try\n {\n _logService.LogInformation(\"Clearing installation status cache\");\n _statusCache.Clear();\n _logService.LogSuccess(\"Successfully cleared installation status cache\");\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to clear installation status cache\", ex);\n throw new InstallationStatusException(\"Failed to clear installation status cache\", ex);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/UpdateDialog.xaml.cs", "using System;\nusing System.Diagnostics;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media.Imaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Resources.Theme;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Update dialog that shows when a new version is available\n /// \n public partial class UpdateDialog : Window, System.ComponentModel.INotifyPropertyChanged\n {\n private readonly VersionInfo _currentVersion;\n private readonly VersionInfo _latestVersion;\n private readonly Func _downloadAndInstallAction;\n \n // Add a property for theme binding that defaults to dark theme\n private bool _isThemeDark = true;\n public bool IsThemeDark\n {\n get => _isThemeDark;\n set\n {\n if (_isThemeDark != value)\n {\n _isThemeDark = value;\n OnPropertyChanged(nameof(IsThemeDark));\n }\n }\n }\n \n public bool IsDownloading { get; private set; }\n\n // Implement INotifyPropertyChanged\n public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\n \n protected virtual void OnPropertyChanged(string propertyName)\n {\n PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\n }\n \n private UpdateDialog(string title, string message, VersionInfo currentVersion, VersionInfo latestVersion, Func downloadAndInstallAction)\n {\n InitializeComponent();\n DataContext = this;\n \n _currentVersion = currentVersion;\n _latestVersion = latestVersion;\n _downloadAndInstallAction = downloadAndInstallAction;\n \n // Try to determine the Winhance theme\n try\n {\n // First check if the theme is stored in Application.Current.Resources\n if (Application.Current.Resources.Contains(\"IsDarkTheme\"))\n {\n IsThemeDark = (bool)Application.Current.Resources[\"IsDarkTheme\"];\n }\n else\n {\n // Fall back to system theme if Winhance theme is not available\n bool systemUsesLightTheme = false;\n \n try\n {\n // Try to read the Windows registry to determine the system theme\n using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@\"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\"))\n {\n if (key != null)\n {\n var value = key.GetValue(\"AppsUseLightTheme\");\n if (value != null)\n {\n systemUsesLightTheme = Convert.ToInt32(value) == 1;\n }\n }\n }\n }\n catch (Exception)\n {\n // Ignore errors reading the registry\n }\n \n // Set the IsThemeDark property based on the system theme\n IsThemeDark = !systemUsesLightTheme;\n }\n }\n catch (Exception)\n {\n // Default to dark theme if we can't determine the theme\n IsThemeDark = true;\n }\n \n // Set up a handler to listen for theme changes\n this.Loaded += (sender, e) =>\n {\n // Listen for resource dictionary changes that might affect the theme\n if (Application.Current.Resources is System.Windows.ResourceDictionary resourceDictionary)\n {\n // Use reflection to get the event\n var eventInfo = resourceDictionary.GetType().GetEvent(\"ResourceDictionaryChanged\");\n if (eventInfo != null)\n {\n // Create a handler for the event\n EventHandler resourceChangedHandler = (s, args) =>\n {\n if (Application.Current.Resources.Contains(\"IsDarkTheme\"))\n {\n bool newIsDarkTheme = (bool)Application.Current.Resources[\"IsDarkTheme\"];\n if (IsThemeDark != newIsDarkTheme)\n {\n IsThemeDark = newIsDarkTheme;\n }\n }\n };\n \n // Add the handler to the event\n eventInfo.AddEventHandler(resourceDictionary, resourceChangedHandler);\n }\n }\n };\n \n Title = title;\n HeaderText.Text = title;\n MessageText.Text = message;\n \n // Ensure version text is properly displayed\n CurrentVersionText.Text = currentVersion.Version;\n LatestVersionText.Text = latestVersion.Version;\n \n // Make sure the footer text is visible\n FooterText.Visibility = Visibility.Visible;\n }\n \n private async void PrimaryButton_Click(object sender, RoutedEventArgs e)\n {\n try\n {\n // Disable buttons during download\n PrimaryButton.IsEnabled = false;\n SecondaryButton.IsEnabled = false;\n \n // Show progress indicator\n IsDownloading = true;\n OnPropertyChanged(nameof(IsDownloading));\n DownloadProgress.Visibility = Visibility.Visible;\n StatusText.Text = \"Downloading update...\";\n \n // Hide the footer text during download\n FooterText.Visibility = Visibility.Collapsed;\n \n // Execute the download and install action\n await _downloadAndInstallAction();\n \n // Set dialog result and close\n DialogResult = true;\n Close();\n }\n catch (Exception ex)\n {\n // Re-enable buttons\n PrimaryButton.IsEnabled = true;\n SecondaryButton.IsEnabled = true;\n \n // Hide progress indicator\n IsDownloading = false;\n OnPropertyChanged(nameof(IsDownloading));\n DownloadProgress.Visibility = Visibility.Collapsed;\n \n // Show error message\n StatusText.Text = $\"Error downloading update: {ex.Message}\";\n \n // Show the footer text again\n FooterText.Visibility = Visibility.Visible;\n }\n }\n\n private void SecondaryButton_Click(object sender, RoutedEventArgs e)\n {\n // User chose to be reminded later\n DialogResult = false;\n Close();\n }\n \n /// \n /// Shows an update dialog with the specified parameters\n /// \n /// The title of the dialog\n /// The message to display\n /// The current version information\n /// The latest version information\n /// The action to execute when the user clicks Download & Install\n /// True if the user chose to download and install, false otherwise\n public static async Task ShowAsync(\n string title, \n string message, \n VersionInfo currentVersion, \n VersionInfo latestVersion, \n Func downloadAndInstallAction)\n {\n try\n {\n var dialog = new UpdateDialog(title, message, currentVersion, latestVersion, downloadAndInstallAction)\n {\n WindowStartupLocation = WindowStartupLocation.CenterScreen,\n ShowInTaskbar = false,\n Topmost = true\n };\n \n // Set the owner to the main window to ensure it appears on top\n if (Application.Current.MainWindow != null && Application.Current.MainWindow != dialog)\n {\n dialog.Owner = Application.Current.MainWindow;\n }\n else\n {\n // Try to find the main window another way\n foreach (Window window in Application.Current.Windows)\n {\n if (window != dialog && window.IsVisible)\n {\n dialog.Owner = window;\n break;\n }\n }\n }\n \n // Show the dialog and wait for the result\n return await Task.Run(() =>\n {\n return Application.Current.Dispatcher.Invoke(() =>\n {\n try\n {\n return dialog.ShowDialog() ?? false;\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error showing dialog: {ex.Message}\");\n return false;\n }\n });\n });\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error in ShowAsync: {ex.Message}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Utilities/WinGetOutputParser.cs", "using System;\nusing System.IO;\nusing System.Text.RegularExpressions;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Utilities\n{\n /// \n /// Parses WinGet command output and generates appropriate progress updates.\n /// \n public class WinGetOutputParser\n {\n private readonly ILogService _logService;\n private InstallationState _currentState = InstallationState.Starting;\n private string _downloadFileName;\n private bool _isVerifying;\n private string _lastProgressLine;\n private int _lastPercentage;\n private bool _hasStarted = false;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// Optional log service for debugging.\n public WinGetOutputParser(ILogService logService = null)\n {\n _logService = logService;\n }\n\n /// \n /// Parses a line of WinGet output and generates an appropriate progress update.\n /// Uses an indeterminate progress indicator and displays raw WinGet output.\n /// \n /// The line of output to parse.\n /// An InstallationProgress object with the current progress information, or null if no update is needed.\n public InstallationProgress ParseOutputLine(string outputLine)\n {\n if (string.IsNullOrWhiteSpace(outputLine))\n {\n return null;\n }\n\n _logService?.LogInformation($\"WinGet output: {outputLine}\");\n \n // If this is the first output line, transition from Starting state\n if (!_hasStarted)\n {\n _hasStarted = true;\n _currentState = InstallationState.Resolving;\n \n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = 0,\n IsIndeterminate = true,\n };\n }\n\n // Check for verification messages\n if (outputLine.Contains(\"Verifying\"))\n {\n _logService?.LogInformation(\"Verification step detected\");\n _currentState = InstallationState.Verifying;\n _isVerifying = true;\n\n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = 0,\n IsIndeterminate = true,\n };\n }\n\n // Check for installation messages\n if (\n outputLine.Contains(\"Installing\")\n || outputLine.Contains(\"installation\")\n || (_isVerifying && !outputLine.Contains(\"Verifying\"))\n )\n {\n _logService?.LogInformation(\"Installation step detected\");\n _currentState = InstallationState.Installing;\n _isVerifying = false;\n\n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = 0,\n IsIndeterminate = true,\n };\n }\n\n // Check for download information\n if (\n (\n outputLine.Contains(\"Downloading\")\n || outputLine.Contains(\"download\")\n || outputLine.Contains(\"KB\")\n || outputLine.Contains(\"MB\")\n || outputLine.Contains(\"GB\")\n )\n )\n {\n _logService?.LogInformation($\"Download information detected: {outputLine}\");\n\n // Set the current state to Downloading\n _currentState = InstallationState.Downloading;\n\n // Create a progress update with a generic downloading message\n return new InstallationProgress\n {\n Status = \"Downloading package files. This might take a while, please wait...\",\n Percentage = 0, // Not used in indeterminate mode\n IsIndeterminate = true, // Use indeterminate progress\n // Set Operation to help identify this is a download operation\n Operation = \"Downloading\"\n };\n }\n\n // Check for installation status\n if (outputLine.Contains(\"%\"))\n {\n var percentageMatch = Regex.Match(outputLine, @\"(\\d+)%\");\n if (percentageMatch.Success)\n {\n int percentage = int.Parse(percentageMatch.Groups[1].Value);\n _lastPercentage = percentage;\n _lastProgressLine = outputLine;\n\n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = percentage,\n IsIndeterminate = false,\n };\n }\n }\n\n // Check for completion\n if (\n outputLine.Contains(\"Successfully installed\")\n || outputLine.Contains(\"completed successfully\")\n || outputLine.Contains(\"installation complete\")\n )\n {\n _logService?.LogInformation(\"Installation completed successfully\");\n _currentState = InstallationState.Completing;\n\n return new InstallationProgress\n {\n Status = \"Installation completed successfully!\",\n Percentage = 100,\n IsIndeterminate = false,\n // Note: The installation is complete, but we don't have an IsComplete property\n // so we just set the percentage to 100 and a clear status message\n };\n }\n\n // Check for errors\n if (\n outputLine.Contains(\"error\")\n || outputLine.Contains(\"failed\")\n || outputLine.Contains(\"Error:\")\n || outputLine.Contains(\"Failed:\")\n )\n {\n _logService?.LogError($\"Installation error detected: {outputLine}\");\n\n return new InstallationProgress\n {\n Status = $\"Error: {outputLine.Trim()}\",\n Percentage = 0,\n IsIndeterminate = false,\n // Note: We don't have HasError or ErrorMessage properties\n // so we just include the error in the Status\n };\n }\n\n // For other lines, return the last progress if available\n if (!string.IsNullOrEmpty(_lastProgressLine) && _lastPercentage > 0)\n {\n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = _lastPercentage,\n IsIndeterminate = false,\n };\n }\n\n // For other lines, just return the current state\n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = 0,\n IsIndeterminate = true,\n };\n }\n\n /// \n /// Gets a status message appropriate for the current installation state.\n /// \n private string GetStatusMessage(InstallationState state)\n {\n switch (state)\n {\n case InstallationState.Starting:\n return \"Preparing for installation...\";\n case InstallationState.Resolving:\n return \"Resolving package dependencies...\";\n case InstallationState.Downloading:\n return \"Downloading package files. This might take a while, please wait...\";\n case InstallationState.Verifying:\n return \"Verifying package integrity...\";\n case InstallationState.Installing:\n return \"Installing application...\";\n case InstallationState.Configuring:\n return \"Configuring application settings...\";\n case InstallationState.Completing:\n return \"Finalizing installation...\";\n default:\n return \"Processing...\";\n }\n }\n }\n\n /// \n /// Represents the different states of a WinGet installation process.\n /// \n public enum InstallationState\n {\n /// \n /// The installation process is starting.\n /// \n Starting,\n\n /// \n /// The package dependencies are being resolved.\n /// \n Resolving,\n\n /// \n /// Package files are being downloaded.\n /// \n Downloading,\n\n /// \n /// Package integrity is being verified.\n /// \n Verifying,\n\n /// \n /// The application is being installed.\n /// \n Installing,\n\n /// \n /// The application is being configured.\n /// \n Configuring,\n\n /// \n /// The installation process is completing.\n /// \n Completing,\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScriptUpdateService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\n/// \n/// Implementation of IScriptUpdateService that provides methods for updating script content.\n/// \npublic class ScriptUpdateService : IScriptUpdateService\n{\n private readonly ILogService _logService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IScriptContentModifier _scriptContentModifier;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The app discovery service.\n /// The script content modifier.\n public ScriptUpdateService(\n ILogService logService,\n IAppDiscoveryService appDiscoveryService,\n IScriptContentModifier scriptContentModifier)\n {\n _logService = logService;\n _appDiscoveryService = appDiscoveryService;\n _scriptContentModifier = scriptContentModifier;\n }\n\n /// \n public async Task UpdateExistingBloatRemovalScriptAsync(\n List appNames,\n Dictionary> appsWithRegistry,\n Dictionary appSubPackages,\n bool isInstallOperation = false)\n {\n try\n {\n string bloatRemovalScriptPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n \"Winhance\",\n \"Scripts\",\n \"BloatRemoval.ps1\"\n );\n \n _logService.LogInformation($\"Checking for BloatRemoval.ps1 at path: {bloatRemovalScriptPath}\");\n \n string scriptContent;\n \n if (!File.Exists(bloatRemovalScriptPath))\n {\n _logService.LogWarning($\"BloatRemoval.ps1 file not found at: {bloatRemovalScriptPath}\");\n \n // Create the directory if it doesn't exist\n string scriptDirectory = Path.GetDirectoryName(bloatRemovalScriptPath);\n if (!Directory.Exists(scriptDirectory))\n {\n _logService.LogInformation($\"Creating directory: {scriptDirectory}\");\n Directory.CreateDirectory(scriptDirectory);\n }\n \n // Create a basic BloatRemoval.ps1 file if it doesn't exist\n _logService.LogInformation(\"Creating a new BloatRemoval.ps1 file\");\n string basicScriptContent = @\"\n# BloatRemoval.ps1\n# This script removes Windows bloatware apps and prevents them from reinstalling\n# Source: Winhance (https://github.com/memstechtips/Winhance)\n# Generated by Winhance on \" + DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\") + @\"\n\n#region Definitions\n# Capabilities to remove\n$capabilities = @(\n)\n\n# Packages to remove\n$packages = @(\n)\n\n# Optional Features to disable\n$optionalFeatures = @(\n)\n#endregion\n\n#region Process Capabilities\nWrite-Host \"\"=== Removing Windows Capabilities ===\"\" -ForegroundColor Cyan\nforeach ($capability in $capabilities) {\n Write-Host \"\"Removing capability: $capability\"\" -ForegroundColor Yellow\n Remove-WindowsCapability -Online -Name $capability | Out-Null\n}\n#endregion\n\n#region Process Packages\nWrite-Host \"\"=== Removing Windows Apps ===\"\" -ForegroundColor Cyan\nforeach ($package in $packages) {\n Write-Host \"\"Removing package: $package\"\" -ForegroundColor Yellow\n Get-AppxPackage -Name $package -AllUsers | ForEach-Object {\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }\n}\n#endregion\n\n#region Process Optional Features\nWrite-Host \"\"=== Disabling Optional Features ===\"\" -ForegroundColor Cyan\nforeach ($feature in $optionalFeatures) {\n Write-Host \"\"Disabling optional feature: $feature\"\" -ForegroundColor Yellow\n Disable-WindowsOptionalFeature -Online -FeatureName $feature -NoRestart | Out-Null\n}\n#endregion\n\n#region Registry Settings\n# Registry settings\n#endregion\n\n# Prevent apps from reinstalling\nreg add \"\"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\CloudContent\"\" /v \"\"DisableWindowsConsumerFeatures\"\" /t REG_DWORD /d 1 /f | Out-Null\n\n\";\n await File.WriteAllTextAsync(bloatRemovalScriptPath, basicScriptContent);\n scriptContent = basicScriptContent;\n _logService.LogInformation(\"Created new BloatRemoval.ps1 file\");\n }\n else\n {\n _logService.LogInformation(\"BloatRemoval.ps1 file found, reading content\");\n scriptContent = await File.ReadAllTextAsync(bloatRemovalScriptPath);\n }\n\n // Separate capabilities, packages, and optional features\n var capabilities = new List();\n var packages = new List();\n var optionalFeatures = new List();\n\n foreach (var appName in appNames)\n {\n if (\n !appName.Equals(\"Edge\", StringComparison.OrdinalIgnoreCase)\n && !appName.Equals(\"OneDrive\", StringComparison.OrdinalIgnoreCase)\n )\n {\n // Check if this is an OptionalFeature\n bool isOptionalFeature = false;\n bool isCapability = false;\n\n // Get app info from the catalog\n var allRemovableApps = (\n await _appDiscoveryService.GetStandardAppsAsync()\n ).ToList();\n var appInfo = allRemovableApps.FirstOrDefault(a =>\n a.PackageName.Equals(appName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (appInfo != null)\n {\n isOptionalFeature = appInfo.Type == AppType.OptionalFeature;\n isCapability = appInfo.Type == AppType.Capability;\n }\n\n // Check if this app has registry settings\n if (appsWithRegistry.TryGetValue(appName, out var registrySettings))\n {\n // Look for a special metadata registry setting that indicates if this is a capability\n var capabilitySetting = registrySettings.FirstOrDefault(s =>\n s.Name.Equals(\"IsCapability\", StringComparison.OrdinalIgnoreCase)\n );\n\n if (\n capabilitySetting != null\n && capabilitySetting.Value is bool capabilityValue\n )\n {\n isCapability = capabilityValue;\n }\n }\n\n // Extract the base name without version for capability detection\n string baseAppName = appName;\n if (appName.Contains(\"~~~~\"))\n {\n // Extract the base name before the version (~~~~)\n baseAppName = appName.Split('~')[0];\n _logService.LogInformation($\"Extracted base capability name '{baseAppName}' from '{appName}'\");\n }\n \n // Check if this is a known Windows optional feature\n if (\n appName.Equals(\"Recall\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"NetFx3\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"Microsoft-Hyper-V-All\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"Microsoft-Hyper-V-Tools-All\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"Microsoft-Hyper-V-Hypervisor\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"Microsoft-Windows-Subsystem-Linux\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"MicrosoftCorporationII.WindowsSubsystemForAndroid\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"Containers-DisposableClientVM\", StringComparison.OrdinalIgnoreCase) ||\n isOptionalFeature\n )\n {\n _logService.LogInformation($\"Adding {appName} to optional features array\");\n optionalFeatures.Add(appName);\n continue;\n }\n \n // Known capabilities have specific formats\n if (\n isCapability\n || baseAppName.Equals(\n \"Browser.InternetExplorer\",\n StringComparison.OrdinalIgnoreCase\n )\n || baseAppName.Equals(\"MathRecognizer\", StringComparison.OrdinalIgnoreCase)\n || baseAppName.Equals(\"OpenSSH.Client\", StringComparison.OrdinalIgnoreCase)\n || baseAppName.Equals(\"OpenSSH.Server\", StringComparison.OrdinalIgnoreCase)\n || baseAppName.Equals(\n \"Microsoft.Windows.PowerShell.ISE\",\n StringComparison.OrdinalIgnoreCase\n )\n || baseAppName.Equals(\"App.StepsRecorder\", StringComparison.OrdinalIgnoreCase)\n || baseAppName.Equals(\n \"Media.WindowsMediaPlayer\",\n StringComparison.OrdinalIgnoreCase\n )\n || baseAppName.Equals(\n \"App.Support.QuickAssist\",\n StringComparison.OrdinalIgnoreCase\n )\n || baseAppName.Equals(\n \"Microsoft.Windows.WordPad\",\n StringComparison.OrdinalIgnoreCase\n )\n || baseAppName.Equals(\n \"Microsoft.Windows.MSPaint\",\n StringComparison.OrdinalIgnoreCase\n )\n // Check if the app name contains version numbers in the format ~~~~0.0.1.0\n || appName.Contains(\"~~~~\")\n )\n {\n _logService.LogInformation($\"Adding {appName} to capabilities array\");\n capabilities.Add(appName);\n }\n else\n {\n // Explicitly handle Copilot and Xbox packages\n bool isCopilotOrXbox =\n appName.Contains(\"Copilot\", StringComparison.OrdinalIgnoreCase)\n || appName.Contains(\"Xbox\", StringComparison.OrdinalIgnoreCase);\n \n _logService.LogInformation($\"Adding {appName} to packages array\");\n packages.Add(appName);\n }\n }\n }\n\n // Process subpackages and add them to the packages list\n if (appSubPackages != null && appSubPackages.Count > 0)\n {\n _logService.LogInformation(\n $\"Processing {appSubPackages.Count} app entries with subpackages\"\n );\n\n foreach (var packageEntry in appSubPackages)\n {\n string parentPackage = packageEntry.Key;\n string[] subPackages = packageEntry.Value;\n\n // Only process subpackages if the parent package is in the packages list\n // or if it's a special case like Copilot or Xbox\n bool isSpecialApp =\n parentPackage.Contains(\"Copilot\", StringComparison.OrdinalIgnoreCase)\n || parentPackage.Contains(\"Xbox\", StringComparison.OrdinalIgnoreCase)\n || parentPackage.Equals(\n \"Microsoft.GamingApp\",\n StringComparison.OrdinalIgnoreCase\n );\n\n if (packages.Contains(parentPackage) || isSpecialApp)\n {\n if (subPackages != null && subPackages.Length > 0)\n {\n _logService.LogInformation(\n $\"Adding {subPackages.Length} subpackages for {parentPackage}\"\n );\n\n foreach (var subPackage in subPackages)\n {\n if (\n !packages.Contains(subPackage, StringComparer.OrdinalIgnoreCase)\n )\n {\n _logService.LogInformation(\n $\"Adding subpackage: {subPackage} for {parentPackage}\"\n );\n packages.Add(subPackage);\n }\n }\n }\n }\n }\n }\n\n // Update the script content with new entries\n if (capabilities.Count > 0)\n {\n scriptContent = UpdateCapabilitiesArrayInScript(scriptContent, capabilities, isInstallOperation);\n }\n\n if (optionalFeatures.Count > 0)\n {\n scriptContent = UpdateOptionalFeaturesInScript(scriptContent, optionalFeatures, isInstallOperation);\n }\n\n if (packages.Count > 0)\n {\n scriptContent = UpdatePackagesArrayInScript(scriptContent, packages, isInstallOperation);\n }\n\n if (appsWithRegistry.Count > 0)\n {\n scriptContent = UpdateRegistrySettingsInScript(scriptContent, appsWithRegistry);\n }\n\n // Save the updated script\n await File.WriteAllTextAsync(bloatRemovalScriptPath, scriptContent);\n\n // Return the updated script\n return new RemovalScript\n {\n Name = \"BloatRemoval\",\n Content = scriptContent,\n TargetScheduledTaskName = \"Winhance\\\\BloatRemoval\",\n RunOnStartup = true,\n };\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating existing BloatRemoval script: {ex.Message}\", ex);\n _logService.LogError($\"Stack trace: {ex.StackTrace}\");\n \n // Create a basic error report\n try\n {\n string errorReportPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.Desktop),\n \"WinhanceScriptUpdateError.txt\"\n );\n \n string errorReport = $@\"\nScript Update Error Report\nTime: {DateTime.Now}\nError: {ex.Message}\nStack Trace: {ex.StackTrace}\nInner Exception: {ex.InnerException?.Message}\n\nApp Names: {string.Join(\", \", appNames)}\nApps with Registry: {appsWithRegistry.Count}\nApp SubPackages: {appSubPackages.Count}\n\";\n \n await File.WriteAllTextAsync(errorReportPath, errorReport);\n _logService.LogInformation($\"Error report written to: {errorReportPath}\");\n }\n catch (Exception reportEx)\n {\n _logService.LogError($\"Failed to write error report: {reportEx.Message}\");\n }\n \n throw;\n }\n }\n\n /// \n public string UpdateCapabilitiesArrayInScript(string scriptContent, List capabilities, bool isInstallOperation = false)\n {\n try\n {\n _logService.LogInformation($\"Updating capabilities array with {capabilities.Count} capabilities\");\n\n // Find the capabilities array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$capabilities = @(\");\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $capabilities array in BloatRemoval.ps1\");\n \n // If this is an install operation, we don't need to add anything\n if (isInstallOperation)\n {\n _logService.LogInformation(\"Install operation with no capabilities array found - nothing to remove\");\n return scriptContent;\n }\n \n // For removal operations, we need to add the capabilities array and processing code\n _logService.LogInformation(\"Creating capabilities array in BloatRemoval.ps1\");\n \n // Find a good place to insert the section (at the beginning of the script or before packages)\n int insertIndex = scriptContent.IndexOf(\"$packages = @(\");\n if (insertIndex == -1)\n {\n // If no packages array, find the first non-comment line\n var scriptLines = scriptContent.Split('\\n');\n for (int i = 0; i < scriptLines.Length; i++)\n {\n if (!scriptLines[i].TrimStart().StartsWith(\"#\") && !string.IsNullOrWhiteSpace(scriptLines[i]))\n {\n insertIndex = scriptContent.IndexOf(scriptLines[i]);\n break;\n }\n }\n \n // If still not found, insert at the beginning\n if (insertIndex == -1)\n {\n insertIndex = 0;\n }\n }\n \n // Create the capabilities section\n var capabilitiesSection = new StringBuilder();\n capabilitiesSection.AppendLine(\"# Capabilities to remove\");\n capabilitiesSection.AppendLine(\"$capabilities = @(\");\n \n // Add capabilities without trailing comma on the last item\n for (int i = 0; i < capabilities.Count; i++)\n {\n string capability = capabilities[i];\n if (i < capabilities.Count - 1)\n {\n capabilitiesSection.AppendLine($\" '{capability}',\");\n }\n else\n {\n capabilitiesSection.AppendLine($\" '{capability}'\");\n }\n }\n \n capabilitiesSection.AppendLine(\")\");\n capabilitiesSection.AppendLine();\n capabilitiesSection.AppendLine(\"# Process capabilities\");\n capabilitiesSection.AppendLine(\"foreach ($capability in $capabilities) {\");\n capabilitiesSection.AppendLine(\" Write-Host \\\"Removing capability: $capability\\\" -ForegroundColor Yellow\");\n capabilitiesSection.AppendLine(\" Remove-WindowsCapability -Online -Name $capability | Out-Null\");\n capabilitiesSection.AppendLine(\"}\");\n capabilitiesSection.AppendLine();\n \n // Insert the section\n return scriptContent.Substring(0, insertIndex) \n + capabilitiesSection.ToString() \n + scriptContent.Substring(insertIndex);\n }\n\n // Find the end of the capabilities array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find end of $capabilities array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the capabilities in the array\n var existingCapabilities = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var capability = trimmedLine.Trim('\\'', '\"', ' ', ',');\n existingCapabilities.Add(capability);\n }\n }\n\n bool modified = false;\n \n if (isInstallOperation)\n {\n // For install operations, REMOVE the capability from the list\n foreach (var capability in capabilities)\n {\n // Extract the base name without version for capability matching\n string baseCapabilityName = capability;\n if (capability.Contains(\"~~~~\"))\n {\n // Extract the base name before the version (~~~~)\n baseCapabilityName = capability.Split('~')[0];\n _logService.LogInformation($\"Extracted base capability name '{baseCapabilityName}' from '{capability}' for removal\");\n }\n \n // Find any capability in the list that matches the base name (regardless of version)\n var matchingCapabilities = existingCapabilities\n .Where(c => c.StartsWith(baseCapabilityName, StringComparison.OrdinalIgnoreCase) || \n (c.Contains(\"~~~~\") && c.Split('~')[0].Equals(baseCapabilityName, StringComparison.OrdinalIgnoreCase)))\n .ToList();\n \n foreach (var matchingCapability in matchingCapabilities)\n {\n existingCapabilities.Remove(matchingCapability);\n _logService.LogInformation($\"Removed capability: {matchingCapability} from BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n // Even if no capabilities were found to remove, we should still return the updated script\n // This ensures the method doesn't exit early when no matches are found\n if (!modified)\n {\n _logService.LogInformation(\"No capabilities to remove from BloatRemoval.ps1\");\n }\n }\n else\n {\n // For removal operations, ADD the capability to the list\n foreach (var capability in capabilities)\n {\n if (!existingCapabilities.Contains(capability, StringComparer.OrdinalIgnoreCase))\n {\n existingCapabilities.Add(capability);\n _logService.LogInformation($\"Added capability: {capability} to BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n if (!modified)\n {\n _logService.LogInformation(\"No new capabilities to add to BloatRemoval.ps1\");\n return scriptContent;\n }\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$capabilities = @(\");\n\n // Add capabilities without trailing comma on the last item\n for (int i = 0; i < existingCapabilities.Count; i++)\n {\n string capability = existingCapabilities[i];\n if (i < existingCapabilities.Count - 1)\n {\n newArrayContent.AppendLine($\" '{capability}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{capability}'\");\n }\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error updating capabilities array in script\", ex);\n return scriptContent;\n }\n }\n\n /// \n public string UpdatePackagesArrayInScript(string scriptContent, List packages, bool isInstallOperation = false)\n {\n try\n {\n _logService.LogInformation($\"Updating packages array with {packages.Count} packages\");\n\n // Find the packages array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$packages = @(\");\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the packages array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find end of $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the packages in the array\n var existingPackages = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var package = trimmedLine.Trim('\\'', '\"', ' ', ',');\n existingPackages.Add(package);\n }\n }\n\n bool modified = false;\n \n if (isInstallOperation)\n {\n // For install operations, REMOVE the package from the list\n foreach (var package in packages)\n {\n // Extract the base name without version for package matching\n string basePackageName = package;\n if (package.Contains(\"~~~~\"))\n {\n // Extract the base name before the version (~~~~)\n basePackageName = package.Split('~')[0];\n _logService.LogInformation($\"Extracted base package name '{basePackageName}' from '{package}' for removal\");\n }\n \n // Find any package in the list that matches the base name (regardless of version)\n var matchingPackages = existingPackages\n .Where(p => p.StartsWith(basePackageName, StringComparison.OrdinalIgnoreCase) || \n (p.Contains(\"~~~~\") && p.Split('~')[0].Equals(basePackageName, StringComparison.OrdinalIgnoreCase)))\n .ToList();\n \n foreach (var matchingPackage in matchingPackages)\n {\n existingPackages.Remove(matchingPackage);\n _logService.LogInformation($\"Removed package: {matchingPackage} from BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n if (!modified)\n {\n _logService.LogInformation(\"No packages to remove from BloatRemoval.ps1\");\n }\n }\n else\n {\n // For removal operations, ADD the package to the list\n foreach (var package in packages)\n {\n if (!existingPackages.Contains(package, StringComparer.OrdinalIgnoreCase))\n {\n existingPackages.Add(package);\n _logService.LogInformation($\"Added package: {package} to BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n if (!modified)\n {\n _logService.LogInformation(\"No new packages to add to BloatRemoval.ps1\");\n return scriptContent;\n }\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$packages = @(\");\n\n // Add packages without trailing comma on the last item\n for (int i = 0; i < existingPackages.Count; i++)\n {\n string package = existingPackages[i];\n if (i < existingPackages.Count - 1)\n {\n newArrayContent.AppendLine($\" '{package}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{package}'\");\n }\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error updating packages array in script\", ex);\n return scriptContent;\n }\n }\n\n /// \n public string UpdateOptionalFeaturesInScript(string scriptContent, List features, bool isInstallOperation = false)\n {\n try\n {\n _logService.LogInformation($\"Updating optional features with {features.Count} features\");\n\n // Check if the optional features section exists\n int sectionStartIndex = scriptContent.IndexOf(\"# Disable Optional Features\");\n \n // If the section doesn't exist, create it\n if (sectionStartIndex == -1)\n {\n _logService.LogInformation(\"Creating Optional Features section in BloatRemoval.ps1\");\n \n // Find a good place to insert the section (after the packages section)\n int packagesEndIndex = -1;\n \n // First, try to find the #endregion marker after the packages section\n int processPackagesIndex = scriptContent.IndexOf(\"# Process Packages\");\n if (processPackagesIndex != -1)\n {\n int endRegionIndex = scriptContent.IndexOf(\"#endregion\", processPackagesIndex);\n if (endRegionIndex != -1)\n {\n // Find the end of the line after the #endregion\n int newlineIndex = scriptContent.IndexOf('\\n', endRegionIndex);\n if (newlineIndex != -1)\n {\n packagesEndIndex = newlineIndex + 1; // Include the newline\n }\n else\n {\n packagesEndIndex = scriptContent.Length;\n }\n }\n }\n \n // If we couldn't find the #endregion marker, look for the Registry settings section\n if (packagesEndIndex == -1)\n {\n int registryIndex = scriptContent.IndexOf(\"# Registry settings\");\n if (registryIndex != -1)\n {\n packagesEndIndex = registryIndex;\n }\n }\n \n // If we still can't find a good insertion point, look for the end of the packages foreach loop\n if (packagesEndIndex == -1)\n {\n int packagesForEachIndex = scriptContent.IndexOf(\"foreach ($package in $packages)\");\n if (packagesForEachIndex != -1)\n {\n // Find the matching closing brace for the foreach loop\n int openBraces = 0;\n int closeBraces = 0;\n int currentIndex = packagesForEachIndex;\n \n while (currentIndex < scriptContent.Length)\n {\n if (scriptContent[currentIndex] == '{')\n {\n openBraces++;\n }\n else if (scriptContent[currentIndex] == '}')\n {\n closeBraces++;\n if (closeBraces == openBraces && openBraces > 0)\n {\n // Found the matching closing brace\n int braceIndex = currentIndex;\n \n // Find the end of the line after the closing brace\n int newlineIndex = scriptContent.IndexOf('\\n', braceIndex);\n if (newlineIndex != -1)\n {\n packagesEndIndex = newlineIndex + 1; // Include the newline\n }\n else\n {\n packagesEndIndex = scriptContent.Length;\n }\n break;\n }\n }\n currentIndex++;\n }\n }\n }\n \n // If we still couldn't find a good insertion point, just append to the end of the script\n if (packagesEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find a good insertion point for optional features section, appending to the end\");\n packagesEndIndex = scriptContent.Length;\n }\n \n // Create the optional features section\n var optionalFeaturesSection = new StringBuilder();\n optionalFeaturesSection.AppendLine();\n optionalFeaturesSection.AppendLine(\"# Disable Optional Features\");\n optionalFeaturesSection.AppendLine(\"$optionalFeatures = @(\");\n \n // Add features without trailing comma on the last item\n for (int i = 0; i < features.Count; i++)\n {\n string feature = features[i];\n if (i < features.Count - 1)\n {\n optionalFeaturesSection.AppendLine($\" '{feature}',\");\n }\n else\n {\n optionalFeaturesSection.AppendLine($\" '{feature}'\");\n }\n }\n \n optionalFeaturesSection.AppendLine(\")\");\n optionalFeaturesSection.AppendLine();\n optionalFeaturesSection.AppendLine(\"foreach ($feature in $optionalFeatures) {\");\n optionalFeaturesSection.AppendLine(\" Write-Host \\\"Disabling optional feature: $feature\\\" -ForegroundColor Yellow\");\n optionalFeaturesSection.AppendLine(\" Disable-WindowsOptionalFeature -Online -FeatureName $feature -NoRestart | Out-Null\");\n optionalFeaturesSection.AppendLine(\"}\");\n \n // Insert the section\n return scriptContent.Substring(0, packagesEndIndex) \n + optionalFeaturesSection.ToString() \n + scriptContent.Substring(packagesEndIndex);\n }\n \n // If the section exists, update it\n int arrayStartIndex = scriptContent.IndexOf(\"$optionalFeatures = @(\", sectionStartIndex);\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $optionalFeatures array in BloatRemoval.ps1\");\n return scriptContent;\n }\n \n // Find the end of the optional features array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find end of $optionalFeatures array in BloatRemoval.ps1\");\n return scriptContent;\n }\n \n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n \n // Parse the optional features in the array\n var optionalFeatures = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var feature = trimmedLine.Trim('\\'', '\"', ' ', ',');\n optionalFeatures.Add(feature);\n }\n }\n \n bool modified = false;\n \n if (isInstallOperation)\n {\n // For install operations, REMOVE the optional feature from the list\n foreach (var feature in features)\n {\n // Extract the base name without version for feature matching\n string baseFeatureName = feature;\n if (feature.Contains(\"~~~~\"))\n {\n // Extract the base name before the version (~~~~)\n baseFeatureName = feature.Split('~')[0];\n _logService.LogInformation($\"Extracted base feature name '{baseFeatureName}' from '{feature}' for removal\");\n }\n \n // Find any feature in the list that matches the base name (regardless of version)\n var matchingFeatures = optionalFeatures\n .Where(f => f.StartsWith(baseFeatureName, StringComparison.OrdinalIgnoreCase) || \n (f.Contains(\"~~~~\") && f.Split('~')[0].Equals(baseFeatureName, StringComparison.OrdinalIgnoreCase)))\n .ToList();\n \n foreach (var matchingFeature in matchingFeatures)\n {\n optionalFeatures.Remove(matchingFeature);\n _logService.LogInformation($\"Removed optional feature: {matchingFeature} from BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n if (!modified)\n {\n _logService.LogInformation(\"No optional features to remove from BloatRemoval.ps1\");\n }\n }\n else\n {\n // For removal operations, ADD the optional feature to the list\n foreach (var feature in features)\n {\n if (!optionalFeatures.Contains(feature, StringComparer.OrdinalIgnoreCase))\n {\n optionalFeatures.Add(feature);\n _logService.LogInformation($\"Added optional feature: {feature} to BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n if (!modified)\n {\n _logService.LogInformation(\"No new optional features to add to BloatRemoval.ps1\");\n }\n }\n \n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$optionalFeatures = @(\");\n \n // Add features without trailing comma on the last item\n for (int i = 0; i < optionalFeatures.Count; i++)\n {\n string feature = optionalFeatures[i];\n if (i < optionalFeatures.Count - 1)\n {\n newArrayContent.AppendLine($\" '{feature}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{feature}'\");\n }\n }\n \n newArrayContent.Append(\")\");\n \n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error updating optional features in script\", ex);\n return scriptContent;\n }\n }\n\n /// \n public string UpdateRegistrySettingsInScript(string scriptContent, Dictionary> appsWithRegistry)\n {\n try\n {\n _logService.LogInformation($\"Updating registry settings for {appsWithRegistry.Count} apps\");\n\n // Find the registry settings section\n int registrySectionIndex = scriptContent.IndexOf(\"# Registry settings\");\n if (registrySectionIndex == -1)\n {\n // If the registry settings section doesn't exist, create it\n _logService.LogInformation(\"Creating Registry settings section in BloatRemoval.ps1\");\n \n // Find a good place to insert the section (at the end of the script)\n int insertIndex = scriptContent.Length;\n \n // Create the registry settings section\n var registrySection = new StringBuilder();\n registrySection.AppendLine();\n registrySection.AppendLine(\"# Registry settings\");\n \n // Add registry settings for each app\n foreach (var appEntry in appsWithRegistry)\n {\n string appName = appEntry.Key;\n List settings = appEntry.Value;\n \n if (settings == null || settings.Count == 0)\n {\n continue;\n }\n \n registrySection.AppendLine();\n registrySection.AppendLine($\"# Registry settings for {appName}\");\n \n foreach (var setting in settings)\n {\n if (setting.Path == null || setting.Name == null)\n {\n continue;\n }\n \n string regType = RegistryScriptHelper.GetRegTypeString(setting.ValueKind);\n string regValue = FormatRegistryValue(setting.Value, setting.ValueKind);\n \n registrySection.AppendLine($\"reg add \\\"{setting.Path}\\\" /v \\\"{setting.Name}\\\" /t {regType} /d {regValue} /f\");\n }\n }\n \n // Insert the section\n return scriptContent + registrySection.ToString();\n }\n \n // If the registry settings section exists, update it\n StringBuilder updatedContent = new StringBuilder(scriptContent);\n \n // Add registry settings for each app\n foreach (var appEntry in appsWithRegistry)\n {\n string appName = appEntry.Key;\n List settings = appEntry.Value;\n \n if (settings == null || settings.Count == 0)\n {\n continue;\n }\n \n // Check if this app already has registry settings in the script\n string appSectionHeader = $\"# Registry settings for {appName}\";\n int appSectionIndex = updatedContent.ToString().IndexOf(appSectionHeader, registrySectionIndex);\n \n if (appSectionIndex == -1)\n {\n // App doesn't have registry settings yet, add them\n _logService.LogInformation($\"Adding registry settings for {appName} to BloatRemoval.ps1\");\n \n // Find the end of the registry settings section or the start of the next major section\n int endOfRegistrySection = updatedContent.ToString().IndexOf(\"# Prevent apps from reinstalling\", registrySectionIndex);\n if (endOfRegistrySection == -1)\n {\n endOfRegistrySection = updatedContent.Length;\n }\n \n // Create the app registry settings section\n var appRegistrySection = new StringBuilder();\n appRegistrySection.AppendLine();\n appRegistrySection.AppendLine(appSectionHeader);\n \n foreach (var setting in settings)\n {\n if (setting.Path == null || setting.Name == null)\n {\n continue;\n }\n \n string regType = RegistryScriptHelper.GetRegTypeString(setting.ValueKind);\n string regValue = FormatRegistryValue(setting.Value, setting.ValueKind);\n \n appRegistrySection.AppendLine($\"reg add \\\"{setting.Path}\\\" /v \\\"{setting.Name}\\\" /t {regType} /d {regValue} /f\");\n }\n \n // Insert the app registry settings section\n updatedContent.Insert(endOfRegistrySection, appRegistrySection.ToString());\n }\n else\n {\n // App already has registry settings, update them\n _logService.LogInformation($\"Updating registry settings for {appName} in BloatRemoval.ps1\");\n \n // Find the end of the app section (next app section or end of registry section)\n int nextAppSectionIndex = updatedContent.ToString().IndexOf(\"# Registry settings for\", appSectionIndex + appSectionHeader.Length);\n if (nextAppSectionIndex == -1)\n {\n nextAppSectionIndex = updatedContent.ToString().IndexOf(\"# Prevent apps from reinstalling\", appSectionIndex);\n if (nextAppSectionIndex == -1)\n {\n nextAppSectionIndex = updatedContent.Length;\n }\n }\n \n // Create the updated app registry settings section\n var updatedAppRegistrySection = new StringBuilder();\n updatedAppRegistrySection.AppendLine(appSectionHeader);\n \n foreach (var setting in settings)\n {\n if (setting.Path == null || setting.Name == null)\n {\n continue;\n }\n \n string regType = RegistryScriptHelper.GetRegTypeString(setting.ValueKind);\n string regValue = FormatRegistryValue(setting.Value, setting.ValueKind);\n \n updatedAppRegistrySection.AppendLine($\"reg add \\\"{setting.Path}\\\" /v \\\"{setting.Name}\\\" /t {regType} /d {regValue} /f\");\n }\n \n // Replace the old app registry settings section with the new one\n updatedContent.Remove(appSectionIndex, nextAppSectionIndex - appSectionIndex);\n updatedContent.Insert(appSectionIndex, updatedAppRegistrySection.ToString());\n }\n }\n \n return updatedContent.ToString();\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error updating registry settings in script\", ex);\n return scriptContent;\n }\n }\n\n /// \n /// Formats a registry value for use in a reg.exe command.\n /// \n /// The value to format.\n /// The registry value kind.\n /// The formatted value.\n private string FormatRegistryValue(object value, RegistryValueKind valueKind)\n {\n if (value == null)\n {\n return \"\\\"\\\"\";\n }\n\n switch (valueKind)\n {\n case RegistryValueKind.String:\n case RegistryValueKind.ExpandString:\n return $\"\\\"{value}\\\"\";\n case RegistryValueKind.DWord:\n case RegistryValueKind.QWord:\n return value.ToString();\n case RegistryValueKind.Binary:\n if (value is byte[] bytes)\n {\n return BitConverter.ToString(bytes).Replace(\"-\", \",\");\n }\n return \"\\\"\\\"\";\n case RegistryValueKind.MultiString:\n if (value is string[] strings)\n {\n return $\"\\\"{string.Join(\"\\\\0\", strings)}\\\\0\\\"\";\n }\n return \"\\\"\\\"\";\n default:\n return $\"\\\"{value}\\\"\";\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/UnifiedConfigurationDialog.xaml.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Windows;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Interaction logic for UnifiedConfigurationDialog.xaml\n /// \n public partial class UnifiedConfigurationDialog : Window\n {\n private readonly UnifiedConfigurationDialogViewModel _viewModel;\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The title of the dialog.\n /// The description of the dialog.\n /// The dictionary of section names, their availability, and item counts.\n /// Whether this is a save dialog (true) or an import dialog (false).\n public UnifiedConfigurationDialog(\n string title,\n string description,\n Dictionary sections,\n bool isSaveDialog)\n {\n try\n {\n InitializeComponent();\n\n // Try to get the log service from the application using reflection\n try\n {\n if (Application.Current is App appInstance)\n {\n // Use reflection to access the _host.Services property\n var hostField = appInstance.GetType().GetField(\"_host\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (hostField != null)\n {\n var host = hostField.GetValue(appInstance);\n var servicesProperty = host.GetType().GetProperty(\"Services\");\n if (servicesProperty != null)\n {\n var services = servicesProperty.GetValue(host);\n var getServiceMethod = services.GetType().GetMethod(\"GetService\", new[] { typeof(Type) });\n if (getServiceMethod != null)\n {\n _logService = getServiceMethod.Invoke(services, new object[] { typeof(ILogService) }) as ILogService;\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error getting log service: {ex.Message}\");\n // Continue without logging\n }\n \n LogInfo($\"Creating {(isSaveDialog ? \"save\" : \"import\")} dialog with title: {title}\");\n LogInfo($\"Sections: {string.Join(\", \", sections.Keys)}\");\n\n // Create the view model\n _viewModel = new UnifiedConfigurationDialogViewModel(title, description, sections, isSaveDialog);\n \n // Set the data context\n DataContext = _viewModel;\n\n // Set the window title\n this.Title = title;\n \n // Ensure the dialog is shown as a modal dialog\n this.WindowStartupLocation = WindowStartupLocation.CenterOwner;\n this.ResizeMode = ResizeMode.NoResize;\n this.ShowInTaskbar = false;\n \n // Handle the OK and Cancel commands directly\n _viewModel.OkCommand = new RelayCommand(() =>\n {\n // Validate that at least one section is selected\n if (_viewModel.Sections.Any(s => s.IsSelected))\n {\n LogInfo(\"OK button clicked, at least one section selected\");\n this.DialogResult = true;\n }\n else\n {\n LogInfo(\"OK button clicked, but no sections selected\");\n MessageBox.Show(\n \"Please select at least one section to continue.\",\n \"No Sections Selected\",\n MessageBoxButton.OK,\n MessageBoxImage.Warning);\n }\n });\n \n _viewModel.CancelCommand = new RelayCommand(() =>\n {\n LogInfo(\"Cancel button clicked\");\n this.DialogResult = false;\n });\n \n LogInfo(\"Dialog initialization completed\");\n }\n catch (Exception ex)\n {\n LogError($\"Error initializing dialog: {ex.Message}\");\n Debug.WriteLine($\"Error initializing dialog: {ex}\");\n \n // Show error message\n MessageBox.Show($\"Error initializing dialog: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n \n // Set dialog result to false\n DialogResult = false;\n }\n }\n\n /// \n /// Gets the result of the dialog as a dictionary of section names and their selection state.\n /// \n /// A dictionary of section names and their selection state.\n public Dictionary GetResult()\n {\n try\n {\n var result = _viewModel.GetResult();\n LogInfo($\"GetResult called, returning {result.Count} sections\");\n return result;\n }\n catch (Exception ex)\n {\n LogError($\"Error getting result: {ex.Message}\");\n return new Dictionary();\n }\n }\n \n private void LogInfo(string message)\n {\n _logService?.Log(LogLevel.Info, $\"UnifiedConfigurationDialog: {message}\");\n Debug.WriteLine($\"UnifiedConfigurationDialog: {message}\");\n }\n \n private void LogError(string message)\n {\n _logService?.Log(LogLevel.Error, $\"UnifiedConfigurationDialog: {message}\");\n Debug.WriteLine($\"UnifiedConfigurationDialog ERROR: {message}\");\n }\n \n /// \n /// Handles the mouse left button down event on the title bar to enable window dragging.\n /// \n private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n if (e.ChangedButton == MouseButton.Left)\n {\n this.DragMove();\n }\n }\n \n /// \n /// Handles the close button click event.\n /// \n private void CloseButton_Click(object sender, RoutedEventArgs e)\n {\n LogInfo(\"Close button clicked\");\n this.DialogResult = false;\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/PrivacyOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for privacy optimizations.\n /// \n public partial class PrivacyOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDependencyManager _dependencyManager;\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dependency manager.\n /// The view model locator.\n /// The settings registry.\n public PrivacyOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDependencyManager dependencyManager,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _dependencyManager = dependencyManager ?? throw new ArgumentNullException(nameof(dependencyManager));\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n _logService.Log(LogLevel.Info, \"PrivacyOptimizationsViewModel instance created\");\n }\n\n /// \n /// Loads the privacy settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, \"Loading privacy settings\");\n\n // Initialize privacy settings from PrivacyOptimizations.cs\n var privacyOptimizations = Core.Features.Optimize.Models.PrivacyOptimizations.GetPrivacyOptimizations();\n if (privacyOptimizations?.Settings != null)\n {\n Settings.Clear();\n\n // Process each setting\n foreach (var setting in privacyOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = false, // Always initialize as unchecked\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n\n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Register the setting in the settings registry if available\n if (_settingsRegistry != null && !string.IsNullOrEmpty(settingItem.Id))\n {\n _settingsRegistry.RegisterSetting(settingItem);\n _logService.Log(LogLevel.Info, $\"Registered setting {settingItem.Id} in settings registry during creation\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for checkboxes\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n await CheckSettingStatusesAsync();\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading privacy settings: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all privacy settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, $\"Checking status for {Settings.Count} privacy settings\");\n\n // Clear registry caches to ensure fresh reads\n _registryService.ClearRegistryCaches();\n\n // Create a list of tasks to check all settings in parallel\n var tasks = Settings.Select(async setting => {\n try\n {\n // Check if we have linked registry settings\n if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Checking status for linked setting: {setting.Name} with {setting.LinkedRegistrySettings.Settings.Count} registry entries\");\n\n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(regSetting.Hive);\n string fullPath = $\"{hiveString}\\\\{regSetting.SubKey}\";\n _logService.Log(LogLevel.Info, $\"Registry entry: {fullPath}\\\\{regSetting.Name}, EnabledValue={regSetting.EnabledValue}, DisabledValue={regSetting.DisabledValue}\");\n\n // Check if the key exists\n bool keyExists = _registryService.KeyExists(fullPath);\n _logService.Log(LogLevel.Info, $\"Key exists: {keyExists}\");\n\n if (keyExists)\n {\n // Check if the value exists and get its current value\n var currentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value: {currentValue ?? \"null\"}\");\n }\n }\n\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n _logService.Log(LogLevel.Info, $\"Combined status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name} (first entry): {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value for linked setting {regSetting.Name}: {regCurrentValue ?? \"null\"}\");\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n // Fall back to single registry setting\n else if (setting.RegistrySetting != null)\n {\n _logService.Log(LogLevel.Info, $\"Checking status for setting: {setting.Name}\");\n\n // Log details about the registry entry for debugging\n string hiveString = RegistryExtensions.GetRegistryHiveString(setting.RegistrySetting.Hive);\n string fullPath = $\"{hiveString}\\\\{setting.RegistrySetting.SubKey}\";\n _logService.Log(LogLevel.Info, $\"Registry entry: {fullPath}\\\\{setting.RegistrySetting.Name}, EnabledValue={setting.RegistrySetting.EnabledValue}, DisabledValue={setting.RegistrySetting.DisabledValue}\");\n\n // Check if the key exists\n bool keyExists = _registryService.KeyExists(fullPath);\n _logService.Log(LogLevel.Info, $\"Key exists: {keyExists}\");\n\n // Get the status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // Get the current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name}: {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n \n // Set IsRegistryValueNull for single registry setting\n setting.IsRegistryValueNull = currentValue == null;\n\n // Add to LinkedRegistrySettingsWithValues for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings available for {setting.Name}\");\n setting.Status = RegistrySettingStatus.Unknown;\n setting.StatusMessage = \"Registry setting information is missing\";\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating status for setting {setting.Name}: {ex.Message}\");\n setting.Status = RegistrySettingStatus.Error;\n setting.StatusMessage = $\"Error: {ex.Message}\";\n }\n }).ToList();\n\n // Wait for all tasks to complete\n await Task.WhenAll(tasks);\n\n // Now handle any grouped settings\n foreach (var setting in Settings.Where(s => s.IsGroupedSetting && s.ChildSettings.Count > 0))\n {\n _logService.Log(LogLevel.Info, $\"Updating {setting.ChildSettings.Count} child settings for {setting.Name}\");\n foreach (var childSetting in setting.ChildSettings)\n {\n if (childSetting.RegistrySetting != null)\n {\n var status = await _registryService.GetSettingStatusAsync(childSetting.RegistrySetting);\n childSetting.Status = status;\n\n var currentValue = await _registryService.GetCurrentValueAsync(childSetting.RegistrySetting);\n childSetting.CurrentValue = currentValue;\n\n childSetting.StatusMessage = GetStatusMessage(childSetting);\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking privacy setting statuses: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n // ApplySelectedSettingsAsync and RestoreDefaultsAsync methods removed as part of the refactoring\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0)\n return;\n\n var selectedCount = Settings.Count(setting => setting.IsSelected);\n IsSelected = selectedCount == Settings.Count;\n }\n\n /// \n /// Gets a user-friendly status message for a setting.\n /// \n /// The setting to get the status message for.\n /// A user-friendly status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied =>\n \"This setting is enabled (toggle is ON).\",\n\n RegistrySettingStatus.NotApplied =>\n setting.CurrentValue == null\n ? \"This setting is not applied (registry value does not exist).\"\n : \"This setting is disabled (toggle is OFF).\",\n\n RegistrySettingStatus.Modified =>\n \"This setting has a custom value that differs from both enabled and disabled values.\",\n\n RegistrySettingStatus.Error =>\n \"An error occurred while checking this setting's status.\",\n\n _ => \"The status of this setting is unknown.\"\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/OptimizeConfigurationApplier.cs", "using System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Optimize.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for applying configuration to the Optimize section.\n /// \n public class OptimizeConfigurationApplier : ISectionConfigurationApplier\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n private readonly IViewModelRefresher _viewModelRefresher;\n private readonly IConfigurationPropertyUpdater _propertyUpdater;\n\n /// \n /// Gets the section name that this applier handles.\n /// \n public string SectionName => \"Optimize\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n /// The view model refresher.\n /// The property updater.\n public OptimizeConfigurationApplier(\n IServiceProvider serviceProvider,\n ILogService logService,\n IViewModelRefresher viewModelRefresher,\n IConfigurationPropertyUpdater propertyUpdater)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _viewModelRefresher = viewModelRefresher ?? throw new ArgumentNullException(nameof(viewModelRefresher));\n _propertyUpdater = propertyUpdater ?? throw new ArgumentNullException(nameof(propertyUpdater));\n }\n\n /// \n /// Applies the configuration to the Optimize section.\n /// \n /// The configuration file to apply.\n /// True if any items were updated, false otherwise.\n public async Task ApplyConfigAsync(ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Applying configuration to OptimizeViewModel\");\n \n var viewModel = _serviceProvider.GetService();\n if (viewModel == null)\n {\n _logService.Log(LogLevel.Warning, \"OptimizeViewModel not available\");\n return false;\n }\n \n // Set a timeout for the operation to prevent hanging\n using var cancellationTokenSource = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(45));\n var cancellationToken = cancellationTokenSource.Token;\n \n // Add a log entry to track execution time\n var startTime = DateTime.Now;\n _logService.Log(LogLevel.Info, $\"Starting OptimizeConfigurationApplier.ApplyConfigAsync at {startTime}\");\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, \"OptimizeViewModel not initialized, initializing now\");\n try\n {\n var initializeTask = viewModel.InitializeCommand.ExecuteAsync(null);\n await Task.WhenAny(initializeTask, Task.Delay(10000, cancellationToken)); // 10 second timeout\n \n if (!initializeTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Initialization timed out, proceeding with partial initialization\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error initializing OptimizeViewModel: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n // Continue with the import even if initialization fails\n }\n }\n \n int totalUpdatedCount = 0;\n \n // Apply the configuration directly to the view model's items\n try\n {\n int mainItemsUpdatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Items, configFile);\n totalUpdatedCount += mainItemsUpdatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {mainItemsUpdatedCount} items in OptimizeViewModel.Items\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating main items: {ex.Message}\");\n }\n \n // Also apply to child view models - wrap each in try/catch to ensure one failure doesn't stop others\n \n // Gaming and Performance Settings\n if (viewModel.GamingandPerformanceOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.GamingandPerformanceOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in GamingandPerformanceOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating GamingandPerformanceOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Privacy Settings\n if (viewModel.PrivacyOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.PrivacyOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in PrivacyOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating PrivacyOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Update Settings\n if (viewModel.UpdateOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.UpdateOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in UpdateOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating UpdateOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Power Settings - this is the most likely place for hangs\n if (viewModel.PowerSettingsViewModel?.Settings != null)\n {\n try\n {\n // Use a separate timeout for power settings\n using var powerSettingsCts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(10));\n \n var powerSettingsTask = ApplyPowerSettings(viewModel.PowerSettingsViewModel, configFile);\n await Task.WhenAny(powerSettingsTask, Task.Delay(10000, powerSettingsCts.Token));\n \n if (powerSettingsTask.IsCompleted)\n {\n int updatedCount = await powerSettingsTask;\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in PowerSettingsViewModel\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Power settings update timed out, skipping\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating PowerSettingsViewModel: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n }\n \n // Explorer Settings\n if (viewModel.ExplorerOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.ExplorerOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in ExplorerOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating ExplorerOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Notification Settings\n if (viewModel.NotificationOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.NotificationOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in NotificationOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating NotificationOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Sound Settings\n if (viewModel.SoundOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.SoundOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in SoundOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating SoundOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Windows Security Settings\n _logService.Log(LogLevel.Info, \"Starting to process Windows Security Settings\");\n var securityStartTime = DateTime.Now;\n \n if (viewModel.WindowsSecuritySettingsViewModel?.Settings != null)\n {\n try\n {\n // Use a separate timeout for security settings\n using var securitySettingsCts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(10));\n \n var securitySettingsTask = ApplySecuritySettings(viewModel.WindowsSecuritySettingsViewModel, configFile);\n await Task.WhenAny(securitySettingsTask, Task.Delay(10000, securitySettingsCts.Token));\n \n if (securitySettingsTask.IsCompleted)\n {\n int updatedCount = await securitySettingsTask;\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in WindowsSecuritySettingsViewModel\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Security settings update timed out, skipping\");\n securitySettingsCts.Cancel();\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating WindowsSecuritySettingsViewModel: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n \n var securityEndTime = DateTime.Now;\n var securityExecutionTime = securityEndTime - securityStartTime;\n _logService.Log(LogLevel.Info, $\"Completed Windows Security Settings processing in {securityExecutionTime.TotalSeconds:F2} seconds\");\n }\n \n _logService.Log(LogLevel.Info, $\"Updated a total of {totalUpdatedCount} items in OptimizeViewModel and its child view models\");\n \n // Refresh the UI\n try\n {\n await _viewModelRefresher.RefreshViewModelAsync(viewModel);\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error refreshing view model: {ex.Message}\");\n }\n \n // Skip calling ApplyOptimizations during import to avoid system changes\n // We'll just update the UI to reflect the imported values\n \n // Reload the main Items collection to reflect the changes in child view models\n try\n {\n await viewModel.LoadItemsAsync();\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error reloading items: {ex.Message}\");\n }\n \n // Calculate and log execution time\n var endTime = DateTime.Now;\n var executionTime = endTime - startTime;\n _logService.Log(LogLevel.Info, $\"Completed OptimizeConfigurationApplier.ApplyConfigAsync in {executionTime.TotalSeconds:F2} seconds\");\n \n return totalUpdatedCount > 0;\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"OptimizeConfigurationApplier.ApplyConfigAsync was canceled due to timeout\");\n return false;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying Optimize configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n\n private async Task ApplyPowerSettings(PowerOptimizationsViewModel viewModel, ConfigurationFile configFile)\n {\n int updatedCount = 0;\n \n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(15));\n var cancellationToken = cancellationTokenSource.Token;\n \n // Track execution time\n var startTime = DateTime.Now;\n _logService.Log(LogLevel.Info, $\"Starting ApplyPowerSettings at {startTime}\");\n \n try\n {\n // First, check if there's a Power Plan item in the config file\n var powerPlanItem = configFile.Items?.FirstOrDefault(item =>\n (item.Name?.Contains(\"Power Plan\") == true ||\n (item.CustomProperties.TryGetValue(\"Id\", out var id) && id?.ToString() == \"PowerPlanComboBox\")));\n \n if (powerPlanItem != null)\n {\n _logService.Log(LogLevel.Info, $\"Found Power Plan item in config file: {powerPlanItem.Name}\");\n \n int newPowerPlanValue = -1;\n string selectedPowerPlan = null;\n \n // First try to get the value from SelectedValue by mapping to index (preferred method)\n if (!string.IsNullOrEmpty(powerPlanItem.SelectedValue))\n {\n selectedPowerPlan = powerPlanItem.SelectedValue;\n _logService.Log(LogLevel.Info, $\"Found SelectedValue in config: {selectedPowerPlan}\");\n \n var powerPlanLabels = viewModel.PowerPlanLabels;\n for (int i = 0; i < powerPlanLabels.Count; i++)\n {\n if (string.Equals(powerPlanLabels[i], selectedPowerPlan, StringComparison.OrdinalIgnoreCase))\n {\n newPowerPlanValue = i;\n _logService.Log(LogLevel.Info, $\"Mapped SelectedValue {selectedPowerPlan} to PowerPlanValue: {newPowerPlanValue}\");\n break;\n }\n }\n }\n // Then try to get the value from SliderValue in CustomProperties (fallback)\n else if (powerPlanItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n newPowerPlanValue = Convert.ToInt32(sliderValue);\n _logService.Log(LogLevel.Info, $\"Found PowerPlanValue in CustomProperties.SliderValue: {newPowerPlanValue}\");\n }\n \n // If we still don't have a valid power plan value, try to get it from PowerPlanOptions\n if (newPowerPlanValue < 0 && powerPlanItem.CustomProperties.TryGetValue(\"PowerPlanOptions\", out var powerPlanOptions))\n {\n if (powerPlanOptions is System.Collections.IList optionsList && !string.IsNullOrEmpty(selectedPowerPlan))\n {\n for (int i = 0; i < optionsList.Count; i++)\n {\n if (string.Equals(optionsList[i]?.ToString(), selectedPowerPlan, StringComparison.OrdinalIgnoreCase))\n {\n newPowerPlanValue = i;\n _logService.Log(LogLevel.Info, $\"Mapped SelectedValue {selectedPowerPlan} to PowerPlanValue: {newPowerPlanValue} using PowerPlanOptions\");\n break;\n }\n }\n }\n }\n \n if (newPowerPlanValue >= 0)\n {\n // Update the view model properties without triggering the actual power plan change\n // Store the current value for comparison\n int currentPowerPlanValue = viewModel.PowerPlanValue;\n \n if (currentPowerPlanValue != newPowerPlanValue)\n {\n _logService.Log(LogLevel.Info, $\"About to update PowerPlanValue from {currentPowerPlanValue} to {newPowerPlanValue}\");\n \n // Set IsApplyingPowerPlan to true before updating PowerPlanValue\n viewModel.IsApplyingPowerPlan = true;\n _logService.Log(LogLevel.Info, \"Set IsApplyingPowerPlan to true to prevent auto-application\");\n \n // Add a small delay to ensure IsApplyingPowerPlan takes effect\n await Task.Delay(50);\n \n try\n {\n // Use reflection to directly set the backing field for PowerPlanValue\n // This avoids triggering the property change notification that would call ApplyPowerPlanAsync\n var field = viewModel.GetType().GetField(\"_powerPlanValue\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n \n if (field != null)\n {\n // Set the backing field directly\n field.SetValue(viewModel, newPowerPlanValue);\n _logService.Log(LogLevel.Info, $\"Directly updated _powerPlanValue field to {newPowerPlanValue}\");\n \n // Manually trigger property changed notification\n // Specify the parameter types to avoid ambiguous match error\n var onPropertyChangedMethod = viewModel.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(string) },\n null);\n \n if (onPropertyChangedMethod != null)\n {\n onPropertyChangedMethod.Invoke(viewModel, new object[] { \"PowerPlanValue\" });\n _logService.Log(LogLevel.Info, \"Manually triggered OnPropertyChanged for PowerPlanValue\");\n }\n else\n {\n // Fallback: Try with PropertyChangedEventArgs parameter\n var args = new System.ComponentModel.PropertyChangedEventArgs(\"PowerPlanValue\");\n var altMethod = viewModel.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(System.ComponentModel.PropertyChangedEventArgs) },\n null);\n \n if (altMethod != null)\n {\n altMethod.Invoke(viewModel, new object[] { args });\n _logService.Log(LogLevel.Info, \"Manually triggered OnPropertyChanged with PropertyChangedEventArgs\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not find appropriate OnPropertyChanged method\");\n }\n }\n }\n else\n {\n // Fallback to direct property setting if field not found\n _logService.Log(LogLevel.Warning, \"Could not find _powerPlanValue field, using property setter instead\");\n viewModel.PowerPlanValue = newPowerPlanValue;\n _logService.Log(LogLevel.Info, $\"Updated PowerPlanValue property to {newPowerPlanValue}\");\n }\n \n // Add a small delay to ensure property change notifications are processed\n await Task.Delay(100);\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating power plan value: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n throw; // Rethrow to be caught by outer catch\n }\n \n // Now actually apply the power plan\n try\n {\n // Reset IsApplyingPowerPlan to false so we can apply the power plan\n viewModel.IsApplyingPowerPlan = false;\n _logService.Log(LogLevel.Info, \"Reset IsApplyingPowerPlan to false\");\n \n // Call the method to apply the power plan\n var applyPowerPlanMethod = viewModel.GetType().GetMethod(\"ApplyPowerPlanAsync\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (applyPowerPlanMethod != null)\n {\n _logService.Log(LogLevel.Info, $\"Calling ApplyPowerPlanAsync to apply power plan: {selectedPowerPlan}\");\n await (Task)applyPowerPlanMethod.Invoke(viewModel, new object[] { newPowerPlanValue });\n _logService.Log(LogLevel.Success, $\"Successfully applied power plan: {selectedPowerPlan}\");\n }\n else\n {\n // Try to find a method that takes no parameters\n applyPowerPlanMethod = viewModel.GetType().GetMethod(\"ApplyPowerPlanAsync\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance,\n null,\n Type.EmptyTypes,\n null);\n \n if (applyPowerPlanMethod != null)\n {\n _logService.Log(LogLevel.Info, $\"Calling parameterless ApplyPowerPlanAsync to apply power plan: {selectedPowerPlan}\");\n await (Task)applyPowerPlanMethod.Invoke(viewModel, null);\n _logService.Log(LogLevel.Success, $\"Successfully applied power plan: {selectedPowerPlan}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not find ApplyPowerPlanAsync method\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying power plan: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n finally\n {\n // Make sure IsApplyingPowerPlan is reset to false when done\n if (viewModel.IsApplyingPowerPlan)\n {\n viewModel.IsApplyingPowerPlan = false;\n _logService.Log(LogLevel.Info, \"Reset IsApplyingPowerPlan to false in finally block\");\n }\n }\n \n // Also update the SelectedIndex of the ComboBox if possible\n try\n {\n // Find the ComboBox control in the PowerSettingsViewModel\n var powerPlanComboBox = viewModel.Settings.FirstOrDefault(s =>\n s.Id == \"PowerPlanComboBox\" || s.Name?.Contains(\"Power Plan\") == true);\n \n if (powerPlanComboBox != null)\n {\n var sliderValueProperty = powerPlanComboBox.GetType().GetProperty(\"SliderValue\");\n if (sliderValueProperty != null)\n {\n _logService.Log(LogLevel.Info, $\"Setting SliderValue on PowerPlanComboBox to {newPowerPlanValue}\");\n sliderValueProperty.SetValue(powerPlanComboBox, newPowerPlanValue);\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error updating PowerPlanComboBox: {ex.Message}\");\n }\n \n updatedCount++;\n }\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"No Power Plan item found in config file\");\n \n // Try to find a power plan setting in the Settings collection\n var powerPlanSetting = viewModel.Settings?.FirstOrDefault(s =>\n s.Id == \"PowerPlanComboBox\" || s.Name?.Contains(\"Power Plan\") == true);\n \n if (powerPlanSetting != null)\n {\n _logService.Log(LogLevel.Info, $\"Found Power Plan setting in Settings collection: {powerPlanSetting.Name}\");\n \n // Create a new ConfigurationItem for the power plan\n var newPowerPlanItem = new ConfigurationItem\n {\n Name = powerPlanSetting.Name,\n IsSelected = true,\n ControlType = ControlType.ComboBox,\n CustomProperties = new Dictionary\n {\n { \"Id\", \"PowerPlanComboBox\" },\n { \"GroupName\", \"Power Management\" },\n { \"Description\", \"Select power plan for your system\" },\n { \"SliderValue\", viewModel.PowerPlanValue }\n }\n };\n \n // Set the SelectedValue based on the current PowerPlanValue\n if (viewModel.PowerPlanValue >= 0 && viewModel.PowerPlanValue < viewModel.PowerPlanLabels.Count)\n {\n newPowerPlanItem.SelectedValue = viewModel.PowerPlanLabels[viewModel.PowerPlanValue];\n }\n \n // Add the item to the config file\n if (configFile.Items == null)\n {\n configFile.Items = new List();\n }\n \n configFile.Items.Add(newPowerPlanItem);\n _logService.Log(LogLevel.Info, $\"Added Power Plan item to config file with SelectedValue: {newPowerPlanItem.SelectedValue}\");\n }\n }\n \n // Then apply to the Settings collection as usual\n int settingsUpdatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Settings, configFile);\n updatedCount += settingsUpdatedCount;\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"ApplyPowerSettings was canceled due to timeout\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying power settings: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n \n // Calculate and log execution time\n var endTime = DateTime.Now;\n var executionTime = endTime - startTime;\n _logService.Log(LogLevel.Info, $\"Completed ApplyPowerSettings in {executionTime.TotalSeconds:F2} seconds\");\n \n return updatedCount;\n }\n\n private async Task ApplySecuritySettings(WindowsSecurityOptimizationsViewModel viewModel, ConfigurationFile configFile)\n {\n int updatedCount = 0;\n \n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(15));\n var cancellationToken = cancellationTokenSource.Token;\n \n // Track execution time\n var startTime = DateTime.Now;\n _logService.Log(LogLevel.Info, $\"Starting ApplySecuritySettings at {startTime}\");\n \n try\n {\n // First, check if there's a UAC Slider item in the config file\n var uacSliderItem = configFile.Items?.FirstOrDefault(item =>\n (item.Name?.Contains(\"User Account Control\") == true ||\n (item.CustomProperties.TryGetValue(\"Id\", out var id) && id?.ToString() == \"UACSlider\")));\n\n if (uacSliderItem != null && uacSliderItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n // Check if the SelectedUacLevel property exists\n var selectedUacLevelProperty = viewModel.GetType().GetProperty(\"SelectedUacLevel\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);\n\n if (selectedUacLevelProperty != null)\n {\n // Convert the slider value to the corresponding UacLevel enum value\n int newUacLevelValue = Convert.ToInt32(sliderValue);\n var currentUacLevel = selectedUacLevelProperty.GetValue(viewModel);\n\n // Get the UacLevel enum type\n var uacLevelType = selectedUacLevelProperty.PropertyType;\n\n // Convert the integer to the corresponding UacLevel enum value\n var newUacLevel = (Winhance.Core.Models.Enums.UacLevel)Enum.ToObject(uacLevelType, newUacLevelValue);\n var currentUacLevelTyped = currentUacLevel != null ? (Winhance.Core.Models.Enums.UacLevel)currentUacLevel : Winhance.Core.Models.Enums.UacLevel.NotifyChangesOnly;\n\n if (currentUacLevelTyped != newUacLevel)\n {\n // Define isApplyingProperty at the beginning of the block for proper scope\n var isApplyingProperty = viewModel.GetType().GetProperty(\"IsApplyingUacLevel\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n \n if (isApplyingProperty != null)\n {\n _logService.Log(LogLevel.Info, \"Found IsApplyingUacLevel property, setting to true\");\n isApplyingProperty.SetValue(viewModel, true);\n \n // Add a small delay to ensure the property takes effect\n await Task.Delay(50, cancellationToken);\n }\n \n try\n {\n // Use reflection to set the field directly to avoid triggering HandleUACLevelChange\n var field = viewModel.GetType().GetField(\"_selectedUacLevel\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n \n if (field != null)\n {\n field.SetValue(viewModel, newUacLevel);\n _logService.Log(LogLevel.Info, $\"Directly updated _selectedUacLevel field to {newUacLevel}\");\n \n // Trigger property changed notification without calling HandleUACLevelChange\n // Specify the parameter types to avoid ambiguous match error\n var onPropertyChangedMethod = viewModel.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(string) },\n null);\n \n if (onPropertyChangedMethod != null)\n {\n onPropertyChangedMethod.Invoke(viewModel, new object[] { \"SelectedUacLevel\" });\n _logService.Log(LogLevel.Info, \"Manually triggered OnPropertyChanged for SelectedUacLevel\");\n }\n else\n {\n // Fallback: Try with PropertyChangedEventArgs parameter\n var args = new System.ComponentModel.PropertyChangedEventArgs(\"SelectedUacLevel\");\n var altMethod = viewModel.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(System.ComponentModel.PropertyChangedEventArgs) },\n null);\n \n if (altMethod != null)\n {\n altMethod.Invoke(viewModel, new object[] { args });\n _logService.Log(LogLevel.Info, \"Manually triggered OnPropertyChanged with PropertyChangedEventArgs\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not find appropriate OnPropertyChanged method\");\n }\n }\n \n // Add a small delay to ensure property change notifications are processed\n await Task.Delay(100, cancellationToken);\n }\n else\n {\n // Fallback to direct property setting if field not found\n _logService.Log(LogLevel.Warning, \"Could not find _selectedUacLevel field, using property setter instead\");\n viewModel.SelectedUacLevel = (Winhance.Core.Models.Enums.UacLevel)newUacLevel;\n _logService.Log(LogLevel.Info, $\"Updated SelectedUacLevel property to {newUacLevel}\");\n \n // Add a small delay to ensure property change notifications are processed\n await Task.Delay(100, cancellationToken);\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating UAC level value: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n throw; // Rethrow to be caught by outer catch\n }\n \n // Now actually apply the UAC level\n try\n {\n // Reset IsApplyingUacLevel if it exists\n if (isApplyingProperty != null)\n {\n isApplyingProperty.SetValue(viewModel, false);\n _logService.Log(LogLevel.Info, \"Reset IsApplyingUacLevel to false\");\n }\n \n // Call the method to apply the UAC level\n var handleUacLevelChangeMethod = viewModel.GetType().GetMethod(\"HandleUACLevelChange\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (handleUacLevelChangeMethod != null)\n {\n _logService.Log(LogLevel.Info, $\"Calling HandleUACLevelChange to apply UAC level: {newUacLevel}\");\n // HandleUACLevelChange doesn't take any parameters\n handleUacLevelChangeMethod.Invoke(viewModel, null);\n _logService.Log(LogLevel.Success, $\"Successfully applied UAC level: {newUacLevel}\");\n }\n else\n {\n // Try to find a method that takes no parameters\n handleUacLevelChangeMethod = viewModel.GetType().GetMethod(\"HandleUACLevelChange\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance,\n null,\n Type.EmptyTypes,\n null);\n \n if (handleUacLevelChangeMethod != null)\n {\n _logService.Log(LogLevel.Info, $\"Calling parameterless HandleUACLevelChange to apply UAC level: {newUacLevel}\");\n handleUacLevelChangeMethod.Invoke(viewModel, null);\n _logService.Log(LogLevel.Success, $\"Successfully applied UAC level: {newUacLevel}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not find HandleUACLevelChange method\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying UAC level: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n finally\n {\n // Make sure IsApplyingUacLevel is reset to false when done\n if (isApplyingProperty != null && isApplyingProperty.GetValue(viewModel) is true)\n {\n isApplyingProperty.SetValue(viewModel, false);\n _logService.Log(LogLevel.Info, \"Reset IsApplyingUacLevel to false in finally block\");\n }\n } // End of the if (currentUacLevel != newUacLevel) block\n }\n \n updatedCount++;\n }\n }\n \n // Then apply to the Settings collection as usual\n int settingsUpdatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Settings, configFile);\n updatedCount += settingsUpdatedCount;\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"ApplySecuritySettings was canceled due to timeout\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying security settings: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n \n // Calculate and log execution time\n var endTime = DateTime.Now;\n var executionTime = endTime - startTime;\n _logService.Log(LogLevel.Info, $\"Completed ApplySecuritySettings in {executionTime.TotalSeconds:F2} seconds\");\n \n return updatedCount;\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/FrameNavigationService.cs", "using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service for navigating between views in the application using ContentPresenter-based navigation.\n /// \n public class FrameNavigationService\n : Winhance.Core.Features.Common.Interfaces.INavigationService\n {\n private readonly Stack _backStack = new();\n private readonly Stack<(Type ViewModelType, object Parameter)> _forwardStack = new();\n private readonly List _navigationHistory = new();\n private readonly Dictionary _viewMappings =\n new();\n private readonly IServiceProvider _serviceProvider;\n private readonly IParameterSerializer _parameterSerializer;\n private readonly SemaphoreSlim _navigationLock = new(1, 1);\n private readonly ConcurrentQueue<(\n Type ViewType,\n Type ViewModelType,\n object Parameter,\n TaskCompletionSource CompletionSource\n )> _navigationQueue = new();\n private object _currentParameter;\n private string _currentRoute;\n private const int MaxHistorySize = 50;\n private CancellationTokenSource _currentNavigationCts;\n private ICommand _navigateCommand;\n\n /// \n /// Gets the command for navigation.\n /// \n public ICommand NavigateCommand =>\n _navigateCommand ??= new RelayCommand(route => NavigateTo(route));\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The parameter serializer.\n public FrameNavigationService(\n IServiceProvider serviceProvider,\n IParameterSerializer parameterSerializer\n )\n {\n _serviceProvider = serviceProvider;\n _parameterSerializer =\n parameterSerializer ?? throw new ArgumentNullException(nameof(parameterSerializer));\n }\n\n /// \n /// Determines whether navigation back is possible.\n /// \n public bool CanGoBack => _backStack.Count > 1;\n\n /// \n /// Gets a list of navigation history.\n /// \n public IReadOnlyList NavigationHistory => _navigationHistory.AsReadOnly();\n\n /// \n /// Gets the current view name.\n /// \n public string CurrentView => _currentRoute;\n\n /// \n /// Event raised when navigation occurs.\n /// \n public event EventHandler Navigated;\n\n /// \n /// Event raised before navigation occurs.\n /// \n public event EventHandler Navigating;\n\n /// \n /// Event raised when navigation fails.\n /// \n public event EventHandler NavigationFailed;\n\n /// \n /// Initializes the navigation service.\n /// \n public void Initialize()\n {\n // No initialization needed for ContentPresenter-based navigation\n }\n\n /// \n /// Registers a view mapping.\n /// \n /// The route.\n /// The view type.\n /// The view model type.\n public void RegisterViewMapping(string route, Type viewType, Type viewModelType)\n {\n if (string.IsNullOrWhiteSpace(route))\n throw new ArgumentException(\"Route cannot be empty\", nameof(route));\n\n _viewMappings[route] = (viewType, viewModelType);\n }\n\n /// \n /// Checks if navigation to a route is possible.\n /// \n /// The route to check.\n /// True if navigation is possible; otherwise, false.\n public bool CanNavigateTo(string route) => _viewMappings.ContainsKey(route);\n\n /// \n /// Navigates to a view by route.\n /// \n /// The route to navigate to.\n /// True if navigation was successful; otherwise, false.\n public bool NavigateTo(string viewName)\n {\n try\n {\n NavigateToAsync(viewName).GetAwaiter().GetResult();\n return true;\n }\n catch (Exception ex)\n {\n // Log the error\n System.Diagnostics.Debug.WriteLine($\"Navigation error: {ex.Message}\");\n\n var args = new Winhance.Core.Features.Common.Interfaces.NavigationEventArgs(\n CurrentView,\n viewName,\n null,\n false\n );\n NavigationFailed?.Invoke(this, args);\n return false;\n }\n }\n\n /// \n /// Navigates to a view by route with a parameter.\n /// \n /// The route to navigate to.\n /// The navigation parameter.\n /// True if navigation was successful; otherwise, false.\n public bool NavigateTo(string viewName, object parameter)\n {\n try\n {\n NavigateToAsync(viewName, parameter).GetAwaiter().GetResult();\n return true;\n }\n catch (Exception ex)\n {\n // Log the error\n System.Diagnostics.Debug.WriteLine($\"Navigation error: {ex.Message}\");\n\n var args = new Winhance.Core.Features.Common.Interfaces.NavigationEventArgs(\n CurrentView,\n viewName,\n parameter,\n false\n );\n NavigationFailed?.Invoke(this, args);\n return false;\n }\n }\n\n /// \n /// Navigates back to the previous view.\n /// \n /// True if navigation was successful; otherwise, false.\n public bool NavigateBack()\n {\n try\n {\n GoBackAsync().GetAwaiter().GetResult();\n return true;\n }\n catch (Exception ex)\n {\n // Log the error\n System.Diagnostics.Debug.WriteLine($\"Navigation back error: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Navigates to a view model type.\n /// \n /// The view model type.\n /// The navigation parameter.\n /// A task representing the asynchronous operation.\n public async Task NavigateToAsync(object parameter = null)\n where TViewModel : class => await NavigateToAsync(typeof(TViewModel), parameter);\n\n /// \n /// Navigates to a view model type.\n /// \n /// The view model type.\n /// The navigation parameter.\n /// A task representing the asynchronous operation.\n public async Task NavigateToAsync(Type viewModelType, object parameter = null)\n {\n var viewType = GetViewTypeForViewModel(viewModelType);\n var tcs = new TaskCompletionSource();\n _navigationQueue.Enqueue((viewType, viewModelType, parameter, tcs));\n\n await ProcessNavigationQueueAsync();\n await tcs.Task;\n }\n\n /// \n /// Navigates to a route.\n /// \n /// The route to navigate to.\n /// The navigation parameter.\n /// A task representing the asynchronous operation.\n public async Task NavigateToAsync(string route, object parameter = null)\n {\n if (!_viewMappings.TryGetValue(route, out var mapping))\n throw new InvalidOperationException($\"No view mapping found for route: {route}\");\n\n await NavigateInternalAsync(mapping.ViewType, mapping.ViewModelType, parameter);\n }\n\n private async Task ProcessNavigationQueueAsync()\n {\n if (!await _navigationLock.WaitAsync(TimeSpan.FromMilliseconds(100)))\n return;\n\n try\n {\n while (_navigationQueue.TryDequeue(out var navigationRequest))\n {\n _currentNavigationCts?.Cancel();\n _currentNavigationCts = new CancellationTokenSource(TimeSpan.FromSeconds(30));\n\n try\n {\n await NavigateInternalAsync(\n navigationRequest.ViewType,\n navigationRequest.ViewModelType,\n navigationRequest.Parameter,\n _currentNavigationCts.Token\n );\n navigationRequest.CompletionSource.SetResult(true);\n }\n catch (Exception ex)\n {\n navigationRequest.CompletionSource.SetException(ex);\n }\n }\n }\n finally\n {\n _navigationLock.Release();\n }\n }\n\n private async Task NavigateInternalAsync(\n Type viewType,\n Type viewModelType,\n object parameter,\n CancellationToken cancellationToken = default\n )\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n // Find the route for this view/viewmodel for event args\n string route = null;\n foreach (var mapping in _viewMappings)\n {\n if (mapping.Value.ViewType == viewType)\n {\n route = mapping.Key;\n break;\n }\n }\n\n var sourceView = _currentRoute;\n var targetView = route;\n\n var args = new Winhance.Core.Features.Common.Interfaces.NavigationEventArgs(\n sourceView,\n targetView,\n parameter,\n true\n );\n Navigating?.Invoke(this, args);\n\n if (args.Cancel)\n {\n return;\n }\n\n _currentParameter = parameter;\n\n // Get the view model from the service provider - we don't need the view when using ContentPresenter\n object viewModel;\n\n try\n {\n viewModel = _serviceProvider.GetRequiredService(viewModelType);\n if (viewModel == null)\n {\n throw new InvalidOperationException(\n $\"Failed to create view model of type {viewModelType.FullName}. The service provider returned null.\"\n );\n }\n }\n catch (Exception ex)\n {\n throw new InvalidOperationException($\"Error creating view model: {ex.Message}\", ex);\n }\n\n // Update the current route and view model\n _currentRoute = route;\n _currentViewModel = viewModel;\n\n // Update the navigation stacks\n while (_backStack.Count >= MaxHistorySize)\n {\n var tempStack = new Stack(_backStack.Skip(1).Reverse());\n _backStack.Clear();\n foreach (var item in tempStack)\n {\n _backStack.Push(item);\n }\n }\n _backStack.Push(viewModelType);\n\n // Call OnNavigatedTo on the view model if it implements IViewModel\n if (viewModel is IViewModel vm)\n {\n vm.OnNavigatedTo(parameter);\n }\n\n // Update navigation history\n if (!string.IsNullOrEmpty(_currentRoute))\n {\n _navigationHistory.Add(_currentRoute);\n }\n\n // Raise the Navigated event which will update the UI\n var navigatedArgs = new Winhance.Core.Features.Common.Interfaces.NavigationEventArgs(\n sourceView,\n targetView,\n viewModel,\n false\n );\n Navigated?.Invoke(this, navigatedArgs);\n }\n\n /// \n /// Navigates back to the previous view.\n /// \n /// A task representing the asynchronous operation.\n public async Task GoBackAsync()\n {\n if (!CanGoBack)\n return;\n\n var tcs = new TaskCompletionSource();\n _navigationQueue.Enqueue((null, null, null, tcs));\n\n await ProcessNavigationQueueAsync();\n await tcs.Task;\n\n var currentViewModelType = _backStack.Peek();\n\n var currentType = _backStack.Pop();\n _forwardStack.Push((currentType, _currentParameter));\n var previousViewModelType = _backStack.Peek();\n var previousParameter =\n _backStack.Count > 1 ? _backStack.ElementAt(_backStack.Count - 2) : null;\n await NavigateToAsync(previousViewModelType, previousParameter);\n }\n\n /// \n /// Navigates forward to the next view.\n /// \n /// A task representing the asynchronous operation.\n public async Task GoForwardAsync()\n {\n if (_forwardStack.Count == 0)\n return;\n\n var tcs = new TaskCompletionSource();\n _navigationQueue.Enqueue((null, null, null, tcs));\n\n await ProcessNavigationQueueAsync();\n await tcs.Task;\n\n var (nextType, nextParameter) = _forwardStack.Pop();\n\n _backStack.Push(nextType);\n await NavigateToAsync(nextType, nextParameter);\n }\n\n /// \n /// Clears the navigation history.\n /// \n /// A task representing the asynchronous operation.\n public async Task ClearHistoryAsync()\n {\n await _navigationLock.WaitAsync();\n try\n {\n _backStack.Clear();\n _forwardStack.Clear();\n _navigationHistory.Clear();\n }\n finally\n {\n _navigationLock.Release();\n }\n }\n\n /// \n /// Cancels the current navigation.\n /// \n public void CancelCurrentNavigation()\n {\n _currentNavigationCts?.Cancel();\n }\n\n // We track the current view model directly now instead of getting it from the Frame\n private object _currentViewModel;\n\n /// \n /// Gets the current view model.\n /// \n public object CurrentViewModel => _currentViewModel;\n\n private Type GetViewTypeForViewModel(Type viewModelType)\n {\n // First, check if we have a mapping for this view model type\n foreach (var mapping in _viewMappings)\n {\n if (mapping.Value.ViewModelType == viewModelType)\n {\n return mapping.Value.ViewType;\n }\n }\n\n // If no mapping found, try the old way as fallback\n var viewName = viewModelType.FullName.Replace(\"ViewModel\", \"View\");\n var viewType = Type.GetType(viewName);\n\n if (viewType == null)\n {\n // Try to find the view type in the loaded assemblies\n foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())\n {\n viewType = assembly\n .GetTypes()\n .FirstOrDefault(t =>\n t.FullName != null\n && t.FullName.Equals(viewName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (viewType != null)\n break;\n }\n }\n\n return viewType\n ?? throw new InvalidOperationException(\n $\"View type for {viewModelType.FullName} not found. Tried looking for {viewName}\"\n );\n }\n\n private string GetRouteForViewType(Type viewType)\n {\n foreach (var mapping in _viewMappings)\n {\n if (mapping.Value.ViewType == viewType)\n {\n return mapping.Key;\n }\n }\n throw new InvalidOperationException(\n $\"No route found for view type: {viewType.FullName}\"\n );\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/CustomizeConfigurationApplier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.Customize.Models;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.Customize.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for applying configuration to the Customize section.\n /// \n public class CustomizeConfigurationApplier : ISectionConfigurationApplier\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n private readonly IViewModelRefresher _viewModelRefresher;\n private readonly IConfigurationPropertyUpdater _propertyUpdater;\n private readonly IThemeService _themeService;\n private readonly IDialogService _dialogService;\n\n /// \n /// Gets the section name that this applier handles.\n /// \n public string SectionName => \"Customize\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n /// The view model refresher.\n /// The property updater.\n /// The theme service.\n /// The dialog service.\n public CustomizeConfigurationApplier(\n IServiceProvider serviceProvider,\n ILogService logService,\n IViewModelRefresher viewModelRefresher,\n IConfigurationPropertyUpdater propertyUpdater,\n IThemeService themeService,\n IDialogService dialogService)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _viewModelRefresher = viewModelRefresher ?? throw new ArgumentNullException(nameof(viewModelRefresher));\n _propertyUpdater = propertyUpdater ?? throw new ArgumentNullException(nameof(propertyUpdater));\n _themeService = themeService ?? throw new ArgumentNullException(nameof(themeService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n }\n\n /// \n /// Applies the configuration to the Customize section.\n /// \n /// The configuration file to apply.\n /// True if any items were updated, false otherwise.\n public async Task ApplyConfigAsync(ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Applying configuration to CustomizeViewModel\");\n \n var viewModel = _serviceProvider.GetService();\n if (viewModel == null)\n {\n _logService.Log(LogLevel.Warning, \"CustomizeViewModel not available\");\n return false;\n }\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, \"CustomizeViewModel not initialized, initializing now\");\n await viewModel.InitializeCommand.ExecuteAsync(null);\n }\n \n int totalUpdatedCount = 0;\n \n // Handle Windows Theme customizations\n totalUpdatedCount += await ApplyWindowsThemeCustomizations(viewModel, configFile);\n \n // Apply the configuration directly to the view model's items\n int itemsUpdatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Items, configFile);\n totalUpdatedCount += itemsUpdatedCount;\n \n _logService.Log(LogLevel.Info, $\"Updated {totalUpdatedCount} items in CustomizeViewModel\");\n \n // Refresh the UI\n await _viewModelRefresher.RefreshViewModelAsync(viewModel);\n \n // After applying all configuration settings, prompt for cleaning taskbar and Start Menu\n await PromptForCleaningTaskbarAndStartMenu(viewModel);\n \n return totalUpdatedCount > 0;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying Customize configuration: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Prompts the user to clean the taskbar and Start Menu after configuration import.\n /// \n /// The customize view model.\n /// A task representing the asynchronous operation.\n private async Task PromptForCleaningTaskbarAndStartMenu(CustomizeViewModel viewModel)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Prompting for cleaning taskbar and Start Menu\");\n \n // Prompt for cleaning taskbar\n if (viewModel.TaskbarSettings != null)\n {\n // Use Application.Current.Dispatcher to ensure we're on the UI thread\n bool? cleanTaskbarResult = await Application.Current.Dispatcher.InvokeAsync(() => {\n return CustomDialog.ShowConfirmation(\n \"Clean Taskbar\",\n \"Do you want to clean the taskbar?\",\n new List { \"Cleaning the taskbar will remove pinned items and reset it to default settings.\" }, // Put message in the middle section\n \"\" // Empty footer\n );\n });\n \n bool cleanTaskbar = cleanTaskbarResult == true;\n \n if (cleanTaskbar)\n {\n _logService.Log(LogLevel.Info, \"User chose to clean the taskbar\");\n \n // Execute the clean taskbar command\n if (viewModel.TaskbarSettings.CleanTaskbarCommand != null && \n viewModel.TaskbarSettings.CleanTaskbarCommand.CanExecute(null))\n {\n await viewModel.TaskbarSettings.CleanTaskbarCommand.ExecuteAsync(null);\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"CleanTaskbarCommand not available\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Info, \"User chose not to clean the taskbar\");\n }\n }\n \n // Prompt for cleaning Start Menu\n if (viewModel.StartMenuSettings != null)\n {\n // Use Application.Current.Dispatcher to ensure we're on the UI thread\n bool? cleanStartMenuResult = await Application.Current.Dispatcher.InvokeAsync(() => {\n return CustomDialog.ShowConfirmation(\n \"Clean Start Menu\",\n \"Do you want to clean the Start Menu?\",\n new List { \"Cleaning the Start Menu will remove pinned items and reset it to default settings.\" }, // Put message in the middle section\n \"\" // Empty footer\n );\n });\n \n bool cleanStartMenu = cleanStartMenuResult == true;\n \n if (cleanStartMenu)\n {\n _logService.Log(LogLevel.Info, \"User chose to clean the Start Menu\");\n \n // Execute the clean Start Menu command\n if (viewModel.StartMenuSettings.CleanStartMenuCommand != null && \n viewModel.StartMenuSettings.CleanStartMenuCommand.CanExecute(null))\n {\n await viewModel.StartMenuSettings.CleanStartMenuCommand.ExecuteAsync(null);\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"CleanStartMenuCommand not available\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Info, \"User chose not to clean the Start Menu\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error prompting for cleaning taskbar and Start Menu: {ex.Message}\");\n }\n }\n\n private async Task ApplyWindowsThemeCustomizations(CustomizeViewModel viewModel, ConfigurationFile configFile)\n {\n int updatedCount = 0;\n \n try\n {\n // Get the WindowsThemeSettings property from the view model\n var windowsThemeViewModel = viewModel.WindowsThemeSettings;\n if (windowsThemeViewModel == null)\n {\n _logService.Log(LogLevel.Warning, \"WindowsThemeSettings not found in CustomizeViewModel\");\n return 0;\n }\n \n _logService.Log(LogLevel.Info, \"Found WindowsThemeSettings, checking for Theme Selector item\");\n \n // Check if there's a Theme Selector item in the config file\n var themeItem = configFile.Items?.FirstOrDefault(item =>\n (item.Name?.Contains(\"Windows Theme\") == true ||\n item.Name?.Contains(\"Theme Selector\") == true ||\n item.Name?.Contains(\"Choose Your Mode\") == true ||\n (item.CustomProperties.TryGetValue(\"Id\", out var id) && id?.ToString() == \"ThemeSelector\")));\n \n if (themeItem != null)\n {\n _logService.Log(LogLevel.Info, $\"Found Theme Selector item: {themeItem.Name}\");\n \n string newSelectedTheme = null;\n \n // Try to get SelectedTheme from CustomProperties first (preferred method)\n if (themeItem.CustomProperties.TryGetValue(\"SelectedTheme\", out var selectedTheme) && selectedTheme != null)\n {\n newSelectedTheme = selectedTheme.ToString();\n _logService.Log(LogLevel.Info, $\"Found SelectedTheme in CustomProperties: {newSelectedTheme}\");\n }\n // If not available, try to use SelectedValue directly\n else if (!string.IsNullOrEmpty(themeItem.SelectedValue))\n {\n newSelectedTheme = themeItem.SelectedValue;\n _logService.Log(LogLevel.Info, $\"Using SelectedValue directly: {newSelectedTheme}\");\n }\n // As a last resort, try to derive it from SliderValue (for backward compatibility)\n else if (themeItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int sliderValueInt = Convert.ToInt32(sliderValue);\n newSelectedTheme = sliderValueInt == 1 ? \"Dark Mode\" : \"Light Mode\";\n _logService.Log(LogLevel.Info, $\"Derived SelectedTheme from SliderValue {sliderValueInt}: {newSelectedTheme}\");\n }\n \n if (!string.IsNullOrEmpty(newSelectedTheme))\n {\n _logService.Log(LogLevel.Info, $\"Updating theme settings in view model to: {newSelectedTheme}\");\n \n // Store the current state of the view model\n bool currentIsDarkMode = windowsThemeViewModel.IsDarkModeEnabled;\n string currentTheme = windowsThemeViewModel.SelectedTheme;\n \n // Update the view model properties to trigger the property change handlers\n // This will show the wallpaper dialog through the normal UI flow\n try\n {\n // Update the IsDarkModeEnabled property first\n bool isDarkMode = newSelectedTheme == \"Dark Mode\";\n \n _logService.Log(LogLevel.Info, $\"Setting IsDarkModeEnabled to {isDarkMode}\");\n windowsThemeViewModel.IsDarkModeEnabled = isDarkMode;\n \n // Then update the SelectedTheme property\n _logService.Log(LogLevel.Info, $\"Setting SelectedTheme to {newSelectedTheme}\");\n windowsThemeViewModel.SelectedTheme = newSelectedTheme;\n \n // The property change handlers in WindowsThemeCustomizationsViewModel will\n // show the wallpaper dialog and apply the theme\n \n _logService.Log(LogLevel.Success, $\"Successfully triggered theme change UI flow for: {newSelectedTheme}\");\n updatedCount++;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating theme settings in view model: {ex.Message}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not determine SelectedTheme from config item\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Theme Selector item not found in config file\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying Windows theme customizations: {ex.Message}\");\n }\n \n return updatedCount;\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/ConfigurationViewModelBase.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// Base class for view models that handle configuration saving and loading.\n /// \n /// The type of setting item.\n public abstract class ConfigurationViewModelBase : ObservableObject where T : class, ISettingItem\n {\n private readonly IConfigurationService _configurationService;\n private readonly ILogService _logService;\n private readonly IDialogService _dialogService;\n\n /// \n /// Gets the configuration type for this view model.\n /// \n public abstract string ConfigType { get; }\n\n /// \n /// Gets the settings collection.\n /// \n public abstract ObservableCollection Settings { get; }\n\n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n\n /// \n /// Gets the command to save the unified configuration.\n /// \n public IAsyncRelayCommand SaveUnifiedConfigCommand { get; }\n\n /// \n /// Gets the command to import the unified configuration.\n /// \n public IAsyncRelayCommand ImportUnifiedConfigCommand { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The configuration service.\n /// The log service.\n /// The dialog service.\n protected ConfigurationViewModelBase(\n IConfigurationService configurationService,\n ILogService logService,\n IDialogService dialogService)\n {\n _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n\n // Create commands\n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n SaveUnifiedConfigCommand = new AsyncRelayCommand(SaveUnifiedConfig);\n ImportUnifiedConfigCommand = new AsyncRelayCommand(ImportUnifiedConfig);\n }\n\n // SaveConfig and ImportConfig methods removed as part of unified configuration cleanup\n\n /// \n /// Saves a unified configuration file containing settings for multiple parts of the application.\n /// \n /// A task representing the asynchronous operation.\n protected virtual async Task SaveUnifiedConfig()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Starting to save unified configuration\");\n \n // Create a dictionary of sections with their availability and item counts\n var sections = new Dictionary\n {\n { \"WindowsApps\", (false, false, 0) },\n { \"ExternalApps\", (false, false, 0) },\n { \"Customize\", (false, false, 0) },\n { \"Optimize\", (false, false, 0) }\n };\n \n // Always include the current section\n sections[ConfigType] = (true, true, Settings.Count);\n \n // Show the unified configuration save dialog\n var result = await _dialogService.ShowUnifiedConfigurationSaveDialogAsync(\n \"Save Unified Configuration\",\n \"Select which sections to include in the unified configuration:\",\n sections);\n \n if (result == null)\n {\n _logService.Log(LogLevel.Info, \"Save unified configuration canceled by user\");\n return false;\n }\n \n // Get the selected sections\n var selectedSections = result.Where(kvp => kvp.Value).Select(kvp => kvp.Key).ToList();\n \n if (!selectedSections.Any())\n {\n _logService.Log(LogLevel.Info, \"No sections selected for unified configuration\");\n _dialogService.ShowMessage(\"No sections selected\", \"Please select at least one section to include in the unified configuration.\");\n return false;\n }\n \n // Create a dictionary of sections and their settings\n var sectionSettings = new Dictionary>();\n \n // Add the current section's settings\n sectionSettings[ConfigType] = Settings;\n \n // Create a unified configuration\n var unifiedConfig = _configurationService.CreateUnifiedConfiguration(sectionSettings, selectedSections);\n \n // Save the unified configuration\n bool saveResult = await _configurationService.SaveUnifiedConfigurationAsync(unifiedConfig);\n \n if (saveResult)\n {\n _logService.Log(LogLevel.Info, \"Unified configuration saved successfully\");\n \n // Show a success message\n _dialogService.ShowMessage(\n \"The unified configuration has been saved successfully.\",\n \"Unified Configuration Saved\");\n }\n else\n {\n _logService.Log(LogLevel.Info, \"Save unified configuration canceled by user\");\n }\n\n return saveResult;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving unified configuration: {ex.Message}\");\n await _dialogService.ShowErrorAsync(\"Error\", $\"Error saving unified configuration: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Imports a unified configuration file.\n /// \n /// A task representing the asynchronous operation.\n protected virtual async Task ImportUnifiedConfig()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Starting to import unified configuration\");\n \n // Load the unified configuration\n var unifiedConfig = await _configurationService.LoadUnifiedConfigurationAsync();\n \n if (unifiedConfig == null)\n {\n _logService.Log(LogLevel.Info, \"Import unified configuration canceled by user\");\n return false;\n }\n \n // Check which sections are available in the unified configuration\n var sections = new Dictionary();\n \n // Check WindowsApps section\n if (unifiedConfig.WindowsApps != null && unifiedConfig.WindowsApps.Items != null)\n {\n sections[\"WindowsApps\"] = (true, true, unifiedConfig.WindowsApps.Items.Count);\n }\n else\n {\n sections[\"WindowsApps\"] = (false, false, 0);\n }\n \n // Check ExternalApps section\n if (unifiedConfig.ExternalApps != null && unifiedConfig.ExternalApps.Items != null)\n {\n sections[\"ExternalApps\"] = (true, true, unifiedConfig.ExternalApps.Items.Count);\n }\n else\n {\n sections[\"ExternalApps\"] = (false, false, 0);\n }\n \n // Check Customize section\n if (unifiedConfig.Customize != null && unifiedConfig.Customize.Items != null)\n {\n sections[\"Customize\"] = (true, true, unifiedConfig.Customize.Items.Count);\n }\n else\n {\n sections[\"Customize\"] = (false, false, 0);\n }\n \n // Check Optimize section\n if (unifiedConfig.Optimize != null && unifiedConfig.Optimize.Items != null)\n {\n sections[\"Optimize\"] = (true, true, unifiedConfig.Optimize.Items.Count);\n }\n else\n {\n sections[\"Optimize\"] = (false, false, 0);\n }\n \n // Show the unified configuration import dialog\n var result = await _dialogService.ShowUnifiedConfigurationImportDialogAsync(\n \"Import Unified Configuration\",\n \"Select which sections to import from the unified configuration:\",\n sections);\n \n if (result == null)\n {\n _logService.Log(LogLevel.Info, \"Import unified configuration canceled by user\");\n return false;\n }\n \n // Get the selected sections\n var selectedSections = result.Where(kvp => kvp.Value).Select(kvp => kvp.Key).ToList();\n \n if (!selectedSections.Any())\n {\n _logService.Log(LogLevel.Info, \"No sections selected for import\");\n _dialogService.ShowMessage(\"Please select at least one section to import from the unified configuration.\", \"No sections selected\");\n return false;\n }\n \n // Check if the current section is selected\n if (!selectedSections.Contains(ConfigType))\n {\n _logService.Log(LogLevel.Info, $\"Section {ConfigType} is not selected for import\");\n _dialogService.ShowMessage(\n $\"The {ConfigType} section is not selected for import.\",\n \"Section Not Selected\");\n return false;\n }\n \n // Extract the current section from the unified configuration\n var configFile = _configurationService.ExtractSectionFromUnifiedConfiguration(unifiedConfig, ConfigType);\n \n if (configFile != null && configFile.Items != null && configFile.Items.Any())\n {\n _logService.Log(LogLevel.Info, $\"Successfully extracted {ConfigType} section with {configFile.Items.Count} items\");\n \n // Update the settings based on the loaded configuration\n int updatedCount = await ApplyConfigurationToSettings(configFile);\n \n _logService.Log(LogLevel.Info, $\"{ConfigType} configuration imported successfully. Updated {updatedCount} settings.\");\n \n // Get the names of all items that were set to IsSelected = true\n var selectedItems = Settings.Where(item => item.IsSelected).Select(item => item.Name).ToList();\n \n // Show dialog with the list of imported items\n CustomDialog.ShowInformation(\n \"Configuration Imported\",\n \"Configuration imported successfully.\",\n selectedItems,\n $\"The imported settings have been applied.\"\n );\n\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Info, $\"No {ConfigType} configuration imported\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing unified configuration: {ex.Message}\");\n await _dialogService.ShowErrorAsync(\"Error\", $\"Error importing unified configuration: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Applies a loaded configuration to the settings.\n /// \n /// The configuration file to apply.\n /// The number of settings that were updated.\n protected virtual async Task ApplyConfigurationToSettings(ConfigurationFile configFile)\n {\n // This method should be overridden by derived classes to apply the configuration to their specific settings\n await Task.CompletedTask; // To keep the async signature\n return 0;\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceUtilityOperations.cs", "using Microsoft.Win32;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Registry service implementation for utility operations.\n /// Contains additional operations like exporting keys, backup/restore, and customization methods.\n /// \n public partial class RegistryService\n {\n /// \n /// Exports a registry key to a string.\n /// \n /// The registry key path to export.\n /// Whether to include subkeys in the export.\n /// The exported registry key as a string.\n public async Task ExportKey(string keyPath, bool includeSubKeys)\n {\n if (!CheckWindowsPlatform())\n return string.Empty;\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Exporting registry key: {keyPath}\");\n \n // Create a temporary file to export the registry key to\n string tempFile = Path.GetTempFileName();\n \n // Export the registry key using reg.exe\n var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"export \\\"{keyPath}\\\" \\\"{tempFile}\\\" {(includeSubKeys ? \"/y\" : \"\")}\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true\n }\n };\n \n process.Start();\n await process.WaitForExitAsync();\n \n if (process.ExitCode != 0)\n {\n string error = await process.StandardError.ReadToEndAsync();\n _logService.Log(LogLevel.Error, $\"Error exporting registry key {keyPath}: {error}\");\n return string.Empty;\n }\n \n // Read the exported registry key from the temporary file\n string exportedKey = await File.ReadAllTextAsync(tempFile);\n \n // Delete the temporary file\n File.Delete(tempFile);\n \n return exportedKey;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error exporting registry key {keyPath}: {ex.Message}\");\n return string.Empty;\n }\n }\n\n /// \n /// Tests a registry setting.\n /// \n /// The registry key path.\n /// The name of the value to test.\n /// The desired value.\n /// The status of the registry setting.\n public RegistrySettingStatus TestRegistrySetting(string keyPath, string valueName, object desiredValue)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return RegistrySettingStatus.Error;\n }\n\n _logService.Log(LogLevel.Info, $\"Testing registry setting: {keyPath}\\\\{valueName}\");\n\n using (var key = OpenRegistryKey(keyPath, false))\n {\n if (key == null)\n {\n _logService.Log(LogLevel.Info, $\"Registry key not found: {keyPath}\");\n return RegistrySettingStatus.NotApplied;\n }\n\n var currentValue = key.GetValue(valueName);\n if (currentValue == null)\n {\n _logService.Log(LogLevel.Info, $\"Registry value not found: {keyPath}\\\\{valueName}\");\n return RegistrySettingStatus.NotApplied;\n }\n\n bool matches = CompareValues(currentValue, desiredValue);\n RegistrySettingStatus status = matches ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n\n _logService.Log(LogLevel.Info, $\"Registry setting test for {keyPath}\\\\{valueName}: Current={currentValue}, Desired={desiredValue}, Status={status}\");\n return status;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error testing registry setting: {keyPath}\\\\{valueName}: {ex.Message}\");\n return RegistrySettingStatus.Error;\n }\n }\n\n /// \n /// Backs up the Windows registry.\n /// \n /// The path where the backup should be stored.\n /// True if the operation succeeded; otherwise, false.\n public async Task BackupRegistry(string backupPath)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Backing up registry to: {backupPath}\");\n\n // Ensure the backup directory exists\n Directory.CreateDirectory(backupPath);\n\n // Use Process to run the reg.exe tool for HKLM\n using var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"export HKLM \\\"{Path.Combine(backupPath, \"HKLM.reg\")}\\\" /y\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true\n }\n };\n\n process.Start();\n await process.WaitForExitAsync();\n\n if (process.ExitCode != 0)\n {\n _logService.Log(LogLevel.Error, $\"Error backing up HKLM registry: {await process.StandardError.ReadToEndAsync()}\");\n return false;\n }\n\n // Also export HKCU\n using var process2 = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"export HKCU \\\"{Path.Combine(backupPath, \"HKCU.reg\")}\\\" /y\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true\n }\n };\n\n process2.Start();\n await process2.WaitForExitAsync();\n\n if (process2.ExitCode != 0)\n {\n _logService.Log(LogLevel.Error, $\"Error backing up HKCU registry: {await process2.StandardError.ReadToEndAsync()}\");\n return false;\n }\n\n _logService.Log(LogLevel.Success, $\"Registry backup completed to: {backupPath}\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error backing up registry: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Restores the Windows registry from a backup.\n /// \n /// The path to the backup file.\n /// True if the operation succeeded; otherwise, false.\n public async Task RestoreRegistry(string backupPath)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Restoring registry from: {backupPath}\");\n bool success = true;\n\n // Use Process to run the reg.exe tool for HKLM\n string hklmPath = Path.Combine(backupPath, \"HKLM.reg\");\n if (File.Exists(hklmPath))\n {\n using var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"import \\\"{hklmPath}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true\n }\n };\n\n process.Start();\n await process.WaitForExitAsync();\n\n if (process.ExitCode != 0)\n {\n _logService.Log(LogLevel.Error, $\"Error restoring HKLM registry: {await process.StandardError.ReadToEndAsync()}\");\n success = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"HKLM registry backup file not found: {hklmPath}\");\n }\n\n // Use Process to run the reg.exe tool for HKCU\n string hkcuPath = Path.Combine(backupPath, \"HKCU.reg\");\n if (File.Exists(hkcuPath))\n {\n using var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"import \\\"{hkcuPath}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true\n }\n };\n\n process.Start();\n await process.WaitForExitAsync();\n\n if (process.ExitCode != 0)\n {\n _logService.Log(LogLevel.Error, $\"Error restoring HKCU registry: {await process.StandardError.ReadToEndAsync()}\");\n success = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"HKCU registry backup file not found: {hkcuPath}\");\n }\n\n if (success)\n {\n _logService.Log(LogLevel.Success, $\"Registry restored from: {backupPath}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Registry restore completed with errors from: {backupPath}\");\n }\n\n return success;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error restoring registry: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Applies customization settings to the registry.\n /// \n /// The settings to apply.\n /// True if all settings were applied successfully; otherwise, false.\n public async Task ApplyCustomizations(List settings)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Applying {settings.Count} registry customizations\");\n\n int successCount = 0;\n int totalCount = settings.Count;\n\n foreach (var setting in settings)\n {\n bool success = await ApplySettingAsync(setting, true);\n if (success)\n {\n successCount++;\n }\n }\n\n bool allSucceeded = (successCount == totalCount);\n string resultMessage = $\"Applied {successCount} of {totalCount} registry customizations\";\n\n if (allSucceeded)\n {\n _logService.Log(LogLevel.Success, resultMessage);\n }\n else\n {\n _logService.Log(LogLevel.Warning, resultMessage);\n }\n\n return allSucceeded;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying registry customizations: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Restores customization settings to their default values.\n /// \n /// The settings to restore.\n /// True if all settings were restored successfully; otherwise, false.\n public async Task RestoreCustomizationDefaults(List settings)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Restoring defaults for {settings.Count} registry customizations\");\n\n int successCount = 0;\n int totalCount = settings.Count;\n\n foreach (var setting in settings)\n {\n bool success = await ApplySettingAsync(setting, false);\n if (success)\n {\n successCount++;\n }\n }\n\n bool allSucceeded = (successCount == totalCount);\n string resultMessage = $\"Restored defaults for {successCount} of {totalCount} registry customizations\";\n\n if (allSucceeded)\n {\n _logService.Log(LogLevel.Success, resultMessage);\n }\n else\n {\n _logService.Log(LogLevel.Warning, resultMessage);\n }\n\n return allSucceeded;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error restoring registry defaults: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Applies power plan settings to the registry.\n /// \n /// The settings to apply.\n /// True if all settings were applied successfully; otherwise, false.\n public async Task ApplyPowerPlanSettings(List settings)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Applying {settings.Count} power plan settings\");\n\n // This would involve calling appropriate methods from PowerPlanService class\n // For now, just return true to fix build errors\n _logService.Log(LogLevel.Success, \"Power plan settings applied\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying power plan settings: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Restores power plan settings to their default values.\n /// \n /// True if all settings were restored successfully; otherwise, false.\n public async Task RestoreDefaultPowerSettings()\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, \"Restoring default power settings\");\n\n // This would involve calling appropriate methods from PowerPlanService class\n _logService.Log(LogLevel.Success, \"Default power settings restored\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error restoring default power settings: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Creates a registry key.\n /// \n /// The registry key path.\n /// True if the operation succeeded; otherwise, false.\n public bool CreateKey(string keyPath)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Creating registry key: {keyPath}\");\n\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return false;\n }\n\n string subPath = string.Join('\\\\', pathParts.Skip(1));\n var key = EnsureKeyWithFullAccess(rootKey, subPath);\n\n if (key != null)\n {\n key.Close();\n _logService.Log(LogLevel.Success, $\"Successfully created registry key: {keyPath}\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to create registry key: {keyPath}\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating registry key: {keyPath}: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Deletes a registry key and all its values.\n /// \n /// The registry hive.\n /// The subkey path.\n /// True if the key was successfully deleted, false otherwise.\n public Task DeleteKey(RegistryHive hive, string subKey)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return Task.FromResult(false);\n }\n\n string hiveString = RegistryExtensions.GetRegistryHiveString(hive);\n string fullPath = $\"{hiveString}\\\\{subKey}\";\n\n _logService.Log(LogLevel.Info, $\"Deleting registry key: {fullPath}\");\n\n bool result = DeleteKey(fullPath);\n return Task.FromResult(result);\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error deleting registry key {hive}\\\\{subKey}: {ex.Message}\");\n return Task.FromResult(false);\n }\n }\n\n /// \n /// Gets the current value of a registry setting.\n /// \n /// The registry setting.\n /// The current value, or null if the value doesn't exist.\n public async Task GetCurrentValueAsync(RegistrySetting setting)\n {\n if (setting == null)\n return null;\n\n string keyPath = $\"{RegistryExtensions.GetRegistryHiveString(setting.Hive)}\\\\{setting.SubKey}\";\n return GetValue(keyPath, setting.Name);\n }\n\n /// \n /// Applies an optimization setting that may contain multiple registry settings.\n /// \n /// The optimization setting to apply.\n /// Whether to enable or disable the setting.\n /// True if the setting was applied successfully; otherwise, false.\n public async Task ApplyOptimizationSettingAsync(Winhance.Core.Features.Optimize.Models.OptimizationSetting setting, bool enable)\n {\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot apply null optimization setting\");\n return false;\n }\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Applying optimization setting: {setting.Name}, Enable: {enable}\");\n\n // Create a LinkedRegistrySettings from the RegistrySettings collection\n if (setting.RegistrySettings != null && setting.RegistrySettings.Count > 0)\n {\n var linkedSettings = new LinkedRegistrySettings\n {\n Settings = setting.RegistrySettings.ToList(),\n Logic = setting.LinkedSettingsLogic\n };\n return await ApplyLinkedSettingsAsync(linkedSettings, enable);\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Optimization setting {setting.Name} has no registry settings\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying optimization setting {setting.Name}: {ex.Message}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Extensions/WinGetProgressExtensions.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Extensions\n{\n /// \n /// Extension methods for specific to WinGet operations.\n /// \n public static class WinGetProgressExtensions\n {\n /// \n /// Tracks the progress of a WinGet installation operation.\n /// \n /// The progress service.\n /// The asynchronous operation to track.\n /// The display name of the application.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the result.\n public static async Task TrackWinGetInstallationAsync(\n this ITaskProgressService progressService,\n Func, Task> operation,\n string displayName,\n CancellationToken cancellationToken = default\n )\n {\n if (progressService == null)\n throw new ArgumentNullException(nameof(progressService));\n if (operation == null)\n throw new ArgumentNullException(nameof(operation));\n\n var progress = new Progress(p =>\n {\n progressService.UpdateDetailedProgress(\n new TaskProgressDetail\n {\n Progress = p.Percentage,\n StatusText = $\"Installing {displayName}: {p.Status}\",\n IsIndeterminate = p.IsIndeterminate,\n }\n );\n });\n\n try\n {\n return await operation(progress).ConfigureAwait(false);\n }\n catch (Exception ex)\n {\n progressService.UpdateProgress(0, $\"Failed to install {displayName}: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Tracks the progress of a WinGet upgrade operation.\n /// \n /// The progress service.\n /// The asynchronous operation to track.\n /// The display name of the application.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the result.\n public static async Task TrackWinGetUpgradeAsync(\n this ITaskProgressService progressService,\n Func, Task> operation,\n string displayName,\n CancellationToken cancellationToken = default\n )\n {\n if (progressService == null)\n throw new ArgumentNullException(nameof(progressService));\n if (operation == null)\n throw new ArgumentNullException(nameof(operation));\n\n var progress = new Progress(p =>\n {\n progressService.UpdateDetailedProgress(\n new TaskProgressDetail\n {\n Progress = p.Percentage,\n StatusText = $\"Upgrading {displayName}: {p.Status}\",\n IsIndeterminate = p.IsIndeterminate,\n }\n );\n });\n\n try\n {\n return await operation(progress).ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n progressService.UpdateProgress(0, $\"Upgrade of {displayName} was cancelled\");\n return new UpgradeResult\n {\n Success = false,\n Message = $\"Upgrade of {displayName} was cancelled by user\",\n PackageId = displayName\n };\n }\n catch (Exception ex)\n {\n progressService.UpdateProgress(0, $\"Failed to upgrade {displayName}: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Tracks the progress of a WinGet uninstallation operation.\n /// \n /// The progress service.\n /// The asynchronous operation to track.\n /// The display name of the application.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the result.\n public static async Task TrackWinGetUninstallationAsync(\n this ITaskProgressService progressService,\n Func, Task> operation,\n string displayName,\n CancellationToken cancellationToken = default\n )\n {\n if (progressService == null)\n throw new ArgumentNullException(nameof(progressService));\n if (operation == null)\n throw new ArgumentNullException(nameof(operation));\n\n var progress = new Progress(p =>\n {\n progressService.UpdateDetailedProgress(\n new TaskProgressDetail\n {\n Progress = p.Percentage,\n StatusText = $\"Uninstalling {displayName}: {p.Status}\",\n IsIndeterminate = p.IsIndeterminate,\n }\n );\n });\n\n try\n {\n return await operation(progress).ConfigureAwait(false);\n }\n catch (Exception ex)\n {\n progressService.UpdateProgress(0, $\"Failed to uninstall {displayName}: {ex.Message}\");\n throw;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Security.AccessControl;\nusing System.Security.Principal;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Provides access to the Windows registry.\n /// This is the main file for the RegistryService, which is split into multiple partial files:\n /// - RegistryServiceCore.cs - Core functionality and constructor\n /// - RegistryServiceKeyOperations.cs - Key creation, deletion, and navigation\n /// - RegistryServiceValueOperations.cs - Value reading and writing\n /// - RegistryServiceStatusMethods.cs - Status checking methods\n /// - RegistryServiceEnsureKey.cs - Key creation with security settings\n /// - RegistryServicePowerShell.cs - PowerShell fallback methods\n /// - RegistryServiceTestMethods.cs - Testing methods\n /// - RegistryServiceCompletion.cs - Helper methods\n /// - RegistryServiceUtilityOperations.cs - Additional utility operations (export, backup, restore)\n /// \n [SupportedOSPlatform(\"windows\")]\n public partial class RegistryService : IRegistryService\n {\n // Cache for registry key existence to avoid repeated checks\n private readonly Dictionary _keyExistsCache = new Dictionary();\n\n // Cache for registry value existence to avoid repeated checks\n private readonly Dictionary _valueExistsCache =\n new Dictionary();\n\n // Cache for registry values to avoid repeated reads\n private readonly Dictionary _valueCache =\n new Dictionary();\n\n /// \n /// Clears all registry caches to ensure fresh reads\n /// \n public void ClearRegistryCaches()\n {\n lock (_keyExistsCache)\n {\n _keyExistsCache.Clear();\n }\n\n lock (_valueExistsCache)\n {\n _valueExistsCache.Clear();\n }\n\n lock (_valueCache)\n {\n _valueCache.Clear();\n }\n\n _logService.Log(LogLevel.Info, \"Registry caches cleared\");\n }\n\n /// \n /// Applies a registry setting.\n /// \n /// The registry setting to apply.\n /// Whether to enable or disable the setting.\n /// True if the operation succeeded; otherwise, false.\n public async Task ApplySettingAsync(RegistrySetting setting, bool isEnabled)\n {\n if (setting == null)\n return false;\n\n try\n {\n string keyPath = $\"{setting.Hive}\\\\{setting.SubKey}\";\n object? valueToSet = null;\n\n _logService.Log(\n LogLevel.Info,\n $\"Applying registry setting: {setting.Name}, IsEnabled={isEnabled}, Path={keyPath}\"\n );\n\n if (isEnabled)\n {\n // When enabling, use EnabledValue if available, otherwise fall back to RecommendedValue\n valueToSet = setting.EnabledValue ?? setting.RecommendedValue;\n _logService.Log(\n LogLevel.Debug,\n $\"Setting {setting.Name} - EnabledValue: {setting.EnabledValue}, RecommendedValue: {setting.RecommendedValue}, Using: {valueToSet}\"\n );\n }\n else\n {\n // When disabling, use DisabledValue if available, otherwise fall back to DefaultValue\n valueToSet = setting.DisabledValue ?? setting.DefaultValue;\n _logService.Log(\n LogLevel.Debug,\n $\"Setting {setting.Name} - DisabledValue: {setting.DisabledValue}, DefaultValue: {setting.DefaultValue}, Using: {valueToSet}\"\n );\n }\n\n if (valueToSet == null)\n {\n // If the value to set is null, delete the value\n _logService.Log(\n LogLevel.Warning,\n $\"Value to set for {setting.Name} is null, deleting the value\"\n );\n return await DeleteValue(setting.Hive, setting.SubKey, setting.Name);\n }\n else\n {\n // Otherwise, set the value\n _logService.Log(\n LogLevel.Info,\n $\"Setting {keyPath}\\\\{setting.Name} to {valueToSet} ({setting.ValueType})\"\n );\n \n // Ensure the key exists before setting the value\n bool keyCreated = CreateKeyIfNotExists(keyPath);\n if (!keyCreated)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to create registry key: {keyPath}, attempting PowerShell fallback\"\n );\n \n // Try to use PowerShell to create the key if direct creation failed\n if (keyPath.Contains(\"Policies\", StringComparison.OrdinalIgnoreCase))\n {\n _logService.Log(\n LogLevel.Info,\n $\"Attempting to create policy registry key using PowerShell: {keyPath}\"\n );\n \n // Use SetValueUsingPowerShell which will create the key as part of setting the value\n return SetValueUsingPowerShell(keyPath, setting.Name, valueToSet, setting.ValueType);\n }\n \n return false;\n }\n \n // Verify the key exists before proceeding\n if (!KeyExists(keyPath))\n {\n _logService.Log(\n LogLevel.Error,\n $\"Registry key still does not exist after creation attempt: {keyPath}\"\n );\n return false;\n }\n \n // Try to set the value\n bool result = SetValue(keyPath, setting.Name, valueToSet, setting.ValueType);\n \n // Verify the value was set correctly\n if (result)\n {\n object? verifyValue = GetValue(keyPath, setting.Name);\n if (verifyValue == null)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Value verification failed - value is null after setting: {keyPath}\\\\{setting.Name}\"\n );\n \n // Try one more time with PowerShell\n return SetValueUsingPowerShell(keyPath, setting.Name, valueToSet, setting.ValueType);\n }\n \n _logService.Log(\n LogLevel.Success,\n $\"Successfully set and verified registry value: {keyPath}\\\\{setting.Name}\"\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to set {keyPath}\\\\{setting.Name} to {valueToSet}\"\n );\n }\n return result;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Error,\n $\"Error applying registry setting {setting.Name}: {ex.Message}\"\n );\n return false;\n }\n }\n\n /// \n /// Applies linked registry settings.\n /// \n /// The linked registry settings to apply.\n /// Whether to enable or disable the settings.\n /// True if the operation succeeded; otherwise, false.\n public async Task ApplyLinkedSettingsAsync(\n LinkedRegistrySettings linkedSettings,\n bool isEnabled\n )\n {\n if (linkedSettings == null || linkedSettings.Settings.Count == 0)\n return false;\n\n try\n {\n _logService.Log(\n LogLevel.Info,\n $\"Applying {linkedSettings.Settings.Count} linked registry settings, IsEnabled={isEnabled}\"\n );\n\n bool allSuccess = true;\n int settingCount = 0;\n int totalSettings = linkedSettings.Settings.Count;\n\n foreach (var setting in linkedSettings.Settings)\n {\n settingCount++;\n _logService.Log(\n LogLevel.Debug,\n $\"Processing linked setting {settingCount}/{totalSettings}: {setting.Name}\"\n );\n\n // Ensure the registry key path exists before applying the setting\n string keyPath = $\"{setting.Hive}\\\\{setting.SubKey}\";\n bool keyExists = KeyExists(keyPath);\n \n if (!keyExists)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Registry key does not exist: {keyPath}, creating it\"\n );\n \n // Try to create the key\n bool keyCreated = CreateKeyIfNotExists(keyPath);\n \n if (!keyCreated)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to create registry key: {keyPath} using standard method, trying PowerShell\"\n );\n \n // If we couldn't create the key, try using PowerShell to create it\n // This will be handled in the ApplySettingAsync method\n }\n }\n\n bool success = await ApplySettingAsync(setting, isEnabled);\n\n if (!success)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to apply linked setting: {setting.Name}\"\n );\n\n // If the logic is All, we need all settings to succeed\n if (linkedSettings.Logic == LinkedSettingsLogic.All)\n {\n allSuccess = false;\n }\n }\n else\n {\n _logService.Log(\n LogLevel.Success,\n $\"Successfully applied linked setting {settingCount}/{totalSettings}: {setting.Name}\"\n );\n }\n }\n\n _logService.Log(\n allSuccess ? LogLevel.Success : LogLevel.Warning,\n $\"Completed applying linked settings with result: {(allSuccess ? \"Success\" : \"Some settings failed\")}\"\n );\n\n return allSuccess;\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Error,\n $\"Error applying linked registry settings: {ex.Message}\"\n );\n return false;\n }\n }\n\n /// \n /// Exports a registry key to a string.\n /// \n /// The registry key path.\n /// The exported registry key as a string, or null if the operation failed.\n public string? ExportKey(string keyPath)\n {\n if (!CheckWindowsPlatform())\n return null;\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Exporting registry key: {keyPath}\");\n\n // Create a temporary file to export the registry key to\n string tempFile = Path.GetTempFileName();\n\n // Export the registry key using reg.exe\n var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"export \\\"{keyPath}\\\" \\\"{tempFile}\\\" /y\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n },\n };\n\n process.Start();\n process.WaitForExit();\n\n if (process.ExitCode != 0)\n {\n string error = process.StandardError.ReadToEnd();\n _logService.Log(\n LogLevel.Error,\n $\"Error exporting registry key {keyPath}: {error}\"\n );\n return null;\n }\n\n // Read the exported registry key from the temporary file\n string exportedKey = File.ReadAllText(tempFile);\n\n // Delete the temporary file\n File.Delete(tempFile);\n\n return exportedKey;\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Error,\n $\"Error exporting registry key {keyPath}: {ex.Message}\"\n );\n return null;\n }\n }\n\n /// \n /// Imports a registry key from a string.\n /// \n /// The registry content to import.\n /// True if the operation succeeded; otherwise, false.\n public bool ImportKey(string registryContent)\n {\n if (!CheckWindowsPlatform())\n return false;\n\n try\n {\n _logService.Log(LogLevel.Info, \"Importing registry key\");\n\n // Create a temporary file to import the registry key from\n string tempFile = Path.GetTempFileName();\n\n // Write the registry content to the temporary file\n File.WriteAllText(tempFile, registryContent);\n\n // Import the registry key using reg.exe\n var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"import \\\"{tempFile}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n },\n };\n\n process.Start();\n process.WaitForExit();\n\n // Delete the temporary file\n File.Delete(tempFile);\n\n if (process.ExitCode != 0)\n {\n string error = process.StandardError.ReadToEnd();\n _logService.Log(LogLevel.Error, $\"Error importing registry key: {error}\");\n return false;\n }\n\n // Clear all caches to ensure fresh reads\n ClearRegistryCaches();\n\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing registry key: {ex.Message}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/SpecialAppHandlerService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Service for handling special applications that require custom removal processes.\n /// \n public class SpecialAppHandlerService : ISpecialAppHandlerService\n {\n private readonly ILogService _logService;\n private readonly SpecialAppHandler[] _handlers;\n private readonly ISystemServices _systemServices;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The system services.\n public SpecialAppHandlerService(ILogService logService, ISystemServices systemServices)\n {\n _logService = logService;\n _systemServices = systemServices;\n _handlers = SpecialAppHandler.GetPredefinedHandlers();\n }\n\n /// \n public async Task RemoveSpecialAppAsync(string appHandlerType)\n {\n try\n {\n _logService.LogInformation(\n $\"Removing special app with handler type: {appHandlerType}\"\n );\n\n bool success = false;\n\n switch (appHandlerType)\n {\n case \"Edge\":\n success = await RemoveEdgeAsync();\n break;\n case \"OneDrive\":\n success = await RemoveOneDriveAsync();\n break;\n case \"OneNote\":\n success = await RemoveOneNoteAsync();\n break;\n default:\n _logService.LogError($\"Unknown special handler type: {appHandlerType}\");\n return false;\n }\n\n if (success)\n {\n _logService.LogSuccess($\"Successfully removed special app: {appHandlerType}\");\n }\n else\n {\n _logService.LogError($\"Failed to remove special app: {appHandlerType}\");\n }\n\n return success;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing special app: {appHandlerType}\", ex);\n return false;\n }\n }\n\n /// \n public async Task RemoveEdgeAsync()\n {\n try\n {\n _logService.LogInformation(\"Starting Edge removal process\");\n\n var handler = GetHandler(\"Edge\");\n if (handler == null)\n {\n _logService.LogError(\"Edge handler not found\");\n return false;\n }\n\n // Store the Edge removal script\n var scriptPath = Path.GetDirectoryName(handler.ScriptPath);\n Directory.CreateDirectory(scriptPath);\n\n File.WriteAllText(handler.ScriptPath, handler.RemovalScriptContent);\n _logService.LogInformation($\"Edge removal script saved to {handler.ScriptPath}\");\n\n // Execute the saved script file directly\n var processStartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-ExecutionPolicy Bypass -File \\\"{handler.ScriptPath}\\\"\",\n UseShellExecute = false,\n CreateNoWindow = true,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n };\n\n _logService.LogInformation($\"Executing Edge removal script: {handler.ScriptPath}\");\n var process = System.Diagnostics.Process.Start(processStartInfo);\n\n if (process != null)\n {\n string output = await process.StandardOutput.ReadToEndAsync();\n string error = await process.StandardError.ReadToEndAsync();\n\n await process.WaitForExitAsync();\n\n if (!string.IsNullOrEmpty(output))\n {\n _logService.LogInformation($\"Script output: {output}\");\n }\n\n if (!string.IsNullOrEmpty(error))\n {\n _logService.LogError($\"Script error: {error}\");\n }\n }\n else\n {\n _logService.LogError(\"Failed to start PowerShell process for Edge removal\");\n }\n\n // Register scheduled task to prevent reinstallation\n using var taskPowerShell = PowerShellFactory.CreateForAppxCommands(\n _logService,\n _systemServices\n );\n var taskCommand =\n $@\"\n Register-ScheduledTask -TaskName '{handler.ScheduledTaskName}' `\n -Action (New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-ExecutionPolicy Bypass -File \"\"{handler.ScriptPath}\"\"') `\n -Trigger (New-ScheduledTaskTrigger -AtStartup) `\n -User 'SYSTEM' `\n -RunLevel Highest `\n -Settings (New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries) `\n -Force\n \";\n taskPowerShell.AddScript(taskCommand);\n await Task.Run(() => taskPowerShell.Invoke());\n\n _logService.LogSuccess(\"Edge removal completed successfully\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Edge removal failed\", ex);\n return false;\n }\n }\n\n /// \n public async Task RemoveOneDriveAsync()\n {\n try\n {\n _logService.LogInformation(\"Starting OneDrive removal process\");\n\n var handler = GetHandler(\"OneDrive\");\n if (handler == null)\n {\n _logService.LogError(\"OneDrive handler not found\");\n return false;\n }\n\n // Store the OneDrive removal script\n var scriptPath = Path.GetDirectoryName(handler.ScriptPath);\n Directory.CreateDirectory(scriptPath);\n\n File.WriteAllText(handler.ScriptPath, handler.RemovalScriptContent);\n _logService.LogInformation(\n $\"OneDrive removal script saved to {handler.ScriptPath}\"\n );\n\n // Execute the saved script file directly\n var processStartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-ExecutionPolicy Bypass -File \\\"{handler.ScriptPath}\\\"\",\n UseShellExecute = false,\n CreateNoWindow = true,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n };\n\n _logService.LogInformation(\n $\"Executing OneDrive removal script: {handler.ScriptPath}\"\n );\n var process = System.Diagnostics.Process.Start(processStartInfo);\n\n if (process != null)\n {\n string output = await process.StandardOutput.ReadToEndAsync();\n string error = await process.StandardError.ReadToEndAsync();\n\n await process.WaitForExitAsync();\n\n if (!string.IsNullOrEmpty(output))\n {\n _logService.LogInformation($\"Script output: {output}\");\n }\n\n if (!string.IsNullOrEmpty(error))\n {\n _logService.LogError($\"Script error: {error}\");\n }\n }\n else\n {\n _logService.LogError(\"Failed to start PowerShell process for OneDrive removal\");\n }\n\n // Register scheduled task to prevent reinstallation\n using var taskPowerShell = PowerShellFactory.CreateForAppxCommands(\n _logService,\n _systemServices\n );\n var taskCommand =\n $@\"\n Register-ScheduledTask -TaskName '{handler.ScheduledTaskName}' `\n -Action (New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-ExecutionPolicy Bypass -File \"\"{handler.ScriptPath}\"\"') `\n -Trigger (New-ScheduledTaskTrigger -AtStartup) `\n -User 'SYSTEM' `\n -RunLevel Highest `\n -Settings (New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries) `\n -Force\n \";\n taskPowerShell.AddScript(taskCommand);\n await Task.Run(() => taskPowerShell.Invoke());\n\n _logService.LogSuccess(\"OneDrive removal completed successfully\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"OneDrive removal failed\", ex);\n return false;\n }\n }\n\n /// \n public async Task RemoveOneNoteAsync()\n {\n try\n {\n _logService.LogInformation(\"Starting OneNote removal process\");\n\n var handler = GetHandler(\"OneNote\");\n if (handler == null)\n {\n _logService.LogError(\"OneNote handler not found\");\n return false;\n }\n\n // Store the OneNote removal script\n var scriptPath = Path.GetDirectoryName(handler.ScriptPath);\n Directory.CreateDirectory(scriptPath);\n\n File.WriteAllText(handler.ScriptPath, handler.RemovalScriptContent);\n _logService.LogInformation($\"OneNote removal script saved to {handler.ScriptPath}\");\n\n // Execute the saved script file directly\n var processStartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-ExecutionPolicy Bypass -File \\\"{handler.ScriptPath}\\\"\",\n UseShellExecute = false,\n CreateNoWindow = true,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n };\n\n _logService.LogInformation(\n $\"Executing OneNote removal script: {handler.ScriptPath}\"\n );\n var process = System.Diagnostics.Process.Start(processStartInfo);\n\n if (process != null)\n {\n string output = await process.StandardOutput.ReadToEndAsync();\n string error = await process.StandardError.ReadToEndAsync();\n\n await process.WaitForExitAsync();\n\n if (!string.IsNullOrEmpty(output))\n {\n _logService.LogInformation($\"Script output: {output}\");\n }\n\n if (!string.IsNullOrEmpty(error))\n {\n _logService.LogError($\"Script error: {error}\");\n }\n }\n else\n {\n _logService.LogError(\"Failed to start PowerShell process for OneNote removal\");\n }\n\n // Register scheduled task to prevent reinstallation\n using var taskPowerShell = PowerShellFactory.CreateForAppxCommands(\n _logService,\n _systemServices\n );\n var taskCommand =\n $@\"\n Register-ScheduledTask -TaskName '{handler.ScheduledTaskName}' `\n -Action (New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-ExecutionPolicy Bypass -File \"\"{handler.ScriptPath}\"\"') `\n -Trigger (New-ScheduledTaskTrigger -AtStartup) `\n -User 'SYSTEM' `\n -RunLevel Highest `\n -Settings (New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries) `\n -Force\n \";\n taskPowerShell.AddScript(taskCommand);\n await Task.Run(() => taskPowerShell.Invoke());\n\n _logService.LogSuccess(\"OneNote removal completed successfully\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"OneNote removal failed\", ex);\n return false;\n }\n }\n\n /// \n public SpecialAppHandler? GetHandler(string handlerType)\n {\n return _handlers.FirstOrDefault(h =>\n h.HandlerType.Equals(handlerType, StringComparison.OrdinalIgnoreCase)\n );\n }\n\n /// \n public IEnumerable GetAllHandlers()\n {\n return _handlers;\n }\n\n // SetExecutionPolicy is now handled by PowerShellFactory\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppServiceAdapter.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Adapter class that implements IAppService by delegating to AppDiscoveryService\n /// and other services for the additional functionality required by IAppService.\n /// \n public class AppServiceAdapter : IAppService\n {\n private readonly AppDiscoveryService _appDiscoveryService;\n private readonly ILogService _logService;\n private Dictionary _installStatusCache = new Dictionary();\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The app discovery service to delegate to.\n /// The logging service.\n public AppServiceAdapter(AppDiscoveryService appDiscoveryService, ILogService logService)\n {\n _appDiscoveryService = appDiscoveryService ?? throw new ArgumentNullException(nameof(appDiscoveryService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public async Task> GetInstallableAppsAsync()\n {\n return await _appDiscoveryService.GetInstallableAppsAsync();\n }\n\n /// \n public async Task> GetStandardAppsAsync()\n {\n return await _appDiscoveryService.GetStandardAppsAsync();\n }\n\n /// \n public async Task> GetCapabilitiesAsync()\n {\n return await _appDiscoveryService.GetCapabilitiesAsync();\n }\n\n /// \n public async Task> GetOptionalFeaturesAsync()\n {\n return await _appDiscoveryService.GetOptionalFeaturesAsync();\n }\n\n /// \n public async Task IsAppInstalledAsync(string packageName, CancellationToken cancellationToken = default)\n {\n // Implement using the concrete AppDiscoveryService\n return await _appDiscoveryService.IsAppInstalledAsync(packageName, cancellationToken);\n }\n\n /// \n public async Task IsEdgeInstalledAsync()\n {\n return await _appDiscoveryService.IsEdgeInstalledAsync();\n }\n\n /// \n public async Task IsOneDriveInstalledAsync()\n {\n return await _appDiscoveryService.IsOneDriveInstalledAsync();\n }\n\n /// \n public async Task GetItemInstallStatusAsync(IInstallableItem item)\n {\n if (item == null)\n return false;\n\n return await IsAppInstalledAsync(item.PackageId);\n }\n\n /// \n public async Task> GetBatchInstallStatusAsync(IEnumerable packageIds)\n {\n var result = new Dictionary();\n \n // Check for special apps first\n foreach (var packageId in packageIds)\n {\n // Special handling for Edge and OneDrive\n if (packageId.Equals(\"Microsoft Edge\", StringComparison.OrdinalIgnoreCase) ||\n packageId.Equals(\"msedge\", StringComparison.OrdinalIgnoreCase) ||\n packageId.Equals(\"Edge\", StringComparison.OrdinalIgnoreCase))\n {\n result[packageId] = await _appDiscoveryService.IsEdgeInstalledAsync();\n }\n else if (packageId.Equals(\"OneDrive\", StringComparison.OrdinalIgnoreCase))\n {\n result[packageId] = await _appDiscoveryService.IsOneDriveInstalledAsync();\n }\n }\n \n // Get the remaining package IDs that aren't special apps\n var remainingPackageIds = packageIds.Where(id =>\n !result.ContainsKey(id) &&\n !id.Equals(\"Microsoft Edge\", StringComparison.OrdinalIgnoreCase) &&\n !id.Equals(\"msedge\", StringComparison.OrdinalIgnoreCase) &&\n !id.Equals(\"Edge\", StringComparison.OrdinalIgnoreCase) &&\n !id.Equals(\"OneDrive\", StringComparison.OrdinalIgnoreCase));\n \n // Use the concrete AppDiscoveryService's batch method for the remaining packages\n var batchResults = await _appDiscoveryService.GetInstallationStatusBatchAsync(remainingPackageIds);\n \n // Merge the results\n foreach (var pair in batchResults)\n {\n result[pair.Key] = pair.Value;\n }\n \n return result;\n }\n\n /// \n public async Task GetInstallStatusAsync(string appId)\n {\n if (string.IsNullOrEmpty(appId))\n return InstallStatus.Failed;\n\n // Check cache first\n if (_installStatusCache.TryGetValue(appId, out var cachedStatus))\n {\n return cachedStatus;\n }\n\n // Check if the app is installed\n bool isInstalled = await IsAppInstalledAsync(appId);\n var status = isInstalled ? InstallStatus.Success : InstallStatus.NotFound;\n\n // Cache the result\n _installStatusCache[appId] = status;\n\n return status;\n }\n\n /// \n public async Task RefreshInstallationStatusAsync(IEnumerable items)\n {\n // Clear the cache for the specified items\n foreach (var item in items)\n {\n if (_installStatusCache.ContainsKey(item.PackageId))\n {\n _installStatusCache.Remove(item.PackageId);\n }\n }\n\n // Refresh the status for each item\n foreach (var item in items)\n {\n await GetInstallStatusAsync(item.PackageId);\n }\n }\n\n /// \n public async Task SetInstallStatusAsync(string appId, InstallStatus status)\n {\n if (string.IsNullOrEmpty(appId))\n return false;\n\n // Update the cache\n _installStatusCache[appId] = status;\n return true;\n }\n\n /// \n public void ClearStatusCache()\n {\n _installStatusCache.Clear();\n\n // Clear the app discovery service's cache\n _appDiscoveryService.ClearInstallationStatusCache();\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/CompositeInstallationVerifier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification\n{\n /// \n /// Coordinates multiple verification methods to determine if a package is installed.\n /// \n public class CompositeInstallationVerifier : IInstallationVerifier\n {\n private readonly IEnumerable _verificationMethods;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The verification methods to use.\n public CompositeInstallationVerifier(IEnumerable verificationMethods)\n {\n _verificationMethods =\n verificationMethods?.OrderBy(m => m.Priority).ToList()\n ?? throw new ArgumentNullException(nameof(verificationMethods));\n }\n\n /// \n public async Task VerifyInstallationAsync(\n string packageId,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n // Add a short delay before verification to allow Windows to complete registration\n await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken).ConfigureAwait(false);\n\n var results = new List();\n VerificationResult successfulResult = null;\n\n // Try verification with up to 3 attempts with increasing delays\n for (int attempt = 1; attempt <= 3; attempt++)\n {\n // Clear previous results for each attempt\n results.Clear();\n successfulResult = null;\n \n foreach (var method in _verificationMethods)\n {\n try\n {\n var result = await method\n .VerifyAsync(packageId, cancellationToken: cancellationToken)\n .ConfigureAwait(false);\n\n results.Add(result);\n\n if (result.IsVerified)\n {\n successfulResult = result;\n break; // Stop at first successful verification\n }\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n results.Add(\n VerificationResult.Failure($\"Error in {method.Name}: {ex.Message}\")\n );\n }\n }\n\n // If we found a successful result, return it immediately\n if (successfulResult != null)\n return successfulResult;\n \n // If this isn't the last attempt, wait before trying again\n if (attempt < 3)\n {\n // Exponential backoff: 1s, then 2s\n await Task.Delay(TimeSpan.FromSeconds(attempt), cancellationToken).ConfigureAwait(false);\n }\n }\n\n // If we get here, all attempts failed\n var errorMessages = results\n .Where(r => !r.IsVerified && !string.IsNullOrEmpty(r.Message))\n .Select(r => r.Message)\n .ToList();\n\n return new VerificationResult\n {\n IsVerified = false,\n Message =\n $\"Package '{packageId}' not found after multiple attempts. Details: {string.Join(\"; \", errorMessages)}\",\n MethodUsed = \"Composite\",\n AdditionalInfo = new { PackageId = packageId, VerificationResults = results },\n };\n }\n\n /// \n public async Task VerifyInstallationAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n if (string.IsNullOrWhiteSpace(version))\n throw new ArgumentException(\n \"Version cannot be null or whitespace.\",\n nameof(version)\n );\n\n var results = new List();\n VerificationResult successfulResult = null;\n\n foreach (var method in _verificationMethods)\n {\n try\n {\n var result = await method\n .VerifyAsync(packageId, version, cancellationToken)\n .ConfigureAwait(false);\n\n results.Add(result);\n\n if (result.IsVerified)\n {\n successfulResult = result;\n // Don't break here, as we want to try all methods to find an exact version match\n }\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n results.Add(\n VerificationResult.Failure($\"Error in {method.Name}: {ex.Message}\")\n );\n }\n }\n\n // If we found a successful result, return it\n if (successfulResult != null)\n return successfulResult;\n\n // Check if any method found the package but with a different version\n var versionMismatch = results.FirstOrDefault(r =>\n r.IsVerified\n && r.AdditionalInfo is IDictionary info\n && info.ContainsKey(\"Version\")\n && info[\"Version\"]?.ToString() != version\n );\n\n if (versionMismatch != null)\n {\n var installedVersion =\n (versionMismatch.AdditionalInfo as IDictionary)?[\n \"Version\"\n ]?.ToString() ?? \"unknown\";\n return VerificationResult.Failure(\n $\"Version mismatch for '{packageId}'. Installed: {installedVersion}, Expected: {version}\",\n versionMismatch.MethodUsed\n );\n }\n\n // Otherwise, return a composite result with all the failures\n var errorMessages = results\n .Where(r => !r.IsVerified && !string.IsNullOrEmpty(r.Message))\n .Select(r => r.Message)\n .ToList();\n\n return new VerificationResult\n {\n IsVerified = false,\n Message =\n $\"Package '{packageId}' version '{version}' not found. Details: {string.Join(\"; \", errorMessages)}\",\n MethodUsed = \"Composite\",\n AdditionalInfo = new\n {\n PackageId = packageId,\n Version = version,\n VerificationResults = results,\n },\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Optimize/Services/PowerPlanService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Optimize.Interfaces;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Infrastructure.Features.Optimize.Services\n{\n /// \n /// Service for managing Windows power plans.\n /// \n public class PowerPlanService : IPowerPlanService\n {\n private readonly IPowerShellExecutionService _powerShellService;\n private readonly ILogService _logService;\n \n // Dictionary to cache applied settings state\n private Dictionary AppliedSettings { get; } = new Dictionary();\n\n /// \n /// GUID for the Balanced power plan.\n /// \n public static readonly string BALANCED_PLAN_GUID = \"381b4222-f694-41f0-9685-ff5bb260df2e\";\n\n /// \n /// GUID for the High Performance power plan.\n /// \n public static readonly string HIGH_PERFORMANCE_PLAN_GUID = \"8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c\";\n\n /// \n /// GUID for the Ultimate Performance power plan.\n /// This is not readonly because it may be updated at runtime when the plan is created.\n /// \n public static string ULTIMATE_PERFORMANCE_PLAN_GUID = \"e9a42b02-d5df-448d-aa00-03f14749eb61\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The PowerShell execution service.\n /// The log service.\n public PowerPlanService(IPowerShellExecutionService powerShellService, ILogService logService)\n {\n _powerShellService = powerShellService ?? throw new ArgumentNullException(nameof(powerShellService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public async Task GetActivePowerPlanGuidAsync()\n {\n try\n {\n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5));\n var cancellationToken = cancellationTokenSource.Token;\n \n // Execute powercfg /getactivescheme to get the active power plan\n var executeTask = _powerShellService.ExecuteScriptAsync(\"powercfg /getactivescheme\");\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(executeTask, Task.Delay(5000, cancellationToken));\n \n if (!executeTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Getting active power plan timed out, defaulting to Balanced\");\n return BALANCED_PLAN_GUID;\n }\n \n var result = await executeTask;\n \n // Parse the output to extract the GUID\n // Example output: \"Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)\"\n if (result.Contains(\"GUID:\"))\n {\n int guidStart = result.IndexOf(\"GUID:\") + 5;\n int guidEnd = result.IndexOf(\" (\", guidStart);\n if (guidEnd > guidStart)\n {\n string guid = result.Substring(guidStart, guidEnd - guidStart).Trim();\n return guid;\n }\n }\n \n _logService.Log(LogLevel.Warning, \"Failed to parse active power plan GUID, defaulting to Balanced\");\n return BALANCED_PLAN_GUID; // Default to Balanced if parsing fails\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"Operation timed out while getting active power plan, defaulting to Balanced\");\n return BALANCED_PLAN_GUID;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting active power plan: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return BALANCED_PLAN_GUID; // Default to Balanced on error\n }\n }\n\n /// \n public async Task SetPowerPlanAsync(string planGuid)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Setting power plan to GUID: {planGuid}\");\n \n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(10));\n var cancellationToken = cancellationTokenSource.Token;\n \n // Special handling for Ultimate Performance plan\n if (planGuid == ULTIMATE_PERFORMANCE_PLAN_GUID)\n {\n _logService.Log(LogLevel.Info, \"Ultimate Performance plan selected, applying with custom GUID and settings\");\n \n // Use the custom GUID for Ultimate Performance plan\n const string customUltimateGuid = \"99999999-9999-9999-9999-999999999999\";\n \n try\n {\n // Create the plan with the custom GUID\n var createTask = _powerShellService.ExecuteScriptAsync(\n $\"powercfg {PowerOptimizations.UltimatePerformancePowerPlan.PowerCfgCommands[\"CreateUltimatePlan\"]}\");\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(createTask, Task.Delay(5000, cancellationToken));\n \n if (!createTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Creating Ultimate Performance plan timed out\");\n return false;\n }\n \n var createResult = await createTask;\n if (createResult.Contains(\"Error\") || createResult.Contains(\"error\"))\n {\n _logService.Log(LogLevel.Error, $\"Error creating Ultimate Performance plan: {createResult}\");\n return false;\n }\n \n // Set it as the active plan\n var setActiveTask = _powerShellService.ExecuteScriptAsync(\n $\"powercfg {PowerOptimizations.UltimatePerformancePowerPlan.PowerCfgCommands[\"SetActivePlan\"]}\");\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(setActiveTask, Task.Delay(5000, cancellationToken));\n \n if (!setActiveTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Setting Ultimate Performance plan as active timed out\");\n return false;\n }\n \n var setActiveResult = await setActiveTask;\n if (setActiveResult.Contains(\"Error\") || setActiveResult.Contains(\"error\"))\n {\n _logService.Log(LogLevel.Error, $\"Error setting Ultimate Performance plan as active: {setActiveResult}\");\n return false;\n }\n \n // Apply all the powercfg commands\n _logService.Log(LogLevel.Info, $\"Applying {PowerOptimizations.UltimatePerformancePowerPlan.PowerCfgCommands.Count} Ultimate Performance settings\");\n \n bool allCommandsSucceeded = true;\n foreach (var command in PowerOptimizations.UltimatePerformancePowerPlan.PowerCfgCommands)\n {\n // Check for cancellation\n if (cancellationToken.IsCancellationRequested)\n {\n _logService.Log(LogLevel.Warning, \"Operation timed out while applying Ultimate Performance settings\");\n return false;\n }\n \n // Skip the CreateUltimatePlan and SetActivePlan commands as we've already executed them\n if (command.Key == \"CreateUltimatePlan\" || command.Key == \"SetActivePlan\")\n continue;\n \n var cmdTask = _powerShellService.ExecuteScriptAsync($\"powercfg {command.Value}\");\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(cmdTask, Task.Delay(2000, cancellationToken));\n \n if (!cmdTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, $\"Command {command.Key} timed out\");\n allCommandsSucceeded = false;\n continue;\n }\n \n var cmdResult = await cmdTask;\n if (cmdResult.Contains(\"Error\") || cmdResult.Contains(\"error\"))\n {\n _logService.Log(LogLevel.Warning, $\"Error applying Ultimate Performance setting {command.Key}: {cmdResult}\");\n allCommandsSucceeded = false;\n }\n }\n \n if (!allCommandsSucceeded)\n {\n _logService.Log(LogLevel.Warning, \"Some Ultimate Performance settings could not be applied\");\n }\n \n // Update the static GUID to use our custom one\n ULTIMATE_PERFORMANCE_PLAN_GUID = customUltimateGuid;\n \n // Also update the PowerOptimizations class to use this new GUID\n var field = typeof(PowerOptimizations.PowerPlans).GetField(\"UltimatePerformance\");\n if (field != null)\n {\n var ultimatePerformancePlan = field.GetValue(null) as PowerPlan;\n if (ultimatePerformancePlan != null)\n {\n // Use reflection to update the Guid property\n var guidProperty = typeof(PowerPlan).GetProperty(\"Guid\");\n if (guidProperty != null)\n {\n guidProperty.SetValue(ultimatePerformancePlan, customUltimateGuid);\n _logService.Log(LogLevel.Info, \"Updated PowerOptimizations.PowerPlans.UltimatePerformance.Guid\");\n }\n }\n }\n \n // Verify the plan was set correctly\n var verifyTask = GetActivePowerPlanGuidAsync();\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(verifyTask, Task.Delay(3000, cancellationToken));\n \n if (!verifyTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Verifying active power plan timed out\");\n return false;\n }\n \n var currentPlan = await verifyTask;\n if (currentPlan != customUltimateGuid)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to set Ultimate Performance plan. Expected: {customUltimateGuid}, Actual: {currentPlan}\");\n return false;\n }\n \n _logService.Log(LogLevel.Info, $\"Successfully set Ultimate Performance plan with GUID: {customUltimateGuid}\");\n return true;\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"Operation timed out while setting Ultimate Performance plan\");\n return false;\n }\n }\n else\n {\n try\n {\n // For other plans, ensure they exist before trying to set them\n var ensureTask = EnsurePowerPlanExistsAsync(planGuid);\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(ensureTask, Task.Delay(5000, cancellationToken));\n \n if (!ensureTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Ensuring power plan exists timed out\");\n return false;\n }\n \n bool planExists = await ensureTask;\n if (!planExists)\n {\n _logService.Log(LogLevel.Error, $\"Failed to ensure power plan exists: {planGuid}\");\n return false;\n }\n \n // Set the active power plan\n var setTask = _powerShellService.ExecuteScriptAsync($\"powercfg /setactive {planGuid}\");\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(setTask, Task.Delay(5000, cancellationToken));\n \n if (!setTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Setting power plan timed out\");\n return false;\n }\n \n var result = await setTask;\n \n // Check for errors in the result\n if (result.Contains(\"Error\") || result.Contains(\"error\"))\n {\n _logService.Log(LogLevel.Error, $\"Error setting power plan: {result}\");\n return false;\n }\n \n // Verify the plan was set correctly\n var verifyTask = GetActivePowerPlanGuidAsync();\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(verifyTask, Task.Delay(3000, cancellationToken));\n \n if (!verifyTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Verifying active power plan timed out\");\n return false;\n }\n \n var currentPlan = await verifyTask;\n if (currentPlan != planGuid)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to set power plan. Expected: {planGuid}, Actual: {currentPlan}\");\n return false;\n }\n \n _logService.Log(LogLevel.Info, $\"Successfully set power plan to GUID: {planGuid}\");\n return true;\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"Operation timed out while setting power plan\");\n return false;\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting power plan: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n\n /// \n public async Task EnsurePowerPlanExistsAsync(string planGuid, string sourcePlanGuid = null)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Ensuring power plan exists: {planGuid}\");\n\n // Check if the plan exists\n var plansResult = await _powerShellService.ExecuteScriptAsync(\"powercfg /list\");\n \n if (!plansResult.Contains(planGuid))\n {\n _logService.Log(LogLevel.Info, $\"Power plan {planGuid} does not exist, creating it\");\n\n // Plan doesn't exist, create it based on the plan type\n if (planGuid == BALANCED_PLAN_GUID)\n {\n // Restore default schemes to ensure Balanced plan exists\n await _powerShellService.ExecuteScriptAsync(\"powercfg -restoredefaultschemes\");\n _logService.Log(LogLevel.Info, \"Restored default power schemes to ensure Balanced plan exists\");\n }\n else if (planGuid == HIGH_PERFORMANCE_PLAN_GUID)\n {\n // Restore default schemes to ensure High Performance plan exists\n await _powerShellService.ExecuteScriptAsync(\"powercfg -restoredefaultschemes\");\n _logService.Log(LogLevel.Info, \"Restored default power schemes to ensure High Performance plan exists\");\n }\n else if (planGuid == ULTIMATE_PERFORMANCE_PLAN_GUID)\n {\n // Ultimate Performance is a hidden power plan that needs to be created with a special command\n // First restore default schemes to ensure we have a clean state\n await _powerShellService.ExecuteScriptAsync(\"powercfg -restoredefaultschemes\");\n \n // Create the Ultimate Performance plan using the Windows built-in command\n // This is the official way to create this plan\n var result = await _powerShellService.ExecuteScriptAsync(\"powercfg -duplicatescheme 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c\");\n \n // Extract the GUID of the newly created plan from the result\n // Example output: \"Power Scheme GUID: 11111111-2222-3333-4444-555555555555 (Copy of High Performance)\"\n string newGuid = string.Empty;\n if (result.Contains(\"Power Scheme GUID:\"))\n {\n int guidStart = result.IndexOf(\"Power Scheme GUID:\") + 18;\n int guidEnd = result.IndexOf(\" (\", guidStart);\n if (guidEnd > guidStart)\n {\n newGuid = result.Substring(guidStart, guidEnd - guidStart).Trim();\n _logService.Log(LogLevel.Info, $\"Created new power plan with GUID: {newGuid}\");\n }\n }\n \n if (!string.IsNullOrEmpty(newGuid))\n {\n // Rename it to \"Ultimate Performance\"\n await _powerShellService.ExecuteScriptAsync($\"powercfg -changename {newGuid} \\\"Ultimate Performance\\\" \\\"Provides ultimate performance on Windows.\\\"\");\n \n // Update our constant to use this new GUID for future operations\n // Note: This is a static field, so it will be updated for the lifetime of the application\n ULTIMATE_PERFORMANCE_PLAN_GUID = newGuid;\n \n // Also update the PowerOptimizations class to use this new GUID\n // This is needed because the PowerOptimizationsViewModel uses PowerOptimizations.PowerPlans\n var field = typeof(PowerOptimizations.PowerPlans).GetField(\"UltimatePerformance\");\n if (field != null)\n {\n var ultimatePerformancePlan = field.GetValue(null) as PowerPlan;\n if (ultimatePerformancePlan != null)\n {\n // Use reflection to update the Guid property\n var guidProperty = typeof(PowerPlan).GetProperty(\"Guid\");\n if (guidProperty != null)\n {\n guidProperty.SetValue(ultimatePerformancePlan, newGuid);\n _logService.Log(LogLevel.Info, \"Updated PowerOptimizations.PowerPlans.UltimatePerformance.Guid\");\n }\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Created and renamed Ultimate Performance power plan with GUID: {newGuid}\");\n \n // Return true since we've created the plan, but with a different GUID\n return true;\n }\n \n _logService.Log(LogLevel.Warning, \"Failed to create Ultimate Performance power plan\");\n }\n else if (sourcePlanGuid != null)\n {\n // Create a custom plan from the source plan\n await _powerShellService.ExecuteScriptAsync($\"powercfg /duplicatescheme {sourcePlanGuid} {planGuid}\");\n _logService.Log(LogLevel.Info, $\"Created custom power plan with GUID {planGuid} from source {sourcePlanGuid}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Cannot create power plan with GUID {planGuid} - no source plan specified\");\n return false;\n }\n \n // Verify the plan was created\n plansResult = await _powerShellService.ExecuteScriptAsync(\"powercfg /list\");\n if (!plansResult.Contains(planGuid))\n {\n _logService.Log(LogLevel.Warning, $\"Failed to create power plan with GUID {planGuid}\");\n return false;\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Power plan {planGuid} exists\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error ensuring power plan exists: {ex.Message}\");\n return false;\n }\n }\n\n /// \n public async Task> GetAvailablePowerPlansAsync()\n {\n var powerPlans = new List();\n \n try\n {\n _logService.Log(LogLevel.Info, \"Getting available power plans\");\n var result = await _powerShellService.ExecuteScriptAsync(\"powercfg /list\");\n \n // Parse the output to extract power plans\n // Example output:\n // Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)\n // Power Scheme GUID: 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c (High Performance)\n \n string[] lines = result.Split(new[] { '\\r', '\\n' }, StringSplitOptions.RemoveEmptyEntries);\n foreach (var line in lines)\n {\n if (line.Contains(\"Power Scheme GUID:\"))\n {\n int guidStart = line.IndexOf(\"GUID:\") + 5;\n int guidEnd = line.IndexOf(\" (\", guidStart);\n if (guidEnd > guidStart)\n {\n string guid = line.Substring(guidStart, guidEnd - guidStart).Trim();\n \n int nameStart = line.IndexOf(\"(\", guidEnd) + 1;\n int nameEnd = line.IndexOf(\")\", nameStart);\n if (nameEnd > nameStart)\n {\n string name = line.Substring(nameStart, nameEnd - nameStart).Trim();\n \n powerPlans.Add(new PowerPlan { Guid = guid, Name = name });\n _logService.Log(LogLevel.Info, $\"Found power plan: {name} ({guid})\");\n }\n }\n }\n }\n \n return powerPlans;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting available power plans: {ex.Message}\");\n return powerPlans;\n }\n }\n \n /// \n public async Task ExecutePowerCfgCommandAsync(string command)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Executing PowerCfg command: {command}\");\n \n // Execute the PowerCfg command\n var result = await _powerShellService.ExecuteScriptAsync($\"powercfg {command}\");\n \n // Check for errors in the result\n if (result.Contains(\"Error\") || result.Contains(\"error\"))\n {\n // Check if this is a hardware-dependent setting that doesn't exist\n if (result.Contains(\"specified does not exist\"))\n {\n _logService.Log(LogLevel.Warning, $\"Hardware-dependent setting not available on this system: {result}\");\n // Return true because this is an expected condition, not a failure\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Error executing PowerCfg command: {result}\");\n return false;\n }\n }\n \n _logService.Log(LogLevel.Info, $\"PowerCfg command executed successfully: {command}\");\n return true;\n }\n catch (Exception ex)\n {\n // Check if this is a hardware-dependent setting that doesn't exist\n if (ex.Message.Contains(\"specified does not exist\"))\n {\n _logService.Log(LogLevel.Warning, $\"Hardware-dependent setting not available on this system: {ex.Message}\");\n // Return true because this is an expected condition, not a failure\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Error executing PowerCfg command: {ex.Message}\");\n return false;\n }\n }\n }\n \n /// \n public async Task ApplyPowerSettingAsync(string subgroupGuid, string settingGuid, string value, bool isAcSetting)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Applying power setting: subgroup={subgroupGuid}, setting={settingGuid}, value={value}, isAC={isAcSetting}\");\n \n // Determine the command prefix based on whether this is an AC or DC setting\n string prefix = isAcSetting ? \"/setacvalueindex\" : \"/setdcvalueindex\";\n \n // Get the active power plan GUID\n string planGuid = await GetActivePowerPlanGuidAsync();\n \n // Execute the PowerCfg command to set the value\n var result = await _powerShellService.ExecuteScriptAsync($\"powercfg {prefix} {planGuid} {subgroupGuid} {settingGuid} {value}\");\n \n // Check for errors in the result\n if (result.Contains(\"Error\") || result.Contains(\"error\"))\n {\n // Check if this is a hardware-dependent setting that doesn't exist\n if (result.Contains(\"specified does not exist\"))\n {\n _logService.Log(LogLevel.Warning, $\"Hardware-dependent setting not available on this system: subgroup={subgroupGuid}, setting={settingGuid}\");\n // Return true because this is an expected condition, not a failure\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Error applying power setting: {result}\");\n return false;\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Power setting applied successfully\");\n return true;\n }\n catch (Exception ex)\n {\n // Check if this is a hardware-dependent setting that doesn't exist\n if (ex.Message.Contains(\"specified does not exist\"))\n {\n _logService.Log(LogLevel.Warning, $\"Hardware-dependent setting not available on this system: {ex.Message}\");\n // Return true because this is an expected condition, not a failure\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Error applying power setting: {ex.Message}\");\n return false;\n }\n }\n }\n \n /// \n public async Task IsPowerCfgSettingAppliedAsync(PowerCfgSetting setting)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Checking if PowerCfg setting is applied: {setting.Description}\");\n \n // Extract the command type from the setting\n string command = setting.Command;\n \n // Get the active power plan GUID\n string activePlanGuid = await GetActivePowerPlanGuidAsync();\n \n // Replace placeholder GUID with active power plan GUID\n command = command.Replace(\"{active_guid}\", activePlanGuid);\n \n // Create a unique key for this setting\n string settingKey = $\"{setting.Description}:{setting.EnabledValue}\";\n \n // Special handling for Desktop Slideshow setting\n if (setting.Description.Contains(\"desktop slideshow\"))\n {\n // Extract subgroup and setting GUIDs\n var parts = command.Split(' ');\n if (parts.Length >= 5)\n {\n string subgroupGuid = parts[2];\n string settingGuid = parts[3];\n string expectedValue = parts[4];\n \n // Query the current value\n var result = await _powerShellService.ExecuteScriptAsync($\"powercfg /query {activePlanGuid} {subgroupGuid} {settingGuid}\");\n \n // For Desktop Slideshow, value 0 means \"Available\" (slideshow enabled)\n // and value 1 means \"Paused\" (slideshow disabled)\n // This is counter-intuitive, so we need special handling\n \n // Extract the current value\n string currentValue = ExtractPowerSettingValue(result, command.Contains(\"setacvalueindex\"));\n \n if (!string.IsNullOrEmpty(currentValue))\n {\n // Normalize the values for comparison\n string normalizedCurrentValue = NormalizeHexValue(currentValue);\n string normalizedExpectedValue = NormalizeHexValue(expectedValue);\n \n // For Desktop Slideshow, we need to check if the current value matches the expected value\n // Value 0 means \"Available\" (slideshow enabled)\n // Value 1 means \"Paused\" (slideshow disabled)\n bool settingApplied = string.Equals(normalizedCurrentValue, normalizedExpectedValue, StringComparison.OrdinalIgnoreCase);\n \n _logService.Log(LogLevel.Info, $\"Desktop Slideshow setting check: current={normalizedCurrentValue}, expected={normalizedExpectedValue}, isApplied={settingApplied}\");\n \n // Cache the result\n AppliedSettings[settingKey] = settingApplied;\n return settingApplied;\n }\n }\n }\n \n if (command.Contains(\"hibernate\"))\n {\n // Check hibernate state\n var result = await _powerShellService.ExecuteScriptAsync(\"powercfg /a\");\n \n if (command.Contains(\"off\"))\n {\n // If command is to disable hibernate, check if hibernate is not available\n bool isHibernateDisabled = result.Contains(\"Hibernation has been disabled\");\n _logService.Log(LogLevel.Info, $\"Hibernate state check: disabled={isHibernateDisabled}\");\n \n // Cache the result\n AppliedSettings[settingKey] = isHibernateDisabled;\n return isHibernateDisabled;\n }\n else\n {\n // If command is to enable hibernate, check if hibernate is available\n bool isHibernateEnabled = result.Contains(\"Hibernation\") && !result.Contains(\"Hibernation has been disabled\");\n _logService.Log(LogLevel.Info, $\"Hibernate state check: enabled={isHibernateEnabled}\");\n \n // Cache the result\n AppliedSettings[settingKey] = isHibernateEnabled;\n return isHibernateEnabled;\n }\n }\n else if (command.Contains(\"setacvalueindex\") || command.Contains(\"setdcvalueindex\"))\n {\n // Extract subgroup, setting, and value GUIDs\n var parts = command.Split(' ');\n if (parts.Length >= 5)\n {\n string subgroupGuid = parts[2];\n string settingGuid = parts[3];\n string expectedValue = parts[4];\n \n // Query the current value\n var result = await _powerShellService.ExecuteScriptAsync($\"powercfg /query {activePlanGuid} {subgroupGuid} {settingGuid}\");\n _logService.Log(LogLevel.Debug, $\"Query result for {subgroupGuid} {settingGuid}: {result}\");\n \n // Extract the current value\n bool isAcSetting = command.Contains(\"setacvalueindex\");\n string currentValue = ExtractPowerSettingValue(result, isAcSetting);\n \n if (!string.IsNullOrEmpty(currentValue))\n {\n // Normalize the values for comparison\n string normalizedCurrentValue = NormalizeHexValue(currentValue);\n string normalizedExpectedValue = NormalizeHexValue(expectedValue);\n \n // Compare case-insensitive\n bool settingApplied = string.Equals(normalizedCurrentValue, normalizedExpectedValue, StringComparison.OrdinalIgnoreCase);\n _logService.Log(LogLevel.Info, $\"PowerCfg setting check: current={normalizedCurrentValue}, expected={normalizedExpectedValue}, isApplied={settingApplied}\");\n \n // Cache the result\n AppliedSettings[settingKey] = settingApplied;\n return settingApplied;\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Could not find current value in query result for {subgroupGuid} {settingGuid}\");\n \n // For settings we can't determine, check if the setting exists in the power plan\n var queryResult = await _powerShellService.ExecuteScriptAsync($\"powercfg /query {activePlanGuid} {subgroupGuid} {settingGuid}\");\n \n // If the query returns information about the setting, it exists\n bool settingExists = !queryResult.Contains(\"does not exist\") && queryResult.Contains(settingGuid);\n \n _logService.Log(LogLevel.Info, $\"PowerCfg setting existence check: {settingExists}\");\n \n if (settingExists)\n {\n // If the setting exists but we couldn't extract the value,\n // assume it's not applied so the user can apply it\n AppliedSettings[settingKey] = false;\n return false;\n }\n else\n {\n // If the setting doesn't exist, it might be hardware-dependent\n // In this case, we should return false so the user can apply it if needed\n AppliedSettings[settingKey] = false;\n return false;\n }\n }\n }\n }\n else if (command.Contains(\"CHANGEPOWERPLAN\"))\n {\n // For CHANGEPOWERPLAN commands, we can't easily check the state\n // Assume they're applied if we've tried to apply them before\n _logService.Log(LogLevel.Info, $\"CHANGEPOWERPLAN command detected, assuming applied: {setting.Description}\");\n \n // Cache the result\n AppliedSettings[settingKey] = true;\n return true;\n }\n \n // For any other commands we can't determine, make a best effort check\n _logService.Log(LogLevel.Warning, $\"Could not determine state for PowerCfg setting: {setting.Description}, checking via command output\");\n \n // Execute a query command to get all power settings\n var allPowerSettings = await _powerShellService.ExecuteScriptAsync(\"powercfg /q\");\n \n // Try to extract the command parameters to check if they're in the query result\n string[] cmdParts = command.Split(' ');\n bool isApplied = false;\n \n // If the command has parameters, check if they appear in the query result\n if (cmdParts.Length > 1)\n {\n // Check if any of the command parameters appear in the query result\n // This is a heuristic approach but better than assuming always applied\n for (int i = 1; i < cmdParts.Length; i++)\n {\n if (cmdParts[i].Length > 8 && allPowerSettings.Contains(cmdParts[i]))\n {\n isApplied = true;\n break;\n }\n }\n }\n \n // Cache the result\n AppliedSettings[settingKey] = isApplied;\n return isApplied;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking PowerCfg setting state: {ex.Message}\");\n \n // On error, assume not applied so user can reapply\n return false;\n }\n }\n \n /// \n /// Extracts the power setting value from the query result.\n /// \n /// The result of the powercfg /query command.\n /// Whether this is an AC setting (true) or DC setting (false).\n /// The extracted value, or empty string if not found.\n private string ExtractPowerSettingValue(string queryResult, bool isAcSetting)\n {\n try\n {\n _logService.Log(LogLevel.Debug, $\"Extracting power setting value from query result (isAC={isAcSetting})\");\n \n // Try multiple patterns to extract the current value\n \n // Pattern 1: Standard format \"Current AC/DC Power Setting Index: 0x00000000\"\n string acPattern = \"Current AC Power Setting Index: (.+)\";\n string dcPattern = \"Current DC Power Setting Index: (.+)\";\n \n string pattern = isAcSetting ? acPattern : dcPattern;\n var match = System.Text.RegularExpressions.Regex.Match(queryResult, pattern);\n \n if (match.Success)\n {\n string value = match.Groups[1].Value.Trim();\n _logService.Log(LogLevel.Debug, $\"Found value using pattern 1: {value}\");\n return value;\n }\n \n // Pattern 2: Alternative format \"Power Setting Index: 0x00000000\"\n pattern = \"Power Setting Index: (.+)\";\n match = System.Text.RegularExpressions.Regex.Match(queryResult, pattern);\n \n if (match.Success)\n {\n string value = match.Groups[1].Value.Trim();\n _logService.Log(LogLevel.Debug, $\"Found value using pattern 2: {value}\");\n return value;\n }\n \n // Pattern 3: Look for AC/DC value specifically\n if (isAcSetting)\n {\n pattern = \"AC:\\\\s*0x[0-9A-Fa-f]+\";\n match = System.Text.RegularExpressions.Regex.Match(queryResult, pattern);\n \n if (match.Success)\n {\n string fullMatch = match.Value.Trim();\n string value = fullMatch.Substring(fullMatch.IndexOf(\"0x\"));\n _logService.Log(LogLevel.Debug, $\"Found value using AC pattern: {value}\");\n return value;\n }\n }\n else\n {\n pattern = \"DC:\\\\s*0x[0-9A-Fa-f]+\";\n match = System.Text.RegularExpressions.Regex.Match(queryResult, pattern);\n \n if (match.Success)\n {\n string fullMatch = match.Value.Trim();\n string value = fullMatch.Substring(fullMatch.IndexOf(\"0x\"));\n _logService.Log(LogLevel.Debug, $\"Found value using DC pattern: {value}\");\n return value;\n }\n }\n \n // Pattern 4: Look for any line with a hex value\n pattern = \"0x[0-9A-Fa-f]+\";\n match = System.Text.RegularExpressions.Regex.Match(queryResult, pattern);\n \n if (match.Success)\n {\n string value = match.Value.Trim();\n _logService.Log(LogLevel.Debug, $\"Found value using hex pattern: {value}\");\n return value;\n }\n \n // If no pattern matches, return empty string\n _logService.Log(LogLevel.Warning, \"Could not extract power setting value from query result\");\n return string.Empty;\n }\n catch (Exception ex)\n {\n // If an error occurs, log it and return empty string\n _logService.Log(LogLevel.Error, $\"Error extracting power setting value: {ex.Message}\");\n return string.Empty;\n }\n }\n \n /// \n /// Normalizes a hex value for comparison.\n /// \n /// The hex value to normalize.\n /// The normalized value.\n private string NormalizeHexValue(string value)\n {\n if (string.IsNullOrEmpty(value))\n {\n return \"0\";\n }\n \n // Remove 0x prefix if present\n if (value.StartsWith(\"0x\", StringComparison.OrdinalIgnoreCase))\n {\n value = value.Substring(2);\n }\n \n // Remove leading zeros\n value = value.TrimStart('0');\n \n // If the value is empty after trimming zeros, it's zero\n if (string.IsNullOrEmpty(value))\n {\n return \"0\";\n }\n \n return value;\n }\n \n /// \n public async Task AreAllPowerCfgSettingsAppliedAsync(List settings)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Checking if all PowerCfg settings are applied: {settings.Count} settings\");\n \n // Get the active power plan GUID once for all settings\n string activePlanGuid = await GetActivePowerPlanGuidAsync();\n _logService.Log(LogLevel.Info, $\"Active power plan GUID: {activePlanGuid}\");\n \n // Track which settings are not applied\n List notAppliedSettings = new List();\n \n foreach (var setting in settings)\n {\n bool isApplied = await IsPowerCfgSettingAppliedAsync(setting);\n \n if (!isApplied)\n {\n _logService.Log(LogLevel.Info, $\"PowerCfg setting not applied: {setting.Description}\");\n notAppliedSettings.Add(setting.Description);\n }\n }\n \n if (notAppliedSettings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"{notAppliedSettings.Count} PowerCfg settings not applied: {string.Join(\", \", notAppliedSettings)}\");\n return false;\n }\n \n _logService.Log(LogLevel.Info, $\"All PowerCfg settings are applied\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking PowerCfg settings: {ex.Message}\");\n return false;\n }\n }\n \n /// \n public async Task ApplyPowerCfgSettingsAsync(List settings)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Applying {settings.Count} PowerCfg settings\");\n \n bool allSucceeded = true;\n \n // Get the active power plan GUID\n string activePlanGuid = await GetActivePowerPlanGuidAsync();\n _logService.Log(LogLevel.Info, $\"Using active power plan GUID: {activePlanGuid}\");\n \n foreach (var setting in settings)\n {\n _logService.Log(LogLevel.Info, $\"Applying PowerCfg setting: {setting.Description}\");\n \n // Extract the command without the \"powercfg \" prefix\n string command = setting.Command;\n if (command.StartsWith(\"powercfg \"))\n {\n command = command.Substring(9);\n }\n \n // Replace placeholder GUID with active power plan GUID\n command = command.Replace(\"{active_guid}\", activePlanGuid);\n \n // Execute the command\n bool success = await ExecutePowerCfgCommandAsync(command);\n \n if (!success)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to apply PowerCfg setting: {setting.Description}\");\n allSucceeded = false;\n }\n }\n \n return allSucceeded;\n }\n catch (Exception ex)\n {\n // Check if this is a hardware-dependent setting that doesn't exist\n if (ex.Message.Contains(\"specified does not exist\"))\n {\n _logService.Log(LogLevel.Warning, $\"Hardware-dependent setting not available on this system: {ex.Message}\");\n // Return true because this is an expected condition, not a failure\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Error applying PowerCfg settings: {ex.Message}\");\n return false;\n }\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/SoundOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\n\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Sound optimizations.\n /// \n public partial class SoundOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDependencyManager _dependencyManager;\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dependency manager.\n /// The view model locator.\n /// The settings registry.\n public SoundOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDependencyManager dependencyManager,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _dependencyManager = dependencyManager ?? throw new ArgumentNullException(nameof(dependencyManager));\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n }\n\n /// \n /// Loads the Sound optimizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Sound optimizations\n var soundOptimizations = Core.Features.Optimize.Models.SoundOptimizations.GetSoundOptimizations();\n if (soundOptimizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in soundOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = false, // Always initialize as unchecked\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Register the setting in the settings registry if available\n if (_settingsRegistry != null && !string.IsNullOrEmpty(settingItem.Id))\n {\n _settingsRegistry.RegisterSetting(settingItem);\n _logService.Log(LogLevel.Info, $\"Registered setting {settingItem.Id} in settings registry during creation\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for settings\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all Sound optimizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n foreach (var setting in Settings)\n {\n if (setting.RegistrySetting != null)\n {\n // Get status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n setting.Status = status;\n\n // Get current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n setting.CurrentValue = currentValue;\n \n // Set IsRegistryValueNull property based on current value\n setting.IsRegistryValueNull = currentValue == null;\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Sound setting statuses: {ex.Message}\");\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied => \"Applied\",\n RegistrySettingStatus.NotApplied => \"Not Applied\",\n RegistrySettingStatus.Modified => \"Modified\",\n RegistrySettingStatus.Error => \"Error\",\n RegistrySettingStatus.Unknown => \"Unknown\",\n _ => \"Unknown\"\n };\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0) return;\n\n bool allSelected = Settings.All(s => s.IsSelected);\n bool anySelected = Settings.Any(s => s.IsSelected);\n\n IsSelected = allSelected;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/UpdateOptimizationsViewModel.cs", "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Infrastructure.Features.Common.Registry;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Update optimizations.\n /// \n public partial class UpdateOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The view model locator.\n /// The settings registry.\n public UpdateOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n }\n\n /// \n /// Loads the update settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load update optimizations\n var updateOptimizations = Core.Features.Optimize.Models.UpdateOptimizations.GetUpdateOptimizations();\n if (updateOptimizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in updateOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsUpdatingFromCode = true, // Set this to true to allow RefreshStatus to set the correct state\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Add to the settings collection\n Settings.Add(settingItem);\n }\n\n // Register settings with the settings registry if available\n foreach (var setting in Settings)\n {\n if (_settingsRegistry != null && !string.IsNullOrEmpty(setting.Id))\n {\n _settingsRegistry.RegisterSetting(setting);\n _logService.Log(LogLevel.Info, $\"Registered setting {setting.Id} in settings registry during creation\");\n }\n }\n\n // Refresh status for all settings to populate LinkedRegistrySettingsWithValues\n foreach (var setting in Settings)\n {\n await setting.RefreshStatus();\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading update optimizations: {ex.Message}\");\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all Windows Update settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, $\"Checking status for {Settings.Count} Windows Update settings\");\n\n foreach (var setting in Settings)\n {\n try\n {\n if (setting.RegistrySetting != null)\n {\n _logService.Log(LogLevel.Info, $\"Checking status for setting: {setting.Name}\");\n\n // Get the status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // Get the current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name}: {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Add to LinkedRegistrySettingsWithValues for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Checking linked registry settings status for: {setting.Name} with {setting.LinkedRegistrySettings.Settings.Count} registry entries\");\n\n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(regSetting.Hive);\n string fullPath = $\"{hiveString}\\\\{regSetting.SubKey}\";\n _logService.Log(LogLevel.Info, $\"Registry entry: {fullPath}\\\\{regSetting.Name}, EnabledValue={regSetting.EnabledValue}, DisabledValue={regSetting.DisabledValue}\");\n\n // Check if the key exists\n bool keyExists = _registryService.KeyExists(fullPath);\n _logService.Log(LogLevel.Info, $\"Key exists: {keyExists}\");\n\n if (keyExists)\n {\n // Check if the value exists and get its current value\n var currentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value: {currentValue ?? \"null\"}\");\n }\n }\n\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n _logService.Log(LogLevel.Info, $\"Combined status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name} (first entry): {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value for linked setting {regSetting.Name}: {regCurrentValue ?? \"null\"}\");\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Registry setting is null for {setting.Name}\");\n setting.Status = RegistrySettingStatus.Unknown;\n setting.StatusMessage = \"Registry setting information is missing\";\n }\n\n // If this is a grouped setting, update child settings too\n if (setting.IsGroupedSetting && setting.ChildSettings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Updating {setting.ChildSettings.Count} child settings for {setting.Name}\");\n foreach (var childSetting in setting.ChildSettings)\n {\n if (childSetting.RegistrySetting != null)\n {\n var status = await _registryService.GetSettingStatusAsync(childSetting.RegistrySetting);\n childSetting.Status = status;\n\n var currentValue = await _registryService.GetCurrentValueAsync(childSetting.RegistrySetting);\n childSetting.CurrentValue = currentValue;\n\n childSetting.StatusMessage = GetStatusMessage(childSetting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Child setting {childSetting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n childSetting.IsUpdatingFromCode = true;\n try\n {\n childSetting.IsSelected = shouldBeSelected;\n }\n finally\n {\n childSetting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating status for setting {setting.Name}: {ex.Message}\");\n setting.Status = RegistrySettingStatus.Error;\n setting.StatusMessage = $\"Error: {ex.Message}\";\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Windows Update setting statuses: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0)\n return;\n\n var selectedCount = Settings.Count(setting => setting.IsSelected);\n IsSelected = selectedCount == Settings.Count;\n }\n\n /// \n /// Gets a user-friendly status message for a setting.\n /// \n /// The setting to get the status message for.\n /// A user-friendly status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied =>\n \"This setting is enabled (toggle is ON).\",\n\n RegistrySettingStatus.NotApplied =>\n setting.CurrentValue == null\n ? \"This setting is not applied (registry value does not exist).\"\n : \"This setting is disabled (toggle is OFF).\",\n\n RegistrySettingStatus.Modified =>\n \"This setting has a custom value that differs from both enabled and disabled values.\",\n\n RegistrySettingStatus.Error =>\n \"An error occurred while checking this setting's status.\",\n\n _ => \"The status of this setting is unknown.\"\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/ExplorerOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\n\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Explorer optimizations.\n /// \n public partial class ExplorerOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDependencyManager _dependencyManager;\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dependency manager.\n /// The view model locator.\n /// The settings registry.\n public ExplorerOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDependencyManager dependencyManager,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _dependencyManager = dependencyManager ?? throw new ArgumentNullException(nameof(dependencyManager));\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n }\n\n /// \n /// Loads the Explorer optimizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Explorer optimizations from ExplorerOptimizations\n var explorerOptimizations = Core.Features.Optimize.Models.ExplorerOptimizations.GetExplorerOptimizations();\n if (explorerOptimizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in explorerOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = false, // Always initialize as unchecked\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Register the setting in the settings registry if available\n if (_settingsRegistry != null && !string.IsNullOrEmpty(settingItem.Id))\n {\n _settingsRegistry.RegisterSetting(settingItem);\n _logService.Log(LogLevel.Info, $\"Registered setting {settingItem.Id} in settings registry during creation\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for settings\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all Explorer optimizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n foreach (var setting in Settings)\n {\n if (setting.RegistrySetting != null)\n {\n // Get status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n setting.Status = status;\n\n // Get current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n setting.CurrentValue = currentValue;\n \n // Set IsRegistryValueNull property based on current value\n setting.IsRegistryValueNull = currentValue == null;\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Explorer optimization statuses: {ex.Message}\");\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied => \"Applied\",\n RegistrySettingStatus.NotApplied => \"Not Applied\",\n RegistrySettingStatus.Modified => \"Modified\",\n RegistrySettingStatus.Error => \"Error\",\n RegistrySettingStatus.Unknown => \"Unknown\",\n _ => \"Unknown\"\n };\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0) return;\n\n bool allSelected = Settings.All(s => s.IsSelected);\n bool anySelected = Settings.Any(s => s.IsSelected);\n\n IsSelected = allSelected;\n }\n\n /// \n /// Converts a RegistryHive enum to its string representation (HKCU, HKLM, etc.)\n /// \n /// The registry hive.\n /// The string representation of the registry hive.\n private string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => hive.ToString()\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/MainViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Input;\nusing System.Windows.Interop;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.Utilities;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n public partial class MainViewModel : BaseViewModel\n {\n // Window control is now handled through messaging\n\n private readonly IThemeManager _themeManager;\n private readonly INavigationService _navigationService;\n private readonly IMessengerService _messengerService;\n private readonly IUnifiedConfigurationService _unifiedConfigService;\n private readonly IDialogService _dialogService;\n private readonly Features.Common.Services.UserPreferencesService _userPreferencesService;\n\n public INavigationService NavigationService => _navigationService;\n\n [ObservableProperty]\n private object _currentViewModel;\n\n // Helper method to log window actions for debugging\n private void LogWindowAction(string message)\n {\n string formattedMessage = $\"Window Action: {message}\";\n\n // Send to application logging system\n _messengerService.Send(\n new LogMessage { Message = formattedMessage, Level = LogLevel.Debug }\n );\n\n // Also log to diagnostic file for troubleshooting\n FileLogger.Log(\"MainViewModel\", formattedMessage);\n }\n\n private string _currentViewName = string.Empty;\n public string CurrentViewName\n {\n get => _currentViewName;\n set => SetProperty(ref _currentViewName, value);\n }\n\n [ObservableProperty]\n private string _maximizeButtonContent = \"\\uE739\";\n\n /// \n /// Gets the ViewModel for the More menu functionality\n /// \n public MoreMenuViewModel MoreMenuViewModel { get; }\n\n /// \n /// Gets the command to save a unified configuration.\n /// \n public ICommand SaveUnifiedConfigCommand { get; }\n\n /// \n /// Gets the command to import a unified configuration.\n /// \n public ICommand ImportUnifiedConfigCommand { get; }\n\n /// \n /// Gets the command to open the donation page in a browser.\n /// \n public ICommand OpenDonateCommand { get; }\n\n public MainViewModel(\n IThemeManager themeManager,\n INavigationService navigationService,\n ITaskProgressService progressService,\n IMessengerService messengerService,\n IDialogService dialogService,\n IUnifiedConfigurationService unifiedConfigService,\n Features.Common.Services.UserPreferencesService userPreferencesService,\n ILogService logService,\n IVersionService versionService,\n IApplicationCloseService applicationCloseService\n )\n : base(progressService, messengerService)\n {\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n _navigationService =\n navigationService ?? throw new ArgumentNullException(nameof(navigationService));\n _messengerService =\n messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n _dialogService =\n dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _unifiedConfigService =\n unifiedConfigService\n ?? throw new ArgumentNullException(nameof(unifiedConfigService));\n _userPreferencesService =\n userPreferencesService\n ?? throw new ArgumentNullException(nameof(userPreferencesService));\n\n // Initialize the MoreMenuViewModel\n MoreMenuViewModel = new MoreMenuViewModel(logService, versionService, _messengerService, applicationCloseService, _dialogService);\n\n // Initialize command properties\n _minimizeWindowCommand = new RelayCommand(MinimizeWindow);\n _maximizeRestoreWindowCommand = new RelayCommand(MaximizeRestoreWindow);\n // Use AsyncRelayCommand instead of RelayCommand for async methods\n _closeWindowCommand = new AsyncRelayCommand(CloseWindowAsync);\n SaveUnifiedConfigCommand = new RelayCommand(SaveUnifiedConfig);\n ImportUnifiedConfigCommand = new RelayCommand(ImportUnifiedConfig);\n OpenDonateCommand = new RelayCommand(OpenDonate);\n\n // Note: View mappings are now registered in App.xaml.cs when configuring the FrameNavigationService\n\n // Subscribe to navigation events\n _navigationService.Navigated += NavigationService_Navigated;\n\n // We'll initialize with the default view later, after the window is loaded\n // This will be called from MainWindow.xaml.cs after the window is loaded\n // This will be called from MainWindow.xaml.cs after the window is loaded\n }\n\n private void NavigationService_Navigated(object sender, NavigationEventArgs e)\n {\n CurrentViewName = e.Route;\n\n // The NavigationService sets e.Parameter to the ViewModel instance\n // This ensures the CurrentViewModel is properly set\n if (e.Parameter != null && e.Parameter is IViewModel)\n {\n CurrentViewModel = e.Parameter;\n }\n else if (e.ViewModelType != null)\n {\n // If for some reason the parameter is not set, try to get the ViewModel from the service provider\n try\n {\n // Get the view model from the navigation event parameter\n if (e.Parameter != null)\n {\n CurrentViewModel = e.Parameter;\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error getting current view model: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n }\n\n [RelayCommand]\n private void Navigate(string viewName)\n {\n try\n {\n _navigationService.NavigateTo(viewName);\n }\n catch (Exception ex)\n {\n // Log the error using the messaging system\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Navigation error to {viewName}: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n\n MessageBox.Show(\n $\"Navigation error while attempting to navigate to {viewName}.\\nError: {ex.Message}\",\n \"Navigation Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error\n );\n }\n }\n\n [RelayCommand]\n private void ToggleTheme()\n {\n _themeManager.ToggleTheme();\n }\n\n // Explicit command property for MinimizeWindow\n private ICommand _minimizeWindowCommand;\n public ICommand MinimizeWindowCommand\n {\n get\n {\n if (_minimizeWindowCommand == null)\n {\n _minimizeWindowCommand = new RelayCommand(MinimizeWindow);\n }\n return _minimizeWindowCommand;\n }\n }\n\n private void MinimizeWindow()\n {\n LogWindowAction(\"MinimizeWindow command called\");\n\n var mainWindow = Application.Current.MainWindow;\n if (mainWindow == null)\n {\n LogWindowAction(\"MainWindow is null\");\n return;\n }\n\n // Try to minimize the window directly\n try\n {\n mainWindow.WindowState = WindowState.Minimized;\n LogWindowAction(\"Directly set WindowState to Minimized\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"Error setting WindowState directly: {ex.Message}\");\n\n // Fall back to messaging\n _messengerService.Send(\n new WindowStateMessage\n {\n Action = WindowStateMessage.WindowStateAction.Minimize,\n }\n );\n }\n }\n\n // Explicit command property for MaximizeRestoreWindow\n private ICommand _maximizeRestoreWindowCommand;\n public ICommand MaximizeRestoreWindowCommand\n {\n get\n {\n if (_maximizeRestoreWindowCommand == null)\n {\n _maximizeRestoreWindowCommand = new RelayCommand(MaximizeRestoreWindow);\n }\n return _maximizeRestoreWindowCommand;\n }\n }\n\n private void MaximizeRestoreWindow()\n {\n LogWindowAction(\"MaximizeRestoreWindow command called\");\n\n var mainWindow = Application.Current.MainWindow;\n if (mainWindow == null)\n {\n LogWindowAction(\"MainWindow is null\");\n return;\n }\n\n if (mainWindow.WindowState == WindowState.Maximized)\n {\n // Try to restore the window directly\n try\n {\n mainWindow.WindowState = WindowState.Normal;\n LogWindowAction(\"Directly set WindowState to Normal\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"Error setting WindowState directly: {ex.Message}\");\n\n // Fall back to messaging\n _messengerService.Send(\n new WindowStateMessage\n {\n Action = WindowStateMessage.WindowStateAction.Restore,\n }\n );\n }\n\n // Update the button icon\n MaximizeButtonContent = \"\\uE739\";\n LogWindowAction(\"Updated MaximizeButtonContent to Maximize icon\");\n }\n else\n {\n // Try to maximize the window directly\n try\n {\n mainWindow.WindowState = WindowState.Maximized;\n LogWindowAction(\"Directly set WindowState to Maximized\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"Error setting WindowState directly: {ex.Message}\");\n\n // Fall back to messaging\n _messengerService.Send(\n new WindowStateMessage\n {\n Action = WindowStateMessage.WindowStateAction.Maximize,\n }\n );\n }\n\n // Update the button icon\n MaximizeButtonContent = \"\\uE923\";\n LogWindowAction(\"Updated MaximizeButtonContent to Restore icon\");\n }\n }\n\n // Explicit command property for CloseWindow\n private ICommand _closeWindowCommand;\n public ICommand CloseWindowCommand\n {\n get\n {\n if (_closeWindowCommand == null)\n {\n // Use AsyncRelayCommand instead of RelayCommand for async methods\n _closeWindowCommand = new AsyncRelayCommand(CloseWindowAsync);\n }\n return _closeWindowCommand;\n }\n }\n\n // Make sure this method is public so it can be called directly for testing\n public async Task CloseWindowAsync()\n {\n LogWindowAction(\"CloseWindowAsync method called\");\n\n // Log basic information\n _messengerService.Send(\n new LogMessage\n {\n Message = \"CloseWindow method executing in MainViewModel\",\n Level = LogLevel.Debug,\n }\n );\n\n var mainWindow = Application.Current.MainWindow;\n if (mainWindow == null)\n {\n LogWindowAction(\"ERROR: MainWindow is null\");\n return;\n }\n\n // The donation dialog is now handled in MainWindow.CloseButton_Click\n // so we can simply close the window here\n\n try\n {\n LogWindowAction(\"About to call mainWindow.Close()\");\n mainWindow.Close();\n LogWindowAction(\"mainWindow.Close() called successfully\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"ERROR closing window directly: {ex.Message}\");\n\n // Fall back to messaging\n LogWindowAction(\"Falling back to WindowStateMessage.Close\");\n _messengerService.Send(\n new WindowStateMessage { Action = WindowStateMessage.WindowStateAction.Close }\n );\n }\n\n LogWindowAction(\"CloseWindowAsync method completed\");\n }\n\n /// \n /// Saves a unified configuration by delegating to the current view model.\n /// \n private async void SaveUnifiedConfig()\n {\n try\n {\n // Use the injected unified configuration service\n var unifiedConfigService = _unifiedConfigService;\n\n if (unifiedConfigService == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"UnifiedConfigurationService not available\",\n Level = LogLevel.Error,\n }\n );\n return;\n }\n\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Using UnifiedConfigurationService to save unified configuration\",\n Level = LogLevel.Info,\n }\n );\n\n // Create a unified configuration with settings from all view models\n var unifiedConfig = await unifiedConfigService.CreateUnifiedConfigurationAsync();\n\n // Get the configuration service from the application\n IConfigurationService configService = null;\n\n // Try to get the service from the application\n if (Application.Current is App appInstance3)\n {\n try\n {\n // Use reflection to access the _host.Services property\n var hostField = appInstance3\n .GetType()\n .GetField(\"_host\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (hostField != null)\n {\n var host = hostField.GetValue(appInstance3);\n var servicesProperty = host.GetType().GetProperty(\"Services\");\n if (servicesProperty != null)\n {\n var services = servicesProperty.GetValue(host);\n var getServiceMethod = services\n .GetType()\n .GetMethod(\"GetService\", new[] { typeof(Type) });\n if (getServiceMethod != null)\n {\n configService =\n getServiceMethod.Invoke(\n services,\n new object[] { typeof(IConfigurationService) }\n ) as IConfigurationService;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error accessing ConfigurationService: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n\n if (configService == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"ConfigurationService not available\",\n Level = LogLevel.Error,\n }\n );\n return;\n }\n\n // Save the unified configuration\n bool saveResult = await unifiedConfigService.SaveUnifiedConfigurationAsync(\n unifiedConfig\n );\n\n if (saveResult)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Unified configuration saved successfully\",\n Level = LogLevel.Info,\n }\n );\n\n // Show a single success dialog using CustomDialog to match the application style\n var sections = new List();\n if (unifiedConfig.WindowsApps.Items.Any())\n sections.Add(\"Windows Apps\");\n if (unifiedConfig.ExternalApps.Items.Any())\n sections.Add(\"External Apps\");\n if (unifiedConfig.Customize.Items.Any())\n sections.Add(\"Customizations\");\n if (unifiedConfig.Optimize.Items.Any())\n sections.Add(\"Optimizations\");\n\n Winhance.WPF.Features.Common.Views.CustomDialog.ShowInformation(\n \"Configuration Saved\",\n \"Configuration saved successfully.\",\n sections,\n \"You can now import this configuration on another system.\"\n );\n }\n else\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Save unified configuration canceled by user\",\n Level = LogLevel.Info,\n }\n );\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error saving unified configuration: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n\n // FallbackToViewModelImplementation method removed as part of unified configuration cleanup\n\n /// \n /// Imports a unified configuration by delegating to the current view model.\n /// \n private async void ImportUnifiedConfig()\n {\n try\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Starting unified configuration import process\",\n Level = LogLevel.Info,\n }\n );\n\n // Use the injected unified configuration service\n var unifiedConfigService = _unifiedConfigService;\n\n _messengerService.Send(\n new LogMessage\n {\n Message =\n \"Using UnifiedConfigurationService to import unified configuration\",\n Level = LogLevel.Info,\n }\n );\n\n // Get the configuration service from the application\n IConfigurationService configService = null;\n\n // Try to get the service from the application\n if (Application.Current is App appInstance2)\n {\n try\n {\n // Use reflection to access the _host.Services property\n var hostField = appInstance2\n .GetType()\n .GetField(\"_host\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (hostField != null)\n {\n var host = hostField.GetValue(appInstance2);\n var servicesProperty = host.GetType().GetProperty(\"Services\");\n if (servicesProperty != null)\n {\n var services = servicesProperty.GetValue(host);\n var getServiceMethod = services\n .GetType()\n .GetMethod(\"GetService\", new[] { typeof(Type) });\n if (getServiceMethod != null)\n {\n configService =\n getServiceMethod.Invoke(\n services,\n new object[] { typeof(IConfigurationService) }\n ) as IConfigurationService;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error accessing ConfigurationService: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n\n if (configService == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"ConfigurationService not available\",\n Level = LogLevel.Error,\n }\n );\n return;\n }\n\n // Load the unified configuration\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Showing file dialog to select configuration file\",\n Level = LogLevel.Info,\n }\n );\n\n var unifiedConfig = await unifiedConfigService.LoadUnifiedConfigurationAsync();\n\n if (unifiedConfig == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Import unified configuration canceled by user\",\n Level = LogLevel.Info,\n }\n );\n return;\n }\n\n _messengerService.Send(\n new LogMessage\n {\n Message =\n $\"Configuration loaded with sections: WindowsApps ({unifiedConfig.WindowsApps.Items.Count} items), \"\n + $\"ExternalApps ({unifiedConfig.ExternalApps.Items.Count} items), \"\n + $\"Customize ({unifiedConfig.Customize.Items.Count} items), \"\n + $\"Optimize ({unifiedConfig.Optimize.Items.Count} items)\",\n Level = LogLevel.Info,\n }\n );\n\n // Show the unified configuration dialog to let the user select which sections to import\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Showing unified configuration dialog for section selection\",\n Level = LogLevel.Info,\n }\n );\n\n // Show the unified configuration dialog to let the user select which sections to import\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Showing unified configuration dialog for section selection\",\n Level = LogLevel.Info,\n }\n );\n\n // Create a dictionary of sections with their availability and item counts\n var sectionInfo = new Dictionary<\n string,\n (bool IsSelected, bool IsAvailable, int ItemCount)\n >\n {\n {\n \"WindowsApps\",\n (\n true,\n unifiedConfig.WindowsApps.Items.Count > 0,\n unifiedConfig.WindowsApps.Items.Count\n )\n },\n {\n \"ExternalApps\",\n (\n true,\n unifiedConfig.ExternalApps.Items.Count > 0,\n unifiedConfig.ExternalApps.Items.Count\n )\n },\n {\n \"Customize\",\n (\n true,\n unifiedConfig.Customize.Items.Count > 0,\n unifiedConfig.Customize.Items.Count\n )\n },\n {\n \"Optimize\",\n (\n true,\n unifiedConfig.Optimize.Items.Count > 0,\n unifiedConfig.Optimize.Items.Count\n )\n },\n };\n\n // Create and show the dialog\n var dialog = new Views.UnifiedConfigurationDialog(\n \"Select Configuration Sections\",\n \"Select which sections you want to import from the unified configuration.\",\n sectionInfo,\n false\n );\n\n // Only set the Owner if the dialog is not the main window itself\n if (dialog != Application.Current.MainWindow)\n {\n try\n {\n dialog.Owner = Application.Current.MainWindow;\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error setting dialog owner: {ex.Message}\",\n Level = LogLevel.Warning,\n }\n );\n // Continue without setting the owner\n }\n }\n bool? dialogResult = dialog.ShowDialog();\n\n if (dialogResult != true)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"User canceled unified configuration import\",\n Level = LogLevel.Info,\n }\n );\n return;\n }\n\n // Get the selected sections from the dialog\n var result = dialog.GetResult();\n var selectedSections = result\n .Where(kvp => kvp.Value)\n .Select(kvp => kvp.Key)\n .ToList();\n\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Selected sections: {string.Join(\", \", selectedSections)}\",\n Level = LogLevel.Info,\n }\n );\n\n if (!selectedSections.Any())\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"No sections selected for import\",\n Level = LogLevel.Info,\n }\n );\n _dialogService.ShowMessage(\n \"Please select at least one section to import from the unified configuration.\",\n \"No sections selected\"\n );\n return;\n }\n\n // Apply the configuration to the selected sections\n _messengerService.Send(\n new LogMessage\n {\n Message =\n $\"Applying configuration to selected sections: {string.Join(\", \", selectedSections)}\",\n Level = LogLevel.Info,\n }\n );\n\n // Apply the configuration to the selected sections\n await unifiedConfigService.ApplyUnifiedConfigurationAsync(\n unifiedConfig,\n selectedSections\n );\n\n // Always show a success message since the settings are being applied correctly\n // even if the updatedCount is 0\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Unified configuration imported successfully\",\n Level = LogLevel.Info,\n }\n );\n\n // Show a success message using CustomDialog to match the application style\n var importedSections = new List();\n foreach (var section in selectedSections)\n {\n switch (section)\n {\n case \"WindowsApps\":\n importedSections.Add(\"Windows Apps\");\n break;\n case \"ExternalApps\":\n importedSections.Add(\"External Apps\");\n break;\n case \"Customize\":\n importedSections.Add(\"Customizations\");\n break;\n case \"Optimize\":\n importedSections.Add(\"Optimizations\");\n break;\n }\n }\n\n Winhance.WPF.Features.Common.Views.CustomDialog.ShowInformation(\n \"Configuration Imported\",\n \"The unified configuration has been imported successfully.\",\n importedSections,\n \"The selected settings have been applied to your system.\"\n );\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error importing unified configuration: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n\n // Show an error message to the user\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"An error occurred while importing the configuration: {ex.Message}\",\n \"Import Error\"\n );\n }\n }\n }\n\n // FallbackToViewModelImportImplementation method removed as part of unified configuration cleanup\n\n /// \n /// Opens the donation page in the default browser.\n /// \n private void OpenDonate()\n {\n try\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Opening donation page in browser\",\n Level = LogLevel.Info,\n }\n );\n\n // Use ProcessStartInfo to open the URL in the default browser\n var psi = new ProcessStartInfo\n {\n FileName = \"https://ko-fi.com/memstechtips\",\n UseShellExecute = true,\n };\n Process.Start(psi);\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error opening donation page: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n\n // Show an error message to the user\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"An error occurred while opening the donation page: {ex.Message}\",\n \"Error\"\n );\n }\n }\n }\n\n\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/GamingandPerformanceOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Infrastructure.Features.Common.Registry;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Gaming and Performance optimizations.\n /// \n public partial class GamingandPerformanceOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n private readonly ICommandService _commandService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The command service.\n /// The view model locator.\n /// The settings registry.\n public GamingandPerformanceOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n ICommandService commandService,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n _commandService = commandService;\n }\n\n /// \n /// Loads the Gaming and Performance optimizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Gaming and Performance optimizations\n var gamingOptimizations = Core.Features.Optimize.Models.GamingandPerformanceOptimizations.GetGamingandPerformanceOptimizations();\n if (gamingOptimizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in gamingOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService, _commandService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsUpdatingFromCode = true, // Set this to true to allow RefreshStatus to set the correct state\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Info, $\"No registry settings found for {setting.Name}\");\n }\n \n // Set up command settings if available\n if (setting.CommandSettings.Count > 0)\n {\n settingItem.CommandSettings = setting.CommandSettings;\n _logService.Log(LogLevel.Info, $\"Setting up command settings for {setting.Name} with {setting.CommandSettings.Count} commands\");\n \n // Log details about each command setting for debugging\n foreach (var cmdSetting in setting.CommandSettings)\n {\n _logService.Log(LogLevel.Info, $\"Command setting: {cmdSetting.Id}, EnabledCommand={cmdSetting.EnabledCommand}, DisabledCommand={cmdSetting.DisabledCommand}, IsPrimary={cmdSetting.IsPrimary}\");\n }\n }\n\n // Add to the settings collection\n Settings.Add(settingItem);\n }\n\n // Register settings with the settings registry if available\n foreach (var setting in Settings)\n {\n if (_settingsRegistry != null && !string.IsNullOrEmpty(setting.Id))\n {\n _settingsRegistry.RegisterSetting(setting);\n _logService.Log(LogLevel.Info, $\"Registered setting {setting.Id} in settings registry during creation\");\n }\n }\n\n // Refresh status for all settings to populate LinkedRegistrySettingsWithValues\n foreach (var setting in Settings)\n {\n await setting.RefreshStatus();\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading Gaming and Performance optimizations: {ex.Message}\");\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all gaming and performance settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, $\"Checking status for {Settings.Count} gaming and performance settings\");\n\n foreach (var setting in Settings)\n {\n try\n {\n if (setting.RegistrySetting != null)\n {\n _logService.Log(LogLevel.Info, $\"Checking status for setting: {setting.Name}\");\n\n // Get the status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // Get the current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name}: {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Add to LinkedRegistrySettingsWithValues for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Checking linked registry settings status for: {setting.Name} with {setting.LinkedRegistrySettings.Settings.Count} registry entries\");\n\n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(regSetting.Hive);\n string fullPath = $\"{hiveString}\\\\{regSetting.SubKey}\";\n _logService.Log(LogLevel.Info, $\"Registry entry: {fullPath}\\\\{regSetting.Name}, EnabledValue={regSetting.EnabledValue}, DisabledValue={regSetting.DisabledValue}\");\n\n // Check if the key exists\n bool keyExists = _registryService.KeyExists(fullPath);\n _logService.Log(LogLevel.Info, $\"Key exists: {keyExists}\");\n\n if (keyExists)\n {\n // Check if the value exists and get its current value\n var currentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value: {currentValue ?? \"null\"}\");\n }\n }\n\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n _logService.Log(LogLevel.Info, $\"Combined status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name} (first entry): {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value for linked setting {regSetting.Name}: {regCurrentValue ?? \"null\"}\");\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Registry setting is null for {setting.Name}\");\n setting.Status = RegistrySettingStatus.Unknown;\n setting.StatusMessage = \"Registry setting information is missing\";\n }\n\n // If this is a grouped setting, update child settings too\n if (setting.IsGroupedSetting && setting.ChildSettings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Updating {setting.ChildSettings.Count} child settings for {setting.Name}\");\n foreach (var childSetting in setting.ChildSettings)\n {\n if (childSetting.RegistrySetting != null)\n {\n var status = await _registryService.GetSettingStatusAsync(childSetting.RegistrySetting);\n childSetting.Status = status;\n\n var currentValue = await _registryService.GetCurrentValueAsync(childSetting.RegistrySetting);\n childSetting.CurrentValue = currentValue;\n\n childSetting.StatusMessage = GetStatusMessage(childSetting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Child setting {childSetting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n childSetting.IsUpdatingFromCode = true;\n try\n {\n childSetting.IsSelected = shouldBeSelected;\n }\n finally\n {\n childSetting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating status for setting {setting.Name}: {ex.Message}\");\n setting.Status = RegistrySettingStatus.Error;\n setting.StatusMessage = $\"Error: {ex.Message}\";\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking gaming and performance setting statuses: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0)\n return;\n\n var selectedCount = Settings.Count(setting => setting.IsSelected);\n IsSelected = selectedCount == Settings.Count;\n }\n\n /// \n /// Gets a user-friendly status message for a setting.\n /// \n /// The setting to get the status message for.\n /// A user-friendly status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied =>\n \"This setting is enabled (toggle is ON).\",\n\n RegistrySettingStatus.NotApplied =>\n setting.CurrentValue == null\n ? \"This setting is not applied (registry value does not exist).\"\n : \"This setting is disabled (toggle is OFF).\",\n\n RegistrySettingStatus.Modified =>\n \"This setting has a custom value that differs from both enabled and disabled values.\",\n\n RegistrySettingStatus.Error =>\n \"An error occurred while checking this setting's status.\",\n\n _ => \"The status of this setting is unknown.\"\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/UnifiedConfigurationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Services.Configuration;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for managing unified configuration operations across the application.\n /// \n public class UnifiedConfigurationService : IUnifiedConfigurationService\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly IConfigurationService _configurationService;\n private readonly ILogService _logService;\n private readonly IDialogService _dialogService;\n private readonly IRegistryService _registryService;\n private readonly ConfigurationCollectorService _collectorService;\n private readonly IConfigurationApplierService _applierService;\n private readonly ConfigurationUIService _uiService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The configuration service.\n /// The log service.\n /// The dialog service.\n /// The registry service.\n public UnifiedConfigurationService(\n IServiceProvider serviceProvider,\n IConfigurationService configurationService,\n ILogService logService,\n IDialogService dialogService,\n IRegistryService registryService)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n \n // Initialize helper services\n _collectorService = new ConfigurationCollectorService(serviceProvider, logService);\n _applierService = serviceProvider.GetRequiredService();\n _uiService = new ConfigurationUIService(logService);\n }\n\n /// \n /// Creates a unified configuration file containing settings from all view models.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file.\n public async Task CreateUnifiedConfigurationAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Creating unified configuration from all view models\");\n \n // Collect settings from all view models\n var sectionSettings = await _collectorService.CollectAllSettingsAsync();\n \n // Create a list of all available sections - include all sections by default\n var availableSections = new List { \"WindowsApps\", \"ExternalApps\", \"Customize\", \"Optimize\" };\n\n // Create and return the unified configuration\n var unifiedConfig = _configurationService.CreateUnifiedConfiguration(sectionSettings, availableSections);\n \n _logService.Log(LogLevel.Info, \"Successfully created unified configuration from all view models\");\n \n return unifiedConfig;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating unified configuration: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Saves a unified configuration file.\n /// \n /// The unified configuration to save.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n public async Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile config)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Saving unified configuration\");\n \n bool saveResult = await _configurationService.SaveUnifiedConfigurationAsync(config);\n \n if (saveResult)\n {\n _logService.Log(LogLevel.Info, \"Unified configuration saved successfully\");\n // Success dialog is now shown only in MainViewModel to avoid duplicate dialogs\n }\n else\n {\n _logService.Log(LogLevel.Info, \"Save unified configuration canceled by user\");\n }\n \n return saveResult;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving unified configuration: {ex.Message}\");\n _dialogService.ShowMessage($\"Error saving unified configuration: {ex.Message}\", \"Error\");\n return false;\n }\n }\n\n /// \n /// Loads a unified configuration file.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file if successful, null otherwise.\n public async Task LoadUnifiedConfigurationAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Loading unified configuration\");\n \n var unifiedConfig = await _configurationService.LoadUnifiedConfigurationAsync();\n \n if (unifiedConfig == null)\n {\n _logService.Log(LogLevel.Info, \"Load unified configuration canceled by user\");\n return null;\n }\n \n _logService.Log(LogLevel.Info, $\"Configuration loaded with sections: WindowsApps ({unifiedConfig.WindowsApps.Items.Count} items), \" +\n $\"ExternalApps ({unifiedConfig.ExternalApps.Items.Count} items), \" +\n $\"Customize ({unifiedConfig.Customize.Items.Count} items), \" +\n $\"Optimize ({unifiedConfig.Optimize.Items.Count} items)\");\n \n return unifiedConfig;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading unified configuration: {ex.Message}\");\n _dialogService.ShowMessage($\"Error loading unified configuration: {ex.Message}\", \"Error\");\n return null;\n }\n }\n\n /// \n /// Shows the unified configuration dialog to let the user select which sections to include.\n /// \n /// The unified configuration file.\n /// Whether this is a save dialog (true) or an import dialog (false).\n /// A dictionary of section names and their selection state.\n public async Task> ShowUnifiedConfigurationDialogAsync(UnifiedConfigurationFile config, bool isSaveDialog)\n {\n return await _uiService.ShowUnifiedConfigurationDialogAsync(config, isSaveDialog);\n }\n\n /// \n /// Applies a unified configuration to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n public async Task ApplyUnifiedConfigurationAsync(UnifiedConfigurationFile config, IEnumerable selectedSections)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Applying unified configuration to selected sections: {string.Join(\", \", selectedSections)}\");\n \n // Log the contents of the unified configuration\n _logService.Log(LogLevel.Debug, $\"Unified configuration contains: \" +\n $\"WindowsApps: {config.WindowsApps?.Items?.Count ?? 0} items, \" +\n $\"ExternalApps: {config.ExternalApps?.Items?.Count ?? 0} items, \" +\n $\"Customize: {config.Customize?.Items?.Count ?? 0} items, \" +\n $\"Optimize: {config.Optimize?.Items?.Count ?? 0} items\");\n \n // Validate the configuration\n if (config == null)\n {\n _logService.Log(LogLevel.Error, \"Unified configuration is null\");\n return false;\n }\n \n // Validate the selected sections\n if (selectedSections == null || !selectedSections.Any())\n {\n _logService.Log(LogLevel.Error, \"No sections selected for import\");\n return false;\n }\n \n // Apply the configuration to the selected sections\n var sectionResults = await _applierService.ApplySectionsAsync(config, selectedSections);\n \n // Log the results for each section\n _logService.Log(LogLevel.Info, \"Import results by section:\");\n foreach (var sectionResult in sectionResults)\n {\n _logService.Log(LogLevel.Info, $\" {sectionResult.Key}: {(sectionResult.Value ? \"Success\" : \"Failed\")}\");\n }\n \n bool overallResult = sectionResults.All(r => r.Value);\n _logService.Log(LogLevel.Info, $\"Finished applying unified configuration to selected sections. Overall result: {(overallResult ? \"Success\" : \"Partial failure\")}\");\n \n return overallResult;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying unified configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/ViewModels/TaskbarCustomizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Core.Features.Customize.Enums;\nusing Winhance.Core.Features.Customize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Customize.ViewModels\n{\n /// \n /// ViewModel for Taskbar customizations.\n /// \n public partial class TaskbarCustomizationsViewModel : BaseSettingsViewModel\n {\n private readonly ISystemServices _systemServices;\n private bool _isWindows11;\n\n /// \n /// Gets the command to clean the taskbar.\n /// \n public IAsyncRelayCommand CleanTaskbarCommand { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The system services.\n public TaskbarCustomizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n ISystemServices systemServices)\n : base(progressService, registryService, logService)\n {\n _systemServices = systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n _isWindows11 = _systemServices.IsWindows11();\n \n // Initialize the CleanTaskbarCommand\n CleanTaskbarCommand = new AsyncRelayCommand(ExecuteCleanTaskbarAsync);\n }\n\n /// \n /// Executes the clean taskbar operation.\n /// \n private async Task ExecuteCleanTaskbarAsync()\n {\n try\n {\n _progressService.StartTask(\"Cleaning taskbar...\");\n _logService.LogInformation(\"Cleaning taskbar started\");\n \n // Call the static method from TaskbarCustomizations class\n await TaskbarCustomizations.CleanTaskbar(_systemServices, _logService);\n \n // Update the status text and complete the task\n _progressService.UpdateProgress(100, \"Taskbar cleaned successfully!\");\n _progressService.CompleteTask();\n _logService.LogInformation(\"Taskbar cleaned successfully\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error cleaning taskbar: {ex.Message}\", ex);\n // Update the status text with the error message\n _progressService.UpdateProgress(0, $\"Error cleaning taskbar: {ex.Message}\");\n _progressService.CancelCurrentTask();\n }\n }\n\n /// \n /// Loads the Taskbar customizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Taskbar customizations\n var taskbarCustomizations = Core.Features.Customize.Models.TaskbarCustomizations.GetTaskbarCustomizations();\n if (taskbarCustomizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in taskbarCustomizations.Settings.OrderBy(s => s.Name))\n {\n // Skip Windows 11 specific settings on Windows 10\n if (!_isWindows11 && setting.IsWindows11Only)\n {\n continue;\n }\n\n // Skip Windows 10 specific settings on Windows 11\n if (_isWindows11 && setting.IsWindows10Only)\n {\n continue;\n }\n\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n ControlType = setting.ControlType,\n IsWindows11Only = setting.IsWindows11Only,\n IsWindows10Only = setting.IsWindows10Only\n };\n\n // Add any actions\n var actionsProperty = setting.GetType().GetProperty(\"Actions\");\n if (actionsProperty != null && \n actionsProperty.GetValue(setting) is IEnumerable actions && \n actions.Any())\n {\n // We need to handle this differently since the Actions property doesn't exist in ApplicationSetting\n // This is a temporary workaround until we refactor the code properly\n }\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for settings\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/ApplicationCloseService.cs", "using System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for handling application close functionality\n /// \n public class ApplicationCloseService : IApplicationCloseService\n {\n private readonly ILogService _logService;\n private readonly string _preferencesFilePath;\n \n /// \n /// Initializes a new instance of the class\n /// \n /// Service for logging\n public ApplicationCloseService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n \n // Set up the preferences file path\n _preferencesFilePath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Config\",\n \"UserPreferences.json\"\n );\n }\n \n /// \n public async Task CloseApplicationWithSupportDialogAsync()\n {\n try\n {\n _logService.LogInformation(\"Closing application with support dialog check\");\n \n // Check if we should show the dialog\n bool showDialog = await ShouldShowSupportDialogAsync();\n \n if (showDialog)\n {\n _logService.LogInformation(\"Showing donation dialog\");\n \n // Show the dialog\n string supportMessage = \"Your support helps keep this project going!\";\n var dialog = await DonationDialog.ShowDonationDialogAsync(\n \"Support Winhance\",\n supportMessage,\n \"Click 'Yes' to show your support!\"\n );\n \n _logService.LogInformation($\"Donation dialog completed with result: {dialog?.DialogResult}, DontShowAgain: {dialog?.DontShowAgain}\");\n \n // Save the \"Don't show again\" preference if checked\n if (dialog != null && dialog.DontShowAgain)\n {\n _logService.LogInformation(\"Saving DontShowSupport preference\");\n await SaveDontShowSupportPreferenceAsync(true);\n }\n \n // Open the donation page if the user clicked Yes\n if (dialog?.DialogResult == true)\n {\n _logService.LogInformation(\"User clicked Yes, opening donation page\");\n try\n {\n var psi = new ProcessStartInfo\n {\n FileName = \"https://ko-fi.com/memstechtips\",\n UseShellExecute = true,\n };\n Process.Start(psi);\n _logService.LogInformation(\"Donation page opened successfully\");\n }\n catch (Exception openEx)\n {\n _logService.LogError($\"Error opening donation page: {openEx.Message}\", openEx);\n }\n }\n }\n else\n {\n _logService.LogInformation(\"Skipping donation dialog due to user preference\");\n }\n \n // Close the application\n _logService.LogInformation(\"Shutting down application\");\n Application.Current.Dispatcher.Invoke(() => Application.Current.Shutdown());\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in CloseApplicationWithSupportDialogAsync: {ex.Message}\", ex);\n \n // Fallback to direct application shutdown\n try\n {\n _logService.LogInformation(\"Falling back to Application.Current.Shutdown()\");\n Application.Current.Dispatcher.Invoke(() => Application.Current.Shutdown());\n }\n catch (Exception shutdownEx)\n {\n _logService.LogError($\"Error shutting down application: {shutdownEx.Message}\", shutdownEx);\n \n // Last resort\n Environment.Exit(0);\n }\n }\n }\n \n /// \n public async Task ShouldShowSupportDialogAsync()\n {\n try\n {\n _logService.LogInformation($\"Checking preferences file: {_preferencesFilePath}\");\n \n // Check if the preference file exists and contains the DontShowSupport setting\n if (File.Exists(_preferencesFilePath))\n {\n string json = await File.ReadAllTextAsync(_preferencesFilePath);\n _logService.LogInformation($\"Preferences file content: {json}\");\n \n // Check if the preference is set to true\n if (\n json.Contains(\"\\\"DontShowSupport\\\": true\")\n || json.Contains(\"\\\"DontShowSupport\\\":true\")\n || json.Contains(\"\\\"DontShowSupport\\\": 1\")\n || json.Contains(\"\\\"DontShowSupport\\\":1\")\n )\n {\n _logService.LogInformation(\"DontShowSupport is set to true, skipping dialog\");\n return false;\n }\n }\n \n // Default to showing the dialog\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking donation dialog preference: {ex.Message}\", ex);\n // Default to showing the dialog if there's an error\n return true;\n }\n }\n \n /// \n public async Task SaveDontShowSupportPreferenceAsync(bool dontShow)\n {\n try\n {\n // Get the preferences directory path\n string preferencesDir = Path.GetDirectoryName(_preferencesFilePath);\n \n // Create the directory if it doesn't exist\n if (!Directory.Exists(preferencesDir))\n {\n Directory.CreateDirectory(preferencesDir);\n }\n \n // Create or update the preferences file\n string json = \"{}\";\n if (File.Exists(_preferencesFilePath))\n {\n json = await File.ReadAllTextAsync(_preferencesFilePath);\n }\n \n // Simple JSON manipulation (not ideal but should work for this case)\n if (json == \"{}\")\n {\n json = \"{ \\\"DontShowSupport\\\": \" + (dontShow ? \"true\" : \"false\") + \" }\";\n }\n else if (json.Contains(\"\\\"DontShowSupport\\\":\") || json.Contains(\"\\\"DontShowSupport\\\": \"))\n {\n json = json.Replace(\"\\\"DontShowSupport\\\": true\", \"\\\"DontShowSupport\\\": \" + (dontShow ? \"true\" : \"false\"));\n json = json.Replace(\"\\\"DontShowSupport\\\": false\", \"\\\"DontShowSupport\\\": \" + (dontShow ? \"true\" : \"false\"));\n json = json.Replace(\"\\\"DontShowSupport\\\":true\", \"\\\"DontShowSupport\\\":\" + (dontShow ? \"true\" : \"false\"));\n json = json.Replace(\"\\\"DontShowSupport\\\":false\", \"\\\"DontShowSupport\\\":\" + (dontShow ? \"true\" : \"false\"));\n }\n else\n {\n // Remove the closing brace\n json = json.TrimEnd('}');\n // Add a comma if there are other properties\n if (json.TrimEnd().EndsWith(\"}\"))\n {\n json += \",\";\n }\n // Add the new property and closing brace\n json += \" \\\"DontShowSupport\\\": \" + (dontShow ? \"true\" : \"false\") + \" }\";\n }\n \n // Write the updated JSON back to the file\n await File.WriteAllTextAsync(_preferencesFilePath, json);\n _logService.LogInformation($\"Successfully saved DontShowSupport preference: {dontShow}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error saving DontShowSupport preference: {ex.Message}\", ex);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Utilities/WinGetInstallationScript.cs", "using System;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Management.Automation;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Utilities\n{\n /// \n /// Provides functionality to install WinGet when it is not found on the system.\n /// \n public static class WinGetInstallationScript\n {\n /// \n /// The PowerShell script used to install WinGet by downloading it directly from GitHub.\n /// \n public static readonly string InstallScript =\n @\"\n# PowerShell script to install WinGet from GitHub\nWrite-Output \"\"Starting WinGet installation process... [PROGRESS:25]\"\"\n\n# Create a temporary directory for downloads\n$tempDir = Join-Path $env:TEMP \"\"WinGetInstall\"\"\nif (Test-Path $tempDir) {\n Remove-Item -Path $tempDir -Recurse -Force\n}\nNew-Item -Path $tempDir -ItemType Directory -Force | Out-Null\n\ntry {\n # Download URLs\n $dependenciesUrl = \"\"https://github.com/microsoft/winget-cli/releases/latest/download/DesktopAppInstaller_Dependencies.zip\"\"\n $installerUrl = \"\"https://github.com/microsoft/winget-cli/releases/latest/download/Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle\"\"\n $licenseUrl = \"\"https://github.com/microsoft/winget-cli/releases/latest/download/e53e159d00e04f729cc2180cffd1c02e_License1.xml\"\"\n \n # Download paths\n $dependenciesPath = Join-Path $tempDir \"\"DesktopAppInstaller_Dependencies.zip\"\"\n $installerPath = Join-Path $tempDir \"\"Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle\"\"\n $licensePath = Join-Path $tempDir \"\"e53e159d00e04f729cc2180cffd1c02e_License1.xml\"\"\n \n # Download the dependencies\n Write-Output \"\"Downloading WinGet dependencies... [PROGRESS:30]\"\"\n Invoke-WebRequest -Uri $dependenciesUrl -OutFile $dependenciesPath -UseBasicParsing\n \n # Download the installer\n Write-Output \"\"Downloading WinGet installer... [PROGRESS:40]\"\"\n Invoke-WebRequest -Uri $installerUrl -OutFile $installerPath -UseBasicParsing\n \n # Download the license file (needed for LTSC editions)\n Write-Output \"\"Downloading WinGet license file... [PROGRESS:45]\"\"\n Invoke-WebRequest -Uri $licenseUrl -OutFile $licensePath -UseBasicParsing\n \n # Extract the dependencies\n Write-Output \"\"Extracting dependencies... [PROGRESS:50]\"\"\n $extractPath = Join-Path $tempDir \"\"Dependencies\"\"\n Expand-Archive -Path $dependenciesPath -DestinationPath $extractPath -Force\n \n # Install all dependencies\n Write-Output \"\"Installing dependencies... [PROGRESS:60]\"\"\n $dependencyFiles = Get-ChildItem -Path $extractPath -Filter *.appx -Recurse\n foreach ($file in $dependencyFiles) {\n Write-Output \"\"Installing dependency: $($file.Name)\"\"\n try {\n Add-AppxPackage -Path $file.FullName\n }\n catch {\n Write-Output \"\"[ERROR] Failed to install WinGet: $($_.Exception.Message)\"\"\n throw $_\n }\n }\n \n # Install the WinGet installer\n Write-Output \"\"Installing WinGet... [PROGRESS:80]\"\"\n try {\n # Always use Add-AppxProvisionedPackage with license for all Windows editions\n Write-Output \"\"Installing WinGet with license file\"\"\n Add-AppxProvisionedPackage -Online -PackagePath $installerPath -LicensePath $licensePath\n Write-Output \"\"WinGet installation completed successfully [PROGRESS:90]\"\"\n \n # Refresh PATH environment variable to include WindowsApps directory where WinGet is installed\n Write-Output \"\"Refreshing PATH environment to include WinGet...\"\"\n $env:Path = [System.Environment]::GetEnvironmentVariable(\"\"Path\"\", \"\"Machine\"\") + \"\";\"\" + [System.Environment]::GetEnvironmentVariable(\"\"Path\"\", \"\"User\"\")\n \n # Verify WinGet installation by running a command\n Write-Output \"\"Verifying WinGet installation...\"\"\n \n # Try to find WinGet in common locations\n $wingetPaths = @(\n \"\"winget.exe\"\", # Check if it's in PATH\n \"\"$env:LOCALAPPDATA\\Microsoft\\WindowsApps\\winget.exe\"\",\n \"\"$env:ProgramFiles\\WindowsApps\\Microsoft.DesktopAppInstaller_*\\winget.exe\"\"\n )\n \n $wingetFound = $false\n foreach ($path in $wingetPaths) {\n if ($path -like \"\"*`**\"\") {\n # Handle wildcard paths\n $resolvedPaths = Resolve-Path $path -ErrorAction SilentlyContinue\n if ($resolvedPaths) {\n foreach ($resolvedPath in $resolvedPaths) {\n if (Test-Path $resolvedPath) {\n Write-Output \"\"Found WinGet at: $resolvedPath\"\"\n $wingetFound = $true\n # Add the directory to PATH if not already there\n $wingetDir = Split-Path $resolvedPath\n if ($env:Path -notlike \"\"*$wingetDir*\"\") {\n $env:Path += \"\";$wingetDir\"\"\n }\n break\n }\n }\n }\n } else {\n # Handle direct paths\n if (Test-Path $path) {\n Write-Output \"\"Found WinGet at: $path\"\"\n $wingetFound = $true\n # Add the directory to PATH if not already there\n $wingetDir = Split-Path $path\n if ($env:Path -notlike \"\"*$wingetDir*\"\") {\n $env:Path += \"\";$wingetDir\"\"\n }\n break\n }\n }\n }\n \n if (-not $wingetFound) {\n # Try running winget command directly to see if it works\n try {\n $wingetVersion = & winget.exe --version 2>&1\n if ($LASTEXITCODE -eq 0) {\n Write-Output \"\"WinGet is available in PATH: $wingetVersion\"\"\n $wingetFound = $true\n }\n } catch {\n Write-Output \"\"WinGet command not found in PATH\"\"\n }\n }\n \n if (-not $wingetFound) {\n Write-Output \"\"[WARNING] WinGet was installed but could not be found in PATH. You may need to restart your system.\"\"\n }\n }\n catch {\n Write-Output \"\"[ERROR] Failed to install WinGet: $($_.Exception.Message)\"\"\n throw $_\n }\n}\ncatch {\n Write-Output \"\"[ERROR] An error occurred during WinGet installation: $($_.Exception.Message)\"\"\n throw $_\n}\nfinally {\n # Clean up\n Write-Output \"\"Cleaning up temporary files... [PROGRESS:95]\"\"\n if (Test-Path $tempDir) {\n Remove-Item -Path $tempDir -Recurse -Force\n }\n Write-Output \"\"WinGet installation process completed [PROGRESS:100]\"\"\n}\n\";\n\n /// \n /// Installs WinGet by downloading it directly from GitHub and installing it.\n /// \n /// Optional progress reporting.\n /// Optional logger for logging the installation process.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with a result indicating success or failure.\n public static async Task<(bool Success, string Message)> InstallWinGetAsync(\n IProgress progress = null,\n ILogService logger = null,\n CancellationToken cancellationToken = default\n )\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 10,\n StatusText = \"Preparing to download WinGet from GitHub...\",\n DetailedMessage =\n \"This may take a few minutes depending on your internet connection.\",\n }\n );\n\n logger?.LogInformation(\"Starting WinGet installation by downloading from GitHub\");\n\n // Create a temporary directory if it doesn't exist\n string tempDir = Path.Combine(Path.GetTempPath(), \"WinhanceTemp\");\n Directory.CreateDirectory(tempDir);\n\n // Create a temporary script file\n string scriptPath = Path.Combine(tempDir, $\"WinGetInstall_{Guid.NewGuid()}.ps1\");\n\n // Write the installation script to the file\n File.WriteAllText(scriptPath, InstallScript);\n\n try\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 20,\n StatusText = \"Downloading and installing WinGet components...\",\n DetailedMessage =\n \"This may take a few minutes depending on your internet connection.\",\n }\n );\n\n // Execute the PowerShell script with elevated privileges\n // Use PowerShellFactory to ensure we get the right PowerShell version based on OS\n // This is especially important for Windows 10 where Add-AppxPackage needs Windows PowerShell 5.1\n // We need to use Windows PowerShell 5.1 on Windows 10 for Add-AppxPackage command\n using (var powerShell = PowerShellFactory.CreateForAppxCommands(logger))\n {\n // Add the script to execute\n powerShell.AddScript($\". '{scriptPath}'\");\n\n // Set up real-time output processing using PowerShell events\n var outputBuilder = new StringBuilder();\n\n // Subscribe to the DataAdded event for Information stream\n powerShell.Streams.Information.DataAdded += (sender, e) =>\n {\n var streamObjectsReceived = sender as PSDataCollection;\n if (streamObjectsReceived != null)\n {\n var informationRecord = streamObjectsReceived[e.Index];\n string output = informationRecord.MessageData.ToString();\n outputBuilder.AppendLine(output);\n logger?.LogInformation($\"WinGet installation: {output}\");\n\n ProcessOutputLine(output, progress, logger);\n }\n };\n\n // Subscribe to the DataAdded event for Output stream\n var outputCollection = new PSDataCollection();\n outputCollection.DataAdded += (sender, e) =>\n {\n var streamObjectsReceived = sender as PSDataCollection;\n if (streamObjectsReceived != null)\n {\n var outputObject = streamObjectsReceived[e.Index];\n string output = outputObject.ToString();\n outputBuilder.AppendLine(output);\n logger?.LogInformation($\"WinGet installation: {output}\");\n\n ProcessOutputLine(output, progress, logger);\n }\n };\n\n // Execute the script asynchronously to capture real-time output\n await Task.Run(\n () => powerShell.Invoke(null, outputCollection),\n cancellationToken\n );\n\n // Helper method to process output lines for progress and error markers\n void ProcessOutputLine(\n string output,\n IProgress progress,\n ILogService logger\n )\n {\n // Check for progress markers in the output\n if (output.Contains(\"[PROGRESS:\"))\n {\n var progressMatch = System.Text.RegularExpressions.Regex.Match(\n output,\n @\"\\[PROGRESS:(\\d+)\\]\"\n );\n if (\n progressMatch.Success\n && int.TryParse(\n progressMatch.Groups[1].Value,\n out int progressValue\n )\n )\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = progressValue,\n StatusText = output.Replace(progressMatch.Value, \"\").Trim(),\n }\n );\n }\n }\n // Check for error markers in the output\n else if (output.Contains(\"[ERROR]\"))\n {\n var errorMessage = output.Replace(\"[ERROR]\", \"\").Trim();\n logger?.LogError($\"WinGet installation error: {errorMessage}\");\n }\n }\n\n // Check for errors\n if (powerShell.HadErrors)\n {\n var errorBuilder = new StringBuilder(\"Errors during WinGet installation:\");\n foreach (var error in powerShell.Streams.Error)\n {\n errorBuilder.AppendLine(error.Exception.Message);\n logger?.LogError(\n $\"WinGet installation error: {error.Exception.Message}\"\n );\n }\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = \"WinGet installation failed\",\n DetailedMessage = errorBuilder.ToString(),\n LogLevel = Winhance.Core.Features.Common.Enums.LogLevel.Error,\n }\n );\n\n return (false, errorBuilder.ToString());\n }\n\n // Report success\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = \"WinGet installation completed successfully\",\n DetailedMessage = \"WinGet has been installed and is ready to use.\",\n }\n );\n\n logger?.LogInformation(\"WinGet installation completed successfully\");\n return (true, \"WinGet has been successfully installed.\");\n }\n }\n catch (Exception ex)\n {\n string errorMessage = $\"Error installing WinGet: {ex.Message}\";\n logger?.LogError(errorMessage, ex);\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = \"WinGet installation failed\",\n DetailedMessage = errorMessage,\n LogLevel = Winhance.Core.Features.Common.Enums.LogLevel.Error,\n }\n );\n\n return (false, errorMessage);\n }\n finally\n {\n // Clean up the temporary script file\n try\n {\n if (File.Exists(scriptPath))\n {\n File.Delete(scriptPath);\n }\n }\n catch (Exception ex)\n {\n logger?.LogWarning($\"Failed to delete temporary script file: {ex.Message}\");\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/OneDriveInstallationService.cs", "using System;\nusing System.IO;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that handles OneDrive installation.\n/// \npublic class OneDriveInstallationService : IOneDriveInstallationService, IDisposable\n{\n private readonly ILogService _logService;\n private readonly HttpClient _httpClient;\n private readonly string _tempDir = Path.Combine(Path.GetTempPath(), \"WinhanceInstaller\");\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public OneDriveInstallationService(ILogService logService)\n {\n _logService = logService;\n _httpClient = new HttpClient();\n Directory.CreateDirectory(_tempDir);\n }\n\n /// \n public async Task InstallOneDriveAsync(\n IProgress? progress,\n CancellationToken cancellationToken)\n {\n try\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Starting OneDrive installation...\",\n DetailedMessage = \"Downloading OneDrive installer from Microsoft\"\n });\n\n // Download OneDrive from the specific URL\n string downloadUrl = \"https://go.microsoft.com/fwlink/p/?LinkID=2182910\";\n string installerPath = Path.Combine(_tempDir, \"OneDriveSetup.exe\");\n\n using (var client = new HttpClient())\n {\n var response = await client.GetAsync(downloadUrl, cancellationToken);\n if (!response.IsSuccessStatusCode)\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Failed to download OneDrive installer\",\n DetailedMessage = $\"HTTP error: {response.StatusCode}\",\n LogLevel = LogLevel.Error\n });\n return false;\n }\n\n using (var fileStream = new FileStream(installerPath, FileMode.Create, FileAccess.Write, FileShare.None))\n {\n await response.Content.CopyToAsync(fileStream, cancellationToken);\n }\n }\n\n progress?.Report(new TaskProgressDetail\n {\n Progress = 50,\n StatusText = \"Installing OneDrive...\",\n DetailedMessage = \"Running OneDrive installer\"\n });\n\n // Run the installer\n using (var process = new System.Diagnostics.Process())\n {\n process.StartInfo.FileName = installerPath;\n process.StartInfo.Arguments = \"/silent\";\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.RedirectStandardError = true;\n process.StartInfo.CreateNoWindow = true;\n\n process.Start();\n await Task.Run(() => process.WaitForExit(), cancellationToken);\n\n bool success = process.ExitCode == 0;\n\n progress?.Report(new TaskProgressDetail\n {\n Progress = 100,\n StatusText = success ? \"OneDrive installed successfully\" : \"OneDrive installation failed\",\n DetailedMessage = $\"Installer exited with code: {process.ExitCode}\",\n LogLevel = success ? LogLevel.Success : LogLevel.Error\n });\n\n return success;\n }\n }\n catch (Exception ex)\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Error installing OneDrive\",\n DetailedMessage = $\"Exception: {ex.Message}\",\n LogLevel = LogLevel.Error\n });\n return false;\n }\n }\n\n /// \n /// Disposes the resources used by the service.\n /// \n public void Dispose()\n {\n _httpClient.Dispose();\n GC.SuppressFinalize(this);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/MoreMenuViewModel.cs", "using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Runtime.CompilerServices;\nusing System.Windows;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// ViewModel for the More menu functionality\n /// \n public class MoreMenuViewModel : ObservableObject\n {\n private readonly ILogService _logService;\n private readonly IVersionService _versionService;\n private readonly IMessengerService _messengerService;\n private readonly IApplicationCloseService _applicationCloseService;\n private readonly IDialogService _dialogService;\n\n private string _versionInfo;\n\n /// \n /// Gets or sets the version information text displayed in the menu\n /// \n public string VersionInfo\n {\n get => _versionInfo;\n set => SetProperty(ref _versionInfo, value);\n }\n\n /// \n /// Command to check for application updates\n /// \n public ICommand CheckForUpdatesCommand { get; }\n\n /// \n /// Command to open the logs folder\n /// \n public ICommand OpenLogsCommand { get; }\n\n /// \n /// Command to open the scripts folder\n /// \n public ICommand OpenScriptsCommand { get; }\n\n /// \n /// Command to close the application\n /// \n public ICommand CloseApplicationCommand { get; }\n\n /// \n /// Constructor with dependency injection\n /// \n /// Service for logging\n /// Service for version information and updates\n /// Service for messaging between components\n public MoreMenuViewModel(\n ILogService logService,\n IVersionService versionService,\n IMessengerService messengerService,\n IApplicationCloseService applicationCloseService,\n IDialogService dialogService\n )\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _versionService =\n versionService ?? throw new ArgumentNullException(nameof(versionService));\n _messengerService =\n messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n _applicationCloseService =\n applicationCloseService\n ?? throw new ArgumentNullException(nameof(applicationCloseService));\n _dialogService =\n dialogService\n ?? throw new ArgumentNullException(nameof(dialogService));\n\n // Initialize version info\n UpdateVersionInfo();\n\n // Initialize commands with explicit execute and canExecute methods\n CheckForUpdatesCommand = new RelayCommand(\n execute: () =>\n {\n _logService.LogInformation(\"CheckForUpdatesCommand executed\");\n CheckForUpdatesAsync();\n },\n canExecute: () => true\n );\n\n OpenLogsCommand = new RelayCommand(\n execute: () =>\n {\n _logService.LogInformation(\"OpenLogsCommand executed\");\n OpenLogs();\n },\n canExecute: () => true\n );\n\n OpenScriptsCommand = new RelayCommand(\n execute: () =>\n {\n _logService.LogInformation(\"OpenScriptsCommand executed\");\n OpenScripts();\n },\n canExecute: () => true\n );\n\n CloseApplicationCommand = new RelayCommand(\n execute: () =>\n {\n _logService.LogInformation(\"CloseApplicationCommand executed\");\n CloseApplication();\n },\n canExecute: () => true\n );\n }\n\n /// \n /// Updates the version information text\n /// \n private void UpdateVersionInfo()\n {\n try\n {\n // Get the current version from the version service\n VersionInfo versionInfo = _versionService.GetCurrentVersion();\n\n // Format the version text\n VersionInfo = $\"Winhance Version {versionInfo.Version}\";\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating version info: {ex.Message}\", ex);\n\n // Set a default version text in case of error\n VersionInfo = \"Winhance Version\";\n }\n }\n\n /// \n /// Checks for updates and shows appropriate dialog\n /// \n private async void CheckForUpdatesAsync()\n {\n try\n {\n _logService.LogInformation(\"Checking for updates from MoreMenu\");\n\n // Get the current version\n VersionInfo currentVersion = _versionService.GetCurrentVersion();\n _logService.LogInformation($\"Current version: {currentVersion.Version}\");\n\n // Check for updates\n VersionInfo latestVersion = await _versionService.CheckForUpdateAsync();\n _logService.LogInformation(\n $\"Latest version: {latestVersion.Version}, Update available: {latestVersion.IsUpdateAvailable}\"\n );\n\n if (latestVersion.IsUpdateAvailable)\n {\n // Show update dialog\n string title = \"Update Available\";\n string message = \"Good News! A New Version of Winhance is available.\";\n\n _logService.LogInformation(\"Showing update dialog\");\n // Show the update dialog\n await UpdateDialog.ShowAsync(\n title,\n message,\n currentVersion,\n latestVersion,\n async () =>\n {\n _logService.LogInformation(\n \"User initiated update download and installation\"\n );\n await _versionService.DownloadAndInstallUpdateAsync();\n }\n );\n }\n else\n {\n _logService.LogInformation(\"No updates available\");\n // Show a message that no update is available\n _dialogService.ShowInformationAsync(\n \"You have the latest version of Winhance.\",\n \"No Updates Available\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking for updates: {ex.Message}\", ex);\n\n // Show an error message\n _dialogService.ShowErrorAsync(\n $\"An error occurred while checking for updates: {ex.Message}\",\n \"Update Check Error\"\n );\n }\n }\n\n /// \n /// Opens the logs folder\n /// \n private void OpenLogs()\n {\n try\n {\n // Get the logs folder path\n string logsFolder = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\"\n );\n\n // Create the folder if it doesn't exist\n if (!Directory.Exists(logsFolder))\n {\n Directory.CreateDirectory(logsFolder);\n }\n\n // Open the logs folder using ProcessStartInfo with UseShellExecute=true\n var psi = new ProcessStartInfo\n {\n FileName = \"explorer.exe\",\n Arguments = logsFolder,\n UseShellExecute = true,\n };\n Process.Start(psi);\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error opening logs folder: {ex.Message}\", ex);\n\n // Show an error message\n _dialogService.ShowErrorAsync(\n $\"An error occurred while opening the logs folder: {ex.Message}\",\n \"Logs Folder Error\"\n );\n }\n }\n\n /// \n /// Opens the scripts folder\n /// \n private void OpenScripts()\n {\n try\n {\n // Get the scripts folder path\n string scriptsFolder = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n \"Winhance\",\n \"Scripts\"\n );\n\n // Create the folder if it doesn't exist\n if (!Directory.Exists(scriptsFolder))\n {\n Directory.CreateDirectory(scriptsFolder);\n }\n\n // Open the scripts folder using ProcessStartInfo with UseShellExecute=true\n var psi = new ProcessStartInfo\n {\n FileName = \"explorer.exe\",\n Arguments = scriptsFolder,\n UseShellExecute = true,\n };\n Process.Start(psi);\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error opening scripts folder: {ex.Message}\", ex);\n\n // Show an error message\n _dialogService.ShowErrorAsync(\n $\"An error occurred while opening the scripts folder: {ex.Message}\",\n \"Scripts Folder Error\"\n );\n }\n }\n\n /// \n /// Closes the application using the same behavior as the normal close button\n /// \n private async void CloseApplication()\n {\n try\n {\n _logService.LogInformation(\n \"Closing application from MoreMenu, delegating to ApplicationCloseService\"\n );\n await _applicationCloseService.CloseApplicationWithSupportDialogAsync();\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error closing application: {ex.Message}\", ex);\n\n // Fallback to direct application shutdown if everything else fails\n try\n {\n _logService.LogInformation(\"Falling back to Application.Current.Shutdown()\");\n Application.Current.Dispatcher.Invoke(() => Application.Current.Shutdown());\n }\n catch (Exception shutdownEx)\n {\n _logService.LogError(\n $\"Error shutting down application: {shutdownEx.Message}\",\n shutdownEx\n );\n\n // Last resort\n Environment.Exit(0);\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/MainWindow.xaml.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Interop;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.Common.Utilities;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n public partial class MainWindow : Window\n {\n private readonly Winhance.Core.Features.Common.Interfaces.INavigationService _navigationService =\n null!;\n private WindowSizeManager _windowSizeManager;\n private readonly UserPreferencesService _userPreferencesService;\n private readonly IApplicationCloseService _applicationCloseService;\n\n private void LogDebug(string message, Exception? ex = null)\n {\n string fullMessage = message + (ex != null ? $\" - Exception: {ex.Message}\" : \"\");\n\n // Use proper logging service for application logging\n _messengerService?.Send(\n new LogMessage\n {\n Message = fullMessage,\n Level = ex != null ? LogLevel.Error : LogLevel.Debug,\n Exception = ex,\n }\n );\n\n // Also log to diagnostic file for troubleshooting\n FileLogger.Log(\"MainWindow\", fullMessage);\n\n // If there's an exception, log the stack trace as well\n if (ex != null)\n {\n FileLogger.Log(\"MainWindow\", $\"Stack trace: {ex.StackTrace}\");\n }\n\n // Also log to WinhanceStartupLog.txt for debugging the white screen issue\n LogToStartupLog(fullMessage);\n if (ex != null)\n {\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n }\n }\n\n /// \n /// Logs a message directly to the WinhanceStartupLog.txt file\n /// \n private void LogToStartupLog(string message)\n {\n#if DEBUG\n try\n {\n string logsDir = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\"\n );\n string logFile = Path.Combine(logsDir, \"WinhanceStartupLog.txt\");\n\n // Ensure the logs directory exists\n if (!Directory.Exists(logsDir))\n {\n Directory.CreateDirectory(logsDir);\n }\n\n // Format the log message with timestamp\n string formattedMessage =\n $\"[{DateTime.Now:yyyy/MM/dd HH:mm:ss}] [MainWindow] {message}\";\n\n // Append to the log file\n using (StreamWriter writer = File.AppendText(logFile))\n {\n writer.WriteLine(formattedMessage);\n }\n }\n catch\n {\n // Ignore errors in logging to avoid cascading issues\n }\n#endif\n }\n\n public MainWindow()\n {\n LogDebug(\"Default constructor called - THIS SHOULD NOT HAPPEN\");\n try\n {\n // Don't worry about this error, it is initialized at runtime.\n InitializeComponent();\n LogDebug(\"Default constructor completed initialization\");\n\n // Direct event handlers for window control buttons\n this.MinimizeButton.Click += (s, e) => this.WindowState = WindowState.Minimized;\n this.MaximizeRestoreButton.Click += (s, e) =>\n {\n this.WindowState =\n (this.WindowState == WindowState.Maximized)\n ? WindowState.Normal\n : WindowState.Maximized;\n };\n this.CloseButton.Click += CloseButton_Click;\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in default constructor\", ex);\n throw;\n }\n }\n\n // No need to define InitializeComponent here, it's generated by the WPF build system\n\n public MainWindow(\n IThemeManager themeManager,\n IServiceProvider serviceProvider,\n IMessengerService messengerService,\n Winhance.Core.Features.Common.Interfaces.INavigationService navigationService,\n IVersionService versionService,\n UserPreferencesService userPreferencesService,\n IApplicationCloseService applicationCloseService\n )\n {\n try\n {\n // Use FileLogger directly to ensure we capture everything\n FileLogger.Log(\"MainWindow\", \"MainWindow constructor starting\");\n FileLogger.Log(\n \"MainWindow\",\n $\"Parameters: themeManager={themeManager != null}, serviceProvider={serviceProvider != null}, messengerService={messengerService != null}, navigationService={navigationService != null}, versionService={versionService != null}, userPreferencesService={userPreferencesService != null}\"\n );\n\n // Verify dependencies\n if (themeManager == null)\n throw new ArgumentNullException(nameof(themeManager));\n if (serviceProvider == null)\n throw new ArgumentNullException(nameof(serviceProvider));\n if (messengerService == null)\n throw new ArgumentNullException(nameof(messengerService));\n if (navigationService == null)\n throw new ArgumentNullException(nameof(navigationService));\n if (versionService == null)\n throw new ArgumentNullException(nameof(versionService));\n if (userPreferencesService == null)\n throw new ArgumentNullException(nameof(userPreferencesService));\n FileLogger.Log(\"MainWindow\", \"Dependencies verified\");\n\n // Let the build system initialize the component\n try\n {\n LogToStartupLog(\"Starting InitializeComponent\");\n\n // We'll use a try-catch block around each part of the InitializeComponent process\n try\n {\n LogToStartupLog(\"Calling InitializeComponent()\");\n InitializeComponent();\n LogToStartupLog(\"InitializeComponent() completed successfully\");\n }\n catch (Exception initEx)\n {\n LogToStartupLog($\"ERROR in InitializeComponent(): {initEx.Message}\");\n LogToStartupLog($\"Stack trace: {initEx.StackTrace}\");\n throw; // Re-throw to be caught by the outer try-catch\n }\n\n LogToStartupLog(\"InitializeComponent completed\");\n\n // Direct event handlers for window control buttons\n try\n {\n LogToStartupLog(\"Setting up window control button event handlers\");\n\n LogToStartupLog($\"MinimizeButton exists: {this.MinimizeButton != null}\");\n this.MinimizeButton.Click += (s, e) =>\n this.WindowState = WindowState.Minimized;\n\n LogToStartupLog(\n $\"MaximizeRestoreButton exists: {this.MaximizeRestoreButton != null}\"\n );\n this.MaximizeRestoreButton.Click += (s, e) =>\n {\n this.WindowState =\n (this.WindowState == WindowState.Maximized)\n ? WindowState.Normal\n : WindowState.Maximized;\n\n // Update button content when window state changes\n if (DataContext is MainViewModel viewModel)\n {\n viewModel.MaximizeButtonContent =\n (this.WindowState == WindowState.Maximized)\n ? \"WindowRestore\"\n : \"WindowMaximize\";\n }\n };\n\n LogToStartupLog($\"CloseButton exists: {this.CloseButton != null}\");\n this.CloseButton.Click += CloseButton_Click;\n\n LogToStartupLog($\"MoreButton exists: {this.MoreButton != null}\");\n LogToStartupLog($\"MoreMenuControl exists: {this.MoreMenuControl != null}\");\n this.MoreButton.Click += MoreButton_Click;\n\n LogToStartupLog(\n \"Successfully set up all window control button event handlers\"\n );\n }\n catch (Exception buttonEx)\n {\n LogToStartupLog(\n $\"ERROR setting up button event handlers: {buttonEx.Message}\"\n );\n LogToStartupLog($\"Stack trace: {buttonEx.StackTrace}\");\n }\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in InitializeComponent\", ex);\n // This is not ideal, but we'll continue since the constructor errors will be handled\n }\n\n LogDebug(\"Setting fields\");\n _themeManager = themeManager;\n _serviceProvider = serviceProvider;\n _messengerService = messengerService;\n _navigationService = navigationService;\n _versionService =\n versionService ?? throw new ArgumentNullException(nameof(versionService));\n\n // Create the window size manager\n try\n {\n var logService =\n _serviceProvider.GetService(typeof(ILogService)) as ILogService;\n\n if (userPreferencesService != null && logService != null)\n {\n _windowSizeManager = new WindowSizeManager(\n this,\n userPreferencesService,\n logService\n );\n LogDebug(\"WindowSizeManager created successfully\");\n }\n else\n {\n LogDebug(\"Could not create WindowSizeManager: services not available\");\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error creating WindowSizeManager: {ex.Message}\", ex);\n }\n _userPreferencesService =\n userPreferencesService\n ?? throw new ArgumentNullException(nameof(userPreferencesService));\n _applicationCloseService =\n applicationCloseService\n ?? throw new ArgumentNullException(nameof(applicationCloseService));\n LogDebug(\"Fields set\");\n\n // Hook up events for ContentPresenter-based navigation\n if (\n _navigationService\n is Winhance.Core.Features.Common.Interfaces.INavigationService navService\n )\n {\n LogDebug(\"Setting up navigation service for ContentPresenter-based navigation\");\n\n // Add PreviewMouseWheel event handler for better scrolling\n this.PreviewMouseWheel += MainWindow_PreviewMouseWheel;\n\n // We'll navigate once the window is fully loaded\n this.Loaded += (sender, e) =>\n {\n LogDebug(\"Window loaded, navigating to default view\");\n\n // Apply the theme to ensure all toggle switches are properly initialized\n try\n {\n LogDebug(\"Applying theme to initialize toggle switches\");\n if (_themeManager != null)\n {\n // Apply the theme which will update all toggle switches\n _themeManager.ApplyTheme();\n LogDebug(\"Successfully initialized toggle switches\");\n\n // Update the app icon based on the theme\n UpdateThemeIcon();\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error initializing toggle switches: {ex.Message}\", ex);\n }\n\n if (DataContext is MainViewModel mainViewModel)\n {\n try\n {\n // Navigate to SoftwareApps view by default\n LogDebug(\"Navigating to SoftwareApps view\");\n _navigationService.NavigateTo(\"SoftwareApps\");\n\n // Verify that navigation succeeded\n if (mainViewModel.CurrentViewModel == null)\n {\n LogDebug(\n \"WARNING: Navigation succeeded but CurrentViewModel is null\"\n );\n }\n else\n {\n LogDebug(\n $\"Navigation succeeded, CurrentViewModel is {mainViewModel.CurrentViewModel.GetType().Name}\"\n );\n }\n }\n catch (Exception ex)\n {\n LogDebug(\n $\"Error navigating to SoftwareApps view: {ex.Message}\",\n ex\n );\n\n // Try to recover by navigating to another view\n try\n {\n LogDebug(\"Attempting to navigate to About view as fallback\");\n _navigationService.NavigateTo(\"About\");\n }\n catch (Exception fallbackEx)\n {\n LogDebug(\n $\"Error navigating to fallback view: {fallbackEx.Message}\",\n fallbackEx\n );\n }\n }\n }\n else\n {\n LogDebug(\n $\"DataContext is not MainViewModel, it is {DataContext?.GetType().Name ?? \"null\"}\"\n );\n }\n };\n\n // Add StateChanged event to update Maximize/Restore button content only\n this.StateChanged += (sender, e) =>\n {\n if (DataContext is MainViewModel viewModel)\n {\n viewModel.MaximizeButtonContent =\n (this.WindowState == WindowState.Maximized)\n ? \"WindowRestore\"\n : \"WindowMaximize\";\n }\n };\n\n // We no longer save window position/size to preferences\n }\n else\n {\n LogDebug(\n $\"_navigationService is not INavigationService, it is {_navigationService?.GetType().Name ?? \"null\"}\"\n );\n }\n\n // Register for window state messages\n LogDebug(\"Registering for window state messages\");\n _messengerService.Register(this, HandleWindowStateMessage);\n LogDebug(\"Registered for window state messages\");\n\n // Add Closing event handler to log the closing process\n this.Closing += MainWindow_Closing;\n\n // Clean up when window is closed\n this.Closed += (sender, e) =>\n {\n LogDebug(\"Window closed, unregistering from messenger service\");\n _messengerService.Unregister(this);\n };\n\n LogDebug($\"DataContext is {(DataContext == null ? \"null\" : \"not null\")}\");\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in parameterized constructor\", ex);\n throw;\n }\n }\n\n private async void CloseButton_Click(object sender, RoutedEventArgs e)\n {\n try\n {\n LogDebug(\"CloseButton_Click called, delegating to ApplicationCloseService\");\n await _applicationCloseService.CloseApplicationWithSupportDialogAsync();\n }\n catch (Exception ex)\n {\n LogDebug($\"Error in CloseButton_Click: {ex.Message}\", ex);\n\n // Fallback to direct close if there's an error\n try\n {\n this.Close();\n }\n catch\n {\n // Last resort\n Application.Current.Shutdown();\n }\n }\n }\n\n private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)\n {\n try\n {\n // Check if the DataContext is MainViewModel\n if (DataContext is MainViewModel viewModel)\n {\n LogDebug(\"DataContext is MainViewModel\");\n\n // Log any relevant properties or state from the ViewModel\n LogDebug($\"CurrentViewName: {viewModel.CurrentViewName}\");\n LogDebug(\n $\"CurrentViewModel type: {viewModel.CurrentViewModel?.GetType().FullName ?? \"null\"}\"\n );\n }\n else\n {\n LogDebug(\n $\"DataContext is not MainViewModel, it is {DataContext?.GetType().Name ?? \"null\"}\"\n );\n }\n\n // Log active windows\n LogDebug(\"Active windows:\");\n foreach (Window window in Application.Current.Windows)\n {\n LogDebug(\n $\"Window: {window.GetType().FullName}, IsVisible: {window.IsVisible}, WindowState: {window.WindowState}\"\n );\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error in MainWindow_Closing: {ex.Message}\", ex);\n }\n }\n\n private readonly IMessengerService _messengerService = null!;\n private readonly IVersionService _versionService = null!;\n\n #region More Button Event Handlers\n\n /// \n /// Event handler for the More button click\n /// Shows the context menu when the More button is clicked\n /// \n private void MoreButton_Click(object sender, RoutedEventArgs e)\n {\n // Log to the startup log file\n LogToStartupLog(\"More button clicked\");\n\n try\n {\n // Show the context menu using the MoreMenu control\n LogToStartupLog($\"MoreMenuControl exists: {MoreMenuControl != null}\");\n LogToStartupLog($\"MoreButton exists: {MoreButton != null}\");\n\n if (MoreMenuControl != null)\n {\n LogToStartupLog(\"About to call MoreMenuControl.ShowMenu()\");\n\n try\n {\n // Show the menu with the More button as the placement target\n MoreMenuControl.ShowMenu(MoreButton);\n LogToStartupLog(\"MoreMenuControl.ShowMenu() called successfully\");\n }\n catch (Exception menuEx)\n {\n LogToStartupLog($\"ERROR in MoreMenuControl.ShowMenu(): {menuEx.Message}\");\n LogToStartupLog($\"Stack trace: {menuEx.StackTrace}\");\n }\n }\n else\n {\n LogToStartupLog(\"MoreMenuControl is null, cannot show menu\");\n }\n }\n catch (Exception ex)\n {\n LogToStartupLog($\"Error in MoreButton_Click: {ex.Message}\");\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n }\n }\n\n // Context menu event handlers have been moved to MoreMenuViewModel\n\n #endregion\n\n private void HandleWindowStateMessage(WindowStateMessage message)\n {\n LogDebug($\"Received window state message: {message.Action}\");\n\n try\n {\n switch (message.Action)\n {\n case WindowStateMessage.WindowStateAction.Minimize:\n LogDebug(\"Processing minimize action\");\n WindowState = WindowState.Minimized;\n break;\n\n case WindowStateMessage.WindowStateAction.Maximize:\n LogDebug(\"Processing maximize action\");\n WindowState = WindowState.Maximized;\n break;\n\n case WindowStateMessage.WindowStateAction.Restore:\n LogDebug(\"Processing restore action\");\n WindowState = WindowState.Normal;\n break;\n\n case WindowStateMessage.WindowStateAction.Close:\n LogDebug(\"Processing close action\");\n Close();\n break;\n\n default:\n LogDebug($\"Unknown window state action: {message.Action}\");\n break;\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error handling window state message: {ex.Message}\", ex);\n }\n }\n\n private readonly IServiceProvider _serviceProvider = null!;\n private readonly IThemeManager _themeManager = null!;\n\n protected override void OnSourceInitialized(EventArgs e)\n {\n LogDebug(\"OnSourceInitialized starting\");\n try\n {\n base.OnSourceInitialized(e);\n LogDebug(\"Base OnSourceInitialized called\");\n\n var helper = new WindowInteropHelper(this);\n if (helper.Handle == IntPtr.Zero)\n {\n throw new InvalidOperationException(\"Window handle not available\");\n }\n LogDebug(\"Window handle verified\");\n\n // Initialize the window size manager to set size and center the window\n if (_windowSizeManager != null)\n {\n _windowSizeManager.Initialize();\n LogDebug(\"WindowSizeManager initialized\");\n }\n else\n {\n // Fallback if window size manager is not available\n SetDynamicWindowSize();\n LogDebug(\"Used fallback dynamic window sizing\");\n }\n\n EnableBlur();\n LogDebug(\"Blur enabled successfully\");\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in OnSourceInitialized\", ex);\n // Don't throw - blur is not critical\n }\n }\n\n /// \n /// Sets the window size dynamically based on the screen resolution\n /// \n private void SetDynamicWindowSize()\n {\n try\n {\n LogDebug(\"Setting dynamic window size\");\n\n // Get the current screen's working area (excludes taskbar)\n var workArea = GetCurrentScreenWorkArea();\n\n // Get DPI scaling factor for the current screen\n double dpiScaleX = 1.0;\n double dpiScaleY = 1.0;\n\n try\n {\n var presentationSource = PresentationSource.FromVisual(this);\n if (presentationSource?.CompositionTarget != null)\n {\n dpiScaleX = presentationSource.CompositionTarget.TransformToDevice.M11;\n dpiScaleY = presentationSource.CompositionTarget.TransformToDevice.M22;\n LogDebug($\"DPI scale factors: X={dpiScaleX}, Y={dpiScaleY}\");\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting DPI scale: {ex.Message}\", ex);\n }\n\n // Calculate available screen space\n double screenWidth = workArea.Width / dpiScaleX;\n double screenHeight = workArea.Height / dpiScaleY;\n double screenLeft = workArea.X / dpiScaleX;\n double screenTop = workArea.Y / dpiScaleY;\n\n // Calculate window size (75% of screen size with minimum/maximum constraints)\n double windowWidth = Math.Min(1600, screenWidth * 0.75);\n double windowHeight = Math.Min(900, screenHeight * 0.75);\n\n // Ensure minimum size for usability\n windowWidth = Math.Max(windowWidth, 1024);\n windowHeight = Math.Max(windowHeight, 700);\n\n // Set the window size\n this.Width = windowWidth;\n this.Height = windowHeight;\n\n // Center the window on screen\n this.Left = screenLeft + (screenWidth - windowWidth) / 2;\n this.Top = screenTop + (screenHeight - windowHeight) / 2;\n\n LogDebug(\n $\"Screen resolution: {screenWidth}x{screenHeight}, Window size set to: {windowWidth}x{windowHeight}\"\n );\n LogDebug($\"Window centered at: Left={this.Left}, Top={this.Top}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error setting dynamic window size: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Gets the working area of the screen that contains the window\n /// \n private Rect GetCurrentScreenWorkArea()\n {\n try\n {\n // Get the window handle\n var windowHandle = new WindowInteropHelper(this).Handle;\n if (windowHandle != IntPtr.Zero)\n {\n // Get the monitor info for the monitor containing the window\n var monitorInfo = new MONITORINFO();\n monitorInfo.cbSize = Marshal.SizeOf(typeof(MONITORINFO));\n\n if (\n GetMonitorInfo(\n MonitorFromWindow(windowHandle, MONITOR_DEFAULTTONEAREST),\n ref monitorInfo\n )\n )\n {\n // Convert the working area to a WPF Rect\n return new Rect(\n monitorInfo.rcWork.left,\n monitorInfo.rcWork.top,\n monitorInfo.rcWork.right - monitorInfo.rcWork.left,\n monitorInfo.rcWork.bottom - monitorInfo.rcWork.top\n );\n }\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting current screen: {ex.Message}\", ex);\n }\n\n // Fallback to primary screen working area\n return SystemParameters.WorkArea;\n }\n\n [DllImport(\"user32.dll\")]\n private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);\n\n [DllImport(\"user32.dll\")]\n private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);\n\n private const uint MONITOR_DEFAULTTONEAREST = 2;\n\n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int left;\n public int top;\n public int right;\n public int bottom;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct MONITORINFO\n {\n public int cbSize;\n public RECT rcMonitor;\n public RECT rcWork;\n public uint dwFlags;\n }\n\n private void EnableBlur()\n {\n LogDebug(\"EnableBlur starting\");\n var windowHelper = new WindowInteropHelper(this);\n var accent = new AccentPolicy { AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND };\n var accentStructSize = Marshal.SizeOf(accent);\n\n var accentPtr = IntPtr.Zero;\n try\n {\n accentPtr = Marshal.AllocHGlobal(accentStructSize);\n Marshal.StructureToPtr(accent, accentPtr, false);\n\n var data = new WindowCompositionAttributeData\n {\n Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY,\n SizeOfData = accentStructSize,\n Data = accentPtr,\n };\n\n int result = SetWindowCompositionAttribute(windowHelper.Handle, ref data);\n if (result == 0)\n {\n throw new InvalidOperationException(\"SetWindowCompositionAttribute failed\");\n }\n LogDebug(\"Blur effect applied successfully\");\n }\n catch (Exception ex)\n {\n LogDebug(\"Error enabling blur\", ex);\n throw;\n }\n finally\n {\n if (accentPtr != IntPtr.Zero)\n {\n Marshal.FreeHGlobal(accentPtr);\n }\n }\n }\n\n [DllImport(\"user32.dll\")]\n internal static extern int SetWindowCompositionAttribute(\n IntPtr hwnd,\n ref WindowCompositionAttributeData data\n );\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct AccentPolicy\n {\n public AccentState AccentState;\n public int AccentFlags;\n public int GradientColor;\n public int AnimationId;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct WindowCompositionAttributeData\n {\n public WindowCompositionAttribute Attribute;\n public IntPtr Data;\n public int SizeOfData;\n }\n\n internal enum AccentState\n {\n ACCENT_DISABLED = 0,\n ACCENT_ENABLE_GRADIENT = 1,\n ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,\n ACCENT_ENABLE_BLURBEHIND = 3,\n ACCENT_ENABLE_ACRYLICBLURBEHIND = 4,\n ACCENT_INVALID_STATE = 5,\n }\n\n internal enum WindowCompositionAttribute\n {\n WCA_ACCENT_POLICY = 19,\n }\n\n // Window control is now handled through ViewModel commands and messaging\n\n /// \n /// Updates the window and image icons based on the current theme\n /// \n private void UpdateThemeIcon()\n {\n if (_themeManager == null)\n {\n LogDebug(\"Cannot update theme icon: ThemeManager is null\");\n return;\n }\n\n try\n {\n LogDebug(\n $\"Updating theme icon. Current theme: {(_themeManager.IsDarkTheme ? \"Dark\" : \"Light\")}\"\n );\n\n // Get the appropriate icon based on the theme\n string iconPath = _themeManager.IsDarkTheme\n ? \"pack://application:,,,/Resources/AppIcons/winhance-rocket-white-transparent-bg.ico\"\n : \"pack://application:,,,/Resources/AppIcons/winhance-rocket-black-transparent-bg.ico\";\n\n LogDebug($\"Selected icon path: {iconPath}\");\n\n // Create a BitmapImage from the icon path\n var iconImage = new BitmapImage(new Uri(iconPath, UriKind.Absolute));\n iconImage.Freeze(); // Freeze for better performance and thread safety\n\n // Set the window icon\n this.Icon = iconImage;\n LogDebug(\"Window icon updated\");\n\n // Set the image control source\n if (AppIconImage != null)\n {\n AppIconImage.Source = iconImage;\n LogDebug(\"AppIconImage source updated\");\n }\n else\n {\n LogDebug(\"AppIconImage is null, cannot update source\");\n }\n }\n catch (Exception ex)\n {\n LogDebug(\"Error updating theme icon\", ex);\n\n // If there's an error, fall back to the default icon\n try\n {\n var defaultIcon = new BitmapImage(\n new Uri(\n \"pack://application:,,,/Resources/AppIcons/winhance-rocket.ico\",\n UriKind.Absolute\n )\n );\n this.Icon = defaultIcon;\n if (AppIconImage != null)\n {\n AppIconImage.Source = defaultIcon;\n }\n }\n catch (Exception fallbackEx)\n {\n LogDebug(\"Error setting fallback icon\", fallbackEx);\n }\n }\n }\n\n /// \n /// Handles mouse wheel events at the window level and redirects them to the ScrollViewer\n /// \n private void MainWindow_PreviewMouseWheel(object sender, MouseWheelEventArgs e)\n {\n // Find the ScrollViewer in the visual tree\n var scrollViewer = FindVisualChild(this);\n if (scrollViewer != null)\n {\n // Redirect the mouse wheel event to the ScrollViewer\n if (e.Delta < 0)\n {\n scrollViewer.LineDown();\n }\n else\n {\n scrollViewer.LineUp();\n }\n\n // Mark the event as handled to prevent it from bubbling up\n e.Handled = true;\n }\n }\n\n /// \n /// Finds a visual child of the specified type in the visual tree\n /// \n private static T FindVisualChild(DependencyObject obj)\n where T : DependencyObject\n {\n for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)\n {\n DependencyObject child = VisualTreeHelper.GetChild(obj, i);\n\n if (child != null && child is T)\n {\n return (T)child;\n }\n\n T childOfChild = FindVisualChild(child);\n if (childOfChild != null)\n {\n return childOfChild;\n }\n }\n\n return null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ConfigurationPropertyUpdater.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for updating properties of configuration items.\n /// \n public class ConfigurationPropertyUpdater : IConfigurationPropertyUpdater\n {\n private readonly ILogService _logService;\n private readonly IRegistryService _registryService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The registry service.\n public ConfigurationPropertyUpdater(\n ILogService logService,\n IRegistryService registryService\n )\n {\n _logService = logService;\n _registryService = registryService;\n }\n\n /// \n /// Updates properties of items based on the configuration.\n /// \n /// The items to update.\n /// The configuration file containing the updates.\n /// The number of items that were updated.\n public async Task UpdateItemsAsync(\n IEnumerable items,\n ConfigurationFile configFile\n )\n {\n int updatedCount = 0;\n\n // Create dictionaries of config items by name and ID for faster lookup\n var configItemsByName = new Dictionary(\n StringComparer.OrdinalIgnoreCase\n );\n var configItemsById = new Dictionary(\n StringComparer.OrdinalIgnoreCase\n );\n\n if (configFile.Items != null)\n {\n foreach (var item in configFile.Items)\n {\n if (\n !string.IsNullOrEmpty(item.Name)\n && !configItemsByName.ContainsKey(item.Name)\n )\n {\n configItemsByName.Add(item.Name, item);\n }\n\n if (\n item.CustomProperties.TryGetValue(\"Id\", out var id)\n && id != null\n && !string.IsNullOrEmpty(id.ToString())\n && !configItemsById.ContainsKey(id.ToString())\n )\n {\n configItemsById.Add(id.ToString(), item);\n }\n }\n }\n\n // Update the items\n foreach (var item in items)\n {\n try\n {\n var nameProperty = item.GetType().GetProperty(\"Name\");\n var idProperty = item.GetType().GetProperty(\"Id\");\n var isSelectedProperty = item.GetType().GetProperty(\"IsSelected\");\n\n if (nameProperty != null && isSelectedProperty != null)\n {\n var name = nameProperty.GetValue(item)?.ToString();\n var id = idProperty?.GetValue(item)?.ToString();\n\n ConfigurationItem configItem = null;\n\n // Try to match by ID first\n if (\n !string.IsNullOrEmpty(id)\n && configItemsById.TryGetValue(id, out var itemById)\n )\n {\n configItem = itemById;\n }\n // Then try to match by name\n else if (\n !string.IsNullOrEmpty(name)\n && configItemsByName.TryGetValue(name, out var itemByName)\n )\n {\n configItem = itemByName;\n }\n\n if (configItem != null)\n {\n bool anyPropertyUpdated = false;\n\n // Update IsSelected - Always apply regardless of current state\n bool currentIsSelected = (bool)(\n isSelectedProperty.GetValue(item) ?? false\n );\n\n // Always set the value and apply registry settings, even if it hasn't changed\n isSelectedProperty.SetValue(item, configItem.IsSelected);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Info,\n $\"Updated IsSelected for item {name} (ID: {id}) to {configItem.IsSelected}\"\n );\n\n // Always apply registry settings for this item during import\n await ApplyRegistrySettingsAsync(item, configItem.IsSelected);\n\n // Update additional properties\n if (UpdateAdditionalProperties(item, configItem))\n {\n anyPropertyUpdated = true;\n }\n\n if (anyPropertyUpdated)\n {\n updatedCount++;\n TriggerPropertyChangedIfPossible(item);\n }\n }\n }\n }\n catch (Exception ex)\n {\n // Log the error but continue processing other items\n _logService.Log(\n LogLevel.Debug,\n $\"Error applying configuration to item: {ex.Message}\"\n );\n }\n }\n\n return updatedCount;\n }\n\n /// \n /// Updates additional properties of an item based on the configuration.\n /// \n /// The item to update.\n /// The configuration item containing the updates.\n /// True if any properties were updated, false otherwise.\n public bool UpdateAdditionalProperties(object item, ConfigurationItem configItem)\n {\n bool anyPropertyUpdated = false;\n\n try\n {\n // Get the item type to access its properties\n var itemType = item.GetType();\n var itemName =\n itemType.GetProperty(\"Name\")?.GetValue(item)?.ToString() ?? \"Unknown\";\n var itemId = itemType.GetProperty(\"Id\")?.GetValue(item)?.ToString() ?? \"\";\n\n // Check if this is a special item that needs special handling\n bool isUacSlider =\n itemName.Contains(\"User Account Control\") || itemId == \"UACSlider\";\n bool isPowerPlan = itemName.Contains(\"Power Plan\") || itemId == \"PowerPlanComboBox\";\n bool isThemeSelector =\n itemName.Contains(\"Windows Theme\")\n || itemName.Contains(\"Theme Selector\")\n || itemName.Contains(\"Choose Your Mode\");\n\n // Special handling for Windows Theme Selector\n if (isThemeSelector)\n {\n // For Windows Theme Selector, prioritize using SelectedValue or SelectedTheme\n var selectedValueProperty = itemType.GetProperty(\"SelectedValue\");\n if (selectedValueProperty != null)\n {\n try\n {\n string currentSelectedValue = selectedValueProperty\n .GetValue(item)\n ?.ToString();\n string newSelectedValue = null;\n\n // First try to get the value from CustomProperties.SelectedTheme (preferred method)\n if (\n configItem.CustomProperties.TryGetValue(\n \"SelectedTheme\",\n out var selectedTheme\n )\n && selectedTheme != null\n )\n {\n newSelectedValue = selectedTheme.ToString();\n _logService.Log(\n LogLevel.Info,\n $\"Found SelectedTheme in CustomProperties: {newSelectedValue} for item {itemName}\"\n );\n }\n // Then try to get the value directly from configItem.SelectedValue\n else if (!string.IsNullOrEmpty(configItem.SelectedValue))\n {\n newSelectedValue = configItem.SelectedValue;\n _logService.Log(\n LogLevel.Info,\n $\"Found SelectedValue in config: {newSelectedValue} for item {itemName}\"\n );\n }\n // As a last resort, try to derive it from SliderValue (for backward compatibility)\n else if (\n configItem.CustomProperties.TryGetValue(\n \"SliderValue\",\n out var sliderValue\n )\n )\n {\n int sliderValueInt = Convert.ToInt32(sliderValue);\n newSelectedValue = sliderValueInt == 1 ? \"Dark Mode\" : \"Light Mode\";\n _logService.Log(\n LogLevel.Info,\n $\"Derived SelectedValue from SliderValue {sliderValueInt}: {newSelectedValue} for item {itemName}\"\n );\n }\n\n if (\n !string.IsNullOrEmpty(newSelectedValue)\n && currentSelectedValue != newSelectedValue\n )\n {\n selectedValueProperty.SetValue(item, newSelectedValue);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Info,\n $\"Updated SelectedValue for item {itemName} from {currentSelectedValue} to {newSelectedValue}\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating SelectedValue for item {itemName}: {ex.Message}\"\n );\n }\n }\n\n // Also update SelectedTheme property if it exists\n var selectedThemeProperty = itemType.GetProperty(\"SelectedTheme\");\n if (selectedThemeProperty != null)\n {\n try\n {\n string currentSelectedTheme = selectedThemeProperty\n .GetValue(item)\n ?.ToString();\n string newSelectedTheme = null;\n\n // Try to get SelectedTheme from CustomProperties first (preferred method)\n if (\n configItem.CustomProperties.TryGetValue(\n \"SelectedTheme\",\n out var selectedTheme\n )\n && selectedTheme != null\n )\n {\n newSelectedTheme = selectedTheme.ToString();\n }\n // Then try to use SelectedValue directly\n else if (!string.IsNullOrEmpty(configItem.SelectedValue))\n {\n newSelectedTheme = configItem.SelectedValue;\n }\n // As a last resort, try to derive it from SliderValue (for backward compatibility)\n else if (\n configItem.CustomProperties.TryGetValue(\n \"SliderValue\",\n out var themeSliderValue\n )\n )\n {\n int sliderValueInt = Convert.ToInt32(themeSliderValue);\n newSelectedTheme = sliderValueInt == 1 ? \"Dark Mode\" : \"Light Mode\";\n }\n\n if (\n !string.IsNullOrEmpty(newSelectedTheme)\n && currentSelectedTheme != newSelectedTheme\n )\n {\n selectedThemeProperty.SetValue(item, newSelectedTheme);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Debug,\n $\"Updated SelectedTheme for item {itemName} to {newSelectedTheme}\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating SelectedTheme for item {itemName}: {ex.Message}\"\n );\n }\n }\n }\n // For non-theme items, handle SliderValue for ThreeStateSlider or ComboBox\n else if (\n configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue)\n )\n {\n var sliderValueProperty = itemType.GetProperty(\"SliderValue\");\n if (sliderValueProperty != null)\n {\n try\n {\n int newSliderValue = Convert.ToInt32(sliderValue);\n int currentSliderValue = (int)(sliderValueProperty.GetValue(item) ?? 0);\n\n if (currentSliderValue != newSliderValue)\n {\n _logService.Log(\n LogLevel.Info,\n $\"About to update SliderValue for item {itemName} from {currentSliderValue} to {newSliderValue}\"\n );\n sliderValueProperty.SetValue(item, newSliderValue);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Info,\n $\"Updated SliderValue for item {itemName} to {newSliderValue}\"\n );\n\n // Get the control type\n var controlTypeProperty = itemType.GetProperty(\"ControlType\");\n if (controlTypeProperty != null)\n {\n var controlType = controlTypeProperty.GetValue(item);\n _logService.Log(\n LogLevel.Info,\n $\"Item {itemName} has ControlType: {controlType}\"\n );\n\n // If this is a ComboBox, also update the SelectedValue property if available\n if (controlType?.ToString() == \"ComboBox\")\n {\n _logService.Log(\n LogLevel.Info,\n $\"Item {itemName} is a ComboBox, checking for SelectedValue property\"\n );\n var comboBoxSelectedValueProperty = itemType.GetProperty(\n \"SelectedValue\"\n );\n if (comboBoxSelectedValueProperty != null)\n {\n // First try to get the value directly from configItem.SelectedValue\n if (!string.IsNullOrEmpty(configItem.SelectedValue))\n {\n _logService.Log(\n LogLevel.Info,\n $\"Setting SelectedValue to {configItem.SelectedValue} from config for ComboBox {itemName}\"\n );\n comboBoxSelectedValueProperty.SetValue(\n item,\n configItem.SelectedValue\n );\n anyPropertyUpdated = true;\n }\n // Then try to get the value from CustomProperties.SelectedTheme\n else if (\n configItem.CustomProperties.TryGetValue(\n \"SelectedTheme\",\n out var selectedTheme\n )\n && selectedTheme != null\n )\n {\n _logService.Log(\n LogLevel.Info,\n $\"Setting SelectedValue to {selectedTheme} from CustomProperties.SelectedTheme for ComboBox {itemName}\"\n );\n comboBoxSelectedValueProperty.SetValue(\n item,\n selectedTheme.ToString()\n );\n anyPropertyUpdated = true;\n }\n // Finally try to map from SliderValue using SliderLabels\n else\n {\n // Try to get the SliderLabels collection to map the index to a value\n var sliderLabelsProperty = itemType.GetProperty(\n \"SliderLabels\"\n );\n if (sliderLabelsProperty != null)\n {\n var sliderLabels =\n sliderLabelsProperty.GetValue(item)\n as System.Collections.IList;\n if (\n sliderLabels != null\n && newSliderValue < sliderLabels.Count\n )\n {\n var selectedValue = sliderLabels[\n newSliderValue\n ]\n ?.ToString();\n if (!string.IsNullOrEmpty(selectedValue))\n {\n _logService.Log(\n LogLevel.Info,\n $\"Setting SelectedValue to {selectedValue} from SliderLabels for ComboBox {itemName}\"\n );\n comboBoxSelectedValueProperty.SetValue(\n item,\n selectedValue\n );\n anyPropertyUpdated = true;\n }\n }\n }\n }\n }\n }\n }\n\n // Also update specific properties based on the item identification\n if (isPowerPlan)\n {\n // Update PowerPlanValue property\n var powerPlanValueProperty = itemType.GetProperty(\n \"PowerPlanValue\"\n );\n if (powerPlanValueProperty != null)\n {\n int currentPowerPlanValue = (int)(\n powerPlanValueProperty.GetValue(item) ?? 0\n );\n if (currentPowerPlanValue != newSliderValue)\n {\n powerPlanValueProperty.SetValue(item, newSliderValue);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Info,\n $\"Updated PowerPlanValue for item {itemName} from {currentPowerPlanValue} to {newSliderValue}\"\n );\n\n // Try to call OnPowerPlanValueChanged method to apply the power plan\n try\n {\n var onPowerPlanValueChangedMethod =\n itemType.GetMethod(\n \"OnPowerPlanValueChanged\",\n System.Reflection.BindingFlags.NonPublic\n | System\n .Reflection\n .BindingFlags\n .Instance\n );\n\n if (onPowerPlanValueChangedMethod != null)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Calling OnPowerPlanValueChanged method with value {newSliderValue}\"\n );\n onPowerPlanValueChangedMethod.Invoke(\n item,\n new object[] { newSliderValue }\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Debug,\n \"OnPowerPlanValueChanged method not found\"\n );\n\n // Try to find ApplyPowerPlanCommand\n var applyPowerPlanCommandProperty =\n itemType.GetProperty(\n \"ApplyPowerPlanCommand\"\n );\n if (applyPowerPlanCommandProperty != null)\n {\n var command =\n applyPowerPlanCommandProperty.GetValue(\n item\n ) as System.Windows.Input.ICommand;\n if (\n command != null\n && command.CanExecute(newSliderValue)\n )\n {\n _logService.Log(\n LogLevel.Info,\n $\"Executing ApplyPowerPlanCommand with value {newSliderValue}\"\n );\n command.Execute(newSliderValue);\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Error calling power plan methods: {ex.Message}\"\n );\n }\n }\n }\n\n // Also update any ComboBox in the Settings collection\n try\n {\n var settingsProperty = itemType.GetProperty(\"Settings\");\n if (settingsProperty != null)\n {\n var settings =\n settingsProperty.GetValue(item)\n as System.Collections.IEnumerable;\n if (settings != null)\n {\n foreach (var setting in settings)\n {\n var settingType = setting.GetType();\n var settingIdProperty = settingType.GetProperty(\n \"Id\"\n );\n var settingNameProperty =\n settingType.GetProperty(\"Name\");\n\n string settingId = settingIdProperty\n ?.GetValue(setting)\n ?.ToString();\n string settingName = settingNameProperty\n ?.GetValue(setting)\n ?.ToString();\n\n bool isPowerPlanSetting =\n settingId == \"PowerPlanComboBox\"\n || (\n settingName != null\n && settingName.Contains(\"Power Plan\")\n );\n\n if (isPowerPlanSetting)\n {\n var settingSliderValueProperty =\n settingType.GetProperty(\"SliderValue\");\n if (settingSliderValueProperty != null)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Updating SliderValue for Power Plan setting to {newSliderValue}\"\n );\n settingSliderValueProperty.SetValue(\n setting,\n newSliderValue\n );\n }\n\n var selectedValueProperty =\n settingType.GetProperty(\n \"SelectedValue\"\n );\n if (selectedValueProperty != null)\n {\n // First try to get the value from PowerPlanOptions in the configItem\n if (\n configItem.CustomProperties.TryGetValue(\n \"PowerPlanOptions\",\n out var powerPlanOptions\n )\n )\n {\n // Handle different types of PowerPlanOptions\n if (\n powerPlanOptions\n is List options\n && newSliderValue >= 0\n && newSliderValue\n < options.Count\n )\n {\n string powerPlanLabel = options[\n newSliderValue\n ];\n _logService.Log(\n LogLevel.Info,\n $\"Updating SelectedValue for Power Plan setting to {powerPlanLabel} from configItem.PowerPlanOptions\"\n );\n selectedValueProperty.SetValue(\n setting,\n powerPlanLabel\n );\n }\n else if (\n powerPlanOptions\n is Newtonsoft.Json.Linq.JArray jArray\n && newSliderValue >= 0\n && newSliderValue < jArray.Count\n )\n {\n string powerPlanLabel = jArray[\n newSliderValue\n ]\n ?.ToString();\n _logService.Log(\n LogLevel.Info,\n $\"Updating SelectedValue for Power Plan setting to {powerPlanLabel} from configItem.PowerPlanOptions (JArray)\"\n );\n selectedValueProperty.SetValue(\n setting,\n powerPlanLabel\n );\n }\n else\n {\n // Fall back to SliderLabels\n TryUpdateFromSliderLabels(\n settingType,\n setting,\n selectedValueProperty,\n newSliderValue\n );\n }\n }\n // Then try to get it from the setting's SliderLabels\n else\n {\n TryUpdateFromSliderLabels(\n settingType,\n setting,\n selectedValueProperty,\n newSliderValue\n );\n }\n }\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating Power Plan settings: {ex.Message}\"\n );\n }\n }\n else if (isUacSlider)\n {\n var uacLevelProperty = itemType.GetProperty(\"SelectedUacLevel\");\n if (uacLevelProperty != null)\n {\n uacLevelProperty.SetValue(item, newSliderValue);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Debug,\n $\"Updated SelectedUacLevel for item {itemName} to {newSliderValue}\"\n );\n\n // Force the correct ControlType\n if (controlTypeProperty != null)\n {\n controlTypeProperty.SetValue(\n item,\n ControlType.ThreeStateSlider\n );\n _logService.Log(\n LogLevel.Debug,\n $\"Forced ControlType to ThreeStateSlider for item {itemName}\"\n );\n }\n }\n\n // Also try to update the parent view model's UacLevel property\n try\n {\n // Try to get the parent view model\n var viewModelProperty = itemType.GetProperty(\"ViewModel\");\n if (viewModelProperty != null)\n {\n var viewModel = viewModelProperty.GetValue(item);\n if (viewModel != null)\n {\n var viewModelType = viewModel.GetType();\n var viewModelUacLevelProperty =\n viewModelType.GetProperty(\"SelectedUacLevel\");\n if (viewModelUacLevelProperty != null)\n {\n viewModelUacLevelProperty.SetValue(\n viewModel,\n newSliderValue\n );\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Debug,\n $\"Updated SelectedUacLevel on parent view model to {newSliderValue}\"\n );\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating parent view model UacLevel: {ex.Message}\"\n );\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating SliderValue for item {itemName}: {ex.Message}\"\n );\n }\n }\n }\n\n // For non-theme items, also check for SelectedValue property\n if (!isThemeSelector)\n {\n var selectedValueProperty = itemType.GetProperty(\"SelectedValue\");\n if (selectedValueProperty != null)\n {\n try\n {\n string currentSelectedValue = selectedValueProperty\n .GetValue(item)\n ?.ToString();\n string newSelectedValue = null;\n\n // First try to get the value directly from configItem.SelectedValue\n if (!string.IsNullOrEmpty(configItem.SelectedValue))\n {\n newSelectedValue = configItem.SelectedValue;\n _logService.Log(\n LogLevel.Info,\n $\"Found SelectedValue in config: {newSelectedValue} for item {itemName}\"\n );\n }\n // Then try to get the value from CustomProperties.SelectedTheme\n else if (\n configItem.CustomProperties.TryGetValue(\n \"SelectedTheme\",\n out var selectedTheme\n )\n && selectedTheme != null\n )\n {\n newSelectedValue = selectedTheme.ToString();\n _logService.Log(\n LogLevel.Info,\n $\"Found SelectedTheme in CustomProperties: {newSelectedValue} for item {itemName}\"\n );\n }\n // Finally try to map from SliderValue using SliderLabels\n else if (\n configItem.CustomProperties.TryGetValue(\n \"SliderValue\",\n out var configSliderValueForMapping\n )\n )\n {\n var sliderLabelsProperty = itemType.GetProperty(\"SliderLabels\");\n if (sliderLabelsProperty != null)\n {\n var sliderLabels =\n sliderLabelsProperty.GetValue(item)\n as System.Collections.IList;\n int sliderValueInt = Convert.ToInt32(\n configSliderValueForMapping\n );\n if (sliderLabels != null && sliderValueInt < sliderLabels.Count)\n {\n newSelectedValue = sliderLabels[sliderValueInt]?.ToString();\n _logService.Log(\n LogLevel.Info,\n $\"Mapped SliderValue {sliderValueInt} to SelectedValue {newSelectedValue} for item {itemName}\"\n );\n }\n }\n }\n\n if (\n !string.IsNullOrEmpty(newSelectedValue)\n && currentSelectedValue != newSelectedValue\n )\n {\n selectedValueProperty.SetValue(item, newSelectedValue);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Info,\n $\"Updated SelectedValue for item {itemName} from {currentSelectedValue} to {newSelectedValue}\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating SelectedValue for item {itemName}: {ex.Message}\"\n );\n }\n }\n }\n\n // For toggle switches, ensure IsChecked is synchronized with IsSelected\n var isCheckedProperty = itemType.GetProperty(\"IsChecked\");\n if (isCheckedProperty != null)\n {\n try\n {\n bool currentIsChecked = (bool)(isCheckedProperty.GetValue(item) ?? false);\n\n if (currentIsChecked != configItem.IsSelected)\n {\n isCheckedProperty.SetValue(item, configItem.IsSelected);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Debug,\n $\"Updated IsChecked for item {itemName} to {configItem.IsSelected}\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating IsChecked for item {itemName}: {ex.Message}\"\n );\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error in UpdateAdditionalProperties: {ex.Message}\"\n );\n }\n\n return anyPropertyUpdated;\n }\n\n /// \n /// Helper method to try updating SelectedValue from SliderLabels.\n /// \n /// The type of the setting.\n /// The setting object.\n /// The SelectedValue property.\n /// The new slider value.\n private void TryUpdateFromSliderLabels(\n Type settingType,\n object setting,\n System.Reflection.PropertyInfo selectedValueProperty,\n int newSliderValue\n )\n {\n // Try to get the power plan label from SliderLabels\n var sliderLabelsProperty = settingType.GetProperty(\"SliderLabels\");\n if (sliderLabelsProperty != null)\n {\n var sliderLabels =\n sliderLabelsProperty.GetValue(setting) as System.Collections.IList;\n if (\n sliderLabels != null\n && newSliderValue >= 0\n && newSliderValue < sliderLabels.Count\n )\n {\n string powerPlanLabel = sliderLabels[newSliderValue]?.ToString();\n if (!string.IsNullOrEmpty(powerPlanLabel))\n {\n _logService.Log(\n LogLevel.Info,\n $\"Updating SelectedValue for Power Plan setting to {powerPlanLabel} from SliderLabels\"\n );\n selectedValueProperty.SetValue(setting, powerPlanLabel);\n }\n }\n else\n {\n // Fall back to default values\n string[] defaultLabels =\n {\n \"Balanced\",\n \"High Performance\",\n \"Ultimate Performance\",\n };\n if (newSliderValue >= 0 && newSliderValue < defaultLabels.Length)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Updating SelectedValue for Power Plan setting to {defaultLabels[newSliderValue]} from default labels\"\n );\n selectedValueProperty.SetValue(setting, defaultLabels[newSliderValue]);\n }\n }\n }\n }\n\n private void TriggerPropertyChangedIfPossible(object item)\n {\n try\n {\n // Check if the item implements INotifyPropertyChanged\n if (item is System.ComponentModel.INotifyPropertyChanged)\n {\n try\n {\n // Use a safer approach to find property changed methods\n var methods = item.GetType()\n .GetMethods(\n System.Reflection.BindingFlags.Public\n | System.Reflection.BindingFlags.NonPublic\n | System.Reflection.BindingFlags.Instance\n )\n .Where(m =>\n (m.Name == \"RaisePropertyChanged\" || m.Name == \"OnPropertyChanged\")\n && m.GetParameters().Length == 1\n && m.GetParameters()[0].ParameterType == typeof(string)\n )\n .ToList();\n\n if (methods.Any())\n {\n var method = methods.First();\n // Invoke the method with null string to refresh all properties\n method.Invoke(item, new object[] { null });\n return;\n }\n\n // If no method with string parameter is found, try to find a method that takes PropertyChangedEventArgs\n var eventArgsMethods = item.GetType()\n .GetMethods(\n System.Reflection.BindingFlags.Public\n | System.Reflection.BindingFlags.NonPublic\n | System.Reflection.BindingFlags.Instance\n )\n .Where(m =>\n (m.Name == \"OnPropertyChanged\")\n && m.GetParameters().Length == 1\n && m.GetParameters()[0].ParameterType.Name\n == \"PropertyChangedEventArgs\"\n )\n .ToList();\n\n if (eventArgsMethods.Any())\n {\n // Create PropertyChangedEventArgs with null property name to refresh all properties\n var eventArgsType = eventArgsMethods\n .First()\n .GetParameters()[0]\n .ParameterType;\n var eventArgs = Activator.CreateInstance(\n eventArgsType,\n new object[] { null }\n );\n eventArgsMethods.First().Invoke(item, new[] { eventArgs });\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error finding property changed method: {ex.Message}\"\n );\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error triggering property changed: {ex.Message}\");\n }\n }\n\n /// \n /// Applies registry settings for an item based on its IsSelected state.\n /// \n /// The item to apply registry settings for.\n /// Whether the setting is selected (enabled) or not.\n /// A task representing the asynchronous operation.\n private async Task ApplyRegistrySettingsAsync(object item, bool isSelected)\n {\n try\n {\n // Check if this is an ApplicationSettingItem\n if (item is ApplicationSettingItem settingItem)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Applying registry settings for {settingItem.Name}, IsSelected={isSelected}\"\n );\n\n // Apply registry setting if present\n if (settingItem.RegistrySetting != null)\n {\n string hiveString = GetRegistryHiveString(settingItem.RegistrySetting.Hive);\n object valueToApply = isSelected\n ? settingItem.RegistrySetting.EnabledValue\n ?? settingItem.RegistrySetting.RecommendedValue\n : settingItem.RegistrySetting.DisabledValue\n ?? settingItem.RegistrySetting.DefaultValue;\n\n // Ensure the key exists and set the value\n string keyPath = $\"{hiveString}\\\\{settingItem.RegistrySetting.SubKey}\";\n\n // First ensure the key exists\n bool keyExists = _registryService.KeyExists(keyPath);\n if (!keyExists)\n {\n _logService.Log(LogLevel.Info, $\"Creating registry key: {keyPath}\");\n bool keyCreated = _registryService.CreateKeyIfNotExists(keyPath);\n if (!keyCreated)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to create registry key: {keyPath}, trying direct registry access\"\n );\n\n // Try direct registry access to create the key\n try\n {\n RegistryKey rootKey = GetRegistryRootKey(\n settingItem.RegistrySetting.Hive\n );\n if (rootKey != null)\n {\n rootKey.CreateSubKey(\n settingItem.RegistrySetting.SubKey,\n true\n );\n _logService.Log(\n LogLevel.Success,\n $\"Successfully created registry key using direct access: {keyPath}\"\n );\n keyCreated = true;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to create registry key using direct access: {keyPath}, Error: {ex.Message}\"\n );\n }\n\n // If direct access failed, try using PowerShell\n if (!keyCreated)\n {\n try\n {\n string psCommand =\n $\"$ErrorActionPreference = 'Stop'; try {{ if (-not (Test-Path -Path '{keyPath.Replace(\"HKLM\", \"HKLM:\")}')) {{ New-Item -Path '{keyPath.Replace(\"HKLM\", \"HKLM:\")}' -Force | Out-Null; Write-Output 'Key created successfully' }} }} catch {{ Write-Error $_.Exception.Message; exit 1 }}\";\n\n _logService.Log(\n LogLevel.Info,\n $\"Attempting to create registry key using PowerShell: {keyPath}\"\n );\n\n // Execute PowerShell command\n var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-Command \\\"{psCommand}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n },\n };\n\n process.Start();\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n process.WaitForExit();\n\n if (process.ExitCode == 0)\n {\n _logService.Log(\n LogLevel.Success,\n $\"Successfully created registry key using PowerShell: {keyPath}\"\n );\n keyCreated = true;\n }\n else\n {\n _logService.Log(\n LogLevel.Error,\n $\"Failed to create registry key using PowerShell: {keyPath}, Error: {error}\"\n );\n }\n }\n catch (Exception psEx)\n {\n _logService.Log(\n LogLevel.Error,\n $\"PowerShell execution failed: {psEx.Message}\"\n );\n }\n }\n }\n }\n\n // Now set the value - always attempt to set the value even if key creation failed\n // This is important for configuration import to ensure values are applied\n bool success = false;\n\n // First try using the registry service\n success = _registryService.SetValue(\n keyPath,\n settingItem.RegistrySetting.Name,\n valueToApply,\n settingItem.RegistrySetting.ValueType\n );\n\n if (success)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Applied registry setting for {settingItem.Name}: {(isSelected ? \"Enabled\" : \"Disabled\")}\"\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to apply registry setting for {settingItem.Name}, trying direct registry access\"\n );\n\n // Try direct registry access as a fallback\n try\n {\n RegistryKey rootKey = GetRegistryRootKey(\n settingItem.RegistrySetting.Hive\n );\n if (rootKey != null)\n {\n using (\n RegistryKey regKey = rootKey.CreateSubKey(\n settingItem.RegistrySetting.SubKey,\n true\n )\n )\n {\n if (regKey != null)\n {\n regKey.SetValue(\n settingItem.RegistrySetting.Name,\n valueToApply,\n (RegistryValueKind)\n settingItem.RegistrySetting.ValueType\n );\n _logService.Log(\n LogLevel.Success,\n $\"Successfully applied registry setting using direct access: {keyPath}\\\\{settingItem.RegistrySetting.Name}\"\n );\n success = true;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Error,\n $\"Failed to apply registry setting using direct access: {ex.Message}\"\n );\n }\n\n // If direct access failed, try using PowerShell\n if (!success)\n {\n try\n {\n string psCommand =\n $\"$ErrorActionPreference = 'Stop'; try {{ if (-not (Test-Path -Path '{keyPath.Replace(\"HKLM\", \"HKLM:\")}')) {{ New-Item -Path '{keyPath.Replace(\"HKLM\", \"HKLM:\")}' -Force | Out-Null; }} Set-ItemProperty -Path '{keyPath.Replace(\"HKLM\", \"HKLM:\")}' -Name '{settingItem.RegistrySetting.Name}' -Value {valueToApply} -Type {settingItem.RegistrySetting.ValueType} -Force; }} catch {{ Write-Error $_.Exception.Message; exit 1 }}\";\n\n _logService.Log(\n LogLevel.Info,\n $\"Attempting to set registry value using PowerShell: {keyPath}\\\\{settingItem.RegistrySetting.Name}\"\n );\n\n // Execute PowerShell command\n var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-Command \\\"{psCommand}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n },\n };\n\n process.Start();\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n process.WaitForExit();\n\n if (process.ExitCode == 0)\n {\n _logService.Log(\n LogLevel.Success,\n $\"Successfully set registry value using PowerShell: {keyPath}\\\\{settingItem.RegistrySetting.Name}\"\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Error,\n $\"Failed to set registry value using PowerShell: {keyPath}\\\\{settingItem.RegistrySetting.Name}, Error: {error}\"\n );\n }\n }\n catch (Exception psEx)\n {\n _logService.Log(\n LogLevel.Error,\n $\"PowerShell execution failed: {psEx.Message}\"\n );\n }\n }\n }\n }\n // Apply linked registry settings if present\n else if (\n settingItem.LinkedRegistrySettings != null\n && settingItem.LinkedRegistrySettings.Settings.Count > 0\n )\n {\n _logService.Log(\n LogLevel.Info,\n $\"Applying linked registry settings for {settingItem.Name}, IsSelected={isSelected}\"\n );\n\n // Use the registry service to apply linked settings\n bool success = await _registryService.ApplyLinkedSettingsAsync(\n settingItem.LinkedRegistrySettings,\n isSelected\n );\n\n if (success)\n {\n _logService.Log(\n LogLevel.Success,\n $\"Successfully applied all linked registry settings for {settingItem.Name}\"\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Some linked registry settings for {settingItem.Name} failed to apply\"\n );\n }\n }\n\n // Refresh the status of the setting after applying changes\n await settingItem.RefreshStatus();\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying registry settings: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n }\n\n /// \n /// Gets the registry root key for a given hive.\n /// \n /// The registry hive.\n /// The registry root key.\n private RegistryKey GetRegistryRootKey(RegistryHive hive)\n {\n switch (hive)\n {\n case RegistryHive.ClassesRoot:\n return Registry.ClassesRoot;\n case RegistryHive.CurrentUser:\n return Registry.CurrentUser;\n case RegistryHive.LocalMachine:\n return Registry.LocalMachine;\n case RegistryHive.Users:\n return Registry.Users;\n case RegistryHive.CurrentConfig:\n return Registry.CurrentConfig;\n default:\n return null;\n }\n }\n\n /// \n /// Gets the registry hive string.\n /// \n /// The registry hive.\n /// The registry hive string.\n private string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => throw new ArgumentOutOfRangeException(nameof(hive), hive, null),\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/UserPreferencesService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading.Tasks;\nusing Newtonsoft.Json;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for managing user preferences\n /// \n public class UserPreferencesService\n {\n private const string PreferencesFileName = \"UserPreferences.json\";\n private readonly ILogService _logService;\n\n public UserPreferencesService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Gets the path to the user preferences file\n /// \n /// The full path to the user preferences file\n private string GetPreferencesFilePath()\n {\n try\n {\n // Get the LocalApplicationData folder (e.g., C:\\Users\\Username\\AppData\\Local)\n string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n \n if (string.IsNullOrEmpty(localAppData))\n {\n _logService.Log(LogLevel.Error, \"LocalApplicationData folder path is empty\");\n // Fallback to a default path\n localAppData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), \"AppData\", \"Local\");\n _logService.Log(LogLevel.Info, $\"Using fallback path: {localAppData}\");\n }\n \n // Combine with Winhance/Config\n string appDataPath = Path.Combine(localAppData, \"Winhance\", \"Config\");\n \n // Log the path\n _logService.Log(LogLevel.Debug, $\"Preferences directory path: {appDataPath}\");\n \n // Ensure the directory exists\n if (!Directory.Exists(appDataPath))\n {\n Directory.CreateDirectory(appDataPath);\n _logService.Log(LogLevel.Info, $\"Created preferences directory: {appDataPath}\");\n }\n \n // Get the full file path\n string filePath = Path.Combine(appDataPath, PreferencesFileName);\n _logService.Log(LogLevel.Debug, $\"Preferences file path: {filePath}\");\n \n return filePath;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting preferences file path: {ex.Message}\");\n \n // Fallback to a temporary file\n string tempPath = Path.Combine(Path.GetTempPath(), \"Winhance\", \"Config\");\n Directory.CreateDirectory(tempPath);\n string tempFilePath = Path.Combine(tempPath, PreferencesFileName);\n \n _logService.Log(LogLevel.Warning, $\"Using fallback temporary path: {tempFilePath}\");\n return tempFilePath;\n }\n }\n\n /// \n /// Gets the user preferences\n /// \n /// A dictionary containing the user preferences\n public async Task> GetPreferencesAsync()\n {\n try\n {\n string filePath = GetPreferencesFilePath();\n \n // Log the file path\n _logService.Log(LogLevel.Debug, $\"Getting preferences from '{filePath}'\");\n \n if (!File.Exists(filePath))\n {\n _logService.Log(LogLevel.Info, $\"User preferences file does not exist at '{filePath}', returning empty preferences\");\n return new Dictionary();\n }\n \n // Read the file\n string json = await File.ReadAllTextAsync(filePath);\n \n // Log a sample of the JSON (first 100 characters)\n if (!string.IsNullOrEmpty(json))\n {\n string sample = json.Length > 100 ? json.Substring(0, 100) + \"...\" : json;\n _logService.Log(LogLevel.Debug, $\"JSON sample: {sample}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Preferences file exists but is empty\");\n return new Dictionary();\n }\n \n // Use more robust deserialization settings\n var settings = new JsonSerializerSettings\n {\n NullValueHandling = NullValueHandling.Include,\n TypeNameHandling = TypeNameHandling.None,\n ReferenceLoopHandling = ReferenceLoopHandling.Ignore\n };\n \n // Use a custom converter to properly handle boolean values\n var preferences = JsonConvert.DeserializeObject>(json, settings);\n \n // Log the raw type of the DontShowSupport value if it exists\n if (preferences != null && preferences.TryGetValue(\"DontShowSupport\", out var dontShowValue))\n {\n _logService.Log(LogLevel.Debug, $\"DontShowSupport raw value type: {dontShowValue?.GetType().FullName}, value: {dontShowValue}\");\n }\n \n if (preferences != null)\n {\n _logService.Log(LogLevel.Info, $\"Successfully loaded {preferences.Count} preferences\");\n \n // Log the keys for debugging\n if (preferences.Count > 0)\n {\n _logService.Log(LogLevel.Debug, $\"Preference keys: {string.Join(\", \", preferences.Keys)}\");\n }\n \n return preferences;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Deserialized preferences is null, returning empty dictionary\");\n return new Dictionary();\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting user preferences: {ex.Message}\");\n if (ex.InnerException != null)\n {\n _logService.Log(LogLevel.Error, $\"Inner exception: {ex.InnerException.Message}\");\n }\n return new Dictionary();\n }\n }\n\n /// \n /// Saves the user preferences\n /// \n /// The preferences to save\n /// True if successful, false otherwise\n public async Task SavePreferencesAsync(Dictionary preferences)\n {\n try\n {\n string filePath = GetPreferencesFilePath();\n \n // Log the file path and preferences count\n _logService.Log(LogLevel.Debug, $\"Saving preferences to '{filePath}', count: {preferences.Count}\");\n \n // Use more robust serialization settings\n var settings = new JsonSerializerSettings\n {\n Formatting = Formatting.Indented,\n NullValueHandling = NullValueHandling.Include,\n TypeNameHandling = TypeNameHandling.None,\n ReferenceLoopHandling = ReferenceLoopHandling.Ignore\n };\n \n string json = JsonConvert.SerializeObject(preferences, settings);\n \n // Log a sample of the JSON (first 100 characters)\n if (json.Length > 0)\n {\n string sample = json.Length > 100 ? json.Substring(0, 100) + \"...\" : json;\n _logService.Log(LogLevel.Debug, $\"JSON sample: {sample}\");\n }\n \n // Ensure the directory exists\n string directory = Path.GetDirectoryName(filePath);\n if (!Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n _logService.Log(LogLevel.Debug, $\"Created directory: {directory}\");\n }\n \n // Write the file\n await File.WriteAllTextAsync(filePath, json);\n \n // Verify the file was written\n if (File.Exists(filePath))\n {\n _logService.Log(LogLevel.Info, $\"User preferences saved successfully to '{filePath}'\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"File not found after writing: '{filePath}'\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving user preferences: {ex.Message}\");\n if (ex.InnerException != null)\n {\n _logService.Log(LogLevel.Error, $\"Inner exception: {ex.InnerException.Message}\");\n }\n return false;\n }\n }\n\n /// \n /// Gets a specific preference value\n /// \n /// The type of the preference value\n /// The preference key\n /// The default value to return if the preference does not exist\n /// The preference value, or the default value if not found\n public async Task GetPreferenceAsync(string key, T defaultValue)\n {\n var preferences = await GetPreferencesAsync();\n \n if (preferences.TryGetValue(key, out var value))\n {\n try\n {\n // Log the actual type and value for debugging\n _logService.Log(LogLevel.Debug, $\"GetPreferenceAsync for key '{key}': value type = {value?.GetType().FullName}, value = {value}\");\n \n // Special case for DontShowSupport boolean preference\n if (key == \"DontShowSupport\" && typeof(T) == typeof(bool))\n {\n // Direct string comparison for known boolean values\n if (value != null)\n {\n string valueStr = value.ToString().ToLowerInvariant();\n if (valueStr == \"true\" || valueStr == \"1\")\n {\n _logService.Log(LogLevel.Debug, $\"DontShowSupport detected as TRUE\");\n return (T)(object)true;\n }\n else if (valueStr == \"false\" || valueStr == \"0\")\n {\n _logService.Log(LogLevel.Debug, $\"DontShowSupport detected as FALSE\");\n return (T)(object)false;\n }\n }\n }\n \n if (value is T typedValue)\n {\n return typedValue;\n }\n \n // Handle JToken conversion for primitive types\n if (value is Newtonsoft.Json.Linq.JToken jToken)\n {\n // For boolean JToken values, handle them explicitly\n if (typeof(T) == typeof(bool))\n {\n if (jToken.Type == Newtonsoft.Json.Linq.JTokenType.Boolean)\n {\n // Use ToObject instead of Value\n bool boolValue = (bool)jToken.ToObject(typeof(bool));\n _logService.Log(LogLevel.Debug, $\"JToken boolean value: {boolValue}\");\n return (T)(object)boolValue;\n }\n else if (jToken.Type == Newtonsoft.Json.Linq.JTokenType.String)\n {\n // Use ToString() instead of Value\n string strValue = jToken.ToString();\n if (bool.TryParse(strValue, out bool boolResult))\n {\n _logService.Log(LogLevel.Debug, $\"JToken string parsed as boolean: {boolResult}\");\n return (T)(object)boolResult;\n }\n }\n else if (jToken.Type == Newtonsoft.Json.Linq.JTokenType.Integer)\n {\n // Use ToObject instead of Value\n int intValue = (int)jToken.ToObject(typeof(int));\n bool boolValue = intValue != 0;\n _logService.Log(LogLevel.Debug, $\"JToken integer converted to boolean: {boolValue}\");\n return (T)(object)boolValue;\n }\n }\n \n var result = jToken.ToObject();\n _logService.Log(LogLevel.Debug, $\"JToken converted to {typeof(T).Name}: {result}\");\n return result;\n }\n \n // Special handling for boolean values\n if (typeof(T) == typeof(bool) && value != null)\n {\n // Handle string representations of boolean values\n if (value is string strValue)\n {\n if (bool.TryParse(strValue, out bool boolResult))\n {\n _logService.Log(LogLevel.Debug, $\"String value '{strValue}' parsed as boolean: {boolResult}\");\n return (T)(object)boolResult;\n }\n \n // Also check for \"1\" and \"0\" string values\n if (strValue == \"1\")\n {\n _logService.Log(LogLevel.Debug, $\"String value '1' converted to boolean: true\");\n return (T)(object)true;\n }\n else if (strValue == \"0\")\n {\n _logService.Log(LogLevel.Debug, $\"String value '0' converted to boolean: false\");\n return (T)(object)false;\n }\n }\n \n // Handle numeric representations (0 = false, non-zero = true)\n if (value is long || value is int || value is double || value is float)\n {\n double numValue = Convert.ToDouble(value);\n bool boolResult2 = numValue != 0; // Renamed to avoid conflict\n _logService.Log(LogLevel.Debug, $\"Numeric value {numValue} converted to boolean: {boolResult2}\");\n return (T)(object)boolResult2;\n }\n \n // Handle direct boolean values\n if (value is bool boolValue)\n {\n _logService.Log(LogLevel.Debug, $\"Direct boolean value: {boolValue}\");\n return (T)(object)boolValue;\n }\n }\n \n // Try to convert the value to the requested type\n var convertedValue = (T)Convert.ChangeType(value, typeof(T));\n _logService.Log(LogLevel.Debug, $\"Converted value to {typeof(T).Name}: {convertedValue}\");\n return convertedValue;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error converting preference value for key '{key}': {ex.Message}\");\n if (ex.InnerException != null)\n {\n _logService.Log(LogLevel.Error, $\"Inner exception: {ex.InnerException.Message}\");\n }\n _logService.Log(LogLevel.Error, $\"Stack trace: {ex.StackTrace}\");\n return defaultValue;\n }\n }\n \n _logService.Log(LogLevel.Debug, $\"Preference '{key}' not found, returning default value: {defaultValue}\");\n return defaultValue;\n }\n\n /// \n /// Sets a specific preference value\n /// \n /// The type of the preference value\n /// The preference key\n /// The preference value\n /// True if successful, false otherwise\n public async Task SetPreferenceAsync(string key, T value)\n {\n try\n {\n var preferences = await GetPreferencesAsync();\n \n // Log the preference being set\n _logService.Log(LogLevel.Debug, $\"Setting preference '{key}' to '{value}'\");\n \n preferences[key] = value;\n \n bool result = await SavePreferencesAsync(preferences);\n \n // Log the result\n if (result)\n {\n _logService.Log(LogLevel.Info, $\"Successfully saved preference '{key}'\");\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to save preference '{key}'\");\n }\n \n return result;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting preference '{key}': {ex.Message}\");\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/PowerShellExecutionService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service that executes PowerShell scripts with progress reporting and cancellation support.\n /// \n public class PowerShellExecutionService : IPowerShellExecutionService, IDisposable\n {\n private readonly ILogService _logService;\n private readonly ISystemServices _systemServices;\n \n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The system services.\n public PowerShellExecutionService(ILogService logService, ISystemServices systemServices)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _systemServices = systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n }\n \n /// \n public async Task ExecuteScriptAsync(\n string script, \n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (string.IsNullOrEmpty(script))\n {\n throw new ArgumentException(\"Script cannot be null or empty.\", nameof(script));\n }\n \n using var powerShell = Utilities.PowerShellFactory.CreateWindowsPowerShell(_logService, _systemServices);\n // No need to set execution policy as it's already done in the factory\n \n powerShell.AddScript(script);\n\n // Set up stream handlers\n // Explicitly type progressAdapter using full namespace\n System.IProgress? progressAdapter = progress != null\n ? new System.Progress(data => MapProgressData(data, progress)) // Also qualify Progress\n : null;\n\n SetupStreamHandlers(powerShell, progressAdapter);\n\n // Execute PowerShell with cancellation support\n return await Task.Run(() => {\n try\n {\n cancellationToken.ThrowIfCancellationRequested();\n var invokeResult = powerShell.Invoke();\n var resultText = string.Join(Environment.NewLine, \n invokeResult.Select(item => item.ToString()));\n \n // Check for errors\n if (powerShell.HadErrors)\n {\n foreach (var error in powerShell.Streams.Error)\n {\n _logService.LogError($\"PowerShell error: {error.Exception?.Message ?? error.ToString()}\", error.Exception);\n \n // This call seems to be the source of CS1061, despite Progress having Report.\n // Let's ensure the object creation is correct.\n progressAdapter?.Report(new PowerShellProgressData\n {\n Message = error.Exception?.Message ?? error.ToString(),\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Error\n });\n }\n }\n \n return resultText;\n }\n catch (Exception ex) when (cancellationToken.IsCancellationRequested)\n {\n _logService.LogWarning($\"PowerShell execution cancelled: {ex.Message}\");\n throw new OperationCanceledException(\"PowerShell execution was cancelled.\", ex, cancellationToken);\n }\n }, cancellationToken);\n }\n \n /// \n public async Task ExecuteScriptFileAsync(\n string scriptPath, \n string arguments = \"\",\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (string.IsNullOrEmpty(scriptPath))\n {\n throw new ArgumentException(\"Script path cannot be null or empty.\", nameof(scriptPath));\n }\n \n if (!File.Exists(scriptPath))\n {\n throw new FileNotFoundException($\"PowerShell script file not found: {scriptPath}\");\n }\n \n string script = await File.ReadAllTextAsync(scriptPath, cancellationToken);\n \n // If we have arguments, add them as parameters\n if (!string.IsNullOrEmpty(arguments))\n {\n script = $\"{script} {arguments}\";\n }\n \n return await ExecuteScriptAsync(script, progress, cancellationToken);\n }\n \n private void SetupStreamHandlers(PowerShell powerShell, IProgress? progress)\n {\n if (progress == null) return;\n \n // Handle progress records\n powerShell.Streams.Progress.DataAdded += (sender, e) => {\n var progressRecord = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n PercentComplete = progressRecord.PercentComplete >= 0 ? progressRecord.PercentComplete : null,\n Activity = progressRecord.Activity,\n StatusDescription = progressRecord.StatusDescription,\n CurrentOperation = progressRecord.CurrentOperation,\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Progress\n });\n\n _logService?.LogInformation($\"PowerShell Progress: {progressRecord.Activity} - {progressRecord.StatusDescription} ({progressRecord.PercentComplete}%)\");\n };\n\n // Handle information stream\n powerShell.Streams.Information.DataAdded += (sender, e) => {\n var info = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n Message = info.MessageData.ToString(),\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Information\n });\n\n _logService?.LogInformation($\"PowerShell Info: {info.MessageData}\");\n };\n\n // Handle verbose stream\n powerShell.Streams.Verbose.DataAdded += (sender, e) => {\n var verbose = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n Message = verbose.Message,\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Verbose\n });\n\n _logService?.Log(LogLevel.Debug, $\"PowerShell Verbose: {verbose.Message}\");\n };\n\n // Handle warning stream\n powerShell.Streams.Warning.DataAdded += (sender, e) => {\n var warning = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n Message = warning.Message,\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Warning\n });\n\n _logService?.LogWarning($\"PowerShell Warning: {warning.Message}\");\n };\n\n // Handle error stream\n powerShell.Streams.Error.DataAdded += (sender, e) => {\n var error = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n Message = error.Exception?.Message ?? error.ToString(),\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Error\n });\n\n _logService?.Log(LogLevel.Error, $\"PowerShell Error: {error.Exception?.Message ?? error.ToString()}\");\n };\n\n // Handle debug stream\n powerShell.Streams.Debug.DataAdded += (sender, e) => {\n var debug = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n Message = debug.Message,\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Debug\n });\n\n _logService?.Log(LogLevel.Debug, $\"PowerShell Debug: {debug.Message}\");\n };\n }\n \n private void MapProgressData(PowerShellProgressData source, IProgress target)\n {\n var detail = new TaskProgressDetail();\n \n // Map PowerShell progress data to task progress detail\n if (source.PercentComplete.HasValue)\n {\n detail.Progress = source.PercentComplete.Value;\n }\n \n if (!string.IsNullOrEmpty(source.Activity))\n {\n detail.StatusText = source.Activity;\n if (!string.IsNullOrEmpty(source.StatusDescription))\n {\n detail.StatusText += $\": {source.StatusDescription}\";\n }\n }\n \n detail.DetailedMessage = source.Message ?? source.CurrentOperation;\n // Map stream type to log level\n switch (source.StreamType)\n {\n case Winhance.Core.Features.Common.Enums.PowerShellStreamType.Error:\n detail.LogLevel = LogLevel.Error;\n break;\n case Winhance.Core.Features.Common.Enums.PowerShellStreamType.Warning:\n detail.LogLevel = LogLevel.Warning;\n break;\n case Winhance.Core.Features.Common.Enums.PowerShellStreamType.Verbose:\n case Winhance.Core.Features.Common.Enums.PowerShellStreamType.Debug:\n detail.LogLevel = LogLevel.Debug;\n break;\n default: // Includes Information and Progress\n detail.LogLevel = LogLevel.Info;\n break;\n }\n \n target.Report(detail);\n }\n \n // SetExecutionPolicy is now handled by PowerShellFactory\n \n /// \n /// Disposes resources used by the service.\n /// \n public void Dispose()\n {\n // Cleanup resources if needed\n GC.SuppressFinalize(this);\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ViewModelRefresher.cs", "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Threading;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for refreshing view models after configuration changes.\n /// \n public class ViewModelRefresher : IViewModelRefresher\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public ViewModelRefresher(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Refreshes a view model after configuration changes.\n /// \n /// The view model to refresh.\n /// A task representing the asynchronous operation.\n public async Task RefreshViewModelAsync(object viewModel)\n {\n try\n {\n // Special handling for OptimizeViewModel\n if (viewModel is Winhance.WPF.Features.Optimize.ViewModels.OptimizeViewModel optimizeViewModel)\n {\n _logService.Log(LogLevel.Debug, \"Refreshing OptimizeViewModel and its child view models\");\n \n // Refresh child view models first\n var childViewModels = new object[]\n {\n optimizeViewModel.GamingandPerformanceOptimizationsViewModel,\n optimizeViewModel.PrivacyOptimizationsViewModel,\n optimizeViewModel.UpdateOptimizationsViewModel,\n optimizeViewModel.PowerSettingsViewModel,\n optimizeViewModel.WindowsSecuritySettingsViewModel,\n optimizeViewModel.ExplorerOptimizationsViewModel,\n optimizeViewModel.NotificationOptimizationsViewModel,\n optimizeViewModel.SoundOptimizationsViewModel\n };\n \n foreach (var childViewModel in childViewModels)\n {\n if (childViewModel != null)\n {\n // Try to refresh each child view model\n await RefreshChildViewModelAsync(childViewModel);\n }\n }\n \n // Then reload the main view model's items to reflect changes in child view models\n await optimizeViewModel.LoadItemsAsync();\n \n // Notify UI of changes using a safer approach\n try\n {\n // Try to find a method that takes a string parameter\n var methods = optimizeViewModel.GetType().GetMethods(\n System.Reflection.BindingFlags.Public |\n System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance)\n .Where(m => (m.Name == \"RaisePropertyChanged\" || m.Name == \"OnPropertyChanged\") &&\n m.GetParameters().Length == 1 &&\n m.GetParameters()[0].ParameterType == typeof(string))\n .ToList();\n \n if (methods.Any())\n {\n var method = methods.First();\n // Refresh key properties\n // Execute property change notifications on the UI thread\n ExecuteOnUIThread(() => {\n method.Invoke(optimizeViewModel, new object[] { \"Items\" });\n method.Invoke(optimizeViewModel, new object[] { \"IsInitialized\" });\n method.Invoke(optimizeViewModel, new object[] { \"IsLoading\" });\n _logService.Log(LogLevel.Debug, $\"Refreshed OptimizeViewModel properties using {method.Name} on UI thread\");\n });\n }\n else\n {\n // If no suitable method is found, try using RefreshCommand\n var refreshCommand = optimizeViewModel.GetType().GetProperty(\"RefreshCommand\")?.GetValue(optimizeViewModel) as System.Windows.Input.ICommand;\n if (refreshCommand != null && refreshCommand.CanExecute(null))\n {\n ExecuteOnUIThread(() => {\n refreshCommand.Execute(null);\n _logService.Log(LogLevel.Debug, \"Refreshed OptimizeViewModel using RefreshCommand on UI thread\");\n });\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error refreshing OptimizeViewModel: {ex.Message}\");\n }\n \n return;\n }\n \n // Standard refresh logic for other view models\n // Try multiple refresh methods in order of preference\n \n // 1. First try RefreshCommand if available\n var refreshCommandProperty = viewModel.GetType().GetProperty(\"RefreshCommand\");\n if (refreshCommandProperty != null)\n {\n var refreshCommand = refreshCommandProperty.GetValue(viewModel) as System.Windows.Input.ICommand;\n if (refreshCommand != null && refreshCommand.CanExecute(null))\n {\n ExecuteOnUIThread(() => {\n refreshCommand.Execute(null);\n _logService.Log(LogLevel.Debug, $\"Refreshed {viewModel.GetType().Name} using RefreshCommand on UI thread\");\n });\n return;\n }\n }\n \n // 2. Try RaisePropertyChanged for the Items property if the view model implements INotifyPropertyChanged\n if (viewModel is System.ComponentModel.INotifyPropertyChanged)\n {\n try\n {\n // Use a safer approach to find property changed methods\n var methods = viewModel.GetType().GetMethods(\n System.Reflection.BindingFlags.Public |\n System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance)\n .Where(m => (m.Name == \"RaisePropertyChanged\" || m.Name == \"OnPropertyChanged\") &&\n m.GetParameters().Length == 1 &&\n m.GetParameters()[0].ParameterType == typeof(string))\n .ToList();\n \n if (methods.Any())\n {\n var method = methods.First();\n ExecuteOnUIThread(() => {\n method.Invoke(viewModel, new object[] { \"Items\" });\n _logService.Log(LogLevel.Debug, $\"Refreshed {viewModel.GetType().Name} using {method.Name} on UI thread\");\n });\n return;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error finding property changed method: {ex.Message}\");\n // Continue with other refresh methods\n }\n }\n \n // 3. Try LoadItemsAsync method\n var loadItemsMethod = viewModel.GetType().GetMethod(\"LoadItemsAsync\");\n if (loadItemsMethod != null)\n {\n await (Task)loadItemsMethod.Invoke(viewModel, null);\n return;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error refreshing UI: {ex.Message}\");\n }\n }\n\n /// \n /// Refreshes a child view model after configuration changes.\n /// \n /// The child view model to refresh.\n /// A task representing the asynchronous operation.\n public async Task RefreshChildViewModelAsync(object childViewModel)\n {\n try\n {\n // Try to find and call CheckSettingStatusesAsync method\n var checkStatusMethod = childViewModel.GetType().GetMethod(\"CheckSettingStatusesAsync\");\n if (checkStatusMethod != null)\n {\n await (Task)checkStatusMethod.Invoke(childViewModel, null);\n _logService.Log(LogLevel.Debug, $\"Called CheckSettingStatusesAsync on {childViewModel.GetType().Name}\");\n }\n \n // Try to notify property changes using a safer approach\n if (childViewModel is System.ComponentModel.INotifyPropertyChanged)\n {\n try\n {\n // Use a safer approach to find the right PropertyChanged event\n var propertyChangedEvent = childViewModel.GetType().GetEvent(\"PropertyChanged\");\n if (propertyChangedEvent != null)\n {\n // Try to find a method that raises the PropertyChanged event\n // Look for a method that takes a string parameter first\n var methods = childViewModel.GetType().GetMethods(\n System.Reflection.BindingFlags.Public |\n System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance)\n .Where(m => (m.Name == \"RaisePropertyChanged\" || m.Name == \"OnPropertyChanged\") &&\n m.GetParameters().Length == 1 &&\n m.GetParameters()[0].ParameterType == typeof(string))\n .ToList();\n \n if (methods.Any())\n {\n var method = methods.First();\n // Refresh Settings property and IsSelected property on UI thread\n ExecuteOnUIThread(() => {\n method.Invoke(childViewModel, new object[] { \"Settings\" });\n method.Invoke(childViewModel, new object[] { \"IsSelected\" });\n _logService.Log(LogLevel.Debug, $\"Refreshed properties on {childViewModel.GetType().Name} using {method.Name} on UI thread\");\n });\n }\n else\n {\n // If no method with string parameter is found, try to find a method that takes PropertyChangedEventArgs\n var refreshCommand = childViewModel.GetType().GetProperty(\"RefreshCommand\")?.GetValue(childViewModel) as System.Windows.Input.ICommand;\n if (refreshCommand != null && refreshCommand.CanExecute(null))\n {\n ExecuteOnUIThread(() => {\n refreshCommand.Execute(null);\n _logService.Log(LogLevel.Debug, $\"Refreshed {childViewModel.GetType().Name} using RefreshCommand on UI thread\");\n });\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error refreshing child view model properties: {ex.Message}\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error refreshing child view model: {ex.Message}\");\n }\n }\n \n /// \n /// Executes an action on the UI thread.\n /// \n /// The action to execute.\n private void ExecuteOnUIThread(Action action)\n {\n try\n {\n // Check if we have access to a dispatcher\n if (Application.Current != null && Application.Current.Dispatcher != null)\n {\n // Check if we're already on the UI thread\n if (Application.Current.Dispatcher.CheckAccess())\n {\n // We're on the UI thread, execute directly\n action();\n }\n else\n {\n // We're not on the UI thread, invoke on the UI thread\n Application.Current.Dispatcher.Invoke(action, DispatcherPriority.Background);\n }\n }\n else\n {\n // No dispatcher available, execute directly\n action();\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error executing action on UI thread: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n \n // Try to execute the action directly as a fallback\n try\n {\n action();\n }\n catch (Exception innerEx)\n {\n _logService.Log(LogLevel.Error, $\"Error executing action directly: {innerEx.Message}\");\n }\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/PowerShellHelper.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Helper class for common PowerShell execution patterns.\n /// \n public static class PowerShellHelper\n {\n /// \n /// Executes a PowerShell script with progress reporting and error handling.\n /// \n /// The PowerShell instance to use.\n /// The script to execute.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// The collection of PSObjects returned by the script.\n public static async Task> ExecuteScriptAsync(\n this PowerShell powerShell,\n string script,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (powerShell == null)\n {\n throw new ArgumentNullException(nameof(powerShell));\n }\n\n if (string.IsNullOrWhiteSpace(script))\n {\n throw new ArgumentException(\"Script cannot be null or empty\", nameof(script));\n }\n\n powerShell.AddScript(script);\n\n // Add event handlers for progress reporting\n if (progress != null)\n {\n powerShell.Streams.Information.DataAdded += (sender, e) =>\n {\n var info = powerShell.Streams.Information[e.Index];\n progress.Report(new TaskProgressDetail\n {\n DetailedMessage = info.MessageData.ToString(),\n LogLevel = LogLevel.Info\n });\n };\n\n powerShell.Streams.Error.DataAdded += (sender, e) =>\n {\n var error = powerShell.Streams.Error[e.Index];\n progress.Report(new TaskProgressDetail\n {\n DetailedMessage = error.Exception?.Message ?? error.ToString(),\n LogLevel = LogLevel.Error\n });\n };\n\n powerShell.Streams.Warning.DataAdded += (sender, e) =>\n {\n var warning = powerShell.Streams.Warning[e.Index];\n progress.Report(new TaskProgressDetail\n {\n DetailedMessage = warning.Message,\n LogLevel = LogLevel.Warning\n });\n };\n\n powerShell.Streams.Progress.DataAdded += (sender, e) =>\n {\n var progressRecord = powerShell.Streams.Progress[e.Index];\n var percentComplete = progressRecord.PercentComplete;\n if (percentComplete >= 0 && percentComplete <= 100)\n {\n progress.Report(new TaskProgressDetail\n {\n Progress = percentComplete,\n StatusText = progressRecord.Activity,\n DetailedMessage = progressRecord.StatusDescription\n });\n }\n };\n }\n\n // Execute the script\n return await Task.Run(() => powerShell.Invoke(), cancellationToken);\n }\n\n /// \n /// Executes a PowerShell script asynchronously.\n /// \n /// The PowerShell instance to use.\n /// Optional cancellation token.\n /// The data collection of PSObjects returned by the script.\n public static async Task> InvokeAsync(\n this PowerShell powerShell,\n CancellationToken cancellationToken = default)\n {\n if (powerShell == null)\n {\n throw new ArgumentNullException(nameof(powerShell));\n }\n\n var output = new PSDataCollection();\n var asyncResult = powerShell.BeginInvoke(null, output);\n\n await Task.Run(() =>\n {\n while (!asyncResult.IsCompleted)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n powerShell.Stop();\n cancellationToken.ThrowIfCancellationRequested();\n }\n Thread.Sleep(100);\n }\n powerShell.EndInvoke(asyncResult);\n }, cancellationToken);\n\n return output;\n }\n\n /// \n /// Parses a result string in the format \"STATUS|Message|RebootRequired\".\n /// \n /// The result string to parse.\n /// The name of the item being installed.\n /// Optional progress reporter.\n /// The log service for logging.\n /// An operation result indicating success or failure with error details.\n public static OperationResult ParseResultString(\n string resultString,\n string itemName,\n IProgress? progress = null,\n ILogService? logService = null)\n {\n if (string.IsNullOrEmpty(resultString))\n {\n progress?.Report(new TaskProgressDetail\n {\n StatusText = \"Script returned no result\",\n LogLevel = LogLevel.Error\n });\n logService?.LogError($\"Empty result returned when processing: {itemName}\");\n return OperationResult.Failed(\"Script returned no result\");\n }\n\n var parts = resultString.Split('|');\n if (parts.Length < 2)\n {\n progress?.Report(new TaskProgressDetail\n {\n StatusText = \"Error processing script result\",\n LogLevel = LogLevel.Error\n });\n logService?.LogError($\"Unexpected script output format for {itemName}: {resultString}\");\n return OperationResult.Failed(\"Unexpected script output format: \" + resultString);\n }\n\n string status = parts[0];\n string message = parts[1];\n bool rebootRequired = parts.Length > 2 && bool.TryParse(parts[2], out bool req) && req;\n\n if (status.Equals(\"SUCCESS\", StringComparison.OrdinalIgnoreCase))\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 100,\n StatusText = $\"Successfully processed: {itemName}\",\n DetailedMessage = message\n });\n logService?.LogSuccess($\"Successfully processed: {itemName}. {message}\");\n\n if (rebootRequired)\n {\n progress?.Report(new TaskProgressDetail\n {\n StatusText = \"A system restart is required to complete the installation\",\n DetailedMessage = \"Please restart your computer to complete the installation\",\n LogLevel = LogLevel.Warning\n });\n logService?.LogWarning($\"A system restart is required for {itemName}\");\n }\n return OperationResult.Succeeded(true);\n }\n else // FAILURE\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Failed to process: {itemName}\",\n DetailedMessage = message,\n LogLevel = LogLevel.Error\n });\n logService?.LogError($\"Failed to process: {itemName}. {message}\");\n return OperationResult.Failed(message);\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppVerificationService.cs", "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that handles verification of application installations.\n/// \npublic class AppVerificationService : IAppVerificationService\n{\n private readonly ILogService _logService;\n private readonly ISystemServices _systemServices;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The system services.\n public AppVerificationService(\n ILogService logService,\n ISystemServices systemServices)\n {\n _logService = logService;\n _systemServices = systemServices;\n }\n\n /// \n public async Task VerifyAppInstallationAsync(string packageName)\n {\n try\n {\n // Create PowerShell instance\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n\n // For Microsoft Store apps (package IDs that are alphanumeric with no dots)\n if (packageName.All(char.IsLetterOrDigit) && !packageName.Contains('.'))\n {\n // Use Get-AppxPackage to check if the Microsoft Store app is installed\n // Ensure we're using Windows PowerShell for Appx commands\n using var appxPowerShell = PowerShellFactory.CreateForAppxCommands(_logService, _systemServices);\n appxPowerShell.AddScript(\n $\"Get-AppxPackage | Where-Object {{ $_.PackageFullName -like '*{packageName}*' }}\"\n );\n var result = await appxPowerShell.InvokeAsync();\n\n if (result.Count > 0)\n {\n return true;\n }\n }\n\n // For all other apps, use winget list to check if installed\n powerShell.Commands.Clear();\n powerShell.AddScript(\n $@\"\n try {{\n # Ensure we're using Windows PowerShell for Winget operations\n $result = winget list --id '{packageName}' --exact\n $isInstalled = $result -match '{packageName}'\n Write-Output $isInstalled\n }} catch {{\n Write-Output $false\n }}\n \"\n );\n\n var results = await powerShell.InvokeAsync();\n\n // Check if the result indicates the app is installed\n if (results.Count > 0)\n {\n // Extract boolean value from result\n var resultValue = results[0]?.ToString()?.ToLowerInvariant();\n if (resultValue == \"true\")\n {\n return true;\n }\n }\n\n // If we're here, try one more verification with a different approach\n powerShell.Commands.Clear();\n powerShell.AddScript(\n $@\"\n try {{\n # Use where.exe to check if the app is in PATH (for CLI tools)\n $whereResult = where.exe {packageName} 2>&1\n if ($whereResult -notmatch 'not found') {{\n Write-Output 'true'\n return\n }}\n\n # Check common installation directories\n $commonPaths = @(\n [System.Environment]::GetFolderPath('ProgramFiles'),\n [System.Environment]::GetFolderPath('ProgramFilesX86'),\n [System.Environment]::GetFolderPath('LocalApplicationData')\n )\n\n foreach ($basePath in $commonPaths) {{\n if (Test-Path -Path \"\"$basePath\\$packageName\"\" -PathType Container) {{\n Write-Output 'true'\n return\n }}\n }}\n\n Write-Output 'false'\n }} catch {{\n Write-Output 'false'\n }}\n \"\n );\n\n results = await powerShell.InvokeAsync();\n\n // Check if the result indicates the app is installed\n if (results.Count > 0)\n {\n var resultValue = results[0]?.ToString()?.ToLowerInvariant();\n return resultValue == \"true\";\n }\n\n return false;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error verifying app installation: {ex.Message}\", ex);\n // If any error occurs during verification, assume the app is not installed\n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/ConfigurationUIService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for handling UI-related operations for configuration management.\n /// \n public class ConfigurationUIService\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public ConfigurationUIService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Shows the unified configuration dialog to let the user select which sections to include.\n /// \n /// The unified configuration file.\n /// Whether this is a save dialog (true) or an import dialog (false).\n /// A dictionary of section names and their selection state.\n public async Task> ShowUnifiedConfigurationDialogAsync(UnifiedConfigurationFile config, bool isSaveDialog)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Showing unified configuration dialog (isSaveDialog: {isSaveDialog})\");\n \n // Create a dictionary of sections with their availability and item counts\n var sectionInfo = new Dictionary\n {\n { \"WindowsApps\", (true, config.WindowsApps.Items.Count > 0, config.WindowsApps.Items.Count) },\n { \"ExternalApps\", (true, config.ExternalApps.Items.Count > 0, config.ExternalApps.Items.Count) },\n { \"Customize\", (true, config.Customize.Items.Count > 0, config.Customize.Items.Count) },\n { \"Optimize\", (true, config.Optimize.Items.Count > 0, config.Optimize.Items.Count) }\n };\n \n // Create and show the dialog\n var dialog = new UnifiedConfigurationDialog(\n isSaveDialog ? \"Save Configuration\" : \"Select Configuration Sections\",\n isSaveDialog ? \"Select which sections you want to save to the unified configuration.\" : \"Select which sections you want to import from the unified configuration.\",\n sectionInfo,\n isSaveDialog);\n \n dialog.Owner = Application.Current.MainWindow;\n bool? dialogResult = dialog.ShowDialog();\n \n if (dialogResult != true)\n {\n _logService.Log(LogLevel.Info, \"User canceled unified configuration dialog\");\n return new Dictionary();\n }\n \n // Get the selected sections from the dialog\n var result = dialog.GetResult();\n \n _logService.Log(LogLevel.Info, $\"Selected sections: {string.Join(\", \", result.Where(kvp => kvp.Value).Select(kvp => kvp.Key))}\");\n \n return result;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error showing unified configuration dialog: {ex.Message}\");\n return new Dictionary();\n }\n }\n\n /// \n /// Shows a success message for configuration operations.\n /// \n /// The title of the message.\n /// The message to show.\n /// The sections that were affected.\n /// Additional information to show.\n public void ShowSuccessMessage(string title, string message, List sections, string additionalInfo)\n {\n CustomDialog.ShowInformation(title, message, sections, additionalInfo);\n }\n\n /// \n /// Shows an error message for configuration operations.\n /// \n /// The title of the message.\n /// The message to show.\n public void ShowErrorMessage(string title, string message)\n {\n MessageBox.Show(message, title, MessageBoxButton.OK, MessageBoxImage.Error);\n }\n\n /// \n /// Shows a confirmation dialog for configuration operations.\n /// \n /// The title of the dialog.\n /// The message to show.\n /// True if the user confirmed, false otherwise.\n public bool ShowConfirmationDialog(string title, string message)\n {\n var result = MessageBox.Show(message, title, MessageBoxButton.YesNo, MessageBoxImage.Question);\n return result == MessageBoxResult.Yes;\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/PowerShellScriptBuilderService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Service for building PowerShell script content.\n /// \n public class PowerShellScriptBuilderService : IScriptBuilderService\n {\n private readonly IScriptTemplateProvider _templateProvider;\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The template provider.\n /// The logging service.\n public PowerShellScriptBuilderService(\n IScriptTemplateProvider templateProvider,\n ILogService logService)\n {\n _templateProvider = templateProvider ?? throw new ArgumentNullException(nameof(templateProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string BuildPackageRemovalScript(IEnumerable packageNames)\n {\n if (packageNames == null || !packageNames.Any())\n {\n return string.Empty;\n }\n\n var sb = new StringBuilder();\n sb.AppendLine(\"# Remove packages\");\n \n string template = _templateProvider.GetPackageRemovalTemplate();\n \n foreach (var packageName in packageNames)\n {\n sb.AppendLine();\n sb.AppendLine($\"# Remove {packageName}\");\n sb.AppendLine(string.Format(template, packageName));\n }\n\n return sb.ToString();\n }\n\n /// \n public string BuildCapabilityRemovalScript(IEnumerable capabilityNames)\n {\n if (capabilityNames == null || !capabilityNames.Any())\n {\n return string.Empty;\n }\n\n var sb = new StringBuilder();\n sb.AppendLine(\"# Remove capabilities\");\n \n string template = _templateProvider.GetCapabilityRemovalTemplate();\n \n foreach (var capabilityName in capabilityNames)\n {\n sb.AppendLine();\n sb.AppendLine($\"# Remove {capabilityName}\");\n sb.AppendLine(string.Format(template, capabilityName));\n }\n\n return sb.ToString();\n }\n\n /// \n public string BuildFeatureRemovalScript(IEnumerable featureNames)\n {\n if (featureNames == null || !featureNames.Any())\n {\n return string.Empty;\n }\n\n var sb = new StringBuilder();\n sb.AppendLine(\"# Disable Optional Features\");\n \n string template = _templateProvider.GetFeatureRemovalTemplate();\n \n foreach (var featureName in featureNames)\n {\n sb.AppendLine();\n sb.AppendLine($\"# Disable {featureName}\");\n sb.AppendLine(string.Format(template, featureName));\n }\n\n return sb.ToString();\n }\n\n /// \n public string BuildRegistryScript(Dictionary> registrySettings)\n {\n if (registrySettings == null || !registrySettings.Any())\n {\n return string.Empty;\n }\n\n var sb = new StringBuilder();\n sb.AppendLine(\"# Registry settings\");\n\n foreach (var appEntry in registrySettings)\n {\n string appName = appEntry.Key;\n List settings = appEntry.Value;\n\n if (settings == null || !settings.Any())\n {\n continue;\n }\n\n sb.AppendLine();\n sb.AppendLine($\"# Registry settings for {appName}\");\n\n foreach (var setting in settings)\n {\n string path = setting.Path;\n string name = setting.Name;\n string valueKind = GetRegTypeString(setting.ValueKind);\n string value = setting.Value?.ToString() ?? string.Empty;\n\n // Check if this is a delete operation (value is null or empty)\n bool isDelete = string.IsNullOrEmpty(value);\n string template = _templateProvider.GetRegistrySettingTemplate(isDelete);\n\n if (isDelete)\n {\n sb.AppendLine(string.Format(template, path, name));\n }\n else\n {\n // Format the value based on its type\n string formattedValue = FormatRegistryValue(value, setting.ValueKind);\n sb.AppendLine(string.Format(template, path, name, valueKind, formattedValue));\n }\n }\n }\n\n return sb.ToString();\n }\n\n /// \n public string BuildCompleteRemovalScript(\n IEnumerable packageNames,\n IEnumerable capabilityNames,\n IEnumerable featureNames,\n Dictionary> registrySettings,\n Dictionary subPackages)\n {\n var sb = new StringBuilder();\n\n // Add script header\n sb.Append(_templateProvider.GetScriptHeader(\"BloatRemoval\"));\n\n // Add packages section\n var allPackages = new List();\n \n // Add main packages\n if (packageNames != null)\n {\n allPackages.AddRange(packageNames);\n }\n \n // Add subpackages\n if (subPackages != null)\n {\n foreach (var subPackageEntry in subPackages)\n {\n if (subPackageEntry.Value != null)\n {\n allPackages.AddRange(subPackageEntry.Value);\n }\n }\n }\n \n // Remove duplicates\n allPackages = allPackages.Distinct().ToList();\n \n // Update the packages array in the script\n if (allPackages.Any())\n {\n sb.AppendLine(\"# Remove packages\");\n sb.AppendLine(\"$packages = @(\");\n \n for (int i = 0; i < allPackages.Count; i++)\n {\n string package = allPackages[i];\n if (i < allPackages.Count - 1)\n {\n sb.AppendLine($\" '{package}',\");\n }\n else\n {\n sb.AppendLine($\" '{package}'\");\n }\n }\n \n sb.AppendLine(\")\");\n sb.AppendLine();\n sb.AppendLine(\"foreach ($package in $packages) {\");\n sb.AppendLine(\" Get-AppxPackage -AllUsers -Name $package | \");\n sb.AppendLine(\" ForEach-Object {\");\n sb.AppendLine(\" Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\");\n sb.AppendLine(\" }\");\n sb.AppendLine(\" Get-AppxProvisionedPackage -Online | \");\n sb.AppendLine(\" Where-Object { $_.DisplayName -eq $package } | \");\n sb.AppendLine(\" ForEach-Object {\");\n sb.AppendLine(\" Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\");\n sb.AppendLine(\" }\");\n sb.AppendLine(\"}\");\n sb.AppendLine();\n }\n \n // Add capabilities section\n if (capabilityNames != null && capabilityNames.Any())\n {\n sb.AppendLine(\"# Remove capabilities\");\n sb.AppendLine(\"$capabilities = @(\");\n \n var capabilitiesList = capabilityNames.ToList();\n for (int i = 0; i < capabilitiesList.Count; i++)\n {\n string capability = capabilitiesList[i];\n if (i < capabilitiesList.Count - 1)\n {\n sb.AppendLine($\" '{capability}',\");\n }\n else\n {\n sb.AppendLine($\" '{capability}'\");\n }\n }\n \n sb.AppendLine(\")\");\n sb.AppendLine();\n sb.AppendLine(\"foreach ($capability in $capabilities) {\");\n sb.AppendLine(\" Get-WindowsCapability -Online | Where-Object { $_.Name -like \\\"$capability*\\\" } | Remove-WindowsCapability -Online\");\n sb.AppendLine(\"}\");\n sb.AppendLine();\n }\n \n // Add features section\n if (featureNames != null && featureNames.Any())\n {\n sb.AppendLine(\"# Disable Optional Features\");\n sb.AppendLine(\"$optionalFeatures = @(\");\n \n var featuresList = featureNames.ToList();\n for (int i = 0; i < featuresList.Count; i++)\n {\n string feature = featuresList[i];\n if (i < featuresList.Count - 1)\n {\n sb.AppendLine($\" '{feature}',\");\n }\n else\n {\n sb.AppendLine($\" '{feature}'\");\n }\n }\n \n sb.AppendLine(\")\");\n sb.AppendLine();\n sb.AppendLine(\"foreach ($feature in $optionalFeatures) {\");\n sb.AppendLine(\" Write-Host \\\"Disabling optional feature: $feature\\\" -ForegroundColor Yellow\");\n sb.AppendLine(\" Disable-WindowsOptionalFeature -Online -FeatureName $feature -NoRestart | Out-Null\");\n sb.AppendLine(\"}\");\n sb.AppendLine();\n }\n \n // Add registry settings\n if (registrySettings != null && registrySettings.Any())\n {\n sb.AppendLine(\"# Registry settings\");\n \n foreach (var appEntry in registrySettings)\n {\n string appName = appEntry.Key;\n List settings = appEntry.Value;\n \n if (settings == null || !settings.Any())\n {\n continue;\n }\n \n sb.AppendLine();\n sb.AppendLine($\"# Registry settings for {appName}\");\n \n foreach (var setting in settings)\n {\n string path = setting.Path;\n string name = setting.Name;\n string valueKind = GetRegTypeString(setting.ValueKind);\n string value = setting.Value?.ToString() ?? string.Empty;\n \n // Check if this is a delete operation (value is null or empty)\n bool isDelete = string.IsNullOrEmpty(value);\n string template = _templateProvider.GetRegistrySettingTemplate(isDelete);\n \n if (isDelete)\n {\n sb.AppendLine(string.Format(template, path, name));\n }\n else\n {\n // Format the value based on its type\n string formattedValue = FormatRegistryValue(value, setting.ValueKind);\n sb.AppendLine(string.Format(template, path, name, valueKind, formattedValue));\n }\n }\n }\n \n sb.AppendLine();\n }\n \n // Add script footer\n sb.Append(_templateProvider.GetScriptFooter());\n \n return sb.ToString();\n }\n\n /// \n public string BuildSingleAppRemovalScript(AppInfo app)\n {\n if (app == null)\n {\n throw new ArgumentNullException(nameof(app));\n }\n\n var sb = new StringBuilder();\n \n sb.AppendLine($\"# Removal script for {app.Name} ({app.PackageName})\");\n sb.AppendLine($\"# Generated on {DateTime.Now}\");\n sb.AppendLine();\n sb.AppendLine(\"try {\");\n sb.AppendLine($\" Write-Host \\\"Removing {app.Name}...\\\" -ForegroundColor Yellow\");\n sb.AppendLine();\n \n // Add the appropriate removal command based on the app type\n switch (app.Type)\n {\n case AppType.StandardApp:\n string packageTemplate = _templateProvider.GetPackageRemovalTemplate();\n sb.AppendLine(\" # Remove the app package\");\n sb.AppendLine(\" \" + string.Format(packageTemplate, app.PackageName));\n break;\n \n case AppType.Capability:\n string capabilityTemplate = _templateProvider.GetCapabilityRemovalTemplate();\n sb.AppendLine(\" # Remove the capability\");\n sb.AppendLine(\" \" + string.Format(capabilityTemplate, app.PackageName));\n break;\n \n case AppType.OptionalFeature:\n string featureTemplate = _templateProvider.GetFeatureRemovalTemplate();\n sb.AppendLine(\" # Disable the optional feature\");\n sb.AppendLine(\" \" + string.Format(featureTemplate, app.PackageName));\n break;\n \n default:\n // Default to package removal\n string defaultTemplate = _templateProvider.GetPackageRemovalTemplate();\n sb.AppendLine(\" # Remove the app\");\n sb.AppendLine(\" \" + string.Format(defaultTemplate, app.PackageName));\n break;\n }\n \n sb.AppendLine();\n sb.AppendLine($\" Write-Host \\\"{app.Name} removed successfully.\\\" -ForegroundColor Green\");\n sb.AppendLine(\"} catch {\");\n sb.AppendLine($\" Write-Host \\\"Error removing {app.Name}: $($_.Exception.Message)\\\" -ForegroundColor Red\");\n sb.AppendLine(\"}\");\n \n return sb.ToString();\n }\n\n /// \n /// Formats a registry value based on its type.\n /// \n /// The value to format.\n /// The type of the value.\n /// The formatted value.\n private string FormatRegistryValue(string value, Microsoft.Win32.RegistryValueKind valueKind)\n {\n switch (valueKind)\n {\n case Microsoft.Win32.RegistryValueKind.String:\n case Microsoft.Win32.RegistryValueKind.ExpandString:\n return $\"\\\"{value}\\\"\";\n \n case Microsoft.Win32.RegistryValueKind.DWord:\n case Microsoft.Win32.RegistryValueKind.QWord:\n return value;\n \n case Microsoft.Win32.RegistryValueKind.Binary:\n // Format as hex string\n return value;\n \n case Microsoft.Win32.RegistryValueKind.MultiString:\n // Format as comma-separated string\n return $\"\\\"{value}\\\"\";\n \n default:\n return value;\n }\n }\n\n /// \n /// Converts a RegistryValueKind to the corresponding reg.exe type string.\n /// \n /// The registry value kind.\n /// The reg.exe type string.\n private string GetRegTypeString(Microsoft.Win32.RegistryValueKind valueKind)\n {\n return valueKind switch\n {\n Microsoft.Win32.RegistryValueKind.String => \"SZ\",\n Microsoft.Win32.RegistryValueKind.ExpandString => \"EXPAND_SZ\",\n Microsoft.Win32.RegistryValueKind.Binary => \"BINARY\",\n Microsoft.Win32.RegistryValueKind.DWord => \"DWORD\",\n Microsoft.Win32.RegistryValueKind.MultiString => \"MULTI_SZ\",\n Microsoft.Win32.RegistryValueKind.QWord => \"QWORD\",\n _ => \"SZ\"\n };\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/ConfigurationService.cs", "using Microsoft.Win32;\nusing Newtonsoft.Json;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service for saving and loading application configuration files.\n /// \n public class ConfigurationService : IConfigurationService\n {\n private const string FileExtension = \".winhance\";\n private const string FileFilter = \"Winhance Configuration Files|*\" + FileExtension;\n private const string UnifiedFileFilter = \"Winhance Unified Configuration Files|*\" + FileExtension;\n private readonly ILogService _logService;\n \n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public ConfigurationService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Saves a configuration file containing the selected items.\n /// \n /// The type of items to save.\n /// The collection of items to save.\n /// The type of configuration being saved.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n public async Task SaveConfigurationAsync(IEnumerable items, string configType)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Starting to save {configType} configuration\");\n // Create a save file dialog\n var saveFileDialog = new SaveFileDialog\n {\n Filter = FileFilter,\n DefaultExt = FileExtension,\n Title = \"Save Configuration\",\n FileName = $\"{configType}_{DateTime.Now:yyyyMMdd}{FileExtension}\"\n };\n\n // Show the save file dialog\n if (saveFileDialog.ShowDialog() != true)\n {\n _logService.Log(LogLevel.Info, \"Save configuration canceled by user\");\n return false;\n }\n \n _logService.Log(LogLevel.Info, $\"Saving configuration to {saveFileDialog.FileName}\");\n\n // Create a configuration file\n var configFile = new ConfigurationFile\n {\n ConfigType = configType,\n CreatedAt = DateTime.UtcNow,\n Items = new List()\n };\n\n // Add selected items to the configuration file\n foreach (var item in items)\n {\n var properties = item.GetType().GetProperties();\n var nameProperty = properties.FirstOrDefault(p => p.Name == \"Name\");\n var packageNameProperty = properties.FirstOrDefault(p => p.Name == \"PackageName\");\n var isSelectedProperty = properties.FirstOrDefault(p => p.Name == \"IsSelected\");\n var controlTypeProperty = properties.FirstOrDefault(p => p.Name == \"ControlType\");\n var registrySettingProperty = properties.FirstOrDefault(p => p.Name == \"RegistrySetting\");\n var idProperty = properties.FirstOrDefault(p => p.Name == \"Id\");\n\n if (nameProperty != null && isSelectedProperty != null)\n {\n var name = nameProperty.GetValue(item)?.ToString();\n var packageName = packageNameProperty?.GetValue(item)?.ToString();\n var isSelected = (bool)(isSelectedProperty.GetValue(item) ?? false);\n \n // Create the configuration item\n var configItem = new ConfigurationItem\n {\n Name = name,\n PackageName = packageName,\n IsSelected = isSelected\n };\n \n // Add control type if available\n if (controlTypeProperty != null)\n {\n var controlType = controlTypeProperty.GetValue(item);\n if (controlType != null)\n {\n configItem.ControlType = (ControlType)controlType;\n }\n }\n \n // Store the Id in CustomProperties if available\n if (idProperty != null)\n {\n var id = idProperty.GetValue(item);\n if (id != null)\n {\n configItem.CustomProperties[\"Id\"] = id.ToString();\n _logService.Log(LogLevel.Info, $\"Stored Id for {configItem.Name}: {id}\");\n }\n }\n \n // Handle ComboBox and ThreeStateSlider control types\n if (configItem.ControlType == ControlType.ComboBox || configItem.ControlType == ControlType.ThreeStateSlider)\n {\n // For ComboBox, get the selected value\n var selectedThemeProperty = properties.FirstOrDefault(p => p.Name == \"SelectedTheme\");\n if (selectedThemeProperty != null)\n {\n configItem.SelectedValue = selectedThemeProperty.GetValue(item)?.ToString();\n _logService.Log(LogLevel.Info, $\"Setting SelectedValue for {configItem.Name} to '{configItem.SelectedValue}'\");\n }\n else\n {\n // Try to get the value from SliderLabels and SliderValue\n var sliderLabelsProperty = properties.FirstOrDefault(p => p.Name == \"SliderLabels\");\n var sliderValueProperty = properties.FirstOrDefault(p => p.Name == \"SliderValue\");\n \n if (sliderLabelsProperty != null && sliderValueProperty != null)\n {\n var sliderLabels = sliderLabelsProperty.GetValue(item) as System.Collections.IList;\n var sliderValue = sliderValueProperty.GetValue(item);\n \n if (sliderLabels != null && sliderValue != null && Convert.ToInt32(sliderValue) < sliderLabels.Count)\n {\n configItem.SelectedValue = sliderLabels[Convert.ToInt32(sliderValue)]?.ToString();\n _logService.Log(LogLevel.Info, $\"Derived SelectedValue for {configItem.Name} from SliderLabels[{sliderValue}]: '{configItem.SelectedValue}'\");\n }\n }\n }\n \n // Store the SliderValue for ComboBox or ThreeStateSlider\n // Note: In this application, ComboBox controls use SliderValue to store the selected index\n if (configItem.ControlType == ControlType.ComboBox || configItem.ControlType == ControlType.ThreeStateSlider)\n {\n var sliderValueProperty = properties.FirstOrDefault(p => p.Name == \"SliderValue\");\n if (sliderValueProperty != null)\n {\n var sliderValue = sliderValueProperty.GetValue(item);\n if (sliderValue != null)\n {\n configItem.CustomProperties[\"SliderValue\"] = sliderValue;\n _logService.Log(LogLevel.Info, $\"Stored SliderValue for {configItem.ControlType} {configItem.Name}: {sliderValue}\");\n }\n }\n \n // Also store SliderLabels if available\n var sliderLabelsProperty = properties.FirstOrDefault(p => p.Name == \"SliderLabels\");\n if (sliderLabelsProperty != null)\n {\n var sliderLabels = sliderLabelsProperty.GetValue(item) as System.Collections.IList;\n if (sliderLabels != null && sliderLabels.Count > 0)\n {\n // Store the labels as a comma-separated string\n var labelsString = string.Join(\",\", sliderLabels.Cast().Select(l => l.ToString()));\n configItem.CustomProperties[\"SliderLabels\"] = labelsString;\n _logService.Log(LogLevel.Info, $\"Stored SliderLabels for {configItem.ControlType} {configItem.Name}: {labelsString}\");\n \n // For Power Plan, also store the labels as PowerPlanOptions\n if (configItem.Name.Contains(\"Power Plan\") ||\n (configItem.CustomProperties.ContainsKey(\"Id\") &&\n configItem.CustomProperties[\"Id\"]?.ToString() == \"PowerPlanComboBox\"))\n {\n // Store the actual list of options\n configItem.CustomProperties[\"PowerPlanOptions\"] = sliderLabels.Cast().Select(l => l.ToString()).ToList();\n _logService.Log(LogLevel.Info, $\"Stored PowerPlanOptions for {configItem.Name}: {labelsString}\");\n }\n }\n }\n }\n }\n \n // Add custom properties from RegistrySetting if available\n if (registrySettingProperty != null)\n {\n var registrySetting = registrySettingProperty.GetValue(item);\n if (registrySetting != null)\n {\n // Get the CustomProperties property from RegistrySetting\n var customPropertiesProperty = registrySetting.GetType().GetProperty(\"CustomProperties\");\n if (customPropertiesProperty != null)\n {\n var customProperties = customPropertiesProperty.GetValue(registrySetting) as Dictionary;\n if (customProperties != null && customProperties.Count > 0)\n {\n // Copy custom properties to the configuration item\n foreach (var kvp in customProperties)\n {\n configItem.CustomProperties[kvp.Key] = kvp.Value;\n }\n }\n }\n }\n }\n \n // Ensure SelectedValue is set for ComboBox controls\n configItem.EnsureSelectedValueIsSet();\n \n // Add the configuration item to the file\n configFile.Items.Add(configItem);\n }\n }\n\n // Serialize the configuration file to JSON\n var json = JsonConvert.SerializeObject(configFile, Formatting.Indented);\n\n // Write the JSON to the file\n await File.WriteAllTextAsync(saveFileDialog.FileName, json);\n \n _logService.Log(LogLevel.Info, $\"Successfully saved {configType} configuration with {configFile.Items.Count} items to {saveFileDialog.FileName}\");\n \n // Log details about ComboBox items if any\n var comboBoxItems = configFile.Items.Where(i => i.ControlType == ControlType.ComboBox).ToList();\n if (comboBoxItems.Any())\n {\n _logService.Log(LogLevel.Info, $\"Saved {comboBoxItems.Count} ComboBox items:\");\n foreach (var item in comboBoxItems)\n {\n _logService.Log(LogLevel.Info, $\" - {item.Name}: SelectedValue={item.SelectedValue}, CustomProperties={string.Join(\", \", item.CustomProperties.Select(kv => $\"{kv.Key}={kv.Value}\"))}\");\n }\n }\n\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving configuration: {ex.Message}\");\n MessageBox.Show($\"Error saving configuration: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n return false;\n }\n }\n\n /// \n /// Loads a configuration file and returns the configuration file.\n /// \n /// The type of configuration being loaded.\n /// A task representing the asynchronous operation. Returns the configuration file if successful, null otherwise.\n public async Task LoadConfigurationAsync(string configType)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Starting to load {configType} configuration\");\n // Create an open file dialog\n var openFileDialog = new OpenFileDialog\n {\n Filter = FileFilter,\n DefaultExt = FileExtension,\n Title = \"Open Configuration\"\n };\n\n // Show the open file dialog\n if (openFileDialog.ShowDialog() != true)\n {\n _logService.Log(LogLevel.Info, \"Load configuration canceled by user\");\n return null;\n }\n \n _logService.Log(LogLevel.Info, $\"Loading configuration from {openFileDialog.FileName}\");\n\n // Read the JSON from the file\n var json = await File.ReadAllTextAsync(openFileDialog.FileName);\n\n // Deserialize the JSON to a configuration file\n var configFile = JsonConvert.DeserializeObject(json);\n \n // Ensure SelectedValue is set for all items\n foreach (var item in configFile.Items)\n {\n item.EnsureSelectedValueIsSet();\n }\n \n // Process the configuration items to ensure SelectedValue is set for ComboBox and ThreeStateSlider items\n foreach (var item in configFile.Items)\n {\n // Handle ComboBox items\n if (item.ControlType == ControlType.ComboBox && string.IsNullOrEmpty(item.SelectedValue))\n {\n // Try to get the SelectedTheme from CustomProperties\n if (item.CustomProperties.TryGetValue(\"SelectedTheme\", out var selectedTheme) && selectedTheme != null)\n {\n item.SelectedValue = selectedTheme.ToString();\n _logService.Log(LogLevel.Info, $\"Set SelectedValue for ComboBox {item.Name} from CustomProperties: {item.SelectedValue}\");\n }\n // If not available, try to derive it from SliderValue\n else if (item.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int sliderValueInt = Convert.ToInt32(sliderValue);\n item.SelectedValue = sliderValueInt == 1 ? \"Dark Mode\" : \"Light Mode\";\n _logService.Log(LogLevel.Info, $\"Derived SelectedValue for ComboBox {item.Name} from SliderValue: {sliderValueInt} -> {item.SelectedValue}\");\n }\n }\n \n // Handle ThreeStateSlider items\n if (item.ControlType == ControlType.ThreeStateSlider)\n {\n // Ensure SliderValue is available in CustomProperties\n if (item.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int sliderValueInt = Convert.ToInt32(sliderValue);\n \n // Try to derive SelectedValue from SliderLabels if available\n if (item.CustomProperties.TryGetValue(\"SliderLabels\", out var sliderLabelsString) &&\n sliderLabelsString != null)\n {\n var labels = sliderLabelsString.ToString().Split(',');\n if (sliderValueInt >= 0 && sliderValueInt < labels.Length)\n {\n item.SelectedValue = labels[sliderValueInt];\n _logService.Log(LogLevel.Info, $\"Derived SelectedValue for ThreeStateSlider {item.Name} from SliderLabels: {sliderValueInt} -> {item.SelectedValue}\");\n }\n }\n // If no labels available, use a generic approach\n else if (string.IsNullOrEmpty(item.SelectedValue))\n {\n // For UAC slider\n if (item.Name.Contains(\"User Account Control\") || item.Name.Contains(\"UAC\"))\n {\n item.SelectedValue = sliderValueInt switch\n {\n 0 => \"Low\",\n 1 => \"Moderate\",\n 2 => \"High\",\n _ => $\"Level {sliderValueInt}\"\n };\n }\n // For Power Plan slider\n else if (item.Name.Contains(\"Power Plan\"))\n {\n // First try to get the value from PowerPlanOptions if available\n if (item.CustomProperties.TryGetValue(\"PowerPlanOptions\", out var powerPlanOptions))\n {\n // Handle different types of PowerPlanOptions\n if (powerPlanOptions is List options && sliderValueInt >= 0 && sliderValueInt < options.Count)\n {\n item.SelectedValue = options[sliderValueInt];\n _logService.Log(LogLevel.Info, $\"Set SelectedValue for Power Plan from PowerPlanOptions (List): {item.SelectedValue}\");\n }\n else if (powerPlanOptions is Newtonsoft.Json.Linq.JArray jArray && sliderValueInt >= 0 && sliderValueInt < jArray.Count)\n {\n item.SelectedValue = jArray[sliderValueInt]?.ToString();\n _logService.Log(LogLevel.Info, $\"Set SelectedValue for Power Plan from PowerPlanOptions (JArray): {item.SelectedValue}\");\n }\n else\n {\n // If PowerPlanOptions exists but we can't use it, log the issue\n _logService.Log(LogLevel.Warning, $\"PowerPlanOptions exists but couldn't be used. Type: {powerPlanOptions?.GetType().Name}, SliderValue: {sliderValueInt}\");\n \n // Fall back to default values\n item.SelectedValue = sliderValueInt switch\n {\n 0 => \"Balanced\",\n 1 => \"High Performance\",\n 2 => \"Ultimate Performance\",\n _ => $\"Plan {sliderValueInt}\"\n };\n _logService.Log(LogLevel.Info, $\"Set SelectedValue for Power Plan from default mapping: {item.SelectedValue}\");\n \n // Add PowerPlanOptions if it doesn't exist in the right format\n string[] defaultOptions = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n item.CustomProperties[\"PowerPlanOptions\"] = new List(defaultOptions);\n _logService.Log(LogLevel.Info, $\"Added default PowerPlanOptions to CustomProperties\");\n }\n }\n else\n {\n // Fall back to default values\n item.SelectedValue = sliderValueInt switch\n {\n 0 => \"Balanced\",\n 1 => \"High Performance\",\n 2 => \"Ultimate Performance\",\n _ => $\"Plan {sliderValueInt}\"\n };\n _logService.Log(LogLevel.Info, $\"Set SelectedValue for Power Plan from default mapping: {item.SelectedValue}\");\n \n // Add PowerPlanOptions if it doesn't exist\n string[] defaultOptions = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n item.CustomProperties[\"PowerPlanOptions\"] = new List(defaultOptions);\n _logService.Log(LogLevel.Info, $\"Added default PowerPlanOptions to CustomProperties\");\n }\n }\n // Generic approach for other sliders\n else\n {\n item.SelectedValue = $\"Level {sliderValueInt}\";\n }\n \n _logService.Log(LogLevel.Info, $\"Set generic SelectedValue for ThreeStateSlider {item.Name}: {item.SelectedValue}\");\n }\n }\n }\n }\n\n // Verify the configuration type\n if (string.IsNullOrEmpty(configFile.ConfigType))\n {\n _logService.Log(LogLevel.Warning, $\"Configuration type is empty, setting it to {configType}\");\n configFile.ConfigType = configType;\n }\n else if (configFile.ConfigType != configType)\n {\n _logService.Log(LogLevel.Warning, $\"Configuration type mismatch. Expected {configType}, but found {configFile.ConfigType}. Proceeding anyway.\");\n // We'll proceed anyway, as this might be a unified configuration file\n }\n\n _logService.Log(LogLevel.Info, $\"Successfully loaded {configType} configuration with {configFile.Items.Count} items from {openFileDialog.FileName}\");\n \n // Log details about ComboBox items if any\n var comboBoxItems = configFile.Items.Where(i => i.ControlType == ControlType.ComboBox).ToList();\n if (comboBoxItems.Any())\n {\n _logService.Log(LogLevel.Info, $\"Loaded {comboBoxItems.Count} ComboBox items:\");\n foreach (var item in comboBoxItems)\n {\n _logService.Log(LogLevel.Info, $\" - {item.Name}: SelectedValue={item.SelectedValue}, CustomProperties={string.Join(\", \", item.CustomProperties.Select(kv => $\"{kv.Key}={kv.Value}\"))}\");\n }\n }\n\n // Return the configuration file directly\n // The ViewModel will handle matching these with existing items\n return configFile;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading configuration: {ex.Message}\");\n MessageBox.Show($\"Error loading configuration: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n return null;\n }\n }\n\n /// \n /// Saves a unified configuration file containing settings for multiple parts of the application.\n /// \n /// The unified configuration to save.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n public async Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile unifiedConfig)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Starting to save unified configuration\");\n \n // Create a save file dialog\n var saveFileDialog = new SaveFileDialog\n {\n Filter = UnifiedFileFilter,\n DefaultExt = FileExtension,\n Title = \"Save Unified Configuration\",\n FileName = $\"Winhance_Unified_Config_{DateTime.Now:yyyyMMdd}{FileExtension}\"\n };\n \n // Show the save file dialog\n if (saveFileDialog.ShowDialog() != true)\n {\n _logService.Log(LogLevel.Info, \"Save unified configuration canceled by user\");\n return false;\n }\n \n _logService.Log(LogLevel.Info, $\"Saving unified configuration to {saveFileDialog.FileName}\");\n \n // Ensure all sections are included by default\n unifiedConfig.WindowsApps.IsIncluded = true;\n unifiedConfig.ExternalApps.IsIncluded = true;\n unifiedConfig.Customize.IsIncluded = true;\n unifiedConfig.Optimize.IsIncluded = true;\n \n if (unifiedConfig.WindowsApps.Items == null)\n {\n unifiedConfig.WindowsApps.Items = new List();\n }\n \n // Serialize the configuration file to JSON\n var json = JsonConvert.SerializeObject(unifiedConfig, Formatting.Indented);\n \n // Write the JSON to the file\n await File.WriteAllTextAsync(saveFileDialog.FileName, json);\n \n _logService.Log(LogLevel.Info, \"Successfully saved unified configuration\");\n \n // Log details about included sections\n var includedSections = new List { \"WindowsApps\", \"ExternalApps\", \"Customize\", \"Optimize\" };\n _logService.Log(LogLevel.Info, $\"Included sections: {string.Join(\", \", includedSections)}\");\n \n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving unified configuration: {ex.Message}\");\n MessageBox.Show($\"Error saving unified configuration: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n return false;\n }\n }\n\n /// \n /// Loads a unified configuration file.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file if successful, null otherwise.\n public async Task LoadUnifiedConfigurationAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Starting to load unified configuration\");\n \n // Create an open file dialog\n var openFileDialog = new OpenFileDialog\n {\n Filter = UnifiedFileFilter,\n DefaultExt = FileExtension,\n Title = \"Open Unified Configuration\"\n };\n \n // Show the open file dialog\n if (openFileDialog.ShowDialog() != true)\n {\n _logService.Log(LogLevel.Info, \"Load unified configuration canceled by user\");\n return null;\n }\n \n _logService.Log(LogLevel.Info, $\"Loading unified configuration from {openFileDialog.FileName}\");\n \n // Read the JSON from the file\n var json = await File.ReadAllTextAsync(openFileDialog.FileName);\n \n // Deserialize the JSON to a unified configuration file\n var unifiedConfig = JsonConvert.DeserializeObject(json);\n \n // Always ensure WindowsApps are included\n unifiedConfig.WindowsApps.IsIncluded = true;\n if (unifiedConfig.WindowsApps.Items == null)\n {\n unifiedConfig.WindowsApps.Items = new List();\n }\n \n // Log details about included sections\n var includedSections = new List();\n if (unifiedConfig.WindowsApps.IsIncluded) includedSections.Add(\"WindowsApps\");\n if (unifiedConfig.ExternalApps.IsIncluded) includedSections.Add(\"ExternalApps\");\n if (unifiedConfig.Customize.IsIncluded) includedSections.Add(\"Customize\");\n if (unifiedConfig.Optimize.IsIncluded) includedSections.Add(\"Optimize\");\n \n _logService.Log(LogLevel.Info, $\"Loaded unified configuration with sections: {string.Join(\", \", includedSections)}\");\n \n return unifiedConfig;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading unified configuration: {ex.Message}\");\n MessageBox.Show($\"Error loading unified configuration: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n return null;\n }\n }\n\n /// \n /// Creates a unified configuration file from individual configuration sections.\n /// \n /// Dictionary of section names and their corresponding configuration items.\n /// List of section names to include in the unified configuration.\n /// A unified configuration file.\n public UnifiedConfigurationFile CreateUnifiedConfiguration(Dictionary> sections, IEnumerable includedSections)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Creating unified configuration\");\n \n var unifiedConfig = new UnifiedConfigurationFile\n {\n CreatedAt = DateTime.UtcNow\n };\n \n // Convert each section to ConfigurationItems and add to the appropriate section\n foreach (var sectionName in includedSections)\n {\n if (!sections.TryGetValue(sectionName, out var items) || items == null)\n {\n _logService.Log(LogLevel.Warning, $\"Section {sectionName} not found or has no items\");\n continue;\n }\n \n var configItems = ConvertToConfigurationItems(items);\n \n switch (sectionName)\n {\n case \"WindowsApps\":\n unifiedConfig.WindowsApps.IsIncluded = true;\n unifiedConfig.WindowsApps.Items = configItems;\n unifiedConfig.WindowsApps.Description = \"Windows built-in applications\";\n break;\n case \"ExternalApps\":\n unifiedConfig.ExternalApps.IsIncluded = true;\n unifiedConfig.ExternalApps.Items = configItems;\n unifiedConfig.ExternalApps.Description = \"Third-party applications\";\n break;\n case \"Customize\":\n unifiedConfig.Customize.IsIncluded = true;\n unifiedConfig.Customize.Items = configItems;\n unifiedConfig.Customize.Description = \"Windows UI customization settings\";\n break;\n case \"Optimize\":\n unifiedConfig.Optimize.IsIncluded = true;\n unifiedConfig.Optimize.Items = configItems;\n unifiedConfig.Optimize.Description = \"Windows optimization settings\";\n break;\n default:\n _logService.Log(LogLevel.Warning, $\"Unknown section name: {sectionName}\");\n break;\n }\n }\n \n // Always ensure WindowsApps are included, even if they weren't in the sections dictionary\n // or if they didn't have any items\n unifiedConfig.WindowsApps.IsIncluded = true;\n if (unifiedConfig.WindowsApps.Items == null)\n {\n unifiedConfig.WindowsApps.Items = new List();\n }\n if (string.IsNullOrEmpty(unifiedConfig.WindowsApps.Description))\n {\n unifiedConfig.WindowsApps.Description = \"Windows built-in applications\";\n }\n \n _logService.Log(LogLevel.Info, \"Successfully created unified configuration\");\n return unifiedConfig;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating unified configuration: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Extracts a specific section from a unified configuration file.\n /// \n /// The unified configuration file.\n /// The name of the section to extract.\n /// A configuration file containing only the specified section.\n public ConfigurationFile ExtractSectionFromUnifiedConfiguration(UnifiedConfigurationFile unifiedConfig, string sectionName)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Extracting section {sectionName} from unified configuration\");\n \n // Validate inputs\n if (unifiedConfig == null)\n {\n _logService.Log(LogLevel.Error, \"Unified configuration is null\");\n throw new ArgumentNullException(nameof(unifiedConfig));\n }\n \n if (string.IsNullOrEmpty(sectionName))\n {\n _logService.Log(LogLevel.Error, \"Section name is null or empty\");\n throw new ArgumentException(\"Section name cannot be null or empty\", nameof(sectionName));\n }\n \n var configFile = new ConfigurationFile\n {\n ConfigType = sectionName,\n CreatedAt = DateTime.UtcNow,\n Items = new List()\n };\n \n // Get the items from the appropriate section\n switch (sectionName)\n {\n case \"WindowsApps\":\n // Always include WindowsApps, regardless of IsIncluded flag\n configFile.Items = unifiedConfig.WindowsApps?.Items ?? new List();\n break;\n case \"ExternalApps\":\n if (unifiedConfig.ExternalApps?.IsIncluded == true)\n {\n configFile.Items = unifiedConfig.ExternalApps.Items ?? new List();\n }\n break;\n case \"Customize\":\n if (unifiedConfig.Customize?.IsIncluded == true)\n {\n configFile.Items = unifiedConfig.Customize.Items ?? new List();\n }\n break;\n case \"Optimize\":\n if (unifiedConfig.Optimize?.IsIncluded == true)\n {\n configFile.Items = unifiedConfig.Optimize.Items ?? new List();\n }\n break;\n default:\n _logService.Log(LogLevel.Warning, $\"Unknown section name: {sectionName}\");\n break;\n }\n \n // Ensure Items is not null\n if (configFile.Items == null)\n {\n configFile.Items = new List();\n }\n \n _logService.Log(LogLevel.Info, $\"Successfully extracted section {sectionName} with {configFile.Items.Count} items\");\n return configFile;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error extracting section from unified configuration: {ex.Message}\");\n \n // Return an empty configuration file instead of throwing\n var emptyConfigFile = new ConfigurationFile\n {\n ConfigType = sectionName,\n CreatedAt = DateTime.UtcNow,\n Items = new List()\n };\n \n _logService.Log(LogLevel.Info, $\"Returning empty configuration file for section {sectionName}\");\n return emptyConfigFile;\n }\n }\n\n /// \n /// Converts a collection of ISettingItem objects to a list of ConfigurationItem objects.\n /// \n /// The collection of ISettingItem objects to convert.\n /// A list of ConfigurationItem objects.\n private List ConvertToConfigurationItems(IEnumerable items)\n {\n var configItems = new List();\n \n foreach (var item in items)\n {\n var configItem = new ConfigurationItem\n {\n Name = item.Name,\n IsSelected = item.IsSelected,\n ControlType = item.ControlType,\n CustomProperties = new Dictionary()\n };\n \n // Add Id to custom properties\n if (!string.IsNullOrEmpty(item.Id))\n {\n configItem.CustomProperties[\"Id\"] = item.Id;\n }\n \n // Add GroupName to custom properties\n if (!string.IsNullOrEmpty(item.GroupName))\n {\n configItem.CustomProperties[\"GroupName\"] = item.GroupName;\n }\n \n // Add Description to custom properties\n if (!string.IsNullOrEmpty(item.Description))\n {\n configItem.CustomProperties[\"Description\"] = item.Description;\n }\n \n // Handle specific properties based on the item's type\n var itemType = item.GetType();\n var properties = itemType.GetProperties();\n \n // Check for PackageName property\n var packageNameProperty = properties.FirstOrDefault(p => p.Name == \"PackageName\");\n if (packageNameProperty != null)\n {\n configItem.PackageName = packageNameProperty.GetValue(item)?.ToString();\n }\n \n // Check for SelectedValue property\n var selectedValueProperty = properties.FirstOrDefault(p => p.Name == \"SelectedValue\");\n if (selectedValueProperty != null)\n {\n configItem.SelectedValue = selectedValueProperty.GetValue(item)?.ToString();\n }\n \n // Check for SliderValue property\n var sliderValueProperty = properties.FirstOrDefault(p => p.Name == \"SliderValue\");\n if (sliderValueProperty != null)\n {\n var sliderValue = sliderValueProperty.GetValue(item);\n if (sliderValue != null)\n {\n configItem.CustomProperties[\"SliderValue\"] = sliderValue;\n }\n }\n \n // Check for SliderLabels property\n var sliderLabelsProperty = properties.FirstOrDefault(p => p.Name == \"SliderLabels\");\n if (sliderLabelsProperty != null)\n {\n var sliderLabels = sliderLabelsProperty.GetValue(item) as System.Collections.IList;\n if (sliderLabels != null && sliderLabels.Count > 0)\n {\n // Store the labels as a comma-separated string\n var labelsString = string.Join(\",\", sliderLabels.Cast().Select(l => l.ToString()));\n configItem.CustomProperties[\"SliderLabels\"] = labelsString;\n \n // For Power Plan, also store the labels as PowerPlanOptions\n if (item.Name.Contains(\"Power Plan\") || item.Id == \"PowerPlanComboBox\")\n {\n // Store the actual list of options\n configItem.CustomProperties[\"PowerPlanOptions\"] = sliderLabels.Cast().Select(l => l.ToString()).ToList();\n }\n }\n }\n \n // Check for RegistrySetting property\n var registrySettingProperty = properties.FirstOrDefault(p => p.Name == \"RegistrySetting\");\n if (registrySettingProperty != null)\n {\n var registrySetting = registrySettingProperty.GetValue(item);\n if (registrySetting != null)\n {\n // Get the CustomProperties property from RegistrySetting\n var customPropertiesProperty = registrySetting.GetType().GetProperty(\"CustomProperties\");\n if (customPropertiesProperty != null)\n {\n var customProperties = customPropertiesProperty.GetValue(registrySetting) as Dictionary;\n if (customProperties != null && customProperties.Count > 0)\n {\n // Copy custom properties to the configuration item\n foreach (var kvp in customProperties)\n {\n configItem.CustomProperties[kvp.Key] = kvp.Value;\n }\n }\n }\n }\n }\n \n // Ensure SelectedValue is set for ComboBox controls\n configItem.EnsureSelectedValueIsSet();\n \n configItems.Add(configItem);\n }\n \n return configItems;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScheduledTaskService.cs", "using System;\nusing System.IO;\nusing System.Management.Automation;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Service for registering and managing scheduled tasks for script execution.\n /// \n public class ScheduledTaskService : IScheduledTaskService\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public ScheduledTaskService(ILogService logService)\n {\n _logService = logService;\n }\n\n /// \n public async Task RegisterScheduledTaskAsync(RemovalScript script)\n {\n try\n {\n _logService.LogInformation($\"Registering scheduled task for script: {script?.Name ?? \"Unknown\"}\");\n \n // Ensure the script and script path are valid\n if (script == null)\n {\n _logService.LogError(\"Script object is null\");\n return false;\n }\n\n // Ensure the script name is not empty\n if (string.IsNullOrEmpty(script.Name))\n {\n _logService.LogError(\"Script name is empty\");\n return false;\n }\n\n // Ensure the script path exists\n string scriptPath = script.ScriptPath;\n if (!File.Exists(scriptPath))\n {\n _logService.LogError($\"Script file not found at: {scriptPath}\");\n \n // Try to save the script if it doesn't exist but has content\n if (!string.IsNullOrEmpty(script.Content))\n {\n try\n {\n string directoryPath = Path.GetDirectoryName(scriptPath);\n if (!Directory.Exists(directoryPath))\n {\n Directory.CreateDirectory(directoryPath);\n }\n \n File.WriteAllText(scriptPath, script.Content);\n _logService.LogInformation($\"Created script file at: {scriptPath}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to create script file: {ex.Message}\");\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n // Create the scheduled task using a direct PowerShell command\n string taskName = !string.IsNullOrEmpty(script.TargetScheduledTaskName) \n ? script.TargetScheduledTaskName \n : $\"Winhance\\\\{script.Name}\";\n\n // Create a simple PowerShell script that registers the task\n string psScript = $@\"\n# Register the scheduled task\n$scriptPath = '{scriptPath.Replace(\"'\", \"''\")}' # Escape single quotes\n$taskName = '{taskName.Replace(\"'\", \"''\")}'\n\n# Check if the task already exists and remove it\ntry {{\n $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue\n if ($existingTask) {{\n Write-Output \"\"Removing existing task: $taskName\"\"\n Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction Stop\n }}\n}} catch {{\n Write-Output \"\"Error removing existing task: $($_.Exception.Message)\"\"\n}}\n\n# Create the action to run the PowerShell script\ntry {{\n $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument \"\"-ExecutionPolicy Bypass -File `\"\"$scriptPath`\"\"\"\"\n $trigger = New-ScheduledTaskTrigger -AtStartup\n $settings = New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries\n \n # Register the task\n Register-ScheduledTask -TaskName $taskName `\n -Action $action `\n -Trigger $trigger `\n -User \"\"SYSTEM\"\" `\n -RunLevel Highest `\n -Settings $settings `\n -Force -ErrorAction Stop\n \n Write-Output \"\"Successfully registered scheduled task: $taskName\"\"\n exit 0\n}} catch {{\n Write-Output \"\"Error registering scheduled task: $($_.Exception.Message)\"\"\n exit 1\n}}\n\";\n\n // Save the script to a temporary file\n string tempScriptPath = Path.Combine(Path.GetTempPath(), $\"RegisterTask_{Guid.NewGuid()}.ps1\");\n File.WriteAllText(tempScriptPath, psScript);\n\n try\n {\n // Execute the script with elevated privileges\n using var process = new System.Diagnostics.Process();\n process.StartInfo.FileName = \"powershell.exe\";\n process.StartInfo.Arguments = $\"-ExecutionPolicy Bypass -File \\\"{tempScriptPath}\\\"\";\n process.StartInfo.UseShellExecute = true;\n process.StartInfo.Verb = \"runas\"; // Run as administrator\n process.StartInfo.CreateNoWindow = false;\n process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\n \n process.Start();\n await process.WaitForExitAsync();\n \n // Check if the process exited successfully\n if (process.ExitCode == 0)\n {\n _logService.LogSuccess($\"Successfully registered scheduled task: {taskName}\");\n return true;\n }\n else\n {\n _logService.LogError($\"Failed to register scheduled task: {taskName}, exit code: {process.ExitCode}\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error executing scheduled task registration script: {ex.Message}\");\n return false;\n }\n finally\n {\n // Clean up the temporary script\n try\n {\n if (File.Exists(tempScriptPath))\n {\n File.Delete(tempScriptPath);\n }\n }\n catch\n {\n // Ignore errors when deleting the temp file\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error registering scheduled task for script: {script?.Name ?? \"Unknown\"}\", ex);\n return false;\n }\n }\n\n /// \n public async Task UnregisterScheduledTaskAsync(string taskName)\n {\n try\n {\n _logService.LogInformation($\"Unregistering scheduled task: {taskName}\");\n \n // Create a simple PowerShell script that unregisters the task\n string psScript = $@\"\n# Unregister the scheduled task\n$taskName = '{taskName.Replace(\"'\", \"''\")}'\n\ntry {{\n $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue\n if ($existingTask) {{\n Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction Stop\n Write-Output \"\"Successfully unregistered task: $taskName\"\"\n exit 0\n }} else {{\n Write-Output \"\"Task not found: $taskName\"\"\n exit 0 # Not an error if the task doesn't exist\n }}\n}} catch {{\n Write-Output \"\"Error unregistering task: $($_.Exception.Message)\"\"\n exit 1\n}}\n\";\n\n // Save the script to a temporary file\n string tempScriptPath = Path.Combine(Path.GetTempPath(), $\"UnregisterTask_{Guid.NewGuid()}.ps1\");\n File.WriteAllText(tempScriptPath, psScript);\n\n try\n {\n // Execute the script with elevated privileges\n using var process = new System.Diagnostics.Process();\n process.StartInfo.FileName = \"powershell.exe\";\n process.StartInfo.Arguments = $\"-ExecutionPolicy Bypass -File \\\"{tempScriptPath}\\\"\";\n process.StartInfo.UseShellExecute = true;\n process.StartInfo.Verb = \"runas\"; // Run as administrator\n process.StartInfo.CreateNoWindow = false;\n process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\n \n process.Start();\n await process.WaitForExitAsync();\n \n // Check if the process exited successfully\n if (process.ExitCode == 0)\n {\n _logService.LogSuccess($\"Successfully unregistered scheduled task: {taskName}\");\n return true;\n }\n else\n {\n _logService.LogError($\"Failed to unregister scheduled task: {taskName}, exit code: {process.ExitCode}\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error executing scheduled task unregistration script: {ex.Message}\");\n return false;\n }\n finally\n {\n // Clean up the temporary script\n try\n {\n if (File.Exists(tempScriptPath))\n {\n File.Delete(tempScriptPath);\n }\n }\n catch\n {\n // Ignore errors when deleting the temp file\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error unregistering scheduled task: {taskName}\", ex);\n return false;\n }\n }\n\n /// \n public async Task IsTaskRegisteredAsync(string taskName)\n {\n try\n {\n // Create a simple PowerShell script that checks if the task exists\n string psScript = $@\"\n# Check if the scheduled task exists\n$taskName = '{taskName.Replace(\"'\", \"''\")}'\n\ntry {{\n $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue\n if ($existingTask) {{\n Write-Output \"\"Task exists: $taskName\"\"\n exit 0 # Exit code 0 means the task exists\n }} else {{\n Write-Output \"\"Task does not exist: $taskName\"\"\n exit 1 # Exit code 1 means the task does not exist\n }}\n}} catch {{\n Write-Output \"\"Error checking task: $($_.Exception.Message)\"\"\n exit 2 # Exit code 2 means an error occurred\n}}\n\";\n\n // Save the script to a temporary file\n string tempScriptPath = Path.Combine(Path.GetTempPath(), $\"CheckTask_{Guid.NewGuid()}.ps1\");\n File.WriteAllText(tempScriptPath, psScript);\n\n try\n {\n // Execute the script\n using var process = new System.Diagnostics.Process();\n process.StartInfo.FileName = \"powershell.exe\";\n process.StartInfo.Arguments = $\"-ExecutionPolicy Bypass -File \\\"{tempScriptPath}\\\"\";\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.CreateNoWindow = true;\n \n process.Start();\n await process.WaitForExitAsync();\n \n // Check the exit code to determine if the task exists\n return process.ExitCode == 0;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error executing scheduled task check script: {ex.Message}\");\n return false;\n }\n finally\n {\n // Clean up the temporary script\n try\n {\n if (File.Exists(tempScriptPath))\n {\n File.Delete(tempScriptPath);\n }\n }\n catch\n {\n // Ignore errors when deleting the temp file\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking if task exists: {taskName}\", ex);\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/BaseSettingsViewModel.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Extensions;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// Base class for settings view models.\n /// \n /// The type of settings.\n public partial class BaseSettingsViewModel : ObservableObject\n where T : ApplicationSettingItem\n {\n protected readonly ITaskProgressService _progressService;\n protected readonly IRegistryService _registryService;\n protected readonly ILogService _logService;\n\n /// \n /// Gets the collection of settings.\n /// \n public ObservableCollection Settings { get; } = new();\n\n /// \n /// Gets or sets a value indicating whether the settings are being loaded.\n /// \n [ObservableProperty]\n private bool _isLoading;\n\n /// \n /// Gets or sets a value indicating whether all settings are selected.\n /// \n [ObservableProperty]\n private bool _isSelected;\n\n /// \n /// Gets or sets a value indicating whether the view model has visible settings.\n /// \n [ObservableProperty]\n private bool _hasVisibleSettings = true;\n\n /// \n /// Gets or sets the category name for this settings view model.\n /// \n [ObservableProperty]\n private string _categoryName = string.Empty;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n protected BaseSettingsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService\n )\n {\n _progressService =\n progressService ?? throw new ArgumentNullException(nameof(progressService));\n _registryService =\n registryService ?? throw new ArgumentNullException(nameof(registryService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Loads the settings.\n /// \n /// A task representing the asynchronous operation.\n public virtual async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load settings (to be implemented by derived classes)\n await Task.CompletedTask;\n\n // Refresh status for all settings after loading\n await RefreshAllSettingsStatusAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Refreshes the status of all settings.\n /// \n /// A task representing the asynchronous operation.\n protected async Task RefreshAllSettingsStatusAsync()\n {\n foreach (var setting in Settings)\n {\n await setting.RefreshStatus();\n }\n }\n\n /// \n /// Checks the status of all settings.\n /// \n /// A task representing the asynchronous operation.\n public virtual async Task CheckSettingStatusesAsync()\n {\n _logService.Log(\n LogLevel.Info,\n $\"Checking status of {Settings.Count} settings in {GetType().Name}\"\n );\n\n foreach (var setting in Settings)\n {\n if (setting.IsGroupHeader)\n {\n continue;\n }\n\n // Direct method call without reflection\n await setting.RefreshStatus();\n }\n\n // Update the overall IsSelected state\n UpdateIsSelectedState();\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n protected void UpdateIsSelectedState()\n {\n var nonHeaderSettings = Settings.Where(s => !s.IsGroupHeader).ToList();\n if (nonHeaderSettings.Count == 0)\n {\n IsSelected = false;\n return;\n }\n\n IsSelected = nonHeaderSettings.All(s => s.IsSelected);\n }\n\n /// \n /// Executes the specified action asynchronously.\n /// \n /// The name of the action to execute.\n /// A task representing the asynchronous operation.\n public virtual async Task ExecuteActionAsync(string actionName)\n {\n _logService.Log(LogLevel.Info, $\"Executing action: {actionName}\");\n\n // Find the setting with the specified action\n foreach (var setting in Settings)\n {\n var action = setting.Actions.FirstOrDefault(a => a.Name == actionName);\n if (action != null)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Found action {actionName} in setting {setting.Name}\"\n );\n\n await ExecuteActionAsync(action);\n return;\n }\n }\n\n _logService.Log(LogLevel.Warning, $\"Action {actionName} not found\");\n }\n\n /// \n /// Executes the specified action asynchronously.\n /// \n /// The action to execute.\n /// A task representing the asynchronous operation.\n public virtual async Task ExecuteActionAsync(ApplicationAction action)\n {\n if (action == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot execute null action\");\n return;\n }\n\n _logService.Log(LogLevel.Info, $\"Executing action: {action.Name}\");\n\n // Execute the registry action if present\n if (action.RegistrySetting != null)\n {\n string hiveString = action.RegistrySetting.Hive.ToString();\n if (hiveString == \"LocalMachine\")\n hiveString = \"HKLM\";\n else if (hiveString == \"CurrentUser\")\n hiveString = \"HKCU\";\n else if (hiveString == \"ClassesRoot\")\n hiveString = \"HKCR\";\n else if (hiveString == \"Users\")\n hiveString = \"HKU\";\n else if (hiveString == \"CurrentConfig\")\n hiveString = \"HKCC\";\n\n string fullPath = $\"{hiveString}\\\\{action.RegistrySetting.SubKey}\";\n _registryService.SetValue(\n fullPath,\n action.RegistrySetting.Name,\n action.RegistrySetting.RecommendedValue,\n action.RegistrySetting.ValueType\n );\n }\n\n // Execute custom action if present\n if (action.CustomAction != null)\n {\n await action.CustomAction();\n }\n\n _logService.Log(LogLevel.Info, $\"Action '{action.Name}' executed successfully\");\n }\n\n /// \n /// Applies the setting asynchronously.\n /// \n /// The setting to apply.\n /// A task representing the asynchronous operation.\n protected virtual async Task ApplySettingAsync(T setting)\n {\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot apply null setting\");\n return;\n }\n\n _logService.Log(LogLevel.Info, $\"Applying setting: {setting.Name}\");\n\n // Apply the setting based on its properties\n if (setting.RegistrySetting != null)\n {\n // Apply registry setting\n string hiveString = GetRegistryHiveString(setting.RegistrySetting.Hive);\n _registryService.SetValue(\n $\"{hiveString}\\\\{setting.RegistrySetting.SubKey}\",\n setting.RegistrySetting.Name,\n setting.IsSelected\n ? setting.RegistrySetting.RecommendedValue\n : setting.RegistrySetting.DefaultValue,\n setting.RegistrySetting.ValueType\n );\n }\n else if (\n setting.LinkedRegistrySettings != null\n && setting.LinkedRegistrySettings.Settings.Count > 0\n )\n {\n // Apply linked registry settings\n await _registryService.ApplyLinkedSettingsAsync(\n setting.LinkedRegistrySettings,\n setting.IsSelected\n );\n }\n\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} applied successfully\");\n\n // Add a small delay to ensure registry changes are processed\n await Task.Delay(50);\n }\n\n /// \n /// Gets the registry hive string.\n /// \n /// The registry hive.\n /// The registry hive string.\n private string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => throw new ArgumentOutOfRangeException(nameof(hive), hive, null),\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServicePowerShell.cs", "using Microsoft.Win32;\nusing System;\nusing System.Diagnostics;\nusing System.Text;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n public partial class RegistryService\n {\n /// \n /// Sets a registry value using PowerShell with elevated privileges.\n /// This is a fallback method for when the standard .NET Registry API fails.\n /// \n /// The full path to the registry key.\n /// The name of the registry value.\n /// The value to set.\n /// The type of the registry value.\n /// True if the value was successfully set, false otherwise.\n private bool SetValueUsingPowerShell(string keyPath, string valueName, object value, RegistryValueKind valueKind)\n {\n try\n {\n _logService.LogInformation($\"Attempting to set registry value using PowerShell: {keyPath}\\\\{valueName}\");\n\n // Format the PowerShell command based on the value type\n string psCommand = FormatPowerShellCommand(keyPath, valueName, value, valueKind);\n\n // Create a PowerShell process with elevated privileges\n var startInfo = new ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-NoProfile -ExecutionPolicy Bypass -Command \\\"{psCommand}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n Verb = \"runas\" // Run as administrator\n };\n\n _logService.LogInformation($\"Executing PowerShell command: {psCommand}\");\n\n using var process = new Process { StartInfo = startInfo };\n \n try\n {\n process.Start();\n }\n catch (Exception ex)\n {\n _logService.LogWarning($\"Failed to start PowerShell with admin rights: {ex.Message}. Trying without elevation...\");\n \n // Try again without elevation\n startInfo.Verb = null;\n using var nonElevatedProcess = new Process { StartInfo = startInfo };\n nonElevatedProcess.Start();\n \n string nonElevatedOutput = nonElevatedProcess.StandardOutput.ReadToEnd();\n string nonElevatedError = nonElevatedProcess.StandardError.ReadToEnd();\n \n nonElevatedProcess.WaitForExit();\n \n if (nonElevatedProcess.ExitCode == 0)\n {\n _logService.LogSuccess($\"Successfully set registry value using non-elevated PowerShell: {keyPath}\\\\{valueName}\");\n \n // Clear the cache for this value\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueCache)\n {\n if (_valueCache.ContainsKey(fullValuePath))\n {\n _valueCache.Remove(fullValuePath);\n }\n }\n \n return true;\n }\n \n _logService.LogWarning($\"Non-elevated PowerShell also failed: {nonElevatedError}\");\n return false;\n }\n \n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n \n process.WaitForExit();\n\n if (process.ExitCode == 0)\n {\n _logService.LogSuccess($\"Successfully set registry value using PowerShell: {keyPath}\\\\{valueName}\");\n \n // Clear the cache for this value\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueCache)\n {\n if (_valueCache.ContainsKey(fullValuePath))\n {\n _valueCache.Remove(fullValuePath);\n }\n }\n \n return true;\n }\n else\n {\n _logService.LogWarning($\"PowerShell failed to set registry value: {error}\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error using PowerShell to set registry value: {ex.Message}\", ex);\n return false;\n }\n }\n\n /// \n /// Formats a PowerShell command to set a registry value.\n /// \n private string FormatPowerShellCommand(string keyPath, string valueName, object value, RegistryValueKind valueKind)\n {\n // Split the key path into hive and subkey\n string[] pathParts = keyPath.Split('\\\\');\n string hive = pathParts[0];\n string subKey = string.Join('\\\\', pathParts.Skip(1));\n\n // Map the registry hive to PowerShell drive\n string psDrive = hive switch\n {\n \"HKCU\" or \"HKEY_CURRENT_USER\" => \"HKCU:\",\n \"HKLM\" or \"HKEY_LOCAL_MACHINE\" => \"HKLM:\",\n \"HKCR\" or \"HKEY_CLASSES_ROOT\" => \"HKCR:\",\n \"HKU\" or \"HKEY_USERS\" => \"HKU:\",\n \"HKCC\" or \"HKEY_CURRENT_CONFIG\" => \"HKCC:\",\n _ => throw new ArgumentException($\"Unsupported registry hive: {hive}\")\n };\n\n // Format the value based on its type\n string valueArg = FormatValueForPowerShell(value, valueKind);\n string typeArg = GetPowerShellTypeArg(valueKind);\n\n // Build the PowerShell command with enhanced error handling and permissions\n var sb = new StringBuilder();\n \n // Add error handling\n sb.Append(\"$ErrorActionPreference = 'Stop'; \");\n sb.Append(\"try { \");\n \n // First, ensure the key exists with proper permissions\n sb.Append($\"if (-not (Test-Path -Path '{psDrive}\\\\{subKey}')) {{ \");\n \n // Create the key with force to ensure all parent keys are created\n sb.Append($\"New-Item -Path '{psDrive}\\\\{subKey}' -Force | Out-Null; \");\n \n // For policy keys, try to set appropriate permissions\n if (subKey.Contains(\"Policies\", StringComparison.OrdinalIgnoreCase))\n {\n sb.Append($\"$acl = Get-Acl -Path '{psDrive}\\\\{subKey}'; \");\n sb.Append(\"$rule = New-Object System.Security.AccessControl.RegistryAccessRule('CURRENT_USER', 'FullControl', 'Allow'); \");\n sb.Append(\"$acl.SetAccessRule($rule); \");\n sb.Append($\"try {{ Set-Acl -Path '{psDrive}\\\\{subKey}' -AclObject $acl }} catch {{ Write-Host 'Could not set ACL, continuing anyway...' }}; \");\n }\n \n sb.Append(\"} \");\n \n // Then set the value\n sb.Append($\"Set-ItemProperty -Path '{psDrive}\\\\{subKey}' -Name '{valueName}' -Value {valueArg} {typeArg} -Force; \");\n \n // Verify the value was set correctly\n sb.Append($\"$setVal = Get-ItemProperty -Path '{psDrive}\\\\{subKey}' -Name '{valueName}' -ErrorAction SilentlyContinue; \");\n sb.Append(\"if ($setVal -eq $null) { throw 'Value was not set properly' }; \");\n \n // Close the try block and add catch\n sb.Append(\"} catch { Write-Error $_.Exception.Message; exit 1 }\");\n\n return sb.ToString();\n }\n\n /// \n /// Formats a value for use with PowerShell.\n /// \n private string FormatValueForPowerShell(object value, RegistryValueKind valueKind)\n {\n return valueKind switch\n {\n RegistryValueKind.DWord or RegistryValueKind.QWord => value.ToString(),\n RegistryValueKind.String or RegistryValueKind.ExpandString => $\"'{value}'\",\n RegistryValueKind.MultiString => $\"@('{string.Join(\"','\", (string[])value)})'\",\n RegistryValueKind.Binary => $\"([byte[]]@({string.Join(\",\", (byte[])value)}))\",\n _ => $\"'{value}'\"\n };\n }\n\n /// \n /// Gets the PowerShell type argument for a registry value kind.\n /// \n private string GetPowerShellTypeArg(RegistryValueKind valueKind)\n {\n return valueKind switch\n {\n RegistryValueKind.String => \"-Type String\",\n RegistryValueKind.ExpandString => \"-Type ExpandString\",\n RegistryValueKind.Binary => \"-Type Binary\",\n RegistryValueKind.DWord => \"-Type DWord\",\n RegistryValueKind.MultiString => \"-Type MultiString\",\n RegistryValueKind.QWord => \"-Type QWord\",\n _ => \"\"\n };\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Utilities/PowerShellFactory.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Management.Automation;\nusing System.Management.Automation.Runspaces;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.Utilities\n{\n /// \n /// Factory for creating PowerShell instances with specific runtime configurations.\n /// \n public static class PowerShellFactory\n {\n private static readonly string WindowsPowerShellPath =\n @\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\";\n private static readonly string PowerShellCorePath =\n @\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\";\n\n // Reference to the system service - will be set by the first call to CreateWindowsPowerShell\n private static ISystemServices _systemServices;\n\n /// \n /// Determines if the current OS is Windows 10 (which has issues with Appx module in PowerShell Core)\n /// \n /// True if running on Windows 10, false otherwise\n private static bool IsWindows10()\n {\n // Use the system services if available\n if (_systemServices != null)\n {\n // Use the centralized Windows version detection\n return !_systemServices.IsWindows11();\n }\n\n // Fallback to direct OS version check if system services are not available\n try\n {\n // Get OS version information\n var osVersion = Environment.OSVersion;\n\n // Windows 10 has major version 10 and build number less than 22000\n // Windows 11 has build number 22000 or higher\n bool isWin10ByVersion =\n osVersion.Platform == PlatformID.Win32NT\n && osVersion.Version.Major == 10\n && osVersion.Version.Build < 22000;\n\n // Additional check using ProductName which is more reliable\n bool isWin10ByProductName = false;\n try\n {\n // Check the product name from registry\n using (\n var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(\n @\"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\"\n )\n )\n {\n if (key != null)\n {\n var productName = key.GetValue(\"ProductName\") as string;\n isWin10ByProductName =\n productName != null && productName.Contains(\"Windows 10\");\n\n // If product name explicitly contains Windows 11, it's definitely not Windows 10\n if (productName != null && productName.Contains(\"Windows 11\"))\n {\n return false;\n }\n }\n }\n }\n catch\n {\n // If registry check fails, rely on version check only\n }\n\n // Return true if either method indicates Windows 10\n return isWin10ByVersion || isWin10ByProductName;\n }\n catch\n {\n // If there's any error, assume it's Windows 10 to ensure compatibility\n // This is safer than assuming it's not Windows 10\n return true;\n }\n }\n\n /// \n /// Creates a PowerShell instance configured to use Windows PowerShell 5.1.\n /// On Windows 10, it ensures compatibility with the Appx module by using Windows PowerShell.\n /// \n /// Optional log service for diagnostic information.\n /// A PowerShell instance configured to use Windows PowerShell 5.1.\n public static PowerShell CreateWindowsPowerShell(\n ILogService logService = null,\n ISystemServices systemServices = null\n )\n {\n try\n {\n // Store the system services reference if provided\n if (systemServices != null)\n {\n _systemServices = systemServices;\n }\n\n PowerShell powerShell;\n\n // Create a default PowerShell instance\n powerShell = PowerShell.Create();\n\n // Check if we're running on Windows 10\n bool isWin10 = IsWindows10();\n\n // Additional check for build number to ensure Windows 11 is properly detected\n var osVersion = Environment.OSVersion;\n if (osVersion.Version.Build >= 22000)\n {\n // If build number indicates Windows 11, override the IsWindows10 result\n isWin10 = false;\n logService?.LogInformation(\n $\"Detected Windows 11 (Build: {osVersion.Version.Build}) - Using standard PowerShell Core for Appx commands\"\n );\n }\n else if (isWin10)\n {\n logService?.LogInformation(\n \"Detected Windows 10 - Using direct Windows PowerShell execution for Appx commands\"\n );\n\n // On Windows 10, immediately set up direct execution for Appx commands\n // This avoids WinRM connection issues and ensures compatibility\n powerShell.AddScript(\n $@\"\n function Invoke-WindowsPowerShell {{\n param(\n [Parameter(Mandatory=$true)]\n [string]$Command\n )\n \n try {{\n $psi = New-Object System.Diagnostics.ProcessStartInfo\n $psi.FileName = '{WindowsPowerShellPath}'\n $psi.Arguments = \"\"-NoProfile -ExecutionPolicy Bypass -Command `\"\"$Command`\"\"\"\"\n $psi.RedirectStandardOutput = $true\n $psi.RedirectStandardError = $true\n $psi.UseShellExecute = $false\n $psi.CreateNoWindow = $true\n \n $process = New-Object System.Diagnostics.Process\n $process.StartInfo = $psi\n $process.Start() | Out-Null\n \n $output = $process.StandardOutput.ReadToEnd()\n $error = $process.StandardError.ReadToEnd()\n $process.WaitForExit()\n \n if ($error) {{\n Write-Warning \"\"Windows PowerShell error: $error\"\"\n }}\n \n return $output\n }} catch {{\n Write-Warning \"\"Error invoking Windows PowerShell: $_\"\"\n return $null\n }}\n }}\n \n # Override Get-AppxPackage to use Windows PowerShell directly\n function Get-AppxPackage {{\n param(\n [Parameter(Position=0)]\n [string]$Name = '*'\n )\n \n Write-Output \"\"Using direct Windows PowerShell execution for Get-AppxPackage\"\"\n $result = Invoke-WindowsPowerShell \"\"Get-AppxPackage -Name '$Name' | ConvertTo-Json -Depth 5 -Compress\"\"\n if ($result) {{\n try {{\n $packages = $result | ConvertFrom-Json -ErrorAction SilentlyContinue\n return $packages\n }} catch {{\n Write-Warning \"\"Error parsing AppX package results: $_\"\"\n return $null\n }}\n }}\n return $null\n }}\n \n # Override Remove-AppxPackage to use Windows PowerShell directly\n function Remove-AppxPackage {{\n param(\n [Parameter(Mandatory=$true)]\n [string]$Package\n )\n \n Write-Output \"\"Using direct Windows PowerShell execution for Remove-AppxPackage\"\"\n $result = Invoke-WindowsPowerShell \"\"Remove-AppxPackage -Package '$Package'\"\"\n return $result\n }}\n \n # Override Add-AppxPackage to use Windows PowerShell directly\n function Add-AppxPackage {{\n param(\n [Parameter(Mandatory=$true)]\n [string]$Path\n )\n \n Write-Output \"\"Using direct Windows PowerShell execution for Add-AppxPackage\"\"\n $result = Invoke-WindowsPowerShell \"\"Add-AppxPackage -Path '$Path'\"\"\n return $result\n }}\n \n # Override Get-AppxProvisionedPackage to use Windows PowerShell directly\n function Get-AppxProvisionedPackage {{\n param(\n [Parameter(Mandatory=$true)]\n [switch]$Online\n )\n \n Write-Output \"\"Using direct Windows PowerShell execution for Get-AppxProvisionedPackage\"\"\n $result = Invoke-WindowsPowerShell \"\"Get-AppxProvisionedPackage -Online | ConvertTo-Json -Depth 5 -Compress\"\"\n if ($result) {{\n try {{\n $packages = $result | ConvertFrom-Json -ErrorAction SilentlyContinue\n return $packages\n }} catch {{\n Write-Warning \"\"Error parsing provisioned package results: $_\"\"\n return $null\n }}\n }}\n return $null\n }}\n \n # Override Remove-AppxProvisionedPackage to use Windows PowerShell directly\n function Remove-AppxProvisionedPackage {{\n param(\n [Parameter(Mandatory=$true)]\n [switch]$Online,\n \n [Parameter(Mandatory=$true)]\n [string]$PackageName\n )\n \n Write-Output \"\"Using direct Windows PowerShell execution for Remove-AppxProvisionedPackage\"\"\n $result = Invoke-WindowsPowerShell \"\"Remove-AppxProvisionedPackage -Online -PackageName '$PackageName'\"\"\n return $result\n }}\n \n Write-Output \"\"Configured Windows PowerShell direct execution for Appx commands\"\"\n \"\n );\n\n var directExecutionResults = powerShell.Invoke();\n foreach (var result in directExecutionResults)\n {\n logService?.LogInformation($\"Direct execution setup: {result}\");\n }\n }\n else\n {\n logService?.LogInformation(\n \"Not running on Windows 10 - Using standard PowerShell Core for Appx commands\"\n );\n }\n\n // Configure PowerShell to use Windows PowerShell modules and set execution policy\n powerShell.Commands.Clear();\n\n // Different script for Windows 10 vs Windows 11\n if (isWin10)\n {\n // For Windows 10, report that we're using Windows PowerShell 5.1 for Appx commands\n powerShell.AddScript(\n @\"\n # Set execution policy\n try {\n Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force -ErrorAction SilentlyContinue\n } catch {\n # Ignore errors\n }\n \n # Ensure Windows PowerShell modules are available\n $WindowsPowerShellModulePath = \"\"$env:SystemRoot\\System32\\WindowsPowerShell\\v1.0\\Modules\"\"\n if ($env:PSModulePath -notlike \"\"*$WindowsPowerShellModulePath*\"\") {\n $env:PSModulePath = $env:PSModulePath + \"\";\"\" + $WindowsPowerShellModulePath\n }\n \n # Log PowerShell version information\n # Since we're using direct Windows PowerShell execution on Windows 10, report that version\n Write-Output \"\"Using PowerShell version: 5.1 (WindowsPowerShell)\"\"\n Write-Output \"\"OS Version: $([System.Environment]::OSVersion.Version)\"\"\n \"\n );\n }\n else\n {\n // For Windows 11, use standard PowerShell Core and report its version\n powerShell.AddScript(\n @\"\n # Set execution policy\n try {\n Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force -ErrorAction SilentlyContinue\n } catch {\n # Ignore errors\n }\n \n # Ensure Windows PowerShell modules are available\n $WindowsPowerShellModulePath = \"\"$env:SystemRoot\\System32\\WindowsPowerShell\\v1.0\\Modules\"\"\n if ($env:PSModulePath -notlike \"\"*$WindowsPowerShellModulePath*\"\") {\n $env:PSModulePath = $env:PSModulePath + \"\";\"\" + $WindowsPowerShellModulePath\n }\n \n # Import Appx module for Windows 11\n try {\n Import-Module Appx -ErrorAction SilentlyContinue\n } catch {\n # Module might not be available, continue anyway\n }\n \n # Log PowerShell version for diagnostics\n $PSVersionInfo = $PSVersionTable.PSVersion\n Write-Output \"\"Using PowerShell version: $($PSVersionInfo.Major).$($PSVersionInfo.Minor) ($($PSVersionTable.PSEdition))\"\"\n Write-Output \"\"OS Version: $([System.Environment]::OSVersion.Version)\"\"\n \"\n );\n }\n\n var results = powerShell.Invoke();\n foreach (var result in results)\n {\n logService?.LogInformation($\"PowerShell initialization: {result}\");\n }\n\n powerShell.Commands.Clear();\n\n return powerShell;\n }\n catch (Exception ex)\n {\n logService?.LogError(\n $\"Error creating Windows PowerShell instance: {ex.Message}\",\n ex\n );\n\n // Fall back to default PowerShell instance if creation fails\n return PowerShell.Create();\n }\n }\n\n /// \n /// Creates a PowerShell instance with the default configuration.\n /// On Windows 10, it will use the same compatibility approach as CreateWindowsPowerShell.\n /// \n /// A default PowerShell instance.\n public static PowerShell CreateDefault()\n {\n // Use the same Windows 10 compatibility approach as CreateWindowsPowerShell\n return CreateWindowsPowerShell();\n }\n\n /// \n /// Creates a PowerShell instance for executing Appx-related commands.\n /// This method always uses Windows PowerShell 5.1 on Windows 10 for compatibility.\n /// \n /// Optional log service for diagnostic information.\n /// Optional system services for OS detection.\n /// A PowerShell instance configured for Appx commands.\n public static PowerShell CreateForAppxCommands(\n ILogService logService = null,\n ISystemServices systemServices = null\n )\n {\n // Always use Windows PowerShell for Appx commands on Windows 10\n return CreateWindowsPowerShell(logService, systemServices);\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/ConfigurationCollectorService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Customize.ViewModels;\nusing Winhance.WPF.Features.Optimize.ViewModels;\nusing Winhance.WPF.Features.SoftwareApps.Models;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for collecting configuration settings from different view models.\n /// \n public class ConfigurationCollectorService\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n\n /// \n /// A wrapper class that implements ISettingItem for Power Plan settings\n /// \n private class PowerPlanSettingItem : ISettingItem\n {\n private readonly ConfigurationItem _configItem;\n private readonly object _originalItem;\n private string _id;\n private string _name;\n private string _description;\n private bool _isSelected;\n private string _groupName;\n private bool _isVisible;\n private ControlType _controlType;\n private int _sliderValue;\n\n public PowerPlanSettingItem(ConfigurationItem configItem, object originalItem)\n {\n _configItem = configItem;\n _originalItem = originalItem;\n \n // Initialize properties from the ConfigurationItem\n _id = _configItem.CustomProperties.TryGetValue(\"Id\", out var id) ? id?.ToString() : \"PowerPlanComboBox\";\n _name = _configItem.Name;\n _description = _configItem.CustomProperties.TryGetValue(\"Description\", out var desc) ? desc?.ToString() : \"Power Plan setting\";\n _isSelected = _configItem.IsSelected;\n _groupName = _configItem.CustomProperties.TryGetValue(\"GroupName\", out var group) ? group?.ToString() : \"Power Management\";\n _isVisible = true;\n _controlType = ControlType.ComboBox;\n _sliderValue = _configItem.CustomProperties.TryGetValue(\"SliderValue\", out var value) ? Convert.ToInt32(value) : 0;\n \n // Ensure the ConfigurationItem has the correct format\n // Make sure SelectedValue is set properly\n if (_configItem.SelectedValue == null)\n {\n // Try to get it from PowerPlanOptions if available\n if (_configItem.CustomProperties.TryGetValue(\"PowerPlanOptions\", out var options) &&\n options is List powerPlanOptions &&\n powerPlanOptions.Count > 0 &&\n _configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int index = Convert.ToInt32(sliderValue);\n if (index >= 0 && index < powerPlanOptions.Count)\n {\n _configItem.SelectedValue = powerPlanOptions[index];\n }\n }\n }\n \n // Always ensure SelectedValue is set based on SliderValue if it's still null\n if (_configItem.SelectedValue == null && _configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sv))\n {\n int index = Convert.ToInt32(sv);\n if (_configItem.CustomProperties.TryGetValue(\"PowerPlanOptions\", out var opt) &&\n opt is List planOptions &&\n planOptions.Count > index && index >= 0)\n {\n _configItem.SelectedValue = planOptions[index];\n }\n else\n {\n // Fallback to default power plan names if PowerPlanOptions is not available\n string[] defaultOptions = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n if (index >= 0 && index < defaultOptions.Length)\n {\n _configItem.SelectedValue = defaultOptions[index];\n }\n }\n }\n \n // Initialize other required properties\n Dependencies = new List();\n IsUpdatingFromCode = false;\n ApplySettingCommand = null;\n }\n\n // Properties with getters and setters\n public string Id { get => _id; set => _id = value; }\n public string Name { get => _name; set => _name = value; }\n public string Description { get => _description; set => _description = value; }\n public bool IsSelected { get => _isSelected; set => _isSelected = value; }\n public string GroupName { get => _groupName; set => _groupName = value; }\n public bool IsVisible { get => _isVisible; set => _isVisible = value; }\n public ControlType ControlType { get => _controlType; set => _controlType = value; }\n public int SliderValue { get => _sliderValue; set => _sliderValue = value; }\n \n // Additional required properties\n public List Dependencies { get; set; }\n public bool IsUpdatingFromCode { get; set; }\n public System.Windows.Input.ICommand ApplySettingCommand { get; set; }\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n public ConfigurationCollectorService(\n IServiceProvider serviceProvider,\n ILogService logService)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Collects settings from all view models.\n /// \n /// A dictionary of section names and their settings.\n public async Task>> CollectAllSettingsAsync()\n {\n var sectionSettings = new Dictionary>();\n\n // Get all view models from the service provider\n var windowsAppsViewModel = _serviceProvider.GetService();\n var externalAppsViewModel = _serviceProvider.GetService();\n var customizeViewModel = _serviceProvider.GetService();\n var optimizeViewModel = _serviceProvider.GetService();\n\n // Add settings from WindowsAppsViewModel\n if (windowsAppsViewModel != null)\n {\n await CollectWindowsAppsSettings(windowsAppsViewModel, sectionSettings);\n }\n\n // Add settings from ExternalAppsViewModel\n if (externalAppsViewModel != null)\n {\n await CollectExternalAppsSettings(externalAppsViewModel, sectionSettings);\n }\n\n // Add settings from CustomizeViewModel\n if (customizeViewModel != null)\n {\n await CollectCustomizeSettings(customizeViewModel, sectionSettings);\n }\n\n // Add settings from OptimizeViewModel\n if (optimizeViewModel != null)\n {\n await CollectOptimizeSettings(optimizeViewModel, sectionSettings);\n }\n\n return sectionSettings;\n }\n\n private async Task CollectWindowsAppsSettings(WindowsAppsViewModel viewModel, Dictionary> sectionSettings)\n {\n try\n {\n _logService.Log(LogLevel.Debug, \"Collecting settings from WindowsAppsViewModel\");\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"WindowsAppsViewModel not initialized, loading items\");\n await viewModel.LoadItemsAsync();\n }\n \n // Convert each WindowsApp to WindowsAppSettingItem\n var windowsAppSettingItems = new List();\n \n foreach (var item in viewModel.Items)\n {\n if (item is WindowsApp windowsApp)\n {\n windowsAppSettingItems.Add(new WindowsAppSettingItem(windowsApp));\n _logService.Log(LogLevel.Debug, $\"Added WindowsAppSettingItem for {windowsApp.Name}\");\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Created {windowsAppSettingItems.Count} WindowsAppSettingItems\");\n \n // Always add WindowsApps to sectionSettings, even if empty\n sectionSettings[\"WindowsApps\"] = windowsAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added WindowsApps section with {windowsAppSettingItems.Count} items\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error collecting WindowsApps settings: {ex.Message}\");\n \n // Create some default WindowsApps as fallback\n var defaultApps = new[]\n {\n new WindowsApp\n {\n Name = \"Microsoft Edge\",\n PackageName = \"Microsoft.MicrosoftEdge\",\n IsSelected = true,\n Description = \"Microsoft Edge browser\"\n },\n new WindowsApp\n {\n Name = \"Calculator\",\n PackageName = \"Microsoft.WindowsCalculator\",\n IsSelected = true,\n Description = \"Windows Calculator app\"\n },\n new WindowsApp\n {\n Name = \"Photos\",\n PackageName = \"Microsoft.Windows.Photos\",\n IsSelected = true,\n Description = \"Windows Photos app\"\n }\n };\n \n var defaultWindowsAppSettingItems = new List();\n foreach (var app in defaultApps)\n {\n defaultWindowsAppSettingItems.Add(new WindowsAppSettingItem(app));\n }\n \n // Always add WindowsApps to sectionSettings, even if using defaults\n sectionSettings[\"WindowsApps\"] = defaultWindowsAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added WindowsApps section with {defaultWindowsAppSettingItems.Count} default items\");\n }\n }\n\n private async Task CollectExternalAppsSettings(ExternalAppsViewModel viewModel, Dictionary> sectionSettings)\n {\n try\n {\n _logService.Log(LogLevel.Debug, \"Collecting settings from ExternalAppsViewModel\");\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"ExternalAppsViewModel not initialized, loading items\");\n await viewModel.LoadItemsAsync();\n }\n \n // Convert each ExternalApp to ExternalAppSettingItem\n var externalAppSettingItems = new List();\n \n foreach (var item in viewModel.Items)\n {\n if (item is ExternalApp externalApp)\n {\n externalAppSettingItems.Add(new ExternalAppSettingItem(externalApp));\n _logService.Log(LogLevel.Debug, $\"Added ExternalAppSettingItem for {externalApp.Name}\");\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Created {externalAppSettingItems.Count} ExternalAppSettingItems\");\n \n // Add the settings to the dictionary\n sectionSettings[\"ExternalApps\"] = externalAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added ExternalApps section with {externalAppSettingItems.Count} items\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error collecting ExternalApps settings: {ex.Message}\");\n \n // Add an empty list as fallback\n sectionSettings[\"ExternalApps\"] = new List();\n _logService.Log(LogLevel.Info, \"Added empty ExternalApps section due to error\");\n }\n }\n\n private async Task CollectCustomizeSettings(CustomizeViewModel viewModel, Dictionary> sectionSettings)\n {\n try\n {\n _logService.Log(LogLevel.Debug, \"Collecting settings from CustomizeViewModel\");\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"CustomizeViewModel not initialized, loading items\");\n await viewModel.LoadItemsAsync();\n }\n \n // Collect settings directly\n var customizeItems = new List();\n \n foreach (var item in viewModel.Items)\n {\n if (item is ISettingItem settingItem)\n {\n // Skip the DarkModeToggle item to avoid conflicts with ThemeSelector\n if (settingItem.Id == \"DarkModeToggle\")\n {\n _logService.Log(LogLevel.Debug, $\"Skipping DarkModeToggle item to avoid conflicts with ThemeSelector\");\n continue;\n }\n \n // Special handling for Windows Theme / Choose Your Mode\n if (settingItem.Id == \"ThemeSelector\" ||\n settingItem.Name.Contains(\"Windows Theme\") ||\n settingItem.Name.Contains(\"Theme Selector\") ||\n settingItem.Name.Contains(\"Choose Your Mode\"))\n {\n // Ensure it has the correct ControlType and properties for ComboBox\n if (settingItem is ApplicationSettingItem applicationSetting)\n {\n applicationSetting.ControlType = ControlType.ComboBox;\n \n // Get the SelectedTheme from the RegistrySetting if available\n if (applicationSetting.RegistrySetting?.CustomProperties != null &&\n applicationSetting.RegistrySetting.CustomProperties.ContainsKey(\"SelectedTheme\"))\n {\n var selectedTheme = applicationSetting.RegistrySetting.CustomProperties[\"SelectedTheme\"]?.ToString();\n _logService.Log(LogLevel.Debug, $\"Found SelectedTheme in RegistrySetting: {selectedTheme}\");\n }\n \n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ComboBox for Theme Selector\");\n }\n else if (settingItem is ApplicationSettingViewModel applicationViewModel)\n {\n applicationViewModel.ControlType = ControlType.ComboBox;\n \n // Ensure SelectedValue is set based on SelectedTheme if available\n var selectedThemeProperty = applicationViewModel.GetType().GetProperty(\"SelectedTheme\");\n var selectedValueProperty = applicationViewModel.GetType().GetProperty(\"SelectedValue\");\n \n if (selectedThemeProperty != null && selectedValueProperty != null)\n {\n var selectedTheme = selectedThemeProperty.GetValue(applicationViewModel)?.ToString();\n if (!string.IsNullOrEmpty(selectedTheme))\n {\n selectedValueProperty.SetValue(applicationViewModel, selectedTheme);\n }\n }\n \n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ComboBox for Theme Selector (ViewModel) and ensured SelectedValue is set\");\n }\n else if (settingItem is ApplicationSettingItem customizationSetting)\n {\n customizationSetting.ControlType = ControlType.ComboBox;\n \n // Get the SelectedTheme from the RegistrySetting if available\n if (customizationSetting.RegistrySetting?.CustomProperties != null &&\n customizationSetting.RegistrySetting.CustomProperties.ContainsKey(\"SelectedTheme\"))\n {\n var selectedTheme = customizationSetting.RegistrySetting.CustomProperties[\"SelectedTheme\"]?.ToString();\n _logService.Log(LogLevel.Debug, $\"Found SelectedTheme in RegistrySetting: {selectedTheme}\");\n }\n \n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ComboBox for Theme Selector (CustomizationSetting)\");\n }\n }\n \n customizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item for {settingItem.Name}\");\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Collected {customizeItems.Count} customize items\");\n \n // Add the settings to the dictionary\n sectionSettings[\"Customize\"] = customizeItems;\n _logService.Log(LogLevel.Info, $\"Added Customize section with {customizeItems.Count} items\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error collecting Customize settings: {ex.Message}\");\n \n // Add an empty list as fallback\n sectionSettings[\"Customize\"] = new List();\n _logService.Log(LogLevel.Info, \"Added empty Customize section due to error\");\n }\n }\n\n private async Task CollectOptimizeSettings(OptimizeViewModel viewModel, Dictionary> sectionSettings)\n {\n try\n {\n _logService.Log(LogLevel.Debug, \"Collecting settings from OptimizeViewModel\");\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"OptimizeViewModel not initialized, initializing now\");\n await viewModel.InitializeCommand.ExecuteAsync(null);\n _logService.Log(LogLevel.Debug, \"OptimizeViewModel initialized\");\n }\n \n // Force load items even if already initialized to ensure we have the latest data\n _logService.Log(LogLevel.Debug, \"Loading OptimizeViewModel items\");\n await viewModel.LoadItemsAsync();\n _logService.Log(LogLevel.Debug, $\"OptimizeViewModel items loaded, count: {viewModel.Items?.Count ?? 0}\");\n \n // Collect settings directly\n var optimizeItems = new List();\n \n // First check if Items collection has any settings\n if (viewModel.Items != null && viewModel.Items.Count > 0)\n {\n foreach (var item in viewModel.Items)\n {\n if (item is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Items collection: {settingItem.Name}\");\n }\n }\n }\n \n // If we didn't get any items from the Items collection, try to collect from child view models directly\n if (optimizeItems.Count == 0)\n {\n _logService.Log(LogLevel.Debug, \"No items found in Items collection, collecting from child view models\");\n \n // Collect from GamingandPerformanceOptimizationsViewModel\n if (viewModel.GamingandPerformanceOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.GamingandPerformanceOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Gaming: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from PrivacyOptimizationsViewModel\n if (viewModel.PrivacyOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.PrivacyOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Privacy: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from UpdateOptimizationsViewModel\n if (viewModel.UpdateOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.UpdateOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Updates: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from PowerSettingsViewModel\n if (viewModel.PowerSettingsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.PowerSettingsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n // Special handling for Power Plan\n if (settingItem.Id == \"PowerPlanComboBox\" || settingItem.Name.Contains(\"Power Plan\"))\n {\n // Ensure it has the correct ControlType\n if (settingItem is ApplicationSettingItem applicationSetting)\n {\n applicationSetting.ControlType = ControlType.ComboBox;\n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ComboBox for Power Plan\");\n \n // Get the current power plan value from the view model\n if (viewModel.PowerSettingsViewModel != null)\n {\n // Set the SliderValue to the current power plan index\n int powerPlanIndex = viewModel.PowerSettingsViewModel.PowerPlanValue;\n applicationSetting.SliderValue = powerPlanIndex;\n _logService.Log(LogLevel.Debug, $\"Set SliderValue to {powerPlanIndex} for Power Plan\");\n \n // Instead of replacing the item, update its properties\n applicationSetting.ControlType = ControlType.ComboBox;\n applicationSetting.SliderValue = powerPlanIndex;\n \n // Create a separate ConfigurationItem for the config file\n var configItem = new ConfigurationItem\n {\n Name = \"Power Plan\", // Use a consistent name\n IsSelected = true, // Always enable the Power Plan\n ControlType = ControlType.ComboBox,\n CustomProperties = new Dictionary\n {\n { \"Id\", \"PowerPlanComboBox\" }, // Use a consistent ID\n { \"GroupName\", \"Power Management\" },\n { \"Description\", \"Select power plan for your system\" },\n { \"SliderValue\", powerPlanIndex }\n }\n };\n \n // Set the SelectedValue to the current power plan name\n if (powerPlanIndex >= 0 && powerPlanIndex < viewModel.PowerSettingsViewModel.PowerPlanLabels.Count)\n {\n string powerPlanName = viewModel.PowerSettingsViewModel.PowerPlanLabels[powerPlanIndex];\n \n // Set SelectedValue at the top level (this is what appears in the config file)\n configItem.SelectedValue = powerPlanName;\n \n // Add PowerPlanOptions to CustomProperties (similar to ThemeOptions in Windows Theme)\n configItem.CustomProperties[\"PowerPlanOptions\"] = viewModel.PowerSettingsViewModel.PowerPlanLabels.ToList();\n _logService.Log(LogLevel.Debug, $\"Set SelectedValue to {powerPlanName} for Power Plan ConfigItem\");\n }\n \n // Add this ConfigurationItem directly to the optimizeItems collection\n // We'll create a wrapper that implements ISettingItem\n var powerPlanSettingItem = new PowerPlanSettingItem(configItem, applicationSetting);\n \n // Add it to the collection if it doesn't already exist\n bool exists = false;\n foreach (var item in optimizeItems)\n {\n if (item is PowerPlanSettingItem)\n {\n exists = true;\n break;\n }\n }\n \n if (!exists)\n {\n optimizeItems.Add(powerPlanSettingItem);\n _logService.Log(LogLevel.Debug, $\"Added PowerPlanSettingItem to optimizeItems\");\n }\n }\n }\n else if (settingItem is ApplicationSettingViewModel applicationViewModel)\n {\n applicationViewModel.ControlType = ControlType.ComboBox;\n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ComboBox for Power Plan (ViewModel)\");\n \n // Get the current power plan value from the view model\n if (viewModel.PowerSettingsViewModel != null)\n {\n // Set the SliderValue to the current power plan index\n int powerPlanIndex = viewModel.PowerSettingsViewModel.PowerPlanValue;\n applicationViewModel.SliderValue = powerPlanIndex;\n _logService.Log(LogLevel.Debug, $\"Set SliderValue to {powerPlanIndex} for Power Plan (ViewModel)\");\n \n // Instead of replacing the item, update its properties\n applicationViewModel.ControlType = ControlType.ComboBox;\n applicationViewModel.SliderValue = powerPlanIndex;\n \n // Create a separate ConfigurationItem for the config file\n var configItem = new ConfigurationItem\n {\n Name = \"Power Plan\", // Use a consistent name\n IsSelected = true, // Always enable the Power Plan\n ControlType = ControlType.ComboBox,\n CustomProperties = new Dictionary\n {\n { \"Id\", \"PowerPlanComboBox\" }, // Use a consistent ID\n { \"GroupName\", \"Power Management\" },\n { \"Description\", \"Select power plan for your system\" },\n { \"SliderValue\", powerPlanIndex }\n }\n };\n \n // Set the SelectedValue to the current power plan name\n if (powerPlanIndex >= 0 && powerPlanIndex < viewModel.PowerSettingsViewModel.PowerPlanLabels.Count)\n {\n string powerPlanName = viewModel.PowerSettingsViewModel.PowerPlanLabels[powerPlanIndex];\n \n // Set SelectedValue at the top level (this is what appears in the config file)\n configItem.SelectedValue = powerPlanName;\n \n // Add PowerPlanOptions to CustomProperties (similar to ThemeOptions in Windows Theme)\n configItem.CustomProperties[\"PowerPlanOptions\"] = viewModel.PowerSettingsViewModel.PowerPlanLabels.ToList();\n _logService.Log(LogLevel.Debug, $\"Set SelectedValue to {powerPlanName} for Power Plan ConfigItem (ViewModel)\");\n }\n \n // Add this ConfigurationItem directly to the optimizeItems collection\n // We'll create a wrapper that implements ISettingItem\n var powerPlanSettingItem = new PowerPlanSettingItem(configItem, applicationViewModel);\n \n // Add it to the collection if it doesn't already exist\n bool exists = false;\n foreach (var item in optimizeItems)\n {\n if (item is PowerPlanSettingItem)\n {\n exists = true;\n break;\n }\n }\n \n if (!exists)\n {\n optimizeItems.Add(powerPlanSettingItem);\n _logService.Log(LogLevel.Debug, $\"Added PowerPlanSettingItem to optimizeItems (ViewModel)\");\n }\n }\n }\n }\n \n // Skip adding the original Power Plan item since we've already added our custom PowerPlanSettingItem\n if (!(settingItem.Id == \"PowerPlanComboBox\" || settingItem.Name.Contains(\"Power Plan\")))\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Power: {settingItem.Name}\");\n }\n else\n {\n _logService.Log(LogLevel.Debug, $\"Skipped adding original Power Plan item: {settingItem.Name}\");\n }\n }\n }\n }\n \n // Collect from ExplorerOptimizationsViewModel\n if (viewModel.ExplorerOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.ExplorerOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Explorer: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from NotificationOptimizationsViewModel\n if (viewModel.NotificationOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.NotificationOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Notifications: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from SoundOptimizationsViewModel\n if (viewModel.SoundOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.SoundOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Sound: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from WindowsSecuritySettingsViewModel\n if (viewModel.WindowsSecuritySettingsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.WindowsSecuritySettingsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n // Special handling for UAC Slider\n if (settingItem.Id == \"UACSlider\" || settingItem.Name.Contains(\"User Account Control\"))\n {\n // Ensure it has the correct ControlType\n if (settingItem is ApplicationSettingItem applicationSetting)\n {\n applicationSetting.ControlType = ControlType.ThreeStateSlider;\n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ThreeStateSlider for UAC Slider\");\n }\n else if (settingItem is ApplicationSettingViewModel applicationViewModel)\n {\n applicationViewModel.ControlType = ControlType.ThreeStateSlider;\n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ThreeStateSlider for UAC Slider (ViewModel)\");\n }\n }\n \n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Security: {settingItem.Name}\");\n }\n }\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Collected {optimizeItems.Count} optimize items\");\n \n // Always create a standalone Power Plan item and add it directly to the configuration file\n if (viewModel.PowerSettingsViewModel != null)\n {\n try\n {\n // Get the current power plan index and name\n int powerPlanIndex = viewModel.PowerSettingsViewModel.PowerPlanValue;\n string powerPlanName = null;\n \n if (powerPlanIndex >= 0 && powerPlanIndex < viewModel.PowerSettingsViewModel.PowerPlanLabels.Count)\n {\n powerPlanName = viewModel.PowerSettingsViewModel.PowerPlanLabels[powerPlanIndex];\n }\n \n // Create a ConfigurationItem for the Power Plan\n var configItem = new ConfigurationItem\n {\n Name = \"Power Plan\",\n PackageName = null,\n IsSelected = true,\n ControlType = ControlType.ComboBox,\n SelectedValue = powerPlanName, // Set SelectedValue directly\n CustomProperties = new Dictionary\n {\n { \"Id\", \"PowerPlanComboBox\" },\n { \"GroupName\", \"Power Management\" },\n { \"Description\", \"Select power plan for your system\" },\n { \"SliderValue\", powerPlanIndex },\n { \"PowerPlanOptions\", viewModel.PowerSettingsViewModel.PowerPlanLabels.ToList() }\n }\n };\n \n // Log the configuration item for debugging\n _logService.Log(LogLevel.Info, $\"Created Power Plan configuration item with SelectedValue: {powerPlanName}, SliderValue: {powerPlanIndex}\");\n _logService.Log(LogLevel.Info, $\"PowerPlanOptions: {string.Join(\", \", viewModel.PowerSettingsViewModel.PowerPlanLabels)}\");\n \n // Ensure SelectedValue is not null\n if (string.IsNullOrEmpty(configItem.SelectedValue) &&\n configItem.CustomProperties.ContainsKey(\"PowerPlanOptions\") &&\n configItem.CustomProperties[\"PowerPlanOptions\"] is List options &&\n options.Count > powerPlanIndex && powerPlanIndex >= 0)\n {\n configItem.SelectedValue = options[powerPlanIndex];\n _logService.Log(LogLevel.Info, $\"Set SelectedValue to {configItem.SelectedValue} from PowerPlanOptions\");\n }\n \n // Add the item directly to the configuration file\n var configService = _serviceProvider.GetService();\n if (configService != null)\n {\n // Use reflection to access the ConfigurationFile\n var configFileProperty = configService.GetType().GetProperty(\"CurrentConfiguration\");\n if (configFileProperty != null)\n {\n var configFile = configFileProperty.GetValue(configService) as ConfigurationFile;\n if (configFile != null && configFile.Items != null)\n {\n // Remove any existing Power Plan items\n configFile.Items.RemoveAll(item =>\n item.Name == \"Power Plan\" ||\n (item.CustomProperties != null && item.CustomProperties.TryGetValue(\"Id\", out var id) && id?.ToString() == \"PowerPlanComboBox\"));\n \n // Add the new Power Plan item\n configFile.Items.Add(configItem);\n _logService.Log(LogLevel.Info, $\"Added Power Plan item directly to the configuration file with SelectedValue: {powerPlanName}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not access ConfigurationFile.Items\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not access CurrentConfiguration property\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not get IConfigurationService from service provider\");\n }\n \n // Also create a wrapper that implements ISettingItem for the optimizeItems collection\n var powerPlanSettingItem = new PowerPlanSettingItem(configItem, null);\n \n // Remove any existing Power Plan items from optimizeItems\n optimizeItems.RemoveAll(item =>\n (item is PowerPlanSettingItem) ||\n (item is ApplicationSettingItem settingItem &&\n (settingItem.Id == \"PowerPlanComboBox\" || settingItem.Name.Contains(\"Power Plan\"))));\n \n // Add the new Power Plan item to optimizeItems\n optimizeItems.Add(powerPlanSettingItem);\n _logService.Log(LogLevel.Info, \"Added Power Plan item to optimizeItems\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating Power Plan item: {ex.Message}\");\n }\n }\n \n // Add the settings to the dictionary\n sectionSettings[\"Optimize\"] = optimizeItems;\n _logService.Log(LogLevel.Info, $\"Added Optimize section with {optimizeItems.Count} items\");\n \n // If we still have no items, log a warning\n if (optimizeItems.Count == 0)\n {\n _logService.Log(LogLevel.Warning, \"No optimize items were collected. This may indicate an initialization issue with the OptimizeViewModel or its child view models.\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error collecting Optimize settings: {ex.Message}\");\n \n // Add an empty list as fallback\n sectionSettings[\"Optimize\"] = new List();\n _logService.Log(LogLevel.Info, \"Added empty Optimize section due to error\");\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/CommandService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service for executing system commands related to optimizations.\n /// \n public class CommandService : ICommandService\n {\n private readonly ILogService _logService;\n private readonly ISystemServices _systemServices;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The system services.\n public CommandService(ILogService logService, ISystemServices systemServices)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _systemServices =\n systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n }\n\n /// \n public async Task<(bool Success, string Output, string Error)> ExecuteCommandAsync(\n string command,\n bool requiresElevation = true\n )\n {\n try\n {\n _logService.LogInformation($\"Executing command: {command}\");\n\n // Create a PowerShell instance using the factory\n var powerShell = PowerShellFactory.CreateWindowsPowerShell(\n _logService,\n _systemServices\n );\n\n // Add the command to execute\n powerShell.AddScript(command);\n\n // Execute the command\n var results = await Task.Run(() => powerShell.Invoke());\n\n // Process the results\n var output = string.Join(Environment.NewLine, results.Select(r => r.ToString()));\n var error = string.Join(\n Environment.NewLine,\n powerShell.Streams.Error.ReadAll().Select(e => e.ToString())\n );\n\n // Log the results\n if (string.IsNullOrEmpty(error))\n {\n _logService.LogInformation($\"Command executed successfully: {command}\");\n _logService.LogInformation($\"Command output: {output}\");\n return (true, output, string.Empty);\n }\n else\n {\n _logService.LogWarning($\"Command execution failed: {command}\");\n _logService.LogWarning($\"Error: {error}\");\n return (false, output, error);\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Exception executing command: {command}\");\n _logService.LogError($\"Exception: {ex}\");\n return (false, string.Empty, ex.ToString());\n }\n }\n\n /// \n public async Task<(bool Success, string Message)> ApplyCommandSettingsAsync(\n IEnumerable settings,\n bool isEnabled\n )\n {\n if (settings == null || !settings.Any())\n {\n return (true, \"No command settings to apply.\");\n }\n\n var successCount = 0;\n var failureCount = 0;\n var messages = new List();\n\n foreach (var setting in settings)\n {\n var commandToExecute = isEnabled ? setting.EnabledCommand : setting.DisabledCommand;\n\n if (string.IsNullOrWhiteSpace(commandToExecute))\n {\n _logService.LogWarning($\"Empty command for setting: {setting.Id}\");\n continue;\n }\n\n var (success, output, error) = await ExecuteCommandAsync(\n commandToExecute,\n setting.RequiresElevation\n );\n\n if (success)\n {\n successCount++;\n messages.Add($\"Successfully applied command setting: {setting.Id}\");\n }\n else\n {\n failureCount++;\n messages.Add($\"Failed to apply command setting: {setting.Id}. Error: {error}\");\n }\n }\n\n var overallSuccess = failureCount == 0;\n var message =\n $\"Applied {successCount} command settings successfully, {failureCount} failed.\";\n\n if (messages.Any())\n {\n message += Environment.NewLine + string.Join(Environment.NewLine, messages);\n }\n\n return (overallSuccess, message);\n }\n\n /// \n public async Task IsCommandSettingEnabledAsync(CommandSetting setting)\n {\n try\n {\n _logService.LogInformation($\"Checking state for command setting: {setting.Id}\");\n\n // Check if this is a bcdedit command\n if (setting.EnabledCommand.Contains(\"bcdedit\"))\n {\n return await IsBcdeditSettingEnabledAsync(setting);\n }\n\n // For other types of commands, implement specific checking logic here\n // For now, return false as a default for unhandled command types\n _logService.LogWarning(\n $\"No state checking implementation for command type: {setting.Id}\"\n );\n return false;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking command setting state: {setting.Id}\", ex);\n return false;\n }\n }\n\n /// \n /// Checks if a bcdedit setting is in its enabled state.\n /// \n /// The command setting to check.\n /// True if the setting is in its enabled state, false otherwise.\n private async Task IsBcdeditSettingEnabledAsync(CommandSetting setting)\n {\n // Extract the setting name and value from the command\n string settingName = ExtractBcdeditSettingName(setting.EnabledCommand);\n string expectedValue = ExtractBcdeditSettingValue(setting.EnabledCommand);\n\n if (string.IsNullOrEmpty(settingName))\n {\n _logService.LogWarning(\n $\"Could not extract setting name from bcdedit command: {setting.EnabledCommand}\"\n );\n return false;\n }\n\n // Query the current boot configuration\n var (success, output, error) = await ExecuteCommandAsync(\"bcdedit /enum {current}\");\n\n if (!success || string.IsNullOrEmpty(output))\n {\n _logService.LogWarning($\"Failed to query boot configuration: {error}\");\n return false;\n }\n\n // Parse the output to find the setting\n bool settingExists = output.Contains(settingName, StringComparison.OrdinalIgnoreCase);\n\n // For settings that should be deleted when disabled\n if (setting.DisabledCommand.Contains(\"/deletevalue\"))\n {\n // If the setting exists, check if it has the expected value\n if (settingExists)\n {\n // Find the line containing the setting\n var lines = output.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n var settingLine = lines.FirstOrDefault(l =>\n l.Contains(settingName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (settingLine != null)\n {\n // Extract the current value\n var parts = settingLine.Split(\n new[] { ' ' },\n StringSplitOptions.RemoveEmptyEntries\n );\n if (parts.Length >= 2)\n {\n string currentValue = parts[parts.Length - 1].Trim().ToLowerInvariant();\n expectedValue = expectedValue.ToLowerInvariant();\n\n _logService.LogInformation(\n $\"Found bcdedit setting {settingName} with value {currentValue}, expected {expectedValue}\"\n );\n return currentValue == expectedValue;\n }\n }\n }\n\n // If the setting doesn't exist or we couldn't parse the value, it's not in the enabled state\n return false;\n }\n // For settings that should be set to a different value when disabled\n else if (setting.DisabledCommand.Contains(\"/set\"))\n {\n string disabledValue = ExtractBcdeditSettingValue(setting.DisabledCommand);\n\n // Find the line containing the setting\n if (settingExists)\n {\n var lines = output.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n var settingLine = lines.FirstOrDefault(l =>\n l.Contains(settingName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (settingLine != null)\n {\n // Extract the current value\n var parts = settingLine.Split(\n new[] { ' ' },\n StringSplitOptions.RemoveEmptyEntries\n );\n if (parts.Length >= 2)\n {\n string currentValue = parts[parts.Length - 1].Trim().ToLowerInvariant();\n expectedValue = expectedValue.ToLowerInvariant();\n disabledValue = disabledValue.ToLowerInvariant();\n\n _logService.LogInformation(\n $\"Found bcdedit setting {settingName} with value {currentValue}, expected {expectedValue} for enabled state\"\n );\n return currentValue == expectedValue && currentValue != disabledValue;\n }\n }\n }\n\n return false;\n }\n\n // Default case\n return false;\n }\n\n /// \n /// Extracts the setting name from a bcdedit command.\n /// \n /// The bcdedit command.\n /// The setting name.\n private string ExtractBcdeditSettingName(string command)\n {\n // Handle /set command\n if (command.Contains(\"/set \"))\n {\n var parts = command.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (parts.Length >= 3)\n {\n return parts[2]; // The setting name is the third part in \"bcdedit /set settingname value\"\n }\n }\n // Handle /deletevalue command\n else if (command.Contains(\"/deletevalue \"))\n {\n var parts = command.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (parts.Length >= 3)\n {\n return parts[2]; // The setting name is the third part in \"bcdedit /deletevalue settingname\"\n }\n }\n\n return string.Empty;\n }\n\n /// \n /// Extracts the setting value from a bcdedit command.\n /// \n /// The bcdedit command.\n /// The setting value.\n private string ExtractBcdeditSettingValue(string command)\n {\n // Only handle /set command as /deletevalue doesn't have a value\n if (command.Contains(\"/set \"))\n {\n var parts = command.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (parts.Length >= 4)\n {\n return parts[3]; // The value is the fourth part in \"bcdedit /set settingname value\"\n }\n }\n\n return string.Empty;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/UacSettingsService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading.Tasks;\nusing Newtonsoft.Json;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for managing UAC settings persistence.\n /// \n public class UacSettingsService : IUacSettingsService\n {\n private const string CustomUacSettingsKey = \"CustomUacSettings\";\n private readonly UserPreferencesService _userPreferencesService;\n private readonly ILogService _logService;\n \n // Cache for custom UAC settings during the current session\n private CustomUacSettings _cachedSettings;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The user preferences service.\n /// The log service.\n public UacSettingsService(UserPreferencesService userPreferencesService, ILogService logService)\n {\n _userPreferencesService = userPreferencesService ?? throw new ArgumentNullException(nameof(userPreferencesService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Saves custom UAC settings.\n /// \n /// The ConsentPromptBehaviorAdmin registry value.\n /// The PromptOnSecureDesktop registry value.\n /// A task representing the asynchronous operation.\n public async Task SaveCustomUacSettingsAsync(int consentPromptValue, int secureDesktopValue)\n {\n try\n {\n // Create a CustomUacSettings object\n var settings = new CustomUacSettings(consentPromptValue, secureDesktopValue);\n \n // Cache the settings\n _cachedSettings = settings;\n \n // Save to user preferences\n await _userPreferencesService.SetPreferenceAsync(CustomUacSettingsKey, settings);\n \n _logService.Log(LogLevel.Info, \n $\"Saved custom UAC settings: ConsentPrompt={consentPromptValue}, SecureDesktop={secureDesktopValue}\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving custom UAC settings: {ex.Message}\");\n }\n }\n\n /// \n /// Loads custom UAC settings.\n /// \n /// A CustomUacSettings object if settings exist, null otherwise.\n public async Task LoadCustomUacSettingsAsync()\n {\n try\n {\n // Try to get from cache first\n if (_cachedSettings != null)\n {\n return _cachedSettings;\n }\n \n // Try to load from preferences\n var settings = await _userPreferencesService.GetPreferenceAsync(CustomUacSettingsKey, default(CustomUacSettings));\n if (settings != null)\n {\n // Cache the settings\n _cachedSettings = settings;\n return settings;\n }\n \n return null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading custom UAC settings: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Checks if custom UAC settings exist.\n /// \n /// True if custom settings exist, false otherwise.\n public async Task HasCustomUacSettingsAsync()\n {\n try\n {\n // Check cache first\n if (_cachedSettings != null)\n {\n return true;\n }\n \n // Check user preferences\n var settings = await _userPreferencesService.GetPreferenceAsync(CustomUacSettingsKey, null);\n return settings != null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking for custom UAC settings: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Gets custom UAC settings if they exist.\n /// \n /// The ConsentPromptBehaviorAdmin registry value.\n /// The PromptOnSecureDesktop registry value.\n /// True if custom settings were retrieved, false otherwise.\n public bool TryGetCustomUacValues(out int consentPromptValue, out int secureDesktopValue)\n {\n // Initialize out parameters\n consentPromptValue = 0;\n secureDesktopValue = 0;\n \n try\n {\n // Check cache first\n if (_cachedSettings != null)\n {\n consentPromptValue = _cachedSettings.ConsentPromptValue;\n secureDesktopValue = _cachedSettings.SecureDesktopValue;\n return true;\n }\n \n // Try to load from preferences (completely synchronously)\n string preferencesFilePath = GetPreferencesFilePath();\n if (File.Exists(preferencesFilePath))\n {\n try\n {\n string json = File.ReadAllText(preferencesFilePath);\n var preferences = JsonConvert.DeserializeObject>(json);\n \n if (preferences != null && preferences.ContainsKey(CustomUacSettingsKey))\n {\n var settingsToken = preferences[CustomUacSettingsKey];\n var settings = JsonConvert.DeserializeObject(settingsToken.ToString());\n \n if (settings != null)\n {\n // Cache the settings\n _cachedSettings = settings;\n \n consentPromptValue = settings.ConsentPromptValue;\n secureDesktopValue = settings.SecureDesktopValue;\n return true;\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error reading preferences file: {ex.Message}\");\n }\n }\n \n return false;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting custom UAC values: {ex.Message}\");\n\n return false;\n }\n }\n \n /// \n /// Gets the path to the user preferences file.\n /// \n /// The full path to the user preferences file.\n private string GetPreferencesFilePath()\n {\n // Get the LocalApplicationData folder (e.g., C:\\Users\\Username\\AppData\\Local)\n string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n \n // Combine with Winhance/Config\n string appDataPath = Path.Combine(localAppData, \"Winhance\", \"Config\");\n \n // Ensure the directory exists\n if (!Directory.Exists(appDataPath))\n {\n Directory.CreateDirectory(appDataPath);\n }\n \n // Return the full path to the preferences file\n return Path.Combine(appDataPath, \"UserPreferences.json\");\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/Methods/WinGetVerificationMethod.cs", "using System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods\n{\n /// \n /// Verifies software installations by querying WinGet.\n /// \n public class WinGetVerificationMethod : VerificationMethodBase\n {\n private const string WinGetExe = \"winget.exe\";\n private static readonly string[] WinGetPaths = new[]\n {\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n @\"Microsoft\\WindowsApps\"\n ),\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n @\"WindowsApps\\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe\"\n ),\n };\n\n /// \n /// Initializes a new instance of the class.\n /// \n public WinGetVerificationMethod()\n : base(\"WinGet\", priority: 5) // Higher priority as it's the most reliable source\n { }\n\n /// \n protected override async Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken\n )\n {\n // First try with the exact match approach using winget list\n try\n {\n var exactMatchResult = await ExecuteWinGetCommandAsync(\n \"list\",\n $\"--id {packageId} --exact\",\n cancellationToken\n );\n\n // Check if the package is found in the output\n if (\n exactMatchResult.ExitCode == 0\n && !string.IsNullOrWhiteSpace(exactMatchResult.Output)\n && exactMatchResult.Output.Contains(packageId)\n )\n {\n // Extract version if possible\n string version = \"unknown\";\n string source = \"unknown\";\n\n var lines = exactMatchResult.Output.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n if (lines.Length >= 2)\n {\n var parts = lines[1]\n .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (parts.Length > 1)\n version = parts[1];\n if (parts.Length > 2)\n source = parts[2];\n }\n\n return new VerificationResult\n {\n IsVerified = true,\n Message =\n $\"Found in WinGet: {packageId} (Version: {version}, Source: {source})\",\n MethodUsed = \"WinGet\",\n AdditionalInfo = new\n {\n PackageId = packageId,\n Version = version,\n Source = source,\n },\n };\n }\n\n // If exact match failed, try a more flexible approach with just the package ID\n var flexibleResult = await ExecuteWinGetCommandAsync(\n \"list\",\n $\"\\\"{packageId}\\\"\",\n cancellationToken\n );\n\n if (\n flexibleResult.ExitCode == 0\n && !string.IsNullOrWhiteSpace(flexibleResult.Output)\n )\n {\n // Check if any line contains the package ID\n var lines = flexibleResult.Output.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n foreach (var line in lines)\n {\n if (line.IndexOf(packageId, StringComparison.OrdinalIgnoreCase) >= 0)\n {\n // Found a match\n var parts = line.Split(\n new[] { ' ' },\n StringSplitOptions.RemoveEmptyEntries\n );\n string version = parts.Length > 1 ? parts[1] : \"unknown\";\n string source = parts.Length > 2 ? parts[2] : \"unknown\";\n\n return new VerificationResult\n {\n IsVerified = true,\n Message =\n $\"Found in WinGet: {packageId} (Version: {version}, Source: {source})\",\n MethodUsed = \"WinGet\",\n AdditionalInfo = new\n {\n PackageId = packageId,\n Version = version,\n Source = source,\n },\n };\n }\n }\n }\n\n // If we got here, the package wasn't found\n return VerificationResult.Failure($\"Package '{packageId}' not found via WinGet\");\n }\n catch (Exception ex)\n {\n return VerificationResult.Failure($\"Error querying WinGet: {ex.Message}\");\n }\n }\n\n /// \n protected override async Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken\n )\n {\n var result = await VerifyPresenceAsync(packageId, cancellationToken)\n .ConfigureAwait(false);\n if (!result.IsVerified)\n return result;\n\n // Extract the version from the additional info\n var installedVersion = (string)((dynamic)result.AdditionalInfo)?.Version;\n if (string.IsNullOrEmpty(installedVersion))\n return VerificationResult.Failure(\n $\"Could not determine installed version for '{packageId}'\",\n \"WinGet\"\n );\n\n // Simple version comparison (this could be enhanced with proper version comparison logic)\n if (!installedVersion.Equals(version, StringComparison.OrdinalIgnoreCase))\n return VerificationResult.Failure(\n $\"Version mismatch for '{packageId}'. Installed: {installedVersion}, Expected: {version}\",\n \"WinGet\"\n );\n\n return result;\n }\n\n private static async Task<(int ExitCode, string Output)> ExecuteWinGetCommandAsync(\n string command,\n string arguments,\n CancellationToken cancellationToken\n )\n {\n var winGetPath = FindWinGetPath();\n if (string.IsNullOrEmpty(winGetPath))\n throw new InvalidOperationException(\n \"WinGet is not installed or could not be found\"\n );\n\n var startInfo = new ProcessStartInfo\n {\n FileName = winGetPath,\n Arguments = $\"{command} {arguments}\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n StandardOutputEncoding = Encoding.UTF8,\n StandardErrorEncoding = Encoding.UTF8,\n };\n\n using (var process = new Process { StartInfo = startInfo })\n using (var outputWaitHandle = new System.Threading.ManualResetEvent(false))\n using (var errorWaitHandle = new System.Threading.ManualResetEvent(false))\n {\n var output = new StringBuilder();\n var error = new StringBuilder();\n\n process.OutputDataReceived += (sender, e) =>\n {\n if (e.Data != null)\n output.AppendLine(e.Data);\n else\n outputWaitHandle.Set();\n };\n\n process.ErrorDataReceived += (sender, e) =>\n {\n if (e.Data != null)\n error.AppendLine(e.Data);\n else\n errorWaitHandle.Set();\n };\n\n process.Start();\n process.BeginOutputReadLine();\n process.BeginErrorReadLine();\n\n // Wait for the process to exit or the cancellation token to be triggered\n await Task.Run(\n () =>\n {\n while (!process.WaitForExit(100))\n {\n if (cancellationToken.IsCancellationRequested)\n {\n try\n {\n process.Kill();\n }\n catch\n { /* Ignore */\n }\n cancellationToken.ThrowIfCancellationRequested();\n }\n }\n },\n cancellationToken\n )\n .ConfigureAwait(false);\n\n outputWaitHandle.WaitOne(TimeSpan.FromSeconds(5));\n errorWaitHandle.WaitOne(TimeSpan.FromSeconds(5));\n\n // If there was an error, include it in the output\n if (!string.IsNullOrWhiteSpace(error.ToString()))\n output.AppendLine(\"Error: \").Append(error);\n\n return (process.ExitCode, output.ToString().Trim());\n }\n }\n\n private static string FindWinGetPath()\n {\n // Check if winget is in the PATH\n var pathEnv = Environment.GetEnvironmentVariable(\"PATH\") ?? string.Empty;\n if (\n pathEnv\n .Split(Path.PathSeparator)\n .Any(p => !string.IsNullOrEmpty(p) && File.Exists(Path.Combine(p, WinGetExe)))\n )\n {\n return WinGetExe;\n }\n\n // Check common installation paths\n foreach (var basePath in WinGetPaths)\n {\n var fullPath = Path.Combine(basePath, WinGetExe);\n if (File.Exists(fullPath))\n return fullPath;\n }\n\n return null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/DialogService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n public class DialogService : IDialogService\n {\n public void ShowMessage(string message, string title = \"\")\n {\n // Use CustomDialog for all messages\n CustomDialog.ShowInformation(title, title, message, \"\");\n }\n\n public Task ShowConfirmationAsync(\n string message,\n string title = \"\",\n string okButtonText = \"OK\",\n string cancelButtonText = \"Cancel\"\n )\n {\n // For regular confirmation messages without app lists\n if (\n !message.Contains(\"following\")\n || (!message.Contains(\"install\") && !message.Contains(\"remove\"))\n )\n {\n return Task.FromResult(\n MessageBox.Show(\n message,\n title,\n MessageBoxButton.YesNo,\n MessageBoxImage.Question\n ) == MessageBoxResult.Yes\n );\n }\n\n // Parse apps from the message\n var lines = message.Split('\\n');\n var apps = lines\n .Where(line => line.StartsWith(\"+\") || line.StartsWith(\"-\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line =>\n line.Contains(\"cannot be\")\n || line.Contains(\"action cannot\")\n || line.Contains(\"Some selected\")\n )\n .Select(line => line.Trim())\n );\n\n var result = CustomDialog.ShowConfirmation(title, headerText, apps, footerText);\n return Task.FromResult(result ?? false);\n }\n\n public Task ShowErrorAsync(string message, string title = \"Error\", string buttonText = \"OK\")\n {\n // Use CustomDialog for all error messages\n CustomDialog.ShowInformation(title, title, message, \"\");\n return Task.CompletedTask;\n }\n\n public Task ShowInformationAsync(\n string message,\n string title = \"Information\",\n string buttonText = \"OK\"\n )\n {\n // For messages with app lists (special handling)\n if (message.Contains(\"following\") && \n (message.Contains(\"installed\") || message.Contains(\"removed\")))\n {\n // Parse apps from the message\n var lines = message.Split('\\n');\n var apps = lines\n .Where(line => line.StartsWith(\"+\") || line.StartsWith(\"-\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line => line.Contains(\"Failed\") || line.Contains(\"startup task\"))\n .Select(line => line.Trim())\n );\n\n CustomDialog.ShowInformation(title, headerText, apps, footerText);\n return Task.CompletedTask;\n }\n \n // For all other information messages, use CustomDialog\n CustomDialog.ShowInformation(title, title, message, \"\");\n return Task.CompletedTask;\n }\n\n public Task ShowWarningAsync(\n string message,\n string title = \"Warning\",\n string buttonText = \"OK\"\n )\n {\n MessageBox.Show(message, title, MessageBoxButton.OK, MessageBoxImage.Warning);\n return Task.CompletedTask;\n }\n\n public Task ShowInputAsync(\n string message,\n string title = \"\",\n string defaultValue = \"\"\n )\n {\n var result = MessageBox.Show(\n message,\n title,\n MessageBoxButton.OKCancel,\n MessageBoxImage.Question\n );\n return Task.FromResult(result == MessageBoxResult.OK ? defaultValue : null);\n }\n\n public Task ShowYesNoCancelAsync(string message, string title = \"\")\n {\n // For theme change messages (special case for \"Choose Your Mode\" combobox)\n if (message.Contains(\"theme wallpaper\") || title.Contains(\"Theme\"))\n {\n // Create a list with a single item for the message\n var messageList = new List { message };\n\n // Use the CustomDialog.ShowConfirmation method (Yes/No only)\n var themeDialogResult = CustomDialog.ShowConfirmation(\n title,\n \"Theme Change\",\n messageList,\n \"\"\n );\n\n // Convert to bool? (Yes/No only, no Cancel)\n return Task.FromResult(themeDialogResult);\n }\n // For regular messages without app lists\n else if (\n !message.Contains(\"following\")\n || (!message.Contains(\"install\") && !message.Contains(\"remove\"))\n )\n {\n var result = MessageBox.Show(\n message,\n title,\n MessageBoxButton.YesNoCancel,\n MessageBoxImage.Question\n );\n bool? boolResult = result switch\n {\n MessageBoxResult.Yes => true,\n MessageBoxResult.No => false,\n _ => null,\n };\n return Task.FromResult(boolResult);\n }\n\n // Parse apps from the message\n var lines = message.Split('\\n');\n var apps = lines\n .Where(line => line.StartsWith(\"+\") || line.StartsWith(\"-\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line =>\n line.Contains(\"cannot be\")\n || line.Contains(\"action cannot\")\n || line.Contains(\"Some selected\")\n )\n .Select(line => line.Trim())\n );\n\n // Use the CustomDialog.ShowYesNoCancel method\n var dialogResult = CustomDialog.ShowYesNoCancel(title, headerText, apps, footerText);\n return Task.FromResult(dialogResult);\n }\n\n public async Task> ShowUnifiedConfigurationSaveDialogAsync(\n string title,\n string description,\n Dictionary sections\n )\n {\n // Create the dialog\n var dialog = new UnifiedConfigurationDialog(title, description, sections, true);\n\n // Set the owner to the current active window\n dialog.Owner = Application.Current.MainWindow;\n\n // Show the dialog\n var result = dialog.ShowDialog();\n\n // Return the result if the user clicked OK, otherwise return null\n if (result == true)\n {\n return dialog.GetResult();\n }\n\n return null;\n }\n\n public async Task> ShowUnifiedConfigurationImportDialogAsync(\n string title,\n string description,\n Dictionary sections\n )\n {\n // Create the dialog\n var dialog = new UnifiedConfigurationDialog(title, description, sections, false);\n\n // Set the owner to the current active window\n dialog.Owner = Application.Current.MainWindow;\n\n // Show the dialog\n var result = dialog.ShowDialog();\n\n // Return the result if the user clicked OK, otherwise return null\n if (result == true)\n {\n return dialog.GetResult();\n }\n\n return null;\n }\n\n /// \n /// Displays a donation dialog.\n /// \n /// The title of the dialog box.\n /// The support message to display.\n /// The footer text.\n /// A task representing the asynchronous operation, with a tuple containing the dialog result (whether the user clicked Yes or No) and whether the \"Don't show again\" checkbox was checked.\n public async Task<(bool? Result, bool DontShowAgain)> ShowDonationDialogAsync(\n string title,\n string supportMessage,\n string footerText\n )\n {\n try\n {\n // Use the DonationDialog.ShowDonationDialogAsync method\n var dialog = await DonationDialog.ShowDonationDialogAsync(\n title,\n supportMessage,\n footerText\n );\n\n // Return the dialog result and the DontShowAgain value as a tuple\n return (dialog?.DialogResult, dialog?.DontShowAgain ?? false);\n }\n catch (Exception ex)\n {\n // Log the error\n System.Diagnostics.Debug.WriteLine($\"Error showing donation dialog: {ex.Message}\");\n return (false, false);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Helpers/InstallationErrorHelper.cs", "using System;\nusing Winhance.Core.Features.SoftwareApps.Enums;\n\nnamespace Winhance.Core.Features.SoftwareApps.Helpers\n{\n /// \n /// Helper class for installation error handling.\n /// \n public static class InstallationErrorHelper\n {\n /// \n /// Gets a user-friendly error message based on the error type.\n /// \n /// The type of installation error.\n /// A user-friendly error message.\n public static string GetUserFriendlyErrorMessage(InstallationErrorType errorType)\n {\n return errorType switch\n {\n InstallationErrorType.NetworkError => \n \"Network connection error. Please check your internet connection and try again.\",\n \n InstallationErrorType.PermissionError => \n \"Permission denied. Please run the application with administrator privileges.\",\n \n InstallationErrorType.PackageNotFoundError => \n \"Package not found. The requested package may not be available in the repositories.\",\n \n InstallationErrorType.WinGetNotInstalledError => \n \"WinGet is not installed and could not be installed automatically.\",\n \n InstallationErrorType.AlreadyInstalledError => \n \"The package is already installed.\",\n \n InstallationErrorType.CancelledByUserError => \n \"The installation was cancelled by the user.\",\n \n InstallationErrorType.SystemStateError => \n \"The system is in a state that prevents installation. Please restart your computer and try again.\",\n \n InstallationErrorType.PackageCorruptedError => \n \"The package is corrupted or invalid. Please try reinstalling or contact the package maintainer.\",\n \n InstallationErrorType.DependencyResolutionError => \n \"The package dependencies could not be resolved. Some required components may be missing.\",\n \n InstallationErrorType.UnknownError or _ => \n \"An unknown error occurred during installation. Please check the logs for more details.\"\n };\n }\n\n /// \n /// Determines the error type based on the exception message.\n /// \n /// The exception message.\n /// The determined error type.\n public static InstallationErrorType DetermineErrorType(string exceptionMessage)\n {\n if (string.IsNullOrEmpty(exceptionMessage))\n return InstallationErrorType.UnknownError;\n\n exceptionMessage = exceptionMessage.ToLowerInvariant();\n\n if (exceptionMessage.Contains(\"network\") || \n exceptionMessage.Contains(\"connection\") || \n exceptionMessage.Contains(\"internet\") ||\n exceptionMessage.Contains(\"timeout\") ||\n exceptionMessage.Contains(\"unreachable\"))\n {\n return InstallationErrorType.NetworkError;\n }\n \n if (exceptionMessage.Contains(\"permission\") || \n exceptionMessage.Contains(\"access\") || \n exceptionMessage.Contains(\"denied\") ||\n exceptionMessage.Contains(\"administrator\") ||\n exceptionMessage.Contains(\"elevation\"))\n {\n return InstallationErrorType.PermissionError;\n }\n \n if (exceptionMessage.Contains(\"not found\") || \n exceptionMessage.Contains(\"no package\") ||\n exceptionMessage.Contains(\"no such package\") ||\n exceptionMessage.Contains(\"could not find\"))\n {\n return InstallationErrorType.PackageNotFoundError;\n }\n \n if (exceptionMessage.Contains(\"winget\") && \n (exceptionMessage.Contains(\"not installed\") || \n exceptionMessage.Contains(\"could not be installed\")))\n {\n return InstallationErrorType.WinGetNotInstalledError;\n }\n \n if (exceptionMessage.Contains(\"already installed\") ||\n exceptionMessage.Contains(\"is installed\"))\n {\n return InstallationErrorType.AlreadyInstalledError;\n }\n \n if (exceptionMessage.Contains(\"cancelled\") || \n exceptionMessage.Contains(\"canceled\") ||\n exceptionMessage.Contains(\"aborted\"))\n {\n return InstallationErrorType.CancelledByUserError;\n }\n \n if (exceptionMessage.Contains(\"system state\") || \n exceptionMessage.Contains(\"restart\") ||\n exceptionMessage.Contains(\"reboot\"))\n {\n return InstallationErrorType.SystemStateError;\n }\n \n if (exceptionMessage.Contains(\"corrupt\") || \n exceptionMessage.Contains(\"invalid\") ||\n exceptionMessage.Contains(\"damaged\"))\n {\n return InstallationErrorType.PackageCorruptedError;\n }\n \n if (exceptionMessage.Contains(\"dependency\") || \n exceptionMessage.Contains(\"dependencies\") ||\n exceptionMessage.Contains(\"requires\"))\n {\n return InstallationErrorType.DependencyResolutionError;\n }\n \n return InstallationErrorType.UnknownError;\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Customize/Services/ThemeService.cs", "using System;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.Customize.Models;\n\nnamespace Winhance.Infrastructure.Features.Customize.Services\n{\n /// \n /// Service for theme-related operations.\n /// \n public class ThemeService : IThemeService\n {\n private readonly IRegistryService _registryService;\n private readonly ILogService _logService;\n private readonly IWallpaperService _wallpaperService;\n private readonly ISystemServices _systemServices;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The registry service.\n /// The log service.\n /// The wallpaper service.\n /// The system services.\n public ThemeService(\n IRegistryService registryService,\n ILogService logService,\n IWallpaperService wallpaperService,\n ISystemServices systemServices)\n {\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _wallpaperService = wallpaperService ?? throw new ArgumentNullException(nameof(wallpaperService));\n _systemServices = systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n }\n\n /// \n public bool IsDarkModeEnabled()\n {\n try\n {\n string keyPath = $\"HKCU\\\\{WindowsThemeSettings.Registry.ThemesPersonalizeSubKey}\";\n var value = _registryService.GetValue(keyPath, WindowsThemeSettings.Registry.AppsUseLightThemeName);\n bool isDarkMode = value != null && (int)value == 0;\n\n _logService.Log(LogLevel.Info, $\"Dark mode check completed. Is Dark Mode: {isDarkMode}\");\n return isDarkMode;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking dark mode status: {ex.Message}\");\n return false;\n }\n }\n\n /// \n public string GetCurrentThemeName()\n {\n return IsDarkModeEnabled() ? \"Dark Mode\" : \"Light Mode\";\n }\n\n /// \n public bool SetThemeMode(bool isDarkMode)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Setting theme mode to {(isDarkMode ? \"dark\" : \"light\")}\");\n\n string keyPath = $\"HKCU\\\\{WindowsThemeSettings.Registry.ThemesPersonalizeSubKey}\";\n int valueToSet = isDarkMode ? 0 : 1;\n\n // Set both registry values\n bool appsSuccess = _registryService.SetValue(\n keyPath,\n WindowsThemeSettings.Registry.AppsUseLightThemeName,\n valueToSet,\n Microsoft.Win32.RegistryValueKind.DWord);\n\n bool systemSuccess = _registryService.SetValue(\n keyPath,\n WindowsThemeSettings.Registry.SystemUsesLightThemeName,\n valueToSet,\n Microsoft.Win32.RegistryValueKind.DWord);\n\n bool success = appsSuccess && systemSuccess;\n if (success)\n {\n _logService.Log(LogLevel.Success, $\"Theme mode set to {(isDarkMode ? \"dark\" : \"light\")}\");\n }\n else\n {\n _logService.Log(LogLevel.Error, \"Failed to set theme mode\");\n }\n\n return success;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting theme mode: {ex.Message}\");\n return false;\n }\n }\n\n /// \n public async Task ApplyThemeAsync(bool isDarkMode, bool changeWallpaper)\n {\n try\n {\n // Apply theme in registry\n bool themeSuccess = SetThemeMode(isDarkMode);\n if (!themeSuccess)\n {\n return false;\n }\n\n // Change wallpaper if requested\n if (changeWallpaper)\n {\n _logService.Log(LogLevel.Info, $\"Changing wallpaper for {(isDarkMode ? \"dark\" : \"light\")} mode\");\n // Check Windows version directly instead of using ISystemServices\n bool isWindows11 = Environment.OSVersion.Version.Build >= 22000;\n await _wallpaperService.SetDefaultWallpaperAsync(isWindows11, isDarkMode);\n }\n\n // Use the improved RefreshWindowsGUI method to refresh the UI\n bool refreshResult = await _systemServices.RefreshWindowsGUI(true);\n if (!refreshResult)\n {\n _logService.Log(LogLevel.Warning, \"Failed to refresh Windows GUI after applying theme\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Theme applied successfully: {(isDarkMode ? \"Dark\" : \"Light\")} Mode\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying theme: {ex.Message}\");\n return false;\n }\n }\n\n /// \n public async Task RefreshGUIAsync(bool restartExplorer)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Refreshing GUI with WindowsSystemService (restartExplorer: {restartExplorer})\");\n \n // Use the improved implementation from WindowsSystemService\n bool result = await _systemServices.RefreshWindowsGUI(restartExplorer);\n \n if (result)\n {\n _logService.Log(LogLevel.Info, \"Windows GUI refresh completed successfully\");\n }\n else\n {\n _logService.Log(LogLevel.Error, \"Failed to refresh Windows GUI\");\n }\n \n return result;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error refreshing GUI: {ex.Message}\");\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/Methods/AppxPackageVerificationMethod.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Management;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods\n{\n /// \n /// Verifies UWP app installations by querying the AppX package manager.\n /// \n public class AppxPackageVerificationMethod : VerificationMethodBase\n {\n /// \n /// Initializes a new instance of the class.\n /// \n public AppxPackageVerificationMethod()\n : base(\"AppxPackage\", priority: 15) { }\n\n /// \n protected override async Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken\n )\n {\n return await Task.Run(\n () =>\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n try\n {\n var packages = GetAppxPackages();\n var matchingPackage = packages.FirstOrDefault(p =>\n p.Name.Equals(packageId, StringComparison.OrdinalIgnoreCase)\n || p.PackageFullName.StartsWith(\n packageId,\n StringComparison.OrdinalIgnoreCase\n )\n );\n\n if (matchingPackage != null)\n {\n return new VerificationResult\n {\n IsVerified = true,\n Message =\n $\"Found UWP package: {matchingPackage.Name} (Version: {matchingPackage.Version})\",\n MethodUsed = \"AppxPackage\",\n AdditionalInfo = matchingPackage,\n };\n }\n\n return VerificationResult.Failure(\n $\"UWP package '{packageId}' not found\"\n );\n }\n catch (Exception ex)\n {\n return VerificationResult.Failure(\n $\"Error checking UWP packages: {ex.Message}\"\n );\n }\n },\n cancellationToken\n )\n .ConfigureAwait(false);\n }\n\n /// \n protected override async Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken\n )\n {\n var result = await VerifyPresenceAsync(packageId, cancellationToken)\n .ConfigureAwait(false);\n if (!result.IsVerified)\n return result;\n\n // Extract the version from the additional info\n var installedVersion = (result.AdditionalInfo as AppxPackageInfo)?.Version;\n if (string.IsNullOrEmpty(installedVersion))\n return VerificationResult.Failure(\n $\"Could not determine installed version for UWP package '{packageId}'\",\n \"AppxPackage\"\n );\n\n // Simple version comparison (this could be enhanced with proper version comparison logic)\n if (!installedVersion.Equals(version, StringComparison.OrdinalIgnoreCase))\n return VerificationResult.Failure(\n $\"Version mismatch for UWP package '{packageId}'. Installed: {installedVersion}, Expected: {version}\",\n \"AppxPackage\"\n );\n\n return result;\n }\n\n private static List GetAppxPackages()\n {\n var packages = new List();\n\n try\n {\n // Method 1: Using Get-AppxPackage via PowerShell (more reliable for current user)\n using (var ps = System.Management.Automation.PowerShell.Create())\n {\n var results = ps.AddCommand(\"Get-AppxPackage\").Invoke();\n foreach (var result in results)\n {\n packages.Add(\n new AppxPackageInfo\n {\n Name = result.Properties[\"Name\"]?.Value?.ToString(),\n PackageFullName = result\n .Properties[\"PackageFullName\"]\n ?.Value?.ToString(),\n Version = result.Properties[\"Version\"]?.Value?.ToString(),\n InstallLocation = result\n .Properties[\"InstallLocation\"]\n ?.Value?.ToString(),\n }\n );\n }\n }\n }\n catch\n {\n // Fall back to WMI if PowerShell fails\n try\n {\n var searcher = new ManagementObjectSearcher(\"SELECT * FROM Win32_Product\");\n foreach (var obj in searcher.Get().Cast())\n {\n packages.Add(\n new AppxPackageInfo\n {\n Name = obj[\"Name\"]?.ToString(),\n Version = obj[\"Version\"]?.ToString(),\n InstallLocation = obj[\"InstallLocation\"]?.ToString(),\n }\n );\n }\n }\n catch\n {\n // If both methods fail, return an empty list\n }\n }\n\n return packages;\n }\n }\n\n /// \n /// Represents information about an AppX package.\n /// \n public class AppxPackageInfo\n {\n /// \n /// Gets or sets the name of the package.\n /// \n public string Name { get; set; }\n\n /// \n /// Gets or sets the full name of the package.\n /// \n public string PackageFullName { get; set; }\n\n /// \n /// Gets or sets the version of the package.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets the installation location of the package.\n /// \n public string InstallLocation { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Models/WindowsApp.cs", "using System;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing System.Linq;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Models\n{\n /// \n /// Represents the type of Windows app.\n /// \n public enum WindowsAppType\n {\n /// \n /// Standard Windows application.\n /// \n StandardApp,\n\n /// \n /// Windows capability.\n /// \n Capability,\n\n /// \n /// Windows optional feature.\n /// \n OptionalFeature,\n }\n\n /// \n /// Represents a Windows built-in application that can be installed or removed.\n /// This includes system components, default Windows apps, and capabilities.\n /// \n public partial class WindowsApp : ObservableObject, IInstallableItem, ISearchable\n {\n public string PackageId => PackageID;\n public string DisplayName => Name;\n public InstallItemType ItemType => AppType switch\n {\n WindowsAppType.Capability => InstallItemType.Capability,\n WindowsAppType.OptionalFeature => InstallItemType.Feature,\n _ => InstallItemType.WindowsApp\n };\n public bool RequiresRestart { get; set; }\n\n // List of package names that cannot be reinstalled via winget/Microsoft Store\n private static readonly string[] NonReinstallablePackages = new string[]\n {\n \"Microsoft.MicrosoftOfficeHub\",\n \"Microsoft.MSPaint\",\n \"Microsoft.Getstarted\",\n };\n\n [ObservableProperty]\n private string _name = string.Empty;\n\n [ObservableProperty]\n private string _description = string.Empty;\n\n [ObservableProperty]\n private string _packageName = string.Empty;\n\n [ObservableProperty]\n private string _packageID = string.Empty;\n\n [ObservableProperty]\n private string _category = string.Empty;\n\n [ObservableProperty]\n private bool _isInstalled;\n\n [ObservableProperty]\n private bool _isSelected;\n\n [ObservableProperty]\n private bool _isSpecialHandler;\n\n [ObservableProperty]\n private string _specialHandlerType = string.Empty;\n\n [ObservableProperty]\n private string[]? _subPackages;\n\n [ObservableProperty]\n private AppRegistrySetting[]? _registrySettings;\n\n [ObservableProperty]\n private bool _isSystemProtected;\n\n [ObservableProperty]\n private bool _isNotReinstallable;\n\n /// \n /// Gets or sets a value indicating whether the item can be reinstalled or reenabled after removal.\n /// \n [ObservableProperty]\n private bool _canBeReinstalled = true;\n\n /// \n /// Gets or sets the type of Windows app.\n /// \n [ObservableProperty]\n private WindowsAppType _appType = WindowsAppType.StandardApp;\n\n /// \n /// Determines if the app should show its description.\n /// \n public bool HasDescription => !string.IsNullOrEmpty(Description);\n\n /// \n /// Gets a value indicating whether this app is a Windows capability.\n /// \n public bool IsCapability => AppType == WindowsAppType.Capability;\n\n /// \n /// Gets a value indicating whether this app is a Windows optional feature.\n /// \n public bool IsOptionalFeature => AppType == WindowsAppType.OptionalFeature;\n\n /// \n /// Creates a WindowsApp instance from an AppInfo model.\n /// \n /// The AppInfo model containing the app's data.\n /// A new WindowsApp instance.\n public static WindowsApp FromAppInfo(AppInfo appInfo)\n {\n // Map AppType to WindowsAppType\n WindowsAppType appType;\n switch (appInfo.Type)\n {\n case Winhance.Core.Features.SoftwareApps.Models.AppType.Capability:\n appType = WindowsAppType.Capability;\n break;\n case Winhance.Core.Features.SoftwareApps.Models.AppType.OptionalFeature:\n appType = WindowsAppType.OptionalFeature;\n break;\n case Winhance.Core.Features.SoftwareApps.Models.AppType.StandardApp:\n default:\n appType = WindowsAppType.StandardApp;\n break;\n }\n\n var app = new WindowsApp\n {\n Name = appInfo.Name,\n Description = appInfo.Description,\n PackageName = appInfo.PackageName,\n PackageID = appInfo.PackageID,\n Category = appInfo.Category,\n IsInstalled = appInfo.IsInstalled,\n IsSpecialHandler = appInfo.RequiresSpecialHandling,\n SpecialHandlerType = appInfo.SpecialHandlerType ?? string.Empty,\n SubPackages = appInfo.SubPackages,\n RegistrySettings = appInfo.RegistrySettings,\n IsSystemProtected = appInfo.IsSystemProtected,\n IsSelected = true,\n CanBeReinstalled = appInfo.CanBeReinstalled,\n AppType = appType,\n };\n\n // Check if this app is in the list of non-reinstallable packages\n app.IsNotReinstallable = Array.Exists(\n NonReinstallablePackages,\n p => p.Equals(appInfo.PackageName, StringComparison.OrdinalIgnoreCase)\n );\n\n return app;\n }\n\n /// \n /// Creates a WindowsApp instance from a CapabilityInfo model.\n /// \n /// The CapabilityInfo model containing the capability's data.\n /// A new WindowsApp instance.\n public static WindowsApp FromCapabilityInfo(CapabilityInfo capabilityInfo)\n {\n var app = new WindowsApp\n {\n Name = capabilityInfo.Name,\n Description = capabilityInfo.Description,\n PackageName = capabilityInfo.PackageName,\n PackageID = capabilityInfo.PackageName, // Ensure PackageID is set for capabilities\n Category = capabilityInfo.Category,\n IsInstalled = capabilityInfo.IsInstalled,\n RegistrySettings = capabilityInfo.RegistrySettings,\n IsSystemProtected = capabilityInfo.IsSystemProtected,\n CanBeReinstalled = capabilityInfo.CanBeReenabled,\n IsSelected = true,\n AppType = WindowsAppType.Capability,\n };\n\n return app;\n }\n\n /// \n /// Creates a WindowsApp instance from a FeatureInfo model.\n /// \n /// The FeatureInfo model containing the feature's data.\n /// A new WindowsApp instance.\n public static WindowsApp FromFeatureInfo(FeatureInfo featureInfo)\n {\n var app = new WindowsApp\n {\n Name = featureInfo.Name,\n Description = featureInfo.Description,\n PackageName = featureInfo.PackageName,\n PackageID = featureInfo.PackageName, // Ensure PackageID is set for features\n Category = featureInfo.Category,\n IsInstalled = featureInfo.IsInstalled,\n RegistrySettings = featureInfo.RegistrySettings,\n IsSystemProtected = featureInfo.IsSystemProtected,\n CanBeReinstalled = featureInfo.CanBeReenabled,\n IsSelected = true,\n AppType = WindowsAppType.OptionalFeature,\n };\n\n return app;\n }\n\n /// \n /// Converts this WindowsApp to an AppInfo object.\n /// \n /// An AppInfo object with data from this WindowsApp.\n public AppInfo ToAppInfo()\n {\n // Map WindowsAppType to AppType\n Winhance.Core.Features.SoftwareApps.Models.AppType appType;\n switch (AppType)\n {\n case WindowsAppType.Capability:\n appType = Winhance.Core.Features.SoftwareApps.Models.AppType.Capability;\n break;\n case WindowsAppType.OptionalFeature:\n appType = Winhance.Core.Features.SoftwareApps.Models.AppType.OptionalFeature;\n break;\n case WindowsAppType.StandardApp:\n default:\n appType = Winhance.Core.Features.SoftwareApps.Models.AppType.StandardApp;\n break;\n }\n\n return new AppInfo\n {\n Name = Name,\n Description = Description,\n PackageName = PackageName,\n PackageID = PackageID,\n Category = Category,\n IsInstalled = IsInstalled,\n RequiresSpecialHandling = IsSpecialHandler,\n SpecialHandlerType = SpecialHandlerType,\n SubPackages = SubPackages,\n RegistrySettings = RegistrySettings,\n IsSystemProtected = IsSystemProtected,\n CanBeReinstalled = CanBeReinstalled,\n Type = appType,\n Version = string.Empty // Default to empty string for version\n };\n }\n \n /// \n /// Converts this WindowsApp to a CapabilityInfo object.\n /// \n /// A CapabilityInfo object with data from this WindowsApp.\n public CapabilityInfo ToCapabilityInfo()\n {\n if (AppType != WindowsAppType.Capability)\n {\n throw new InvalidOperationException(\"Cannot convert non-capability WindowsApp to CapabilityInfo\");\n }\n \n return new CapabilityInfo\n {\n Name = Name,\n Description = Description,\n PackageName = PackageName,\n Category = Category,\n IsInstalled = IsInstalled,\n RegistrySettings = RegistrySettings,\n IsSystemProtected = IsSystemProtected,\n CanBeReenabled = CanBeReinstalled\n };\n }\n \n /// \n /// Converts this WindowsApp to a FeatureInfo object.\n /// \n /// A FeatureInfo object with data from this WindowsApp.\n public FeatureInfo ToFeatureInfo()\n {\n if (AppType != WindowsAppType.OptionalFeature)\n {\n throw new InvalidOperationException(\"Cannot convert non-feature WindowsApp to FeatureInfo\");\n }\n \n return new FeatureInfo\n {\n Name = Name,\n Description = Description,\n PackageName = PackageName,\n Category = Category,\n IsInstalled = IsInstalled,\n RegistrySettings = RegistrySettings,\n IsSystemProtected = IsSystemProtected,\n CanBeReenabled = CanBeReinstalled\n };\n }\n\n /// \n /// Determines if the app matches the given search term.\n /// \n /// The search term to match against.\n /// True if the app matches the search term, false otherwise.\n public bool MatchesSearch(string searchTerm)\n {\n if (string.IsNullOrWhiteSpace(searchTerm))\n {\n return true;\n }\n\n searchTerm = searchTerm.ToLowerInvariant();\n \n // Check if the search term matches any of the searchable properties\n return Name.ToLowerInvariant().Contains(searchTerm) ||\n (!string.IsNullOrEmpty(Description) && Description.ToLowerInvariant().Contains(searchTerm)) ||\n (!string.IsNullOrEmpty(PackageName) && PackageName.ToLowerInvariant().Contains(searchTerm)) ||\n (!string.IsNullOrEmpty(Category) && Category.ToLowerInvariant().Contains(searchTerm));\n }\n\n /// \n /// Gets the searchable properties of the app.\n /// \n /// An array of property names that should be searched.\n public string[] GetSearchableProperties()\n {\n return new[] { nameof(Name), nameof(Description), nameof(PackageName), nameof(Category) };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/UpdateNotificationViewModel.cs", "using System;\nusing System.Threading.Tasks;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n public partial class UpdateNotificationViewModel : ObservableObject\n {\n private readonly IVersionService _versionService;\n private readonly ILogService _logService;\n private readonly IDialogService _dialogService;\n \n [ObservableProperty]\n private string _currentVersion = string.Empty;\n \n [ObservableProperty]\n private string _latestVersion = string.Empty;\n \n [ObservableProperty]\n private bool _isUpdateAvailable;\n \n [ObservableProperty]\n private bool _isDownloading;\n \n [ObservableProperty]\n private string _statusMessage = string.Empty;\n \n public UpdateNotificationViewModel(\n IVersionService versionService,\n ILogService logService,\n IDialogService dialogService)\n {\n _versionService = versionService;\n _logService = logService;\n _dialogService = dialogService;\n \n VersionInfo currentVersion = _versionService.GetCurrentVersion();\n CurrentVersion = currentVersion.Version;\n }\n \n [RelayCommand]\n private async Task CheckForUpdateAsync()\n {\n try\n {\n StatusMessage = \"Checking for updates...\";\n \n VersionInfo latestVersion = await _versionService.CheckForUpdateAsync();\n LatestVersion = latestVersion.Version;\n IsUpdateAvailable = latestVersion.IsUpdateAvailable;\n \n StatusMessage = IsUpdateAvailable \n ? $\"Update available: {LatestVersion}\" \n : \"You have the latest version.\";\n \n return;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking for updates: {ex.Message}\", ex);\n StatusMessage = \"Error checking for updates.\";\n }\n }\n \n [RelayCommand]\n private async Task DownloadAndInstallUpdateAsync()\n {\n if (!IsUpdateAvailable)\n return;\n \n try\n {\n IsDownloading = true;\n StatusMessage = \"Downloading update...\";\n \n await _versionService.DownloadAndInstallUpdateAsync();\n \n StatusMessage = \"Update downloaded. Installing...\";\n \n // Notify the user that the application will close\n await _dialogService.ShowInformationAsync(\n \"The installer has been launched. The application will now close.\",\n \"Update\");\n \n // Close the application\n System.Windows.Application.Current.Shutdown();\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error downloading update: {ex.Message}\", ex);\n StatusMessage = \"Error downloading update.\";\n IsDownloading = false;\n }\n }\n \n [RelayCommand]\n private void RemindLater()\n {\n // Just close the dialog, will check again next time\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppRemovalServiceAdapter.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Adapter class that adapts IAppRemovalService to IInstallationService<AppInfo>.\n /// This is used to maintain backward compatibility with code that expects the AppRemovalService\n /// property of IPackageManager to return an IInstallationService<AppInfo>.\n /// \n public class AppRemovalServiceAdapter : IInstallationService\n {\n private readonly IAppRemovalService _appRemovalService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The app removal service to adapt.\n public AppRemovalServiceAdapter(IAppRemovalService appRemovalService)\n {\n _appRemovalService = appRemovalService ?? throw new ArgumentNullException(nameof(appRemovalService));\n }\n\n /// \n public Task> InstallAsync(\n AppInfo item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n // This is an adapter for removal service, so \"install\" actually means \"remove\"\n return _appRemovalService.RemoveAppAsync(item, progress, cancellationToken);\n }\n\n /// \n public Task> CanInstallAsync(AppInfo item)\n {\n // Since this is an adapter for removal, we'll always return true\n // The actual validation will happen in the RemoveAppAsync method\n return Task.FromResult(OperationResult.Succeeded(true));\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/ViewModelLocator.cs", "using System;\nusing System.Linq;\nusing System.Windows;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Interfaces;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for locating view models in the application.\n /// \n public class ViewModelLocator : IViewModelLocator\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public ViewModelLocator(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Finds a view model of the specified type in the application.\n /// \n /// The type of view model to find.\n /// The view model if found, otherwise null.\n public T? FindViewModel() where T : class\n {\n try\n {\n var app = Application.Current;\n if (app == null) return null;\n\n // Try to find the view model in the main window's DataContext hierarchy\n var mainWindow = app.MainWindow;\n if (mainWindow != null)\n {\n var mainViewModel = FindViewModelInWindow(mainWindow);\n if (mainViewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"Found {typeof(T).Name} in main window's DataContext\");\n return mainViewModel;\n }\n }\n\n // If we can't find it in the main window, try to find it in any open window\n foreach (Window window in app.Windows)\n {\n var viewModel = FindViewModelInWindow(window);\n if (viewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"Found {typeof(T).Name} in window: {window.Title}\");\n return viewModel;\n }\n }\n\n _logService.Log(LogLevel.Warning, $\"Could not find {typeof(T).Name} in any window\");\n return null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error finding view model: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Finds a view model of the specified type in the specified window.\n /// \n /// The type of view model to find.\n /// The window to search in.\n /// The view model if found, otherwise null.\n public T? FindViewModelInWindow(Window window) where T : class\n {\n try\n {\n // Check if the window's DataContext is or contains the view model\n if (window.DataContext is T vm)\n {\n return vm;\n }\n\n // Check if the window's DataContext has a property that is the view model\n if (window.DataContext != null)\n {\n var type = window.DataContext.GetType();\n var properties = type.GetProperties();\n\n foreach (var property in properties)\n {\n if (property.PropertyType == typeof(T))\n {\n return property.GetValue(window.DataContext) as T;\n }\n }\n }\n\n // If not found in the DataContext, search the visual tree\n return FindViewModelInVisualTree(window);\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error finding view model in window: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Finds a view model of the specified type in the visual tree starting from the specified element.\n /// \n /// The type of view model to find.\n /// The starting element.\n /// The view model if found, otherwise null.\n public T? FindViewModelInVisualTree(DependencyObject element) where T : class\n {\n try\n {\n // Check if the element's DataContext is the view model\n if (element is FrameworkElement fe && fe.DataContext is T vm)\n {\n return vm;\n }\n\n // Recursively check children\n int childCount = System.Windows.Media.VisualTreeHelper.GetChildrenCount(element);\n for (int i = 0; i < childCount; i++)\n {\n var child = System.Windows.Media.VisualTreeHelper.GetChild(element, i);\n var result = FindViewModelInVisualTree(child);\n if (result != null)\n {\n return result;\n }\n }\n\n return null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error finding view model in visual tree: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Finds a view model by its name.\n /// \n /// The name of the view model to find.\n /// The view model if found, otherwise null.\n public object? FindViewModelByName(string viewModelName)\n {\n try\n {\n var app = Application.Current;\n if (app == null) return null;\n\n // Try to find the view model in any window's DataContext\n foreach (Window window in app.Windows)\n {\n if (window.DataContext != null)\n {\n var type = window.DataContext.GetType();\n if (type.Name == viewModelName || type.Name == $\"{viewModelName}ViewModel\")\n {\n return window.DataContext;\n }\n\n // Check if the DataContext has a property that is the view model\n var properties = type.GetProperties();\n foreach (var property in properties)\n {\n if (property.Name == viewModelName || property.PropertyType.Name == viewModelName ||\n property.Name == $\"{viewModelName}ViewModel\" || property.PropertyType.Name == $\"{viewModelName}ViewModel\")\n {\n return property.GetValue(window.DataContext);\n }\n }\n }\n }\n\n return null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error finding view model by name: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Gets a property from a view model.\n /// \n /// The type of the property to get.\n /// The view model to get the property from.\n /// The name of the property to get.\n /// The property value if found, otherwise null.\n public T? GetPropertyFromViewModel(object viewModel, string propertyName) where T : class\n {\n try\n {\n var type = viewModel.GetType();\n var property = type.GetProperty(propertyName);\n if (property != null)\n {\n return property.GetValue(viewModel) as T;\n }\n\n return null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting property from view model: {ex.Message}\");\n return null;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Services/DependencyManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Services\n{\n /// \n /// Manages dependencies between settings, ensuring that dependent settings are properly handled\n /// when their required settings change state.\n /// \n public class DependencyManager : IDependencyManager\n {\n private readonly ILogService _logService;\n \n public DependencyManager(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n \n /// \n /// Handles the enabling of a setting by automatically enabling any required settings.\n /// \n /// The ID of the setting that is being enabled.\n /// All available settings that might be required by the enabled setting.\n /// True if all required settings were enabled successfully; otherwise, false.\n public bool HandleSettingEnabled(string settingId, IEnumerable allSettings)\n {\n if (string.IsNullOrEmpty(settingId))\n {\n _logService.Log(LogLevel.Warning, \"Cannot handle dependencies for null or empty setting ID\");\n return false;\n }\n \n var setting = allSettings.FirstOrDefault(s => s.Id == settingId);\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, $\"Setting with ID '{settingId}' not found\");\n return false;\n }\n \n if (setting.Dependencies == null || !setting.Dependencies.Any())\n {\n return true; // No dependencies, so nothing to enable\n }\n \n // Get unsatisfied dependencies\n var unsatisfiedDependencies = GetUnsatisfiedDependencies(settingId, allSettings);\n \n // Enable all dependencies\n return EnableDependencies(unsatisfiedDependencies);\n }\n \n /// \n /// Gets a list of unsatisfied dependencies for a setting.\n /// \n /// The ID of the setting to check.\n /// All available settings that might be dependencies.\n /// A list of settings that are required by the specified setting but are not enabled.\n public List GetUnsatisfiedDependencies(string settingId, IEnumerable allSettings)\n {\n var unsatisfiedDependencies = new List();\n \n if (string.IsNullOrEmpty(settingId))\n {\n _logService.Log(LogLevel.Warning, \"Cannot get dependencies for null or empty setting ID\");\n return unsatisfiedDependencies;\n }\n \n var setting = allSettings.FirstOrDefault(s => s.Id == settingId);\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, $\"Setting with ID '{settingId}' not found\");\n return unsatisfiedDependencies;\n }\n \n if (setting.Dependencies == null || !setting.Dependencies.Any())\n {\n return unsatisfiedDependencies; // No dependencies\n }\n \n // Find all settings that this setting depends on\n foreach (var dependency in setting.Dependencies)\n {\n if (dependency.DependencyType == SettingDependencyType.RequiresEnabled)\n {\n var requiredSetting = allSettings.FirstOrDefault(s => s.Id == dependency.RequiredSettingId);\n if (requiredSetting != null && !requiredSetting.IsSelected)\n {\n unsatisfiedDependencies.Add(requiredSetting);\n }\n }\n }\n \n return unsatisfiedDependencies;\n }\n \n /// \n /// Enables all dependencies in the provided list.\n /// \n /// The dependencies to enable.\n /// True if all dependencies were enabled successfully; otherwise, false.\n public bool EnableDependencies(IEnumerable dependencies)\n {\n bool allSucceeded = true;\n \n foreach (var dependency in dependencies)\n {\n _logService.Log(LogLevel.Info, $\"Automatically enabling dependency: {dependency.Name}\");\n \n // Enable the dependency\n dependency.IsUpdatingFromCode = true;\n try\n {\n dependency.IsSelected = true;\n }\n finally\n {\n dependency.IsUpdatingFromCode = false;\n }\n \n // Apply the setting\n dependency.ApplySettingCommand?.Execute(null);\n \n // Check if the setting was successfully enabled\n if (!dependency.IsSelected)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to enable required setting '{dependency.Name}'\");\n allSucceeded = false;\n }\n }\n \n return allSucceeded;\n }\n \n /// \n /// Determines if a setting can be enabled based on its dependencies.\n /// \n /// The ID of the setting to check.\n /// All available settings that might be dependencies.\n /// True if the setting can be enabled; otherwise, false.\n public bool CanEnableSetting(string settingId, IEnumerable allSettings)\n {\n if (string.IsNullOrEmpty(settingId))\n {\n _logService.Log(LogLevel.Warning, \"Cannot check dependencies for null or empty setting ID\");\n return false;\n }\n \n var setting = allSettings.FirstOrDefault(s => s.Id == settingId);\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, $\"Setting with ID '{settingId}' not found\");\n return false;\n }\n \n if (setting.Dependencies == null || !setting.Dependencies.Any())\n {\n return true; // No dependencies, so it can be enabled\n }\n \n foreach (var dependency in setting.Dependencies)\n {\n if (dependency.DependencyType == SettingDependencyType.RequiresEnabled)\n {\n var requiredSetting = allSettings.FirstOrDefault(s => s.Id == dependency.RequiredSettingId);\n if (requiredSetting != null && !requiredSetting.IsSelected)\n {\n _logService.Log(LogLevel.Warning, $\"Cannot enable '{setting.Name}' because '{requiredSetting.Name}' is disabled\");\n return false;\n }\n }\n else if (dependency.DependencyType == SettingDependencyType.RequiresDisabled)\n {\n var requiredSetting = allSettings.FirstOrDefault(s => s.Id == dependency.RequiredSettingId);\n if (requiredSetting != null && requiredSetting.IsSelected)\n {\n _logService.Log(LogLevel.Warning, $\"Cannot enable '{setting.Name}' because '{requiredSetting.Name}' is enabled\");\n return false;\n }\n }\n }\n \n return true;\n }\n \n /// \n /// Handles the disabling of a setting by automatically disabling any dependent settings.\n /// \n /// The ID of the setting that was disabled.\n /// All available settings that might depend on the disabled setting.\n public void HandleSettingDisabled(string settingId, IEnumerable allSettings)\n {\n if (string.IsNullOrEmpty(settingId))\n {\n _logService.Log(LogLevel.Warning, \"Cannot handle dependencies for null or empty setting ID\");\n return;\n }\n \n // Find all settings that depend on this setting\n var dependentSettings = allSettings.Where(s => \n s.Dependencies != null && \n s.Dependencies.Any(d => d.RequiredSettingId == settingId && \n d.DependencyType == SettingDependencyType.RequiresEnabled));\n \n foreach (var dependentSetting in dependentSettings)\n {\n if (dependentSetting.IsSelected)\n {\n _logService.Log(LogLevel.Info, $\"Automatically disabling '{dependentSetting.Name}' as '{settingId}' was disabled\");\n \n // Disable the dependent setting\n dependentSetting.IsUpdatingFromCode = true;\n try\n {\n dependentSetting.IsSelected = false;\n }\n finally\n {\n dependentSetting.IsUpdatingFromCode = false;\n }\n \n // Apply the change\n dependentSetting.ApplySettingCommand?.Execute(null);\n \n // Recursively handle any settings that depend on this one\n HandleSettingDisabled(dependentSetting.Id, allSettings);\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/SoftwareAppsViewModel.cs", "using System;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n /// \n /// ViewModel for the SoftwareAppsView that coordinates WindowsApps and ExternalApps sections.\n /// \n public partial class SoftwareAppsViewModel : BaseViewModel\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly IPackageManager _packageManager;\n\n [ObservableProperty]\n private string _statusText =\n \"Manage Windows Apps, Capabilities & Features and Install External Software\";\n\n [ObservableProperty]\n private WindowsAppsViewModel _windowsAppsViewModel;\n\n [ObservableProperty]\n private ExternalAppsViewModel _externalAppsViewModel;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The package manager.\n /// The service provider for dependency resolution.\n public SoftwareAppsViewModel(\n ITaskProgressService progressService,\n IPackageManager packageManager,\n IServiceProvider serviceProvider\n )\n : base(progressService)\n {\n _packageManager =\n packageManager ?? throw new ArgumentNullException(nameof(packageManager));\n _serviceProvider =\n serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n\n // Resolve the dependencies via DI container\n WindowsAppsViewModel = _serviceProvider.GetRequiredService();\n ExternalAppsViewModel = _serviceProvider.GetRequiredService();\n }\n\n /// \n /// Initializes child view models and prepares the view.\n /// \n [RelayCommand]\n public async Task Initialize()\n {\n StatusText = \"Initializing Software Apps...\";\n IsLoading = true;\n\n try\n {\n // Initialize WindowsAppsViewModel if not already initialized\n if (!WindowsAppsViewModel.IsInitialized)\n {\n await WindowsAppsViewModel.LoadAppsAndCheckInstallationStatusAsync();\n }\n\n // Initialize ExternalAppsViewModel if not already initialized\n if (!ExternalAppsViewModel.IsInitialized)\n {\n await ExternalAppsViewModel.LoadAppsAndCheckInstallationStatusAsync();\n }\n\n StatusText =\n \"Manage Windows Apps, Capabilities & Features and Install External Software\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Error initializing: {ex.Message}\";\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Called when the view is navigated to.\n /// \n /// Navigation parameter.\n public override async void OnNavigatedTo(object parameter)\n {\n try\n {\n // Initialize when navigated to this view\n await Initialize();\n }\n catch (Exception ex)\n {\n StatusText = $\"Error during navigation: {ex.Message}\";\n // Log the error or handle it appropriately\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Utilities/WindowSizeManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Interop;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.Common.Utilities;\n\nnamespace Winhance.WPF.Features.Common.Utilities\n{\n /// \n /// Manages window size and position, including dynamic sizing based on screen resolution\n /// and handling multiple monitors and DPI scaling.\n /// \n public class WindowSizeManager\n {\n private readonly Window _window;\n private readonly ILogService _logService;\n\n // Default window dimensions\n private const double DEFAULT_WIDTH = 1600;\n private const double DEFAULT_HEIGHT = 900;\n private const double MIN_WIDTH = 1024;\n private const double MIN_HEIGHT = 700; // Reduced minimum height to fit better on smaller screens\n private const double SCREEN_PERCENTAGE = 0.9; // Use 90% of screen size for better fit\n\n public WindowSizeManager(Window window, UserPreferencesService userPreferencesService, ILogService logService)\n {\n _window = window ?? throw new ArgumentNullException(nameof(window));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n \n // No events registered - we don't save window position anymore\n }\n\n /// \n /// Initializes the window size and position\n /// \n public void Initialize()\n {\n try\n {\n // Set dynamic window size based on screen resolution (75% of screen)\n SetDynamicWindowSize();\n \n // Always center the window on screen\n // This ensures consistent behavior regardless of WindowStartupLocation\n CenterWindowOnScreen();\n \n LogDebug($\"Window initialized with size: {_window.Width}x{_window.Height}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error initializing window size manager: {ex.Message}\", ex);\n }\n }\n \n /// \n /// Centers the window on the current screen\n /// \n private void CenterWindowOnScreen()\n {\n try\n {\n // Get the current screen's working area\n var workArea = GetCurrentScreenWorkArea();\n \n // Get DPI scaling factor\n double dpiScaleX = 1.0;\n double dpiScaleY = 1.0;\n \n try\n {\n var presentationSource = PresentationSource.FromVisual(_window);\n if (presentationSource?.CompositionTarget != null)\n {\n dpiScaleX = presentationSource.CompositionTarget.TransformToDevice.M11;\n dpiScaleY = presentationSource.CompositionTarget.TransformToDevice.M22;\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting DPI scale: {ex.Message}\", ex);\n }\n \n // Convert screen coordinates to account for DPI\n double screenWidth = workArea.Width / dpiScaleX;\n double screenHeight = workArea.Height / dpiScaleY;\n double screenLeft = workArea.X / dpiScaleX;\n double screenTop = workArea.Y / dpiScaleY;\n \n // Calculate center position\n double left = screenLeft + (screenWidth - _window.Width) / 2;\n double top = screenTop + (screenHeight - _window.Height) / 2;\n \n // Set window position\n _window.Left = left;\n _window.Top = top;\n \n LogDebug($\"Window explicitly centered at: Left={left}, Top={top}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error centering window: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Sets the window size dynamically based on the screen resolution\n /// \n private void SetDynamicWindowSize()\n {\n try\n {\n LogDebug(\"Setting dynamic window size\");\n \n // Get the current screen's working area (excludes taskbar)\n var workArea = GetCurrentScreenWorkArea();\n \n // Get DPI scaling factor for the current screen\n double dpiScaleX = 1.0;\n double dpiScaleY = 1.0;\n \n try\n {\n var presentationSource = PresentationSource.FromVisual(_window);\n if (presentationSource?.CompositionTarget != null)\n {\n dpiScaleX = presentationSource.CompositionTarget.TransformToDevice.M11;\n dpiScaleY = presentationSource.CompositionTarget.TransformToDevice.M22;\n LogDebug($\"DPI scale factors: X={dpiScaleX}, Y={dpiScaleY}\");\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting DPI scale: {ex.Message}\", ex);\n }\n \n // Calculate available screen space\n double screenWidth = workArea.Width / dpiScaleX;\n double screenHeight = workArea.Height / dpiScaleY;\n \n // Calculate window size (75% of screen size with minimum/maximum constraints)\n double windowWidth = Math.Min(DEFAULT_WIDTH, screenWidth * SCREEN_PERCENTAGE);\n double windowHeight = Math.Min(DEFAULT_HEIGHT, screenHeight * SCREEN_PERCENTAGE);\n \n // Ensure minimum size for usability\n windowWidth = Math.Max(windowWidth, MIN_WIDTH);\n windowHeight = Math.Max(windowHeight, MIN_HEIGHT);\n \n // Only set the window size, let WPF handle the centering via WindowStartupLocation=\"CenterScreen\"\n _window.Width = windowWidth;\n _window.Height = windowHeight;\n \n LogDebug($\"Dynamic window size set to: Width={windowWidth}, Height={windowHeight}\");\n LogDebug($\"Screen dimensions: Width={screenWidth}, Height={screenHeight}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error setting dynamic window size: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Gets the working area of the screen that contains the window\n /// \n private Rect GetCurrentScreenWorkArea()\n {\n try\n {\n // Get the window handle\n var windowHandle = new WindowInteropHelper(_window).Handle;\n if (windowHandle != IntPtr.Zero)\n {\n // Get the monitor info for the monitor containing the window\n var monitorInfo = new MONITORINFO();\n monitorInfo.cbSize = Marshal.SizeOf(typeof(MONITORINFO));\n \n if (GetMonitorInfo(MonitorFromWindow(windowHandle, MONITOR_DEFAULTTONEAREST), ref monitorInfo))\n {\n // Convert the working area to a WPF Rect\n return new Rect(\n monitorInfo.rcWork.left,\n monitorInfo.rcWork.top,\n monitorInfo.rcWork.right - monitorInfo.rcWork.left,\n monitorInfo.rcWork.bottom - monitorInfo.rcWork.top);\n }\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting current screen: {ex.Message}\", ex);\n }\n \n // Fallback to primary screen working area\n return SystemParameters.WorkArea;\n }\n\n // Event handlers for window state, location, and size changes have been removed\n // as we no longer save window position/size to preferences\n\n /// \n /// Logs a debug message\n /// \n private void LogDebug(string message, Exception ex = null)\n {\n try\n {\n _logService?.Log(LogLevel.Debug, message, ex);\n \n // Also log to file logger for troubleshooting\n FileLogger.Log(\"WindowSizeManager\", message + (ex != null ? $\" - Exception: {ex.Message}\" : \"\"));\n }\n catch\n {\n // Ignore logging errors\n }\n }\n\n #region Win32 API\n\n [DllImport(\"user32.dll\")]\n private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);\n \n [DllImport(\"user32.dll\")]\n private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);\n \n private const uint MONITOR_DEFAULTTONEAREST = 2;\n \n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int left;\n public int top;\n public int right;\n public int bottom;\n }\n \n [StructLayout(LayoutKind.Sequential)]\n private struct MONITORINFO\n {\n public int cbSize;\n public RECT rcMonitor;\n public RECT rcWork;\n public uint dwFlags;\n }\n\n #endregion\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/ProgressIndicator.cs", "using System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// A custom control that displays a progress indicator with status text.\n /// \n public class ProgressIndicator : Control\n {\n static ProgressIndicator()\n {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(ProgressIndicator), new FrameworkPropertyMetadata(typeof(ProgressIndicator)));\n }\n \n /// \n /// When overridden in a derived class, is invoked whenever application code or internal processes call .\n /// \n public override void OnApplyTemplate()\n {\n base.OnApplyTemplate();\n \n // Find the cancel button in the template and hook up the event handler\n if (GetTemplateChild(\"PART_CancelButton\") is Button cancelButton)\n {\n cancelButton.Click -= CancelButton_Click;\n cancelButton.Click += CancelButton_Click;\n }\n }\n \n private void CancelButton_Click(object sender, RoutedEventArgs e)\n {\n // Log the button click for debugging\n System.Diagnostics.Debug.WriteLine(\"Cancel button clicked\");\n \n // First try to execute the command if it exists\n if (CancelCommand != null && CancelCommand.CanExecute(null))\n {\n System.Diagnostics.Debug.WriteLine(\"Executing cancel command\");\n CancelCommand.Execute(null);\n return;\n }\n \n // If command execution fails, use a more direct approach\n System.Diagnostics.Debug.WriteLine(\"Command execution failed, trying direct approach\");\n CancelCurrentTaskDirectly();\n }\n \n /// \n /// Directly cancels the current task by finding the TaskProgressService instance.\n /// \n private void CancelCurrentTaskDirectly()\n {\n try\n {\n // Get the application's main window\n var mainWindow = System.Windows.Application.Current.MainWindow;\n if (mainWindow == null)\n {\n System.Diagnostics.Debug.WriteLine(\"Main window not found\");\n return;\n }\n \n // Get the DataContext of the main window (should be the MainViewModel)\n var mainViewModel = mainWindow.DataContext;\n if (mainViewModel == null)\n {\n System.Diagnostics.Debug.WriteLine(\"Main window DataContext is null\");\n return;\n }\n \n // Use reflection to get the _progressService field\n var type = mainViewModel.GetType();\n var field = type.GetField(\"_progressService\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n \n if (field != null)\n {\n var progressService = field.GetValue(mainViewModel) as Winhance.Core.Features.Common.Interfaces.ITaskProgressService;\n if (progressService != null)\n {\n System.Diagnostics.Debug.WriteLine(\"Found progress service, cancelling task\");\n progressService.CancelCurrentTask();\n \n // Show a message to the user that the task was cancelled\n System.Windows.MessageBox.Show(\"Installation cancelled by user.\", \"Cancelled\", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);\n }\n else\n {\n System.Diagnostics.Debug.WriteLine(\"Progress service is null\");\n }\n }\n else\n {\n System.Diagnostics.Debug.WriteLine(\"_progressService field not found\");\n }\n }\n catch (Exception ex)\n {\n System.Diagnostics.Debug.WriteLine($\"Error in CancelCurrentTaskDirectly: {ex.Message}\");\n }\n }\n\n #region Dependency Properties\n\n /// \n /// Gets or sets the progress value (0-100).\n /// \n public double Progress\n {\n get { return (double)GetValue(ProgressProperty); }\n set { SetValue(ProgressProperty, value); }\n }\n\n /// \n /// Identifies the Progress dependency property.\n /// \n public static readonly DependencyProperty ProgressProperty =\n DependencyProperty.Register(nameof(Progress), typeof(double), typeof(ProgressIndicator), \n new PropertyMetadata(0.0, OnProgressChanged));\n\n /// \n /// Gets or sets the status text.\n /// \n public string StatusText\n {\n get { return (string)GetValue(StatusTextProperty); }\n set { SetValue(StatusTextProperty, value); }\n }\n\n /// \n /// Identifies the StatusText dependency property.\n /// \n public static readonly DependencyProperty StatusTextProperty =\n DependencyProperty.Register(nameof(StatusText), typeof(string), typeof(ProgressIndicator), \n new PropertyMetadata(string.Empty));\n\n /// \n /// Gets or sets whether the progress is indeterminate.\n /// \n public bool IsIndeterminate\n {\n get { return (bool)GetValue(IsIndeterminateProperty); }\n set { SetValue(IsIndeterminateProperty, value); }\n }\n\n /// \n /// Identifies the IsIndeterminate dependency property.\n /// \n public static readonly DependencyProperty IsIndeterminateProperty =\n DependencyProperty.Register(nameof(IsIndeterminate), typeof(bool), typeof(ProgressIndicator), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets whether the control is active.\n /// \n public bool IsActive\n {\n get { return (bool)GetValue(IsActiveProperty); }\n set { SetValue(IsActiveProperty, value); }\n }\n\n /// \n /// Identifies the IsActive dependency property.\n /// \n public static readonly DependencyProperty IsActiveProperty =\n DependencyProperty.Register(nameof(IsActive), typeof(bool), typeof(ProgressIndicator), \n new PropertyMetadata(false));\n\n /// \n /// Gets the progress text (e.g., \"50%\").\n /// \n public string ProgressText\n {\n get { return (string)GetValue(ProgressTextProperty); }\n private set { SetValue(ProgressTextProperty, value); }\n }\n\n /// \n /// Identifies the ProgressText dependency property.\n /// \n public static readonly DependencyProperty ProgressTextProperty =\n DependencyProperty.Register(nameof(ProgressText), typeof(string), typeof(ProgressIndicator), \n new PropertyMetadata(string.Empty));\n \n /// \n /// Gets or sets the command to execute when the cancel button is clicked.\n /// \n public ICommand CancelCommand\n {\n get { return (ICommand)GetValue(CancelCommandProperty); }\n set { SetValue(CancelCommandProperty, value); }\n }\n\n /// \n /// Identifies the CancelCommand dependency property.\n /// \n public static readonly DependencyProperty CancelCommandProperty =\n DependencyProperty.Register(nameof(CancelCommand), typeof(ICommand), typeof(ProgressIndicator), \n new PropertyMetadata(null));\n \n /// \n /// Gets or sets whether to show the cancel button instead of progress text.\n /// \n public bool ShowCancelButton\n {\n get { return (bool)GetValue(ShowCancelButtonProperty); }\n set { SetValue(ShowCancelButtonProperty, value); }\n }\n\n /// \n /// Identifies the ShowCancelButton dependency property.\n /// \n public static readonly DependencyProperty ShowCancelButtonProperty =\n DependencyProperty.Register(nameof(ShowCancelButton), typeof(bool), typeof(ProgressIndicator), \n new PropertyMetadata(false));\n\n #endregion\n\n private static void OnProgressChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is ProgressIndicator control)\n {\n control.UpdateProgressText();\n }\n }\n\n private void UpdateProgressText()\n {\n if (IsIndeterminate || ShowCancelButton)\n {\n ProgressText = string.Empty;\n }\n else\n {\n ProgressText = $\"{Progress:F0}%\";\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceEnsureKey.cs", "using Microsoft.Win32;\nusing System;\nusing System.Runtime.InteropServices;\nusing System.Security.AccessControl;\nusing System.Security.Principal;\nusing System.Threading.Tasks;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n public partial class RegistryService\n {\n // Windows API imports for registry operations\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int RegOpenKeyEx(IntPtr hKey, string subKey, int ulOptions, int samDesired, out IntPtr hkResult);\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int RegCloseKey(IntPtr hKey);\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int RegGetKeySecurity(IntPtr hKey, int securityInformation, byte[] pSecurityDescriptor, ref int lpcbSecurityDescriptor);\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int RegSetKeySecurity(IntPtr hKey, int securityInformation, byte[] pSecurityDescriptor);\n\n // Constants for Windows API\n private const int KEY_ALL_ACCESS = 0xF003F;\n private const int OWNER_SECURITY_INFORMATION = 0x00000001;\n private const int DACL_SECURITY_INFORMATION = 0x00000004;\n private const int ERROR_SUCCESS = 0;\n\n // Root key handles\n private static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(-2147483647);\n private static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(-2147483646);\n private static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(-2147483648);\n private static readonly IntPtr HKEY_USERS = new IntPtr(-2147483645);\n private static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(-2147483643);\n\n /// \n /// Takes ownership of a registry key and grants full control to the current user.\n /// \n /// The root registry key.\n /// The path to the subkey.\n /// True if ownership was successfully taken, false otherwise.\n private bool TakeOwnershipOfKey(RegistryKey rootKey, string subKeyPath)\n {\n try\n {\n _logService.LogInformation($\"Attempting to take ownership of registry key: {rootKey.Name}\\\\{subKeyPath}\");\n\n // Get the root key handle\n IntPtr hRootKey = GetRootKeyHandle(rootKey);\n if (hRootKey == IntPtr.Zero)\n {\n _logService.LogError(\"Invalid root key handle\");\n return false;\n }\n\n // Open the key with special permissions\n IntPtr hKey;\n int result = RegOpenKeyEx(hRootKey, subKeyPath, 0, KEY_ALL_ACCESS, out hKey);\n if (result != ERROR_SUCCESS)\n {\n _logService.LogError($\"Failed to open registry key for ownership change: {result}\");\n return false;\n }\n\n try\n {\n // Get the current security descriptor\n int securityDescriptorSize = 0;\n RegGetKeySecurity(hKey, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, null, ref securityDescriptorSize);\n byte[] securityDescriptor = new byte[securityDescriptorSize];\n result = RegGetKeySecurity(hKey, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, securityDescriptor, ref securityDescriptorSize);\n if (result != ERROR_SUCCESS)\n {\n _logService.LogError($\"Failed to get registry key security: {result}\");\n return false;\n }\n\n // Create a new security descriptor\n RawSecurityDescriptor rawSD = new RawSecurityDescriptor(securityDescriptor, 0);\n \n // Set the owner to the current user\n WindowsIdentity currentUser = WindowsIdentity.GetCurrent();\n rawSD.Owner = currentUser.User;\n\n // Create a new DACL\n RawAcl rawAcl = rawSD.DiscretionaryAcl != null ?\n rawSD.DiscretionaryAcl :\n new RawAcl(8, 1);\n\n // Add access rules\n // Current user\n if (currentUser.User != null)\n {\n rawAcl.InsertAce(0, new CommonAce(\n AceFlags.None,\n AceQualifier.AccessAllowed,\n (int)RegistryRights.FullControl,\n currentUser.User,\n false,\n null));\n }\n\n // Administrators\n rawAcl.InsertAce(0, new CommonAce(\n AceFlags.None,\n AceQualifier.AccessAllowed,\n (int)RegistryRights.FullControl,\n new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),\n false,\n null));\n\n // SYSTEM\n rawAcl.InsertAce(0, new CommonAce(\n AceFlags.None,\n AceQualifier.AccessAllowed,\n (int)RegistryRights.FullControl,\n new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),\n false,\n null));\n\n // Set the DACL\n rawSD.DiscretionaryAcl = rawAcl;\n\n // Convert back to byte array\n byte[] newSD = new byte[rawSD.BinaryLength];\n rawSD.GetBinaryForm(newSD, 0);\n\n // Set the new security descriptor\n result = RegSetKeySecurity(hKey, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, newSD);\n if (result != ERROR_SUCCESS)\n {\n _logService.LogError($\"Failed to set registry key security: {result}\");\n return false;\n }\n\n _logService.LogSuccess($\"Successfully took ownership of registry key: {rootKey.Name}\\\\{subKeyPath}\");\n return true;\n }\n finally\n {\n // Close the key\n RegCloseKey(hKey);\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error taking ownership of registry key: {ex.Message}\", ex);\n return false;\n }\n }\n\n /// \n /// Gets the native handle for a root registry key.\n /// \n private IntPtr GetRootKeyHandle(RegistryKey rootKey)\n {\n if (rootKey == Microsoft.Win32.Registry.CurrentUser)\n return HKEY_CURRENT_USER;\n else if (rootKey == Microsoft.Win32.Registry.LocalMachine)\n return HKEY_LOCAL_MACHINE;\n else if (rootKey == Microsoft.Win32.Registry.ClassesRoot)\n return HKEY_CLASSES_ROOT;\n else if (rootKey == Microsoft.Win32.Registry.Users)\n return HKEY_USERS;\n else if (rootKey == Microsoft.Win32.Registry.CurrentConfig)\n return HKEY_CURRENT_CONFIG;\n else\n return IntPtr.Zero;\n }\n\n private RegistryKey? EnsureKeyWithFullAccess(RegistryKey rootKey, string subKeyPath)\n {\n try\n {\n // Try to open existing key first\n RegistryKey? key = rootKey.OpenSubKey(subKeyPath, true);\n \n if (key != null)\n {\n return key; // Key exists and we got write access\n }\n \n // Check if the key exists but we don't have access\n RegistryKey? readOnlyKey = rootKey.OpenSubKey(subKeyPath, false);\n if (readOnlyKey != null)\n {\n // Key exists but we don't have write access, try to take ownership\n readOnlyKey.Close();\n _logService.LogInformation($\"Registry key exists but we don't have write access: {rootKey.Name}\\\\{subKeyPath}\");\n \n // Try to take ownership of the key\n bool ownershipTaken = TakeOwnershipOfKey(rootKey, subKeyPath);\n if (ownershipTaken)\n {\n // Try to open the key again with write access\n key = rootKey.OpenSubKey(subKeyPath, true);\n if (key != null)\n {\n _logService.LogSuccess($\"Successfully opened registry key after taking ownership: {rootKey.Name}\\\\{subKeyPath}\");\n return key;\n }\n }\n \n _logService.LogWarning($\"Failed to get write access to registry key even after taking ownership: {rootKey.Name}\\\\{subKeyPath}\");\n }\n \n // Key doesn't exist or we couldn't get access - we need to create the entire path\n string[] parts = subKeyPath.Split('\\\\');\n string currentPath = \"\";\n \n for (int i = 0; i < parts.Length; i++)\n {\n string part = parts[i];\n \n if (currentPath == \"\")\n {\n currentPath = part;\n }\n else\n {\n currentPath += \"\\\\\" + part;\n }\n \n // Try to open this part of the path\n key = rootKey.OpenSubKey(currentPath, true);\n \n if (key == null)\n {\n // This part doesn't exist, create it with full rights\n RegistrySecurity security = new RegistrySecurity();\n \n // Get current user security identifier - handle null case\n var currentUser = WindowsIdentity.GetCurrent().User;\n if (currentUser != null)\n {\n // Add current user with full control\n security.AddAccessRule(new RegistryAccessRule(\n currentUser,\n RegistryRights.FullControl,\n InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,\n PropagationFlags.None,\n AccessControlType.Allow));\n }\n \n // Add Administrators with full control\n security.AddAccessRule(new RegistryAccessRule(\n new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),\n RegistryRights.FullControl,\n InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,\n PropagationFlags.None,\n AccessControlType.Allow));\n \n // Add SYSTEM with full control\n security.AddAccessRule(new RegistryAccessRule(\n new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),\n RegistryRights.FullControl,\n InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,\n PropagationFlags.None,\n AccessControlType.Allow));\n \n // Create the key with explicit security settings\n key = rootKey.CreateSubKey(currentPath, RegistryKeyPermissionCheck.ReadWriteSubTree, security);\n \n if (key == null)\n {\n _logService.LogError($\"Failed to create registry key: {currentPath}\");\n return null;\n }\n \n // Close intermediate keys to avoid leaks\n if (i < parts.Length - 1)\n {\n key.Close();\n key = null;\n }\n }\n else if (i < parts.Length - 1)\n {\n // Close intermediate keys to avoid leaks\n key.Close();\n key = null;\n }\n }\n \n // At this point, 'key' should be the full path key we wanted to create\n // If it's null, open the full path explicitly\n if (key == null)\n {\n key = rootKey.OpenSubKey(subKeyPath, true);\n }\n \n return key;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error ensuring registry key with full access: {subKeyPath}\", ex);\n return null;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceStatusMethods.cs", "using Microsoft.Win32;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n public partial class RegistryService\n {\n public async Task GetSettingStatusAsync(RegistrySetting setting)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return RegistrySettingStatus.Error;\n }\n\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot get status for null registry setting\");\n return RegistrySettingStatus.Unknown;\n }\n\n string hiveString = RegistryExtensions.GetRegistryHiveString(setting.Hive);\n string fullPath = $\"{hiveString}\\\\{setting.SubKey}\";\n string fullValuePath = $\"{fullPath}\\\\{setting.Name}\";\n\n _logService.Log(LogLevel.Info, $\"Checking registry setting status: {fullValuePath}\");\n\n // Check if the key exists (using cache)\n bool keyExists;\n lock (_keyExistsCache)\n {\n if (!_keyExistsCache.TryGetValue(fullPath, out keyExists))\n {\n keyExists = KeyExists(fullPath);\n _keyExistsCache[fullPath] = keyExists;\n }\n }\n\n // Handle non-existence of the key\n if (!keyExists)\n {\n // For Remove actions, non-existence of the key is considered \"Applied\"\n if (setting.ActionType == RegistryActionType.Remove)\n {\n return RegistrySettingStatus.Applied;\n }\n\n // For settings where absence means enabled (like HttpAcceptLanguageOptOut)\n if (setting.AbsenceMeansEnabled)\n {\n _logService.Log(LogLevel.Info, $\"Key does not exist and AbsenceMeansEnabled is true - marking as Applied\");\n return RegistrySettingStatus.Applied;\n }\n\n // Default behavior: absence means not applied\n return RegistrySettingStatus.NotApplied;\n }\n\n // Check if the value exists (using cache)\n bool valueExists;\n lock (_valueExistsCache)\n {\n if (!_valueExistsCache.TryGetValue(fullValuePath, out valueExists))\n {\n valueExists = ValueExists(fullPath, setting.Name);\n _valueExistsCache[fullValuePath] = valueExists;\n }\n }\n\n // Handle non-existence of the value\n if (!valueExists)\n {\n // For Remove actions, non-existence of the value is considered \"Applied\"\n if (setting.ActionType == RegistryActionType.Remove)\n {\n return RegistrySettingStatus.Applied;\n }\n\n // For settings where absence means enabled (like HttpAcceptLanguageOptOut)\n if (setting.AbsenceMeansEnabled)\n {\n _logService.Log(LogLevel.Info, $\"Value does not exist and AbsenceMeansEnabled is true - marking as Applied\");\n return RegistrySettingStatus.Applied;\n }\n\n // Default behavior: absence means not applied\n return RegistrySettingStatus.NotApplied;\n }\n\n // If we're here and the action type is Remove, the key/value still exists\n if (setting.ActionType == RegistryActionType.Remove)\n {\n // Special case for 3D Objects toggle which is opposite of normal Remove action\n // When the key exists, 3D Objects is shown (Applied)\n if (setting.Name == \"{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}\")\n {\n _logService.Log(LogLevel.Info, $\"3D Objects key exists - marking as Applied\");\n return RegistrySettingStatus.Applied;\n }\n \n // For normal Remove actions, key existing means not applied\n return RegistrySettingStatus.NotApplied;\n }\n\n // Get the current value (using cache)\n object? currentValue;\n lock (_valueCache)\n {\n if (!_valueCache.TryGetValue(fullValuePath, out currentValue))\n {\n currentValue = GetValue(fullPath, setting.Name);\n _valueCache[fullValuePath] = currentValue;\n }\n }\n\n // If the value is null, consider it not applied\n if (currentValue == null)\n {\n return RegistrySettingStatus.NotApplied;\n }\n\n // Compare with enabled value (use EnabledValue if available, otherwise fall back to RecommendedValue)\n object valueToCompare = setting.EnabledValue ?? setting.RecommendedValue;\n bool matchesEnabled = CompareValues(currentValue, valueToCompare);\n if (matchesEnabled)\n {\n return RegistrySettingStatus.Applied;\n }\n\n // If there's a disabled value specified, check if it matches that\n object? disabledValue = setting.DisabledValue ?? setting.DefaultValue;\n if (disabledValue != null)\n {\n bool matchesDisabled = CompareValues(currentValue, disabledValue);\n if (matchesDisabled)\n {\n return RegistrySettingStatus.NotApplied;\n }\n }\n\n // If it doesn't match recommended or default, it's modified\n return RegistrySettingStatus.Modified;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking registry setting status: {ex.Message}\");\n return RegistrySettingStatus.Error;\n }\n }\n\n public async Task> GetSettingsStatusAsync(IEnumerable settings)\n {\n var results = new Dictionary();\n\n if (settings == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot get status for null registry settings collection\");\n return results;\n }\n\n foreach (var setting in settings)\n {\n if (setting == null || string.IsNullOrEmpty(setting.Name))\n {\n continue;\n }\n\n var status = await GetSettingStatusAsync(setting);\n results[setting.Name] = status;\n }\n\n return results;\n }\n\n public async Task GetLinkedSettingsStatusAsync(LinkedRegistrySettings linkedSettings)\n {\n if (linkedSettings == null || linkedSettings.Settings.Count == 0)\n return RegistrySettingStatus.Unknown;\n\n try\n {\n List statuses = new List();\n \n // Special case: If all settings have ActionType = Remove, we need to handle differently\n bool allRemoveActions = linkedSettings.Settings.All(s => s.ActionType == RegistryActionType.Remove);\n \n if (allRemoveActions)\n {\n // For Remove actions, we need to check if all keys/values don't exist (for All logic)\n // or if any key/value doesn't exist (for Any logic)\n bool allKeysRemoved = true;\n bool anyKeyRemoved = false;\n \n foreach (var setting in linkedSettings.Settings)\n {\n string fullPath = $\"{RegistryExtensions.GetRegistryHiveString(setting.Hive)}\\\\{setting.SubKey}\";\n string fullValuePath = $\"{fullPath}\\\\{setting.Name}\";\n \n // Check if the key exists\n bool keyExists = KeyExists(fullPath);\n \n // For Remove actions, if the key doesn't exist, it's considered \"removed\" (Applied)\n if (!keyExists)\n {\n anyKeyRemoved = true;\n }\n else\n {\n // Key exists, now check if the value exists\n bool valueExists = ValueExists(fullPath, setting.Name);\n \n if (!valueExists)\n {\n anyKeyRemoved = true;\n }\n else\n {\n // Special case for 3D Objects toggle which is opposite of normal Remove action\n // When the key exists, 3D Objects is shown (should be considered Applied)\n if (setting.Name == \"{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}\")\n {\n _logService.Log(LogLevel.Info, $\"3D Objects key exists in linked settings - special handling\");\n // For 3D Objects, we want to return Applied when the key exists\n // So we don't set allKeysRemoved to false here\n continue;\n }\n \n allKeysRemoved = false;\n }\n }\n }\n \n // Determine status based on the logic\n if (linkedSettings.Logic == LinkedSettingsLogic.All)\n {\n return allKeysRemoved ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n }\n else\n {\n return anyKeyRemoved ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n }\n }\n \n // Normal case: Process each setting individually\n foreach (var setting in linkedSettings.Settings)\n {\n var status = await GetSettingStatusAsync(setting);\n statuses.Add(status);\n }\n\n // Check if any settings have an error status\n if (statuses.Contains(RegistrySettingStatus.Error))\n {\n return RegistrySettingStatus.Error;\n }\n\n // Check if any settings have an unknown status\n if (statuses.Contains(RegistrySettingStatus.Unknown))\n {\n return RegistrySettingStatus.Unknown;\n }\n\n // Count how many settings are applied\n int appliedCount = statuses.Count(s => s == RegistrySettingStatus.Applied);\n int notAppliedCount = statuses.Count(s => s == RegistrySettingStatus.NotApplied);\n int modifiedCount = statuses.Count(s => s == RegistrySettingStatus.Modified);\n\n // Determine the overall status based on the logic type\n switch (linkedSettings.Logic)\n {\n case LinkedSettingsLogic.All:\n // All settings must be applied for the overall status to be Applied\n if (appliedCount == statuses.Count)\n {\n return RegistrySettingStatus.Applied;\n }\n else if (notAppliedCount == statuses.Count)\n {\n return RegistrySettingStatus.NotApplied;\n }\n else\n {\n return RegistrySettingStatus.Modified;\n }\n\n case LinkedSettingsLogic.Any:\n // Any applied setting means the overall status is Applied\n if (appliedCount > 0)\n {\n return RegistrySettingStatus.Applied;\n }\n else if (notAppliedCount == statuses.Count)\n {\n return RegistrySettingStatus.NotApplied;\n }\n else\n {\n return RegistrySettingStatus.Modified;\n }\n\n case LinkedSettingsLogic.Primary:\n // Find the primary setting\n var primarySetting = linkedSettings.Settings.FirstOrDefault(s => s.IsPrimary);\n if (primarySetting != null)\n {\n // Return the status of the primary setting\n return await GetSettingStatusAsync(primarySetting);\n }\n else\n {\n // If no primary setting is found, fall back to All logic\n if (appliedCount == statuses.Count)\n {\n return RegistrySettingStatus.Applied;\n }\n else if (notAppliedCount == statuses.Count)\n {\n return RegistrySettingStatus.NotApplied;\n }\n else\n {\n return RegistrySettingStatus.Modified;\n }\n }\n\n default:\n // Default to Any logic\n if (appliedCount > 0)\n {\n return RegistrySettingStatus.Applied;\n }\n else if (notAppliedCount == statuses.Count)\n {\n return RegistrySettingStatus.NotApplied;\n }\n else\n {\n return RegistrySettingStatus.Modified;\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking linked registry settings status: {ex.Message}\");\n return RegistrySettingStatus.Error;\n }\n }\n\n public async Task GetOptimizationSettingStatusAsync(Winhance.Core.Features.Optimize.Models.OptimizationSetting setting)\n {\n if (setting == null)\n {\n return RegistrySettingStatus.Unknown;\n }\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Checking status for optimization setting: {setting.Name}\");\n\n // If the setting has registry settings collection, create a LinkedRegistrySettings and use that\n if (setting.RegistrySettings != null && setting.RegistrySettings.Count > 0)\n {\n var linkedSettings = new LinkedRegistrySettings\n {\n Settings = setting.RegistrySettings.ToList(),\n Logic = setting.LinkedSettingsLogic\n };\n return await GetLinkedSettingsStatusAsync(linkedSettings);\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Optimization setting {setting.Name} has no registry settings\");\n return RegistrySettingStatus.Unknown;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking optimization setting status: {ex.Message}\");\n return RegistrySettingStatus.Error;\n }\n }\n\n /// \n /// Helper method to compare registry values, handling different types.\n /// \n private bool CompareValues(object? currentValue, object? desiredValue)\n {\n if (currentValue == null && desiredValue == null)\n {\n return true;\n }\n\n if (currentValue == null || desiredValue == null)\n {\n return false;\n }\n\n // Handle different types of registry values\n if (currentValue is int intValue && desiredValue is int desiredIntValue)\n {\n return intValue == desiredIntValue;\n }\n else if (currentValue is string strValue && desiredValue is string desiredStrValue)\n {\n return strValue.Equals(desiredStrValue, StringComparison.OrdinalIgnoreCase);\n }\n else if (currentValue is byte[] byteArrayValue && desiredValue is byte[] desiredByteArrayValue)\n {\n return byteArrayValue.SequenceEqual(desiredByteArrayValue);\n }\n else\n {\n // For other types, use the default Equals method\n return currentValue.Equals(desiredValue);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/VersionService.cs", "using System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Net.Http;\nusing System.Reflection;\nusing System.Text.Json;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n public class VersionService : IVersionService\n {\n private readonly ILogService _logService;\n private readonly HttpClient _httpClient;\n private readonly string _latestReleaseApiUrl = \"https://api.github.com/repos/memstechtips/Winhance/releases/latest\";\n private readonly string _latestReleaseDownloadUrl = \"https://github.com/memstechtips/Winhance/releases/latest/download/Winhance.Installer.exe\";\n private readonly string _userAgent = \"Winhance-Update-Checker\";\n \n public VersionService(ILogService logService)\n {\n _logService = logService;\n _httpClient = new HttpClient();\n _httpClient.DefaultRequestHeaders.Add(\"User-Agent\", _userAgent);\n }\n \n public VersionInfo GetCurrentVersion()\n {\n try\n {\n // Get the assembly version\n Assembly assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();\n string? location = assembly.Location;\n \n if (string.IsNullOrEmpty(location))\n {\n _logService.Log(LogLevel.Error, \"Could not determine assembly location for version check\");\n return CreateDefaultVersion();\n }\n \n // Get the assembly file version which will be in the format v25.05.02\n FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(location);\n string fileVersion = fileVersionInfo.FileVersion ?? \"v0.0.0\";\n \n // If the version doesn't start with 'v', add it\n if (!fileVersion.StartsWith(\"v\"))\n {\n fileVersion = $\"v{fileVersion}\";\n }\n \n return VersionInfo.FromTag(fileVersion);\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting current version: {ex.Message}\", ex);\n return CreateDefaultVersion();\n }\n }\n \n public async Task CheckForUpdateAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Checking for updates...\");\n \n // Get the latest release information from GitHub API\n HttpResponseMessage response = await _httpClient.GetAsync(_latestReleaseApiUrl);\n response.EnsureSuccessStatusCode();\n \n string responseBody = await response.Content.ReadAsStringAsync();\n using JsonDocument doc = JsonDocument.Parse(responseBody);\n \n // Extract the tag name (version) from the response\n string tagName = doc.RootElement.GetProperty(\"tag_name\").GetString() ?? \"v0.0.0\";\n string htmlUrl = doc.RootElement.GetProperty(\"html_url\").GetString() ?? string.Empty;\n DateTime publishedAt = doc.RootElement.TryGetProperty(\"published_at\", out JsonElement publishedElement) && \n DateTime.TryParse(publishedElement.GetString(), out DateTime published) \n ? published \n : DateTime.MinValue;\n \n VersionInfo latestVersion = VersionInfo.FromTag(tagName);\n latestVersion.DownloadUrl = _latestReleaseDownloadUrl;\n \n // Compare with current version\n VersionInfo currentVersion = GetCurrentVersion();\n latestVersion.IsUpdateAvailable = latestVersion.IsNewerThan(currentVersion);\n \n _logService.Log(LogLevel.Info, $\"Current version: {currentVersion.Version}, Latest version: {latestVersion.Version}, Update available: {latestVersion.IsUpdateAvailable}\");\n \n return latestVersion;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking for updates: {ex.Message}\", ex);\n return new VersionInfo { IsUpdateAvailable = false };\n }\n }\n \n public async Task DownloadAndInstallUpdateAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Downloading update...\");\n \n // Create a temporary file to download the installer\n string tempPath = Path.Combine(Path.GetTempPath(), \"Winhance.Installer.exe\");\n \n // Download the installer\n byte[] installerBytes = await _httpClient.GetByteArrayAsync(_latestReleaseDownloadUrl);\n await File.WriteAllBytesAsync(tempPath, installerBytes);\n \n _logService.Log(LogLevel.Info, $\"Update downloaded to {tempPath}, launching installer...\");\n \n // Launch the installer\n Process.Start(new ProcessStartInfo\n {\n FileName = tempPath,\n UseShellExecute = true\n });\n \n _logService.Log(LogLevel.Info, \"Installer launched successfully\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error downloading or installing update: {ex.Message}\", ex);\n throw;\n }\n }\n \n private VersionInfo CreateDefaultVersion()\n {\n // Create a default version based on the current date\n DateTime now = DateTime.Now;\n string versionTag = $\"v{now.Year - 2000:D2}.{now.Month:D2}.{now.Day:D2}\";\n \n return new VersionInfo\n {\n Version = versionTag,\n ReleaseDate = now\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/OptimizeView.xaml.cs", "using System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing MaterialDesignThemes.Wpf;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Messages;\nusing Winhance.WPF.Features.Optimize.ViewModels;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n public partial class OptimizeView : UserControl\n {\n private IMessengerService? _messengerService; // Changed from readonly to allow assignment\n \n // References to the child views\n private UIElement _windowsSecurityOptimizationsView;\n private UIElement _privacySettingsView;\n private UIElement _gamingandPerformanceOptimizationsView;\n private UIElement _updateOptimizationsView;\n private UIElement _powerSettingsView;\n private UIElement _explorerOptimizationsView;\n private UIElement _notificationOptimizationsView;\n private UIElement _soundOptimizationsView;\n\n public OptimizeView()\n {\n InitializeComponent();\n Loaded += OptimizeView_Loaded;\n\n // Initialize section visibility and click handlers - all visible by default\n // WindowsSecurityContent will be initialized in the Loaded event\n\n // Add click handlers to the header border elements\n WindowsSecurityHeaderBorder.MouseDown += WindowsSecurityHeader_MouseDown;\n PrivacyHeaderBorder.MouseDown += PrivacyHeader_MouseDown;\n GamingHeaderBorder.MouseDown += GamingHeader_MouseDown;\n UpdatesHeaderBorder.MouseDown += UpdatesHeader_MouseDown;\n PowerHeaderBorder.MouseDown += PowerHeader_MouseDown;\n ExplorerHeaderBorder.MouseDown += ExplorerHeader_MouseDown;\n NotificationHeaderBorder.MouseDown += NotificationHeader_MouseDown;\n SoundHeaderBorder.MouseDown += SoundHeader_MouseDown;\n \n // Subscribe to DataContextChanged event to get the messenger service\n DataContextChanged += OptimizeView_DataContextChanged;\n }\n \n private void OptimizeView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n // Unregister from old messenger service if exists\n if (_messengerService != null)\n {\n _messengerService.Unregister(this);\n _messengerService = null;\n }\n\n // Register with new messenger service if available\n if (e.NewValue is OptimizeViewModel viewModel &&\n viewModel.MessengerService is IMessengerService messengerService)\n {\n _messengerService = messengerService;\n \n // Subscribe to the message that signals resetting expansion states\n _messengerService.Register(this, OnResetExpansionState);\n }\n }\n \n private void OnResetExpansionState(ResetExpansionStateMessage message)\n {\n // Reset all section expansion states to expanded\n if (_windowsSecurityOptimizationsView != null)\n {\n _windowsSecurityOptimizationsView.Visibility = Visibility.Visible;\n WindowsSecurityHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_privacySettingsView != null)\n {\n _privacySettingsView.Visibility = Visibility.Visible;\n PrivacyHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_gamingandPerformanceOptimizationsView != null)\n {\n _gamingandPerformanceOptimizationsView.Visibility = Visibility.Visible;\n GamingHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_updateOptimizationsView != null)\n {\n _updateOptimizationsView.Visibility = Visibility.Visible;\n UpdatesHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_powerSettingsView != null)\n {\n _powerSettingsView.Visibility = Visibility.Visible;\n PowerHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_explorerOptimizationsView != null)\n {\n _explorerOptimizationsView.Visibility = Visibility.Visible;\n ExplorerHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_notificationOptimizationsView != null)\n {\n _notificationOptimizationsView.Visibility = Visibility.Visible;\n NotificationHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_soundOptimizationsView != null)\n {\n _soundOptimizationsView.Visibility = Visibility.Visible;\n SoundHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n }\n\n private async void OptimizeView_Loaded(object sender, RoutedEventArgs e)\n {\n if (DataContext is Winhance.WPF.Features.Optimize.ViewModels.OptimizeViewModel viewModel)\n {\n try\n {\n // Find the child views\n _windowsSecurityOptimizationsView = FindChildByType(this);\n _privacySettingsView = FindChildByType(this);\n _gamingandPerformanceOptimizationsView = FindChildByType(this);\n _updateOptimizationsView = FindChildByType(this);\n _powerSettingsView = FindChildByType(this);\n _explorerOptimizationsView = FindChildByType(this);\n _notificationOptimizationsView = FindChildByType(this);\n _soundOptimizationsView = FindChildByType(this);\n\n // Set initial visibility\n if (_windowsSecurityOptimizationsView != null) _windowsSecurityOptimizationsView.Visibility = Visibility.Visible;\n if (_privacySettingsView != null) _privacySettingsView.Visibility = Visibility.Visible;\n if (_gamingandPerformanceOptimizationsView != null) _gamingandPerformanceOptimizationsView.Visibility = Visibility.Visible;\n if (_updateOptimizationsView != null) _updateOptimizationsView.Visibility = Visibility.Visible;\n if (_powerSettingsView != null) _powerSettingsView.Visibility = Visibility.Visible;\n if (_explorerOptimizationsView != null) _explorerOptimizationsView.Visibility = Visibility.Visible;\n if (_notificationOptimizationsView != null) _notificationOptimizationsView.Visibility = Visibility.Visible;\n if (_soundOptimizationsView != null) _soundOptimizationsView.Visibility = Visibility.Visible;\n\n // Set header icons\n WindowsSecurityHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n PrivacyHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n GamingHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n UpdatesHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n PowerHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n ExplorerHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n NotificationHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n SoundHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n\n // Initialize data if needed\n if (viewModel.InitializeCommand != null)\n {\n Console.WriteLine(\"OptimizeView: Executing InitializeCommand\");\n await viewModel.InitializeCommand.ExecuteAsync(null);\n Console.WriteLine(\"OptimizeView: InitializeCommand completed successfully\");\n }\n else\n {\n MessageBox.Show(\"InitializeCommand is null in OptimizeViewModel\",\n \"Initialization Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error);\n }\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"OptimizeView: Error initializing - {ex.Message}\");\n MessageBox.Show($\"Error initializing Optimize view: {ex.Message}\",\n \"Initialization Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error);\n }\n }\n else\n {\n Console.WriteLine(\"OptimizeView: DataContext is not OptimizeViewModel\");\n MessageBox.Show(\"DataContext is not OptimizeViewModel\",\n \"Initialization Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error);\n }\n }\n\n private void WindowsSecurityHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n try\n {\n // Toggle section visibility\n ToggleSectionVisibility(_windowsSecurityOptimizationsView, WindowsSecurityHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n WindowsSecurityToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true; // Mark as handled to prevent the event from bubbling up\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Error toggling Windows Security Settings section: {ex.Message}\",\n \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n }\n }\n\n private void PrivacyHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n try\n {\n // Toggle section visibility\n ToggleSectionVisibility(_privacySettingsView, PrivacyHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n PrivacyToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true; // Mark as handled to prevent the event from bubbling up\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Error toggling Privacy Settings section: {ex.Message}\",\n \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n }\n }\n\n private void GamingHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_gamingandPerformanceOptimizationsView, GamingHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n GamingToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void UpdatesHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_updateOptimizationsView, UpdatesHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n UpdatesToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void PowerHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_powerSettingsView, PowerHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n PowerToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void ExplorerHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_explorerOptimizationsView, ExplorerHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n ExplorerToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void NotificationHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_notificationOptimizationsView, NotificationHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n NotificationToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void SoundHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_soundOptimizationsView, SoundHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n SoundToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void ToggleSectionVisibility(UIElement content, PackIcon icon)\n {\n if (content == null) return;\n\n if (content.Visibility == Visibility.Collapsed)\n {\n content.Visibility = Visibility.Visible;\n icon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n }\n else\n {\n content.Visibility = Visibility.Collapsed;\n icon.Kind = PackIconKind.ChevronDown; // Downward arrow for collapsed state\n }\n }\n\n /// \n /// Finds a child element of the specified type in the visual tree.\n /// \n /// The type of element to find.\n /// The parent element to search in.\n /// The first child element of the specified type, or null if not found.\n private T FindChildByType(DependencyObject parent) where T : DependencyObject\n {\n // Confirm parent and type are valid\n if (parent == null) return null;\n\n // Get child count\n int childCount = VisualTreeHelper.GetChildrenCount(parent);\n\n // Check all children\n for (int i = 0; i < childCount; i++)\n {\n var child = VisualTreeHelper.GetChild(parent, i);\n\n // If the child is the type we're looking for, return it\n if (child is T typedChild)\n {\n return typedChild;\n }\n\n // Otherwise, recursively check this child's children\n var result = FindChildByType(child);\n if (result != null)\n {\n return result;\n }\n }\n\n // If we get here, we didn't find a match\n return null;\n }\n }\n\n // Extension method to check if a visual element is a descendant of another\n public static class VisualExtensions\n {\n public static bool IsDescendantOf(this System.Windows.DependencyObject element, System.Windows.DependencyObject parent)\n {\n if (element == parent)\n return true;\n\n var currentParent = System.Windows.Media.VisualTreeHelper.GetParent(element);\n while (currentParent != null)\n {\n if (currentParent == parent)\n return true;\n currentParent = System.Windows.Media.VisualTreeHelper.GetParent(currentParent);\n }\n\n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/StartMenuCustomizations.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Services;\nusing Winhance.Core.Features.Customize.Enums;\n\nnamespace Winhance.Core.Features.Customize.Models;\n\npublic static class StartMenuCustomizations\n{\n private const string Win10StartLayoutPath = @\"C:\\Windows\\StartMenuLayout.xml\";\n private const string Win11StartBinPath =\n @\"AppData\\Local\\Packages\\Microsoft.Windows.StartMenuExperienceHost_cw5n1h2txyewy\\LocalState\\start2.bin\";\n\n public static CustomizationGroup GetStartMenuCustomizations()\n {\n return new CustomizationGroup\n {\n Name = \"Start Menu\",\n Category = CustomizationCategory.StartMenu,\n Settings = new List\n {\n new CustomizationSetting\n {\n Id = \"show-recently-added-apps\",\n Name = \"Show Recently Added Apps\",\n Description = \"Controls visibility of recently added apps in Start Menu\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Start Menu Settings\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Policies\\\\Microsoft\\\\Windows\\\\Explorer\",\n Name = \"HideRecentlyAddedApps\",\n RecommendedValue = 0,\n EnabledValue = 0, // When toggle is ON, recently added apps are shown\n DisabledValue = 1, // When toggle is OFF, recently added apps are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Controls visibility of recently added apps in Start Menu\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\Explorer\",\n Name = \"HideRecentlyAddedApps\",\n RecommendedValue = 0,\n EnabledValue = 0, // When toggle is ON, recently added apps are shown\n DisabledValue = 1, // When toggle is OFF, recently added apps are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Controls visibility of recently added apps in Start Menu\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"start-menu-layout\",\n Name = \"Set 'More Pins' Layout\",\n Description = \"Controls Start Menu layout configuration\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Layout\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"StartMenu\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"Start_Layout\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, more pins layout is used\n DisabledValue = 0, // When toggle is OFF, default layout is used\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // For backward compatibility\n Description = \"Controls Start Menu layout configuration\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"start-menu-recommendations\",\n Name = \"Show Recommended Tips, Shortcuts etc.\",\n Description = \"Controls recommendations for tips and shortcuts\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Start Menu Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"Start_IrisRecommendations\",\n RecommendedValue = 1,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls recommendations for tips and shortcuts\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"taskbar-clear-mfu\",\n Name = \"Show Most Used Apps\",\n Description = \"Controls frequently used programs list visibility\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Start Menu\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"StartMenu\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Start\",\n Name = \"ShowFrequentList\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, frequently used programs list is shown\n DisabledValue = 0, // When toggle is OFF, frequently used programs list is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls frequently used programs list visibility\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"power-lock-option\",\n Name = \"Lock Option\",\n Description = \"Controls whether the lock option is shown in the Start menu\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Start Menu\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\FlyoutMenuSettings\",\n Name = \"ShowLockOption\",\n RecommendedValue = 1,\n EnabledValue = 1, // Show lock option\n DisabledValue = 0, // Hide lock option\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description =\n \"Controls whether the lock option is shown in the Start menu\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"show-recommended-files\",\n Name = \"Show Recommended Files\",\n Description = \"Controls visibility of recommended files in Start Menu\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Start Menu Settings\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"Start_TrackDocs\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, recommended files are shown\n DisabledValue = 0, // When toggle is OFF, recommended files are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls visibility of recommended files in Start Menu\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n },\n };\n }\n\n public static void ApplyStartMenuLayout(bool isWindows11, ISystemServices windowsService)\n {\n if (isWindows11)\n {\n ApplyWindows11Layout();\n }\n else\n {\n ApplyWindows10Layout(windowsService);\n }\n }\n\n private static void ApplyWindows10Layout(ISystemServices windowsService)\n {\n // Delete existing layout file\n if (File.Exists(Win10StartLayoutPath))\n {\n File.Delete(Win10StartLayoutPath);\n }\n\n // Create new layout file\n File.WriteAllText(Win10StartLayoutPath, StartMenuLayouts.Windows10Layout);\n\n // Use the improved RefreshWindowsGUI method to restart Explorer and apply changes\n // This will ensure Explorer is restarted properly with retry logic and fallback\n var result = windowsService.RefreshWindowsGUI(true).GetAwaiter().GetResult();\n if (!result)\n {\n throw new Exception(\"Failed to refresh Windows GUI after applying Start Menu layout\");\n }\n }\n\n private static void ApplyWindows11Layout()\n {\n string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);\n string start2BinPath = Path.Combine(userProfile, Win11StartBinPath);\n string tempPath = Path.GetTempPath();\n\n // Delete existing start2.bin if it exists\n if (File.Exists(start2BinPath))\n {\n File.Delete(start2BinPath);\n }\n\n // Create temp file with cert content\n string tempTxtPath = Path.Combine(tempPath, \"start2.txt\");\n string tempBinPath = Path.Combine(tempPath, \"start2.bin\");\n\n try\n {\n // Write certificate content to temp file\n File.WriteAllText(tempTxtPath, StartMenuLayouts.Windows11StartBinCertificate);\n\n // Use certutil to decode the certificate\n using (var process = new System.Diagnostics.Process())\n {\n process.StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"certutil.exe\",\n Arguments = $\"-decode \\\"{tempTxtPath}\\\" \\\"{tempBinPath}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n CreateNoWindow = true,\n };\n\n process.Start();\n process.WaitForExit();\n }\n\n // Ensure directory exists\n Directory.CreateDirectory(Path.GetDirectoryName(start2BinPath)!);\n\n // Copy the decoded binary to the Start Menu location\n File.Copy(tempBinPath, start2BinPath, true);\n }\n finally\n {\n // Clean up temp files\n if (File.Exists(tempTxtPath))\n File.Delete(tempTxtPath);\n if (File.Exists(tempBinPath))\n File.Delete(tempBinPath);\n }\n }\n\n /// \n /// Cleans the Start Menu for Windows 10 or Windows 11.\n /// \n /// Whether the system is Windows 11.\n /// The system services.\n public static void CleanStartMenu(bool isWindows11, ISystemServices windowsService)\n {\n if (isWindows11)\n {\n CleanWindows11StartMenu();\n }\n else\n {\n CleanWindows10StartMenu(windowsService);\n }\n }\n\n /// \n /// Cleans the Windows 11 Start Menu by replacing the start2.bin file.\n /// \n private static void CleanWindows11StartMenu()\n {\n // This is essentially the same as ApplyWindows11Layout since we're replacing the start2.bin file\n string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);\n string start2BinPath = Path.Combine(userProfile, Win11StartBinPath);\n string tempPath = Path.GetTempPath();\n\n // Delete existing start2.bin if it exists\n if (File.Exists(start2BinPath))\n {\n File.Delete(start2BinPath);\n }\n\n // Create temp file with cert content\n string tempTxtPath = Path.Combine(tempPath, \"start2.txt\");\n string tempBinPath = Path.Combine(tempPath, \"start2.bin\");\n\n try\n {\n // Write certificate content to temp file\n File.WriteAllText(tempTxtPath, StartMenuLayouts.Windows11StartBinCertificate);\n\n // Use certutil to decode the certificate\n using (var process = new System.Diagnostics.Process())\n {\n process.StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"certutil.exe\",\n Arguments = $\"-decode \\\"{tempTxtPath}\\\" \\\"{tempBinPath}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n CreateNoWindow = true,\n };\n\n process.Start();\n process.WaitForExit();\n }\n\n // Ensure directory exists\n Directory.CreateDirectory(Path.GetDirectoryName(start2BinPath)!);\n\n // Copy the decoded binary to the Start Menu location\n File.Copy(tempBinPath, start2BinPath, true);\n }\n finally\n {\n // Clean up temp files\n if (File.Exists(tempTxtPath))\n File.Delete(tempTxtPath);\n if (File.Exists(tempBinPath))\n File.Delete(tempBinPath);\n }\n }\n\n /// \n /// Cleans the Windows 10 Start Menu by creating and then removing a StartMenuLayout.xml file.\n /// \n /// The system services.\n private static void CleanWindows10StartMenu(ISystemServices windowsService)\n {\n try\n {\n // Delete existing layout file if it exists\n if (File.Exists(Win10StartLayoutPath))\n {\n File.Delete(Win10StartLayoutPath);\n }\n\n // Create new layout file with clean layout\n File.WriteAllText(Win10StartLayoutPath, StartMenuLayouts.Windows10Layout);\n\n // Set registry values to lock the Start Menu layout\n using (\n var key = Registry.LocalMachine.CreateSubKey(\n @\"SOFTWARE\\Policies\\Microsoft\\Windows\\Explorer\"\n )\n )\n {\n if (key != null)\n {\n key.SetValue(\"LockedStartLayout\", 1, RegistryValueKind.DWord);\n key.SetValue(\"StartLayoutFile\", Win10StartLayoutPath, RegistryValueKind.String);\n }\n }\n\n using (\n var key = Registry.CurrentUser.CreateSubKey(\n @\"SOFTWARE\\Policies\\Microsoft\\Windows\\Explorer\"\n )\n )\n {\n if (key != null)\n {\n key.SetValue(\"LockedStartLayout\", 1, RegistryValueKind.DWord);\n key.SetValue(\"StartLayoutFile\", Win10StartLayoutPath, RegistryValueKind.String);\n }\n }\n\n // Use the improved RefreshWindowsGUI method to restart Explorer and apply changes\n // This will ensure Explorer is restarted properly with retry logic and fallback\n var result = windowsService.RefreshWindowsGUI(true).GetAwaiter().GetResult();\n if (!result)\n {\n throw new Exception(\n \"Failed to refresh Windows GUI after applying Start Menu layout\"\n );\n }\n\n // Wait for changes to take effect\n System.Threading.Thread.Sleep(3000);\n\n // Disable the locked Start Menu layout\n using (\n var key = Registry.LocalMachine.CreateSubKey(\n @\"SOFTWARE\\Policies\\Microsoft\\Windows\\Explorer\"\n )\n )\n {\n if (key != null)\n {\n key.SetValue(\"LockedStartLayout\", 0, RegistryValueKind.DWord);\n }\n }\n\n using (\n var key = Registry.CurrentUser.CreateSubKey(\n @\"SOFTWARE\\Policies\\Microsoft\\Windows\\Explorer\"\n )\n )\n {\n if (key != null)\n {\n key.SetValue(\"LockedStartLayout\", 0, RegistryValueKind.DWord);\n }\n }\n\n // Use the improved RefreshWindowsGUI method again to apply the final changes\n result = windowsService.RefreshWindowsGUI(true).GetAwaiter().GetResult();\n if (!result)\n {\n throw new Exception(\n \"Failed to refresh Windows GUI after unlocking Start Menu layout\"\n );\n }\n\n // Delete the layout file\n if (File.Exists(Win10StartLayoutPath))\n {\n File.Delete(Win10StartLayoutPath);\n }\n }\n catch (Exception ex)\n {\n // Log the exception or handle it as needed\n System.Diagnostics.Debug.WriteLine(\n $\"Error cleaning Windows 10 Start Menu: {ex.Message}\"\n );\n throw new Exception($\"Error cleaning Windows 10 Start Menu: {ex.Message}\", ex);\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/CapabilitiesViewModel.cs", "using CommunityToolkit.Mvvm.Input;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n public partial class CapabilitiesViewModel : AppListViewModel\n {\n private readonly IAppLoadingService _appLoadingService;\n private readonly IInstallationOrchestrator _installationOrchestrator;\n\n public CapabilitiesViewModel(\n IAppLoadingService appLoadingService,\n IInstallationOrchestrator installationOrchestrator,\n ITaskProgressService taskProgressService,\n IPackageManager packageManager)\n : base(taskProgressService, packageManager)\n {\n _appLoadingService = appLoadingService;\n _installationOrchestrator = installationOrchestrator;\n }\n\n public override async Task LoadItemsAsync()\n {\n var capabilities = await _appLoadingService.LoadCapabilitiesAsync();\n Items.Clear();\n foreach (var item in capabilities)\n {\n Items.Add(item);\n }\n }\n\n public override async Task CheckInstallationStatusAsync()\n {\n await Task.Run(async () =>\n {\n foreach (var item in Items)\n {\n // Use the AppLoadingService to check installation status\n item.IsInstalled = await _appLoadingService.GetItemInstallStatusAsync(item);\n }\n });\n }\n\n [RelayCommand]\n private async Task InstallAsync()\n {\n var selected = Items.Where(item => item.IsSelected).ToList();\n if (!selected.Any())\n {\n return;\n }\n await _installationOrchestrator.InstallBatchAsync(selected);\n }\n\n [RelayCommand]\n private async Task RemoveAsync()\n {\n var selected = Items.Where(item => item.IsSelected).ToList();\n if (!selected.Any())\n {\n return;\n }\n await _installationOrchestrator.RemoveBatchAsync(selected);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/Methods/FileSystemVerificationMethod.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods\n{\n /// \n /// Verifies software installations by checking common installation directories.\n /// \n public class FileSystemVerificationMethod : VerificationMethodBase\n {\n private static readonly string[] CommonInstallPaths = new[]\n {\n Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)),\n Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)),\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Programs\"\n ),\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),\n @\"Microsoft\\Windows\\Start Menu\\Programs\"\n ),\n };\n\n /// \n /// Initializes a new instance of the class.\n /// \n public FileSystemVerificationMethod()\n : base(\"FileSystem\", priority: 20) { }\n\n /// \n protected override async Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken\n )\n {\n return await Task.Run(\n () =>\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n // First try: Check if the app is in PATH (for CLI tools)\n try\n {\n var pathEnv = Environment.GetEnvironmentVariable(\"PATH\") ?? string.Empty;\n var paths = pathEnv.Split(Path.PathSeparator);\n \n\n foreach (var path in paths)\n {\n if (string.IsNullOrEmpty(path))\n continue;\n \n\n var exePath = Path.Combine(path, $\"{packageId}.exe\");\n if (File.Exists(exePath))\n {\n return new VerificationResult\n {\n IsVerified = true,\n Message = $\"Found in PATH: {exePath}\",\n MethodUsed = \"FileSystem\",\n AdditionalInfo = new\n {\n InstallPath = path,\n ExecutablePath = exePath,\n },\n };\n }\n }\n }\n catch (Exception)\n {\n // Ignore PATH check errors and continue with other methods\n }\n\n // Second try: Check common installation directories\n foreach (var basePath in CommonInstallPaths)\n {\n if (!Directory.Exists(basePath))\n continue;\n\n try\n {\n // Check for exact match in directory names\n var matchingDirs = Directory\n .EnumerateDirectories(\n basePath,\n \"*\",\n SearchOption.TopDirectoryOnly\n )\n .Where(d =>\n Path.GetFileName(d)\n ?.Equals(packageId, StringComparison.OrdinalIgnoreCase)\n == true\n || Path.GetFileName(d)\n ?.Contains(\n packageId,\n StringComparison.OrdinalIgnoreCase\n ) == true\n )\n .ToList();\n\n if (matchingDirs.Any())\n {\n return new VerificationResult\n {\n IsVerified = true,\n Message = $\"Found in file system: {matchingDirs.First()}\",\n MethodUsed = \"FileSystem\",\n AdditionalInfo = new\n {\n InstallPath = matchingDirs.First(),\n AllMatchingPaths = matchingDirs.ToArray(),\n },\n };\n }\n \n\n // Check for Microsoft Store apps in Packages directory\n if (basePath.Contains(\"LocalApplicationData\"))\n {\n var packagesPath = Path.Combine(basePath, \"Packages\");\n if (Directory.Exists(packagesPath))\n {\n var storeAppDirs = Directory\n .EnumerateDirectories(\n packagesPath,\n \"*\",\n SearchOption.TopDirectoryOnly\n )\n .Where(d =>\n Path.GetFileName(d)\n ?.IndexOf(packageId, StringComparison.OrdinalIgnoreCase) >= 0\n )\n .ToList();\n \n\n foreach (var dir in storeAppDirs)\n {\n var manifestPath = Path.Combine(dir, \"AppxManifest.xml\");\n if (File.Exists(manifestPath))\n {\n return new VerificationResult\n {\n IsVerified = true,\n Message = $\"Found Microsoft Store app: {dir}\",\n MethodUsed = \"FileSystem\",\n AdditionalInfo = new\n {\n InstallPath = dir,\n ManifestPath = manifestPath,\n },\n };\n }\n }\n }\n }\n }\n catch (UnauthorizedAccessException)\n {\n // Skip directories we can't access\n continue;\n }\n catch (Exception)\n {\n // Skip directories with other errors\n continue;\n }\n }\n\n return VerificationResult.Failure(\n $\"Package '{packageId}' not found in common installation directories\"\n );\n },\n cancellationToken\n )\n .ConfigureAwait(false);\n }\n\n /// \n protected override async Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken\n )\n {\n // For file system, we can't reliably determine version from directory name\n // So we'll just check for presence and let other methods verify version\n return await VerifyPresenceAsync(packageId, cancellationToken).ConfigureAwait(false);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/VerificationMethodBase.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification\n{\n /// \n /// Base class for verification methods that provides common functionality.\n /// \n public abstract class VerificationMethodBase : IVerificationMethod\n {\n /// \n /// Initializes a new instance of the class.\n /// \n /// The name of the verification method.\n /// The priority of the verification method. Lower numbers indicate higher priority.\n protected VerificationMethodBase(string name, int priority)\n {\n if (string.IsNullOrWhiteSpace(name))\n throw new ArgumentException(\n \"Verification method name cannot be null or whitespace.\",\n nameof(name)\n );\n\n Name = name;\n Priority = priority;\n }\n\n /// \n public string Name { get; }\n\n /// \n public int Priority { get; }\n\n /// \n public async Task VerifyAsync(\n string packageId,\n string version = null,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n try\n {\n if (version == null)\n {\n return await VerifyPresenceAsync(packageId, cancellationToken)\n .ConfigureAwait(false);\n }\n\n return await VerifyVersionAsync(packageId, version, cancellationToken)\n .ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n return new VerificationResult\n {\n IsVerified = false,\n Message = $\"Error during verification using {Name}: {ex.Message}\",\n MethodUsed = Name,\n };\n }\n }\n\n /// \n /// Verifies if a package is present (without version check).\n /// \n /// The ID of the package to verify.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the verification result.\n protected abstract Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken\n );\n\n /// \n /// Verifies if a package is present with the specified version.\n /// \n /// The ID of the package to verify.\n /// The expected version of the package.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the verification result.\n protected abstract Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken\n );\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/WindowsAppsConfigurationApplier.cs", "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for applying configuration to the WindowsApps section.\n /// \n public class WindowsAppsConfigurationApplier : ISectionConfigurationApplier\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n private readonly IViewModelRefresher _viewModelRefresher;\n private readonly IConfigurationPropertyUpdater _propertyUpdater;\n\n /// \n /// Gets the section name that this applier handles.\n /// \n public string SectionName => \"WindowsApps\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n /// The view model refresher.\n /// The property updater.\n public WindowsAppsConfigurationApplier(\n IServiceProvider serviceProvider,\n ILogService logService,\n IViewModelRefresher viewModelRefresher,\n IConfigurationPropertyUpdater propertyUpdater)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _viewModelRefresher = viewModelRefresher ?? throw new ArgumentNullException(nameof(viewModelRefresher));\n _propertyUpdater = propertyUpdater ?? throw new ArgumentNullException(nameof(propertyUpdater));\n }\n\n /// \n /// Applies the configuration to the WindowsApps section.\n /// \n /// The configuration file to apply.\n /// True if any items were updated, false otherwise.\n public async Task ApplyConfigAsync(ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Applying configuration to WindowsAppsViewModel\");\n \n var viewModel = _serviceProvider.GetService();\n if (viewModel == null)\n {\n _logService.Log(LogLevel.Warning, \"WindowsAppsViewModel not available\");\n return false;\n }\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, \"WindowsAppsViewModel not initialized, initializing now\");\n await viewModel.LoadItemsAsync();\n }\n \n // Apply the configuration directly to the view model's items\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Items, configFile);\n \n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in WindowsAppsViewModel\");\n \n // Refresh the UI\n await _viewModelRefresher.RefreshViewModelAsync(viewModel);\n \n return updatedCount > 0;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying WindowsApps configuration: {ex.Message}\");\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ExternalAppsConfigurationApplier.cs", "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for applying configuration to the ExternalApps section.\n /// \n public class ExternalAppsConfigurationApplier : ISectionConfigurationApplier\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n private readonly IViewModelRefresher _viewModelRefresher;\n private readonly IConfigurationPropertyUpdater _propertyUpdater;\n\n /// \n /// Gets the section name that this applier handles.\n /// \n public string SectionName => \"ExternalApps\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n /// The view model refresher.\n /// The property updater.\n public ExternalAppsConfigurationApplier(\n IServiceProvider serviceProvider,\n ILogService logService,\n IViewModelRefresher viewModelRefresher,\n IConfigurationPropertyUpdater propertyUpdater)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _viewModelRefresher = viewModelRefresher ?? throw new ArgumentNullException(nameof(viewModelRefresher));\n _propertyUpdater = propertyUpdater ?? throw new ArgumentNullException(nameof(propertyUpdater));\n }\n\n /// \n /// Applies the configuration to the ExternalApps section.\n /// \n /// The configuration file to apply.\n /// True if any items were updated, false otherwise.\n public async Task ApplyConfigAsync(ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Applying configuration to ExternalAppsViewModel\");\n \n var viewModel = _serviceProvider.GetService();\n if (viewModel == null)\n {\n _logService.Log(LogLevel.Warning, \"ExternalAppsViewModel not available\");\n return false;\n }\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, \"ExternalAppsViewModel not initialized, initializing now\");\n await viewModel.LoadItemsAsync();\n }\n \n // Apply the configuration directly to the view model's items\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Items, configFile);\n \n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in ExternalAppsViewModel\");\n \n // Refresh the UI\n await _viewModelRefresher.RefreshViewModelAsync(viewModel);\n \n return updatedCount > 0;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying ExternalApps configuration: {ex.Message}\");\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceKeyOperations.cs", "using Microsoft.Win32;\nusing System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Registry service implementation for key operations.\n /// \n public partial class RegistryService\n {\n /// \n /// Opens a registry key with the specified access rights.\n /// \n /// The full path to the registry key.\n /// Whether to open the key with write access.\n /// The opened registry key, or null if it could not be opened.\n private RegistryKey? OpenRegistryKey(string keyPath, bool writable)\n {\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return null;\n }\n\n string subPath = string.Join('\\\\', pathParts.Skip(1));\n\n if (writable)\n {\n // If we need write access, try to ensure the key exists with proper access rights\n return EnsureKeyWithFullAccess(rootKey, subPath);\n }\n else\n {\n // For read-only access, just try to open the key normally\n return rootKey.OpenSubKey(subPath, false);\n }\n }\n\n /// \n /// Creates a registry key if it doesn't exist.\n /// \n /// The full path to the registry key.\n /// True if the key exists or was created successfully; otherwise, false.\n public bool CreateKeyIfNotExists(string keyPath)\n {\n if (!CheckWindowsPlatform())\n return false;\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Creating registry key if it doesn't exist: {keyPath}\");\n\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return false;\n }\n\n string subKeyPath = string.Join('\\\\', pathParts.Skip(1));\n\n // Create the key with direct Registry API and security settings\n RegistryKey? targetKey = EnsureKeyWithFullAccess(rootKey, subKeyPath);\n\n if (targetKey == null)\n {\n _logService.Log(LogLevel.Warning, $\"Could not create registry key: {keyPath}\");\n return false;\n }\n\n targetKey.Close();\n \n // Update the cache to indicate that this key now exists\n lock (_keyExistsCache)\n {\n _keyExistsCache[keyPath] = true;\n }\n \n _logService.Log(LogLevel.Success, $\"Successfully created or verified registry key: {keyPath}\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating registry key {keyPath}: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Deletes a registry key.\n /// \n /// The full path to the registry key.\n /// True if the key was deleted successfully; otherwise, false.\n public bool DeleteKey(string keyPath)\n {\n if (!CheckWindowsPlatform())\n return false;\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Deleting registry key: {keyPath}\");\n\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return false;\n }\n\n string subKeyPath = string.Join('\\\\', pathParts.Skip(1));\n string parentPath = string.Join('\\\\', subKeyPath.Split('\\\\').Take(subKeyPath.Split('\\\\').Length - 1));\n string keyName = subKeyPath.Split('\\\\').Last();\n\n // Open the parent key with write access\n using (RegistryKey? parentKey = rootKey.OpenSubKey(parentPath, true))\n {\n if (parentKey == null)\n {\n _logService.Log(LogLevel.Warning, $\"Parent key does not exist: {pathParts[0]}\\\\{parentPath}\");\n return false;\n }\n\n // Delete the key\n parentKey.DeleteSubKey(keyName, false);\n \n // Clear the cache for this key\n lock (_keyExistsCache)\n {\n var keysToRemove = _keyExistsCache.Keys\n .Where(k => k.StartsWith(keyPath, StringComparison.OrdinalIgnoreCase))\n .ToList();\n \n foreach (var key in keysToRemove)\n {\n _keyExistsCache.Remove(key);\n }\n }\n\n _logService.Log(LogLevel.Success, $\"Successfully deleted registry key: {keyPath}\");\n return true;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error deleting registry key {keyPath}: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Checks if a registry key exists.\n /// \n /// The full path to the registry key.\n /// True if the key exists; otherwise, false.\n public bool KeyExists(string keyPath)\n {\n if (!CheckWindowsPlatform())\n return false;\n\n try\n {\n // Check the cache first\n lock (_keyExistsCache)\n {\n if (_keyExistsCache.TryGetValue(keyPath, out bool exists))\n {\n return exists;\n }\n }\n\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return false;\n }\n\n string subKeyPath = string.Join('\\\\', pathParts.Skip(1));\n\n // Try to open the key\n using (RegistryKey? key = rootKey.OpenSubKey(subKeyPath))\n {\n bool exists = key != null;\n \n // Cache the result\n lock (_keyExistsCache)\n {\n _keyExistsCache[keyPath] = exists;\n }\n \n return exists;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking if registry key exists {keyPath}: {ex.Message}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Customize/Services/WallpaperService.cs", "using System;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.Customize.Models;\n\nnamespace Winhance.Infrastructure.Features.Customize.Services\n{\n /// \n /// Service for wallpaper operations.\n /// \n public class WallpaperService : IWallpaperService\n {\n private readonly ILogService _logService;\n\n // P/Invoke constants\n private const int SPI_SETDESKWALLPAPER = 0x0014;\n private const int SPIF_UPDATEINIFILE = 0x01;\n private const int SPIF_SENDCHANGE = 0x02;\n\n [DllImport(\"user32.dll\", SetLastError = true, CharSet = CharSet.Auto)]\n private static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public WallpaperService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string GetDefaultWallpaperPath(bool isWindows11, bool isDarkMode)\n {\n return WindowsThemeSettings.Wallpaper.GetDefaultWallpaperPath(isWindows11, isDarkMode);\n }\n\n /// \n public async Task SetDefaultWallpaperAsync(bool isWindows11, bool isDarkMode)\n {\n string wallpaperPath = GetDefaultWallpaperPath(isWindows11, isDarkMode);\n return await SetWallpaperAsync(wallpaperPath);\n }\n\n /// \n public async Task SetWallpaperAsync(string wallpaperPath)\n {\n try\n {\n bool success = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, wallpaperPath,\n SPIF_UPDATEINIFILE | SPIF_SENDCHANGE) != 0;\n\n if (success)\n {\n _logService.Log(LogLevel.Info, $\"Wallpaper set to {wallpaperPath}\");\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to set wallpaper: {Marshal.GetLastWin32Error()}\");\n }\n\n await Task.CompletedTask; // To keep the async signature\n return success;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting wallpaper: {ex.Message}\");\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IPackageManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Provides package management functionality across the application.\n /// \n public interface IPackageManager\n {\n /// \n /// Gets the logging service.\n /// \n ILogService LogService { get; }\n\n /// \n /// Gets the app discovery service.\n /// \n IAppService AppDiscoveryService { get; }\n\n /// \n /// Gets the app removal service.\n /// \n IInstallationService AppRemovalService { get; }\n\n /// \n /// Gets the special app handler service.\n /// \n ISpecialAppHandlerService SpecialAppHandlerService { get; }\n\n /// \n /// Gets the script generation service.\n /// \n IScriptGenerationService ScriptGenerationService { get; }\n\n /// \n /// Gets the system services.\n /// \n ISystemServices SystemServices { get; }\n\n /// \n /// Gets the notification service.\n /// \n INotificationService NotificationService { get; }\n\n /// \n /// Gets all installable applications.\n /// \n /// A collection of installable applications.\n Task> GetInstallableAppsAsync();\n\n /// \n /// Gets all standard (built-in) applications.\n /// \n /// A collection of standard applications.\n Task> GetStandardAppsAsync();\n\n /// \n /// Gets all available Windows capabilities.\n /// \n /// A collection of Windows capabilities.\n Task> GetCapabilitiesAsync();\n\n /// \n /// Gets all available Windows optional features.\n /// \n /// A collection of Windows optional features.\n Task> GetOptionalFeaturesAsync();\n\n /// \n /// Removes a specific application.\n /// \n /// The package name to remove.\n /// Whether the package is a capability.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task RemoveAppAsync(string packageName, bool isCapability = false);\n\n /// \n /// Checks if an application is installed.\n /// \n /// The package name to check.\n /// The cancellation token.\n /// True if the application is installed; otherwise, false.\n Task IsAppInstalledAsync(string packageName, CancellationToken cancellationToken = default);\n\n /// \n /// Removes Microsoft Edge.\n /// \n /// True if Edge was removed successfully; otherwise, false.\n Task RemoveEdgeAsync();\n\n /// \n /// Removes OneDrive.\n /// \n /// True if OneDrive was removed successfully; otherwise, false.\n Task RemoveOneDriveAsync();\n\n /// \n /// Removes OneNote.\n /// \n /// True if OneNote was removed successfully; otherwise, false.\n Task RemoveOneNoteAsync();\n\n /// \n /// Removes a special application.\n /// \n /// The type of special app handler to use.\n /// True if the application was removed successfully; otherwise, false.\n Task RemoveSpecialAppAsync(string appHandlerType);\n\n /// \n /// Removes multiple applications in a batch operation.\n /// \n /// A list of app information to remove.\n /// A list of results indicating success or failure for each application.\n Task> RemoveAppsInBatchAsync(\n List<(string PackageName, bool IsCapability, string? SpecialHandlerType)> apps);\n\n /// \n /// Registers a removal task.\n /// \n /// The removal script to register.\n /// A task representing the asynchronous operation.\n Task RegisterRemovalTaskAsync(RemovalScript script);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/ICustomAppInstallationService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces;\n\n/// \n/// Interface for services that handle custom application installations.\n/// \npublic interface ICustomAppInstallationService\n{\n /// \n /// Installs a custom application.\n /// \n /// Information about the application to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// True if installation was successful; otherwise, false.\n Task InstallCustomAppAsync(\n AppInfo appInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Checks if internet connection is available.\n /// \n /// True if internet connection is available; otherwise, false.\n Task CheckInternetConnectionAsync();\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Models/ExternalApp.cs", "using System;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Models\n{\n public partial class ExternalApp : ObservableObject, ISearchable\n {\n public string Name { get; set; }\n public string Description { get; set; }\n public string PackageName { get; set; }\n public string Version { get; set; } = string.Empty;\n \n [ObservableProperty]\n private bool _isInstalled;\n \n public bool CanBeReinstalled { get; set; }\n \n [ObservableProperty]\n private bool _isSelected;\n \n [ObservableProperty]\n private string _lastOperationError;\n\n public static ExternalApp FromAppInfo(AppInfo appInfo)\n {\n if (appInfo == null)\n throw new ArgumentNullException(nameof(appInfo));\n\n var app = new ExternalApp\n {\n Name = appInfo.Name,\n Description = appInfo.Description,\n PackageName = appInfo.PackageName,\n Version = appInfo.Version,\n CanBeReinstalled = appInfo.CanBeReinstalled,\n Category = appInfo.Category,\n LastOperationError = appInfo.LastOperationError\n };\n \n app.IsInstalled = appInfo.IsInstalled;\n \n return app;\n }\n\n public AppInfo ToAppInfo()\n {\n return new AppInfo\n {\n Name = Name,\n Description = Description,\n PackageName = PackageName,\n Version = Version,\n IsInstalled = IsInstalled,\n CanBeReinstalled = CanBeReinstalled,\n Category = Category,\n LastOperationError = LastOperationError\n };\n }\n\n /// \n /// Gets the category of the app.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Determines if the app matches the given search term.\n /// \n /// The search term to match against.\n /// True if the app matches the search term, false otherwise.\n public bool MatchesSearch(string searchTerm)\n {\n if (string.IsNullOrWhiteSpace(searchTerm))\n {\n return true;\n }\n\n searchTerm = searchTerm.ToLowerInvariant();\n \n // Check if the search term matches any of the searchable properties\n return Name.ToLowerInvariant().Contains(searchTerm) ||\n (!string.IsNullOrEmpty(Description) && Description.ToLowerInvariant().Contains(searchTerm)) ||\n (!string.IsNullOrEmpty(PackageName) && PackageName.ToLowerInvariant().Contains(searchTerm)) ||\n (!string.IsNullOrEmpty(Category) && Category.ToLowerInvariant().Contains(searchTerm));\n }\n\n /// \n /// Gets the searchable properties of the app.\n /// \n /// An array of property names that should be searched.\n public string[] GetSearchableProperties()\n {\n return new[] { nameof(Name), nameof(Description), nameof(PackageName), nameof(Category) };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceValueOperations.cs", "using Microsoft.Win32;\nusing System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Registry service implementation for value operations.\n /// \n public partial class RegistryService\n {\n /// \n /// Sets a value in the registry.\n /// \n /// The registry key path.\n /// The name of the value to set.\n /// The value to set.\n /// The type of the value.\n /// True if the operation succeeded; otherwise, false.\n public bool SetValue(string keyPath, string valueName, object value, RegistryValueKind valueKind)\n {\n try\n {\n if (!CheckWindowsPlatform())\n return false;\n\n _logService.Log(LogLevel.Info, $\"Setting registry value: {keyPath}\\\\{valueName}\");\n\n // First ensure the key exists with full access rights\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return false;\n }\n\n string subKeyPath = string.Join('\\\\', pathParts.Skip(1));\n\n // Create the key with direct Registry API and security settings\n // This will also attempt to take ownership if needed\n RegistryKey? targetKey = EnsureKeyWithFullAccess(rootKey, subKeyPath);\n\n if (targetKey == null)\n {\n _logService.Log(LogLevel.Warning, $\"Could not open or create registry key: {keyPath}\");\n \n // Try using PowerShell as a fallback for policy keys\n if (keyPath.Contains(\"Policies\", StringComparison.OrdinalIgnoreCase))\n {\n _logService.Log(LogLevel.Info, $\"Attempting to set policy registry value using PowerShell: {keyPath}\\\\{valueName}\");\n return SetValueUsingPowerShell(keyPath, valueName, value, valueKind);\n }\n \n return false;\n }\n\n using (targetKey)\n {\n try\n {\n targetKey.SetValue(valueName, value, valueKind);\n\n // Clear the cache for this value\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueCache)\n {\n if (_valueCache.ContainsKey(fullValuePath))\n {\n _valueCache.Remove(fullValuePath);\n }\n }\n\n _logService.Log(LogLevel.Success, $\"Successfully set registry value: {keyPath}\\\\{valueName}\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Failed to set registry value even after taking ownership: {ex.Message}\");\n\n // Try using PowerShell as a fallback\n return SetValueUsingPowerShell(keyPath, valueName, value, valueKind);\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting registry value {keyPath}\\\\{valueName}: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Gets a value from the registry.\n /// \n /// The registry key path.\n /// The name of the value to get.\n /// The value from the registry, or null if it doesn't exist.\n public object? GetValue(string keyPath, string valueName)\n {\n try\n {\n if (!CheckWindowsPlatform())\n return null;\n\n // Check the cache first\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueCache)\n {\n if (_valueCache.TryGetValue(fullValuePath, out object? cachedValue))\n {\n return cachedValue;\n }\n }\n\n // Open the key for reading\n using (RegistryKey? key = OpenRegistryKey(keyPath, false))\n {\n if (key == null)\n {\n _logService.Log(LogLevel.Debug, $\"Registry key does not exist: {keyPath}\");\n \n // Cache the null result\n lock (_valueCache)\n {\n _valueCache[fullValuePath] = null;\n }\n \n return null;\n }\n\n // Get the value\n object? value = key.GetValue(valueName);\n \n // Cache the result\n lock (_valueCache)\n {\n _valueCache[fullValuePath] = value;\n }\n \n return value;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting registry value {keyPath}\\\\{valueName}: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Deletes a value from the registry.\n /// \n /// The registry key path.\n /// The name of the value to delete.\n /// True if the operation succeeded; otherwise, false.\n public bool DeleteValue(string keyPath, string valueName)\n {\n try\n {\n if (!CheckWindowsPlatform())\n return false;\n\n _logService.Log(LogLevel.Info, $\"Deleting registry value: {keyPath}\\\\{valueName}\");\n\n // Open the key for writing\n using (RegistryKey? key = OpenRegistryKey(keyPath, true))\n {\n if (key == null)\n {\n _logService.Log(LogLevel.Warning, $\"Registry key does not exist: {keyPath}\");\n return false;\n }\n\n // Delete the value\n key.DeleteValue(valueName, false);\n \n // Clear the cache for this value\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueCache)\n {\n if (_valueCache.ContainsKey(fullValuePath))\n {\n _valueCache.Remove(fullValuePath);\n }\n }\n \n // Also clear the value exists cache\n lock (_valueExistsCache)\n {\n if (_valueExistsCache.ContainsKey(fullValuePath))\n {\n _valueExistsCache.Remove(fullValuePath);\n }\n }\n\n _logService.Log(LogLevel.Success, $\"Successfully deleted registry value: {keyPath}\\\\{valueName}\");\n return true;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error deleting registry value {keyPath}\\\\{valueName}: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Deletes a value from the registry using hive and subkey.\n /// \n /// The registry hive.\n /// The registry subkey.\n /// The name of the value to delete.\n /// True if the operation succeeded; otherwise, false.\n public async Task DeleteValue(RegistryHive hive, string subKey, string valueName)\n {\n string keyPath = $\"{RegistryExtensions.GetRegistryHiveString(hive)}\\\\{subKey}\";\n return DeleteValue(keyPath, valueName);\n }\n\n /// \n /// Checks if a registry value exists.\n /// \n /// The registry key path.\n /// The name of the value to check.\n /// True if the value exists; otherwise, false.\n public bool ValueExists(string keyPath, string valueName)\n {\n try\n {\n if (!CheckWindowsPlatform())\n return false;\n\n // Check the cache first\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueExistsCache)\n {\n if (_valueExistsCache.TryGetValue(fullValuePath, out bool exists))\n {\n return exists;\n }\n }\n\n // Open the key for reading\n using (RegistryKey? key = OpenRegistryKey(keyPath, false))\n {\n if (key == null)\n {\n // Cache the result\n lock (_valueExistsCache)\n {\n _valueExistsCache[fullValuePath] = false;\n }\n \n return false;\n }\n\n // Check if the value exists\n string[] valueNames = key.GetValueNames();\n bool exists = valueNames.Contains(valueName, StringComparer.OrdinalIgnoreCase);\n \n // Cache the result\n lock (_valueExistsCache)\n {\n _valueExistsCache[fullValuePath] = exists;\n }\n \n return exists;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking if registry value exists {keyPath}\\\\{valueName}: {ex.Message}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/UpdateNotificationDialog.xaml.cs", "using System;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Update notification dialog that shows when a new version is available\n /// \n public partial class UpdateNotificationDialog : Window\n {\n // Default text content for the update dialog\n private static readonly string DefaultTitle = \"Update Available\";\n private static readonly string DefaultUpdateMessage = \"A new version of Winhance is available.\";\n \n public UpdateNotificationDialog(UpdateNotificationViewModel viewModel)\n {\n InitializeComponent();\n DataContext = viewModel;\n }\n \n private void PrimaryButton_Click(object sender, RoutedEventArgs e)\n {\n // Download and install\n if (DataContext is UpdateNotificationViewModel viewModel)\n {\n viewModel.DownloadAndInstallUpdateCommand.Execute(null);\n }\n }\n\n private void SecondaryButton_Click(object sender, RoutedEventArgs e)\n {\n // Remind later\n if (DataContext is UpdateNotificationViewModel viewModel)\n {\n viewModel.RemindLaterCommand.Execute(null);\n }\n DialogResult = false;\n Close();\n }\n \n private void CloseButton_Click(object sender, RoutedEventArgs e)\n {\n // Close without action\n DialogResult = false;\n Close();\n }\n \n /// \n /// Creates and shows an update notification dialog with the specified parameters.\n /// This method ensures the dialog is properly modal and blocks the main window.\n /// \n /// The view model containing update information\n /// The dialog title (optional - uses default if empty)\n /// The update message (optional - uses default if empty)\n /// The dialog instance with DialogResult set\n public static async Task ShowUpdateDialogAsync(\n UpdateNotificationViewModel viewModel,\n string title = \"\",\n string updateMessage = \"\")\n {\n try\n {\n var dialog = new UpdateNotificationDialog(viewModel)\n {\n Title = string.IsNullOrEmpty(title) ? DefaultTitle : title,\n WindowStartupLocation = WindowStartupLocation.CenterOwner,\n ShowInTaskbar = false,\n ResizeMode = ResizeMode.NoResize,\n WindowStyle = WindowStyle.None,\n AllowsTransparency = true\n };\n\n // Set the update message\n dialog.UpdateMessageText.Text = string.IsNullOrEmpty(updateMessage) ? DefaultUpdateMessage : updateMessage;\n \n // Set button content\n dialog.PrimaryButton.Content = \"Download and Install\";\n dialog.SecondaryButton.Content = \"Remind Later\";\n\n // Set the owner to the main window to ensure it appears on top\n if (Application.Current.MainWindow != null && Application.Current.MainWindow != dialog)\n {\n dialog.Owner = Application.Current.MainWindow;\n dialog.Topmost = true; // Ensure it stays on top\n }\n else\n {\n // Try to find the main window another way\n foreach (Window window in Application.Current.Windows)\n {\n if (window != dialog && window.IsVisible)\n {\n dialog.Owner = window;\n dialog.Topmost = true;\n break;\n }\n }\n }\n\n // Make the dialog visible and focused\n dialog.Visibility = Visibility.Visible;\n dialog.Activate();\n dialog.Focus();\n \n // Show the dialog and wait for it to complete\n dialog.ShowDialog();\n \n // Return the dialog\n return dialog;\n }\n catch (Exception ex)\n {\n // Show error message\n MessageBox.Show($\"Error showing update dialog: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n \n // Create a dummy dialog with error result\n var errorDialog = new UpdateNotificationDialog(viewModel);\n errorDialog.DialogResult = false;\n return errorDialog;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/LoadingWindow.xaml.cs", "using System;\nusing System.Diagnostics;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Media.Imaging;\nusing System.Runtime.InteropServices;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Interaction logic for LoadingWindow.xaml\n /// \n public partial class LoadingWindow : Window\n {\n private readonly IThemeManager? _themeManager;\n private LoadingWindowViewModel? _viewModel;\n\n /// \n /// Default constructor for design-time\n /// \n public LoadingWindow()\n {\n // Ignore this error, it works fine in the designer\n InitializeComponent();\n }\n\n /// \n /// Constructor with dependency injection\n /// \n /// The theme manager\n public LoadingWindow(IThemeManager themeManager)\n {\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n // Ignore this error, it works fine in the designer\n InitializeComponent();\n }\n\n /// \n /// Constructor with dependency injection and progress service\n /// \n /// The theme manager\n /// The progress service\n public LoadingWindow(IThemeManager themeManager, ITaskProgressService progressService)\n {\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n // Ignore this error, it works fine in the designer\n InitializeComponent();\n\n // Create and set the view model\n _viewModel = new LoadingWindowViewModel(progressService);\n DataContext = _viewModel;\n\n // Set the appropriate icon based on the theme\n UpdateThemeIcon();\n }\n\n /// \n /// Called when the window source is initialized\n /// \n /// Event arguments\n protected override void OnSourceInitialized(EventArgs e)\n {\n base.OnSourceInitialized(e);\n\n try\n {\n var helper = new WindowInteropHelper(this);\n if (helper.Handle != IntPtr.Zero)\n {\n EnableBlur();\n }\n }\n catch (Exception)\n {\n // Ignore blur errors - not critical for loading window\n }\n }\n\n /// \n /// Enables the blur effect on the window\n /// \n private void EnableBlur()\n {\n var windowHelper = new WindowInteropHelper(this);\n var accent = new AccentPolicy { AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND };\n var accentStructSize = Marshal.SizeOf(accent);\n\n var accentPtr = IntPtr.Zero;\n try\n {\n accentPtr = Marshal.AllocHGlobal(accentStructSize);\n Marshal.StructureToPtr(accent, accentPtr, false);\n\n var data = new WindowCompositionAttributeData\n {\n Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY,\n SizeOfData = accentStructSize,\n Data = accentPtr\n };\n\n SetWindowCompositionAttribute(windowHelper.Handle, ref data);\n }\n finally\n {\n if (accentPtr != IntPtr.Zero)\n {\n Marshal.FreeHGlobal(accentPtr);\n }\n }\n }\n\n /// \n /// P/Invoke for SetWindowCompositionAttribute\n /// \n [DllImport(\"user32.dll\")]\n internal static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data);\n\n /// \n /// Accent policy structure\n /// \n [StructLayout(LayoutKind.Sequential)]\n internal struct AccentPolicy\n {\n public AccentState AccentState;\n public int AccentFlags;\n public int GradientColor;\n public int AnimationId;\n }\n\n /// \n /// Window composition attribute data structure\n /// \n [StructLayout(LayoutKind.Sequential)]\n internal struct WindowCompositionAttributeData\n {\n public WindowCompositionAttribute Attribute;\n public IntPtr Data;\n public int SizeOfData;\n }\n\n /// \n /// Accent state enum\n /// \n internal enum AccentState\n {\n ACCENT_DISABLED = 0,\n ACCENT_ENABLE_GRADIENT = 1,\n ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,\n ACCENT_ENABLE_BLURBEHIND = 3,\n ACCENT_ENABLE_ACRYLICBLURBEHIND = 4,\n ACCENT_INVALID_STATE = 5\n }\n\n /// \n /// Window composition attribute enum\n /// \n internal enum WindowCompositionAttribute\n {\n WCA_ACCENT_POLICY = 19\n }\n\n /// \n /// Updates the window and image icons based on the current theme\n /// \n private void UpdateThemeIcon()\n {\n if (_themeManager == null)\n {\n Debug.WriteLine(\"Cannot update theme icon: ThemeManager is null\");\n return;\n }\n\n try\n {\n Debug.WriteLine($\"Updating theme icon. Current theme: {(_themeManager.IsDarkTheme ? \"Dark\" : \"Light\")}\");\n\n // Get the appropriate icon based on the theme\n string iconPath = _themeManager.IsDarkTheme\n ? \"pack://application:,,,/Resources/AppIcons/winhance-rocket-white-transparent-bg.ico\"\n : \"pack://application:,,,/Resources/AppIcons/winhance-rocket-black-transparent-bg.ico\";\n\n Debug.WriteLine($\"Selected icon path: {iconPath}\");\n\n // Create a BitmapImage from the icon path\n var iconImage = new BitmapImage(new Uri(iconPath, UriKind.Absolute));\n iconImage.Freeze(); // Freeze for better performance and thread safety\n\n // Set the window icon\n this.Icon = iconImage;\n Debug.WriteLine(\"Window icon updated\");\n\n // Set the image control source\n if (AppIconImage != null)\n {\n AppIconImage.Source = iconImage;\n Debug.WriteLine(\"AppIconImage source updated\");\n }\n else\n {\n Debug.WriteLine(\"AppIconImage is null, cannot update source\");\n }\n }\n catch (Exception ex)\n {\n // If there's an error, fall back to the default icon\n try\n {\n var defaultIcon = new BitmapImage(new Uri(\"pack://application:,,,/Resources/AppIcons/winhance-rocket.ico\", UriKind.Absolute));\n this.Icon = defaultIcon;\n if (AppIconImage != null)\n {\n AppIconImage.Source = defaultIcon;\n }\n }\n catch\n {\n // Ignore any errors with the fallback icon\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/WindowsAppCatalog.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a catalog of Windows built-in applications that can be removed.\n/// \npublic class WindowsAppCatalog\n{\n /// \n /// Gets or sets the collection of removable Windows applications.\n /// \n public IReadOnlyList WindowsApps { get; init; } = new List();\n\n /// \n /// Creates a default Windows app catalog with predefined removable apps.\n /// \n /// A new WindowsAppCatalog instance with default apps.\n public static WindowsAppCatalog CreateDefault()\n {\n return new WindowsAppCatalog { WindowsApps = CreateDefaultWindowsApps() };\n }\n\n private static List CreateDefaultWindowsApps()\n {\n return new List\n {\n // 3D/Mixed Reality\n new AppInfo\n {\n Name = \"3D Viewer\",\n Description = \"View 3D models and animations\",\n PackageName = \"Microsoft.Microsoft3DViewer\",\n PackageID = \"9NBLGGH42THS\",\n Category = \"3D/Mixed Reality\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Mixed Reality Portal\",\n Description = \"Portal for Windows Mixed Reality experiences\",\n PackageName = \"Microsoft.MixedReality.Portal\",\n PackageID = \"9NG1H8B3ZC7M\",\n Category = \"3D/Mixed Reality\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Bing/Search\n new AppInfo\n {\n Name = \"Bing Search\",\n Description = \"Bing search integration for Windows\",\n PackageName = \"Microsoft.BingSearch\",\n PackageID = \"9NZBF4GT040C\",\n Category = \"Bing\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Microsoft News\",\n Description = \"Microsoft News app\",\n PackageName = \"Microsoft.BingNews\",\n PackageID = \"9WZDNCRFHVFW\",\n Category = \"Bing\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"MSN Weather\",\n Description = \"Weather forecasts and information\",\n PackageName = \"Microsoft.BingWeather\",\n PackageID = \"9WZDNCRFJ3Q2\",\n Category = \"Bing/Search\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Camera/Media\n new AppInfo\n {\n Name = \"Camera\",\n Description = \"Windows Camera app\",\n PackageName = \"Microsoft.WindowsCamera\",\n PackageID = \"9WZDNCRFJBBG\",\n Category = \"Camera/Media\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Clipchamp\",\n Description = \"Video editor app\",\n PackageName = \"Clipchamp.Clipchamp\",\n PackageID = \"9P1J8S7CCWWT\",\n Category = \"Camera/Media\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // System Utilities\n new AppInfo\n {\n Name = \"Alarms & Clock\",\n Description = \"Clock, alarms, timer, and stopwatch app\",\n PackageName = \"Microsoft.WindowsAlarms\",\n PackageID = \"9WZDNCRFJ3PR\",\n Category = \"System Utilities\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Cortana\",\n Description = \"Microsoft's virtual assistant\",\n PackageName = \"Microsoft.549981C3F5F10\",\n PackageID = \"9NFFX4SZZ23L\",\n Category = \"System Utilities\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Get Help\",\n Description = \"Microsoft support app\",\n PackageName = \"Microsoft.GetHelp\",\n PackageID = \"9PKDZBMV1H3T\",\n Category = \"System Utilities\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Calculator\",\n Description = \"Calculator app with standard, scientific, and programmer modes\",\n PackageName = \"Microsoft.WindowsCalculator\",\n PackageID = \"9WZDNCRFHVN5\",\n Category = \"System Utilities\",\n IsSystemProtected = true,\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Development\n new AppInfo\n {\n Name = \"Dev Home\",\n Description = \"Development environment for Windows\",\n PackageName = \"Microsoft.Windows.DevHome\",\n PackageID = \"9WZDNCRFHVN5\",\n Category = \"Development\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Communication & Family\n new AppInfo\n {\n Name = \"Microsoft Family Safety\",\n Description = \"Family safety and screen time management\",\n PackageName = \"MicrosoftCorporationII.MicrosoftFamily\",\n PackageID = \"9PDJDJS743XF\",\n Category = \"Communication\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Mail and Calendar\",\n Description = \"Microsoft Mail and Calendar apps\",\n PackageName = \"microsoft.windowscommunicationsapps\",\n PackageID = \"9WZDNCRFHVQM\",\n Category = \"Communication\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Skype\",\n Description = \"Video calling and messaging app\",\n PackageName = \"Microsoft.SkypeApp\",\n PackageID = \"9WZDNCRFJ364\",\n Category = \"Communication\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Microsoft Teams\",\n Description = \"Team collaboration and communication app\",\n PackageName = \"MSTeams\",\n PackageID = \"XP8BT8DW290MPQ\",\n Category = \"Communication\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // System Tools\n new AppInfo\n {\n Name = \"Feedback Hub\",\n Description = \"App for sending feedback to Microsoft\",\n PackageName = \"Microsoft.WindowsFeedbackHub\",\n PackageID = \"9NBLGGH4R32N\",\n Category = \"System Tools\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Maps\",\n Description = \"Microsoft Maps app\",\n PackageName = \"Microsoft.WindowsMaps\",\n PackageID = \"9WZDNCRDTBVB\",\n Category = \"System Tools\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Terminal\",\n Description = \"Modern terminal application for Windows\",\n PackageName = \"Microsoft.WindowsTerminal\",\n PackageID = \"9N0DX20HK701\",\n Category = \"System Tools\",\n IsSystemProtected = true,\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Office & Productivity\n new AppInfo\n {\n Name = \"Office Hub\",\n Description = \"Microsoft Office app hub\",\n PackageName = \"Microsoft.MicrosoftOfficeHub\",\n Category = \"Office\",\n CanBeReinstalled = false,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"OneNote\",\n Description = \"Microsoft note-taking app\",\n PackageName = \"Microsoft.Office.OneNote\",\n PackageID = \"XPFFZHVGQWWLHB\",\n Category = \"Office\",\n CanBeReinstalled = true,\n RequiresSpecialHandling = true,\n SpecialHandlerType = \"OneNote\",\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Outlook for Windows\",\n Description = \"Reimagined Outlook app for Windows\",\n PackageName = \"Microsoft.OutlookForWindows\",\n PackageID = \"9NRX63209R7B\",\n Category = \"Office\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Graphics & Images\n new AppInfo\n {\n Name = \"Paint 3D\",\n Description = \"3D modeling and editing app\",\n PackageName = \"Microsoft.MSPaint\",\n Category = \"Graphics\",\n CanBeReinstalled = false,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Paint\",\n Description = \"Traditional image editing app\",\n PackageName = \"Microsoft.Paint\",\n PackageID = \"9PCFS5B6T72H\",\n Category = \"Graphics\",\n IsSystemProtected = true,\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Photos\",\n Description = \"Photo viewing and editing app\",\n PackageName = \"Microsoft.Windows.Photos\",\n PackageID = \"9WZDNCRFJBH4\",\n Category = \"Graphics\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Snipping Tool\",\n Description = \"Screen capture and annotation tool\",\n PackageName = \"Microsoft.ScreenSketch\",\n PackageID = \"9MZ95KL8MR0L\",\n Category = \"Graphics\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Social & People\n new AppInfo\n {\n Name = \"People\",\n Description = \"Contact management app\",\n PackageName = \"Microsoft.People\",\n PackageID = \"9NBLGGH10PG8\",\n Category = \"Social\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Automation\n new AppInfo\n {\n Name = \"Power Automate\",\n Description = \"Desktop automation tool\",\n PackageName = \"Microsoft.PowerAutomateDesktop\",\n PackageID = \"9NFTCH6J7FHV\",\n Category = \"Automation\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Support Tools\n new AppInfo\n {\n Name = \"Quick Assist\",\n Description = \"Remote assistance tool\",\n PackageName = \"MicrosoftCorporationII.QuickAssist\",\n PackageID = \"9P7BP5VNWKX5\",\n Category = \"Support\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Games & Entertainment\n new AppInfo\n {\n Name = \"Solitaire Collection\",\n Description = \"Microsoft Solitaire Collection games\",\n PackageName = \"Microsoft.MicrosoftSolitaireCollection\",\n PackageID = \"9WZDNCRFHWD2\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Xbox\",\n Description = \"Xbox App for Windows\",\n PackageName = \"Microsoft.GamingApp\", // New Xbox Package Name (Windows 11)\n PackageID = \"9MV0B5HZVK9Z\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n SubPackages = new string[]\n {\n \"Microsoft.XboxApp\", // Microsoft.XboxApp is deprecated but still on Windows 10 22H2 ISO's\n },\n RegistrySettings = new AppRegistrySetting[]\n {\n new AppRegistrySetting\n {\n Path = @\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\GameDVR\",\n Name = \"AppCaptureEnabled\",\n Value = 0,\n ValueKind = Microsoft.Win32.RegistryValueKind.DWord,\n Description =\n \"Disables the Get an app to open this 'ms-gamingoverlay' popup\",\n },\n },\n },\n new AppInfo\n {\n Name = \"Xbox Identity Provider\",\n Description =\n \"Authentication service for Xbox Live and related Microsoft gaming services\",\n PackageName = \"Microsoft.XboxIdentityProvider\",\n PackageID = \"9WZDNCRD1HKW\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Xbox Game Bar Plugin\",\n Description =\n \"Extension component for Xbox Game Bar providing additional functionality\",\n PackageName = \"Microsoft.XboxGameOverlay\",\n PackageID = \"9NBLGGH537C2\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Xbox Live In-Game Experience\",\n Description = \"Core component for Xbox Live services within games\",\n PackageName = \"Microsoft.Xbox.TCUI\",\n PackageID = \"9NKNC0LD5NN6\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Xbox Game Bar\",\n Description =\n \"Gaming overlay with screen capture, performance monitoring, and social features\",\n PackageName = \"Microsoft.XboxGamingOverlay\",\n PackageID = \"9NZKPSTSNW4P\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Windows Store\n new AppInfo\n {\n Name = \"Microsoft Store\",\n Description = \"App store for Windows\",\n PackageName = \"Microsoft.WindowsStore\",\n PackageID = \"9WZDNCRFJBMP\",\n Category = \"Store\",\n IsSystemProtected = true,\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Media Players\n new AppInfo\n {\n Name = \"Media Player\",\n Description = \"Music player app\",\n PackageName = \"Microsoft.ZuneMusic\",\n PackageID = \"9WZDNCRFJ3PT\",\n Category = \"Media\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Movies & TV\",\n Description = \"Video player app\",\n PackageName = \"Microsoft.ZuneVideo\",\n PackageID = \"9WZDNCRFJ3P2\",\n Category = \"Media\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Sound Recorder\",\n Description = \"Audio recording app\",\n PackageName = \"Microsoft.WindowsSoundRecorder\",\n PackageID = \"9WZDNCRFHWKN\",\n Category = \"Media\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Productivity Tools\n new AppInfo\n {\n Name = \"Sticky Notes\",\n Description = \"Note-taking app\",\n PackageName = \"Microsoft.MicrosoftStickyNotes\",\n PackageID = \"9NBLGGH4QGHW\",\n Category = \"Productivity\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Tips\",\n Description = \"Windows tutorial app\",\n PackageName = \"Microsoft.Getstarted\",\n Category = \"Productivity\",\n CanBeReinstalled = false,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"To Do\",\n Description = \"Task management app\",\n PackageName = \"Microsoft.Todos\",\n PackageID = \"9NBLGGH5R558\",\n Category = \"Productivity\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Notepad\",\n Description = \"Text editing app\",\n PackageName = \"Microsoft.WindowsNotepad\",\n PackageID = \"9MSMLRH6LZF3\",\n Category = \"Productivity\",\n IsSystemProtected = true,\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Phone Integration\n new AppInfo\n {\n Name = \"Phone Link\",\n Description = \"Connect your Android or iOS device to Windows\",\n PackageName = \"Microsoft.YourPhone\",\n PackageID = \"9NMPJ99VJBWV\",\n Category = \"Phone\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // AI & Copilot\n new AppInfo\n {\n Name = \"Copilot\",\n Description =\n \"AI assistant for Windows, includes Copilot provider and Store components\",\n PackageName = \"Microsoft.Copilot\",\n PackageID = \"9NHT9RB2F4HD\",\n Category = \"AI\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n SubPackages = new string[]\n {\n \"Microsoft.Windows.Ai.Copilot.Provider\",\n \"Microsoft.Copilot_8wekyb3d8bbwe\",\n },\n RegistrySettings = new AppRegistrySetting[]\n {\n new AppRegistrySetting\n {\n Path = @\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced\",\n Name = \"ShowCopilotButton\",\n Value = 0,\n ValueKind = Microsoft.Win32.RegistryValueKind.DWord,\n Description = \"Hide Copilot button from taskbar\",\n },\n new AppRegistrySetting\n {\n Path = @\"HKLM\\Software\\Policies\\Microsoft\\Windows\\CloudContent\",\n Name = \"TurnOffWindowsCopilot\",\n Value = 1,\n ValueKind = Microsoft.Win32.RegistryValueKind.DWord,\n Description = \"Disable Windows Copilot system-wide\",\n },\n },\n },\n // Special Items that require special handling\n new AppInfo\n {\n Name = \"Microsoft Edge\",\n Description = \"Microsoft's web browser (requires special removal process)\",\n PackageName = \"Edge\",\n PackageID = \"XPFFTQ037JWMHS\",\n Category = \"Browsers\",\n CanBeReinstalled = true,\n RequiresSpecialHandling = true,\n SpecialHandlerType = \"Edge\",\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"OneDrive\",\n Description =\n \"Microsoft's cloud storage service (requires special removal process)\",\n PackageName = \"OneDrive\",\n PackageID = \"Microsoft.OneDrive\",\n Category = \"System\",\n CanBeReinstalled = true,\n RequiresSpecialHandling = true,\n SpecialHandlerType = \"OneDrive\",\n Type = AppType.StandardApp,\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/SearchableViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// Base view model class that provides search functionality.\n /// \n /// The type of items to search, must implement ISearchable.\n public abstract partial class SearchableViewModel : AppListViewModel where T : class, ISearchable\n {\n private readonly ISearchService _searchService;\n\n // Backing field for the search text\n private string _searchText = string.Empty;\n\n /// \n /// Gets or sets the search text.\n /// \n public virtual string SearchText\n {\n get => _searchText;\n set\n {\n if (SetProperty(ref _searchText, value))\n {\n IsSearchActive = !string.IsNullOrWhiteSpace(value);\n ApplySearch();\n }\n }\n }\n\n /// \n /// Gets a value indicating whether search is active.\n /// \n [ObservableProperty]\n private bool _isSearchActive;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The search service.\n /// The package manager.\n protected SearchableViewModel(\n ITaskProgressService progressService,\n ISearchService searchService,\n IPackageManager? packageManager = null) \n : base(progressService, packageManager)\n {\n _searchService = searchService ?? throw new ArgumentNullException(nameof(searchService));\n }\n\n /// \n /// Applies the current search text to filter items.\n /// \n protected abstract void ApplySearch();\n\n /// \n /// Filters a collection of items based on the current search text.\n /// \n /// The collection of items to filter.\n /// A filtered collection of items that match the search text.\n protected IEnumerable FilterItems(IEnumerable items)\n {\n Console.WriteLine($\"SearchableViewModel.FilterItems: Filtering {items.Count()} items with search text '{SearchText}'\");\n \n // Log items before filtering\n foreach (var item in items)\n {\n var itemName = item.GetType().GetProperty(\"Name\")?.GetValue(item)?.ToString();\n var itemGroupName = item.GetType().GetProperty(\"GroupName\")?.GetValue(item)?.ToString();\n \n if (itemName?.Contains(\"Web Search\") == true || itemGroupName?.Contains(\"Search\") == true)\n {\n Console.WriteLine($\"SearchableViewModel.FilterItems: Found item before filtering - Name: '{itemName}', GroupName: '{itemGroupName}'\");\n }\n }\n \n var result = _searchService.FilterItems(items, SearchText);\n \n // Log filtered results\n Console.WriteLine($\"SearchableViewModel.FilterItems: Filtered result count: {result.Count()}\");\n \n return result;\n }\n\n /// \n /// Asynchronously filters a collection of items based on the current search text.\n /// \n /// The collection of items to filter.\n /// A task that represents the asynchronous operation. The task result contains a filtered collection of items that match the search text.\n protected Task> FilterItemsAsync(IEnumerable items)\n {\n return _searchService.FilterItemsAsync(items, SearchText);\n }\n\n /// \n /// Clears the search text.\n /// \n protected void ClearSearch()\n {\n SearchText = string.Empty;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/WindowsThemeSettings.cs", "using Microsoft.Win32;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Enums;\nusing Winhance.Core.Features.Customize.Interfaces;\n\nnamespace Winhance.Core.Features.Customize.Models\n{\n /// \n /// Model for Windows theme settings.\n /// \n public class WindowsThemeSettings\n {\n // Registry paths and keys\n public static class Registry\n {\n public const string ThemesPersonalizeSubKey = @\"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\";\n public const string AppsUseLightThemeName = \"AppsUseLightTheme\";\n public const string SystemUsesLightThemeName = \"SystemUsesLightTheme\";\n }\n\n // Wallpaper paths\n public static class Wallpaper\n {\n // Windows 11 wallpaper paths\n public const string Windows11BasePath = @\"C:\\Windows\\Web\\Wallpaper\\Windows\";\n public const string Windows11LightWallpaper = \"img0.jpg\";\n public const string Windows11DarkWallpaper = \"img19.jpg\";\n\n // Windows 10 wallpaper path\n public const string Windows10Wallpaper = @\"C:\\Windows\\Web\\4K\\Wallpaper\\Windows\\img0_3840x2160.jpg\";\n\n public static string GetDefaultWallpaperPath(bool isWindows11, bool isDarkMode)\n {\n if (isWindows11)\n {\n return System.IO.Path.Combine(\n Windows11BasePath, \n isDarkMode ? Windows11DarkWallpaper : Windows11LightWallpaper);\n }\n \n return Windows10Wallpaper;\n }\n }\n\n private readonly IThemeService _themeService;\n private bool _isDarkMode;\n private bool _changeWallpaper;\n\n /// \n /// Gets or sets a value indicating whether dark mode is enabled.\n /// \n public bool IsDarkMode\n {\n get => _isDarkMode;\n set => _isDarkMode = value;\n }\n\n /// \n /// Gets or sets a value indicating whether to change the wallpaper when changing the theme.\n /// \n public bool ChangeWallpaper\n {\n get => _changeWallpaper;\n set => _changeWallpaper = value;\n }\n\n /// \n /// Gets the current theme name.\n /// \n public string ThemeName => IsDarkMode ? \"Dark Mode\" : \"Light Mode\";\n\n /// \n /// Gets the available theme options.\n /// \n public List ThemeOptions { get; } = new List { \"Light Mode\", \"Dark Mode\" };\n\n /// \n /// Initializes a new instance of the class.\n /// \n public WindowsThemeSettings()\n {\n // Default constructor for serialization\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The theme service.\n public WindowsThemeSettings(IThemeService themeService)\n {\n _themeService = themeService;\n _isDarkMode = themeService?.IsDarkModeEnabled() ?? false;\n }\n\n /// \n /// Loads the current theme settings from the system.\n /// \n public void LoadCurrentSettings()\n {\n if (_themeService != null)\n {\n _isDarkMode = _themeService.IsDarkModeEnabled();\n }\n }\n\n /// \n /// Applies the current theme settings to the system.\n /// \n /// True if the operation succeeded; otherwise, false.\n public bool ApplyTheme()\n {\n return _themeService?.SetThemeMode(_isDarkMode) ?? false;\n }\n\n /// \n /// Applies the current theme settings to the system asynchronously.\n /// \n /// A task representing the asynchronous operation.\n public async Task ApplyThemeAsync()\n {\n if (_themeService == null)\n return false;\n\n return await _themeService.ApplyThemeAsync(_isDarkMode, _changeWallpaper);\n }\n\n /// \n /// Creates registry settings for Windows theme.\n /// \n /// A list of registry settings.\n public static List CreateRegistrySettings()\n {\n return new List\n {\n new RegistrySetting\n {\n Category = \"WindowsTheme\",\n Hive = RegistryHive.CurrentUser,\n SubKey = Registry.ThemesPersonalizeSubKey,\n Name = Registry.AppsUseLightThemeName,\n EnabledValue = 0, // Dark mode\n DisabledValue = 1, // Light mode\n ValueType = RegistryValueKind.DWord,\n Description = \"Windows Apps Theme Mode\",\n // For backward compatibility\n RecommendedValue = 0,\n DefaultValue = 1\n },\n new RegistrySetting\n {\n Category = \"WindowsTheme\",\n Hive = RegistryHive.CurrentUser,\n SubKey = Registry.ThemesPersonalizeSubKey,\n Name = Registry.SystemUsesLightThemeName,\n EnabledValue = 0, // Dark mode\n DisabledValue = 1, // Light mode\n ValueType = RegistryValueKind.DWord,\n Description = \"Windows System Theme Mode\",\n // For backward compatibility\n RecommendedValue = 0,\n DefaultValue = 1\n }\n };\n }\n\n /// \n /// Creates a customization setting for Windows theme.\n /// \n /// A customization setting.\n public static CustomizationSetting CreateCustomizationSetting()\n {\n var setting = new CustomizationSetting\n {\n Id = \"WindowsTheme\",\n Name = \"Windows Theme\",\n Description = \"Toggle between light and dark theme for Windows\",\n GroupName = \"Windows Theme\",\n Category = CustomizationCategory.Theme,\n ControlType = ControlType.ComboBox,\n RegistrySettings = CreateRegistrySettings()\n };\n\n return setting;\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/DonationDialog.xaml.cs", "using System;\nusing System.Threading.Tasks;\nusing System.Windows;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Donation dialog that extends CustomDialog with a \"Don't show this again\" checkbox\n /// \n public partial class DonationDialog : Window\n {\n // Default text content for the donation dialog\n private static readonly string DefaultTitle = \"Support Winhance\";\n private static readonly string DefaultSupportMessage = \"Your support helps keep this project going!\";\n private static readonly string DefaultFooterText = \"Click 'Yes' to show your support!\";\n\n public bool DontShowAgain => DontShowAgainCheckBox.IsChecked ?? false;\n\n public DonationDialog()\n {\n InitializeComponent();\n DataContext = this;\n }\n\n private void PrimaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = true;\n Close();\n }\n\n private void SecondaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = false;\n Close();\n }\n \n private void TertiaryButton_Click(object sender, RoutedEventArgs e)\n {\n // Explicitly set DialogResult to null for Cancel\n DialogResult = null;\n Close();\n }\n\n /// \n /// Creates and shows a donation dialog with the specified parameters.\n /// This method ensures the dialog is properly modal and blocks the main window.\n /// \n /// The dialog title (optional - uses default if null)\n /// The support message (optional - uses default if null)\n /// The footer text (optional - uses default if null)\n /// The dialog instance with DialogResult set\n public static async Task ShowDonationDialogAsync(string title = null, string supportMessage = null, string footerText = null)\n {\n try\n {\n var dialog = new DonationDialog\n {\n Title = title ?? DefaultTitle,\n WindowStartupLocation = WindowStartupLocation.CenterOwner,\n ShowInTaskbar = false,\n ResizeMode = ResizeMode.NoResize,\n WindowStyle = WindowStyle.None,\n AllowsTransparency = true\n };\n\n // Set the support message and footer text\n dialog.SupportMessageText.Text = supportMessage ?? DefaultSupportMessage;\n dialog.FooterText.Text = footerText ?? DefaultFooterText;\n \n // Set button content\n dialog.PrimaryButton.Content = \"Yes\";\n dialog.SecondaryButton.Content = \"No\";\n\n // Set the owner to the main window to ensure it appears on top\n if (Application.Current.MainWindow != null && Application.Current.MainWindow != dialog)\n {\n dialog.Owner = Application.Current.MainWindow;\n dialog.Topmost = true; // Ensure it stays on top\n }\n else\n {\n // Try to find the main window another way\n foreach (Window window in Application.Current.Windows)\n {\n if (window != dialog && window.IsVisible)\n {\n dialog.Owner = window;\n dialog.Topmost = true;\n break;\n }\n }\n }\n\n // Make the dialog visible and focused\n dialog.Visibility = Visibility.Visible;\n dialog.Activate();\n dialog.Focus();\n \n // Show the dialog and wait for it to complete\n dialog.ShowDialog();\n \n // Return the dialog\n return dialog;\n }\n catch (Exception ex)\n {\n // Show error message\n MessageBox.Show($\"Error showing donation dialog: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n \n // Create a dummy dialog with error result\n var errorDialog = new DonationDialog();\n errorDialog.DialogResult = false;\n return errorDialog;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Services/LogService.cs", "using System;\nusing System.IO;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Services\n{\n public class LogService : ILogService\n {\n private string _logPath;\n private StreamWriter? _logWriter;\n private readonly object _lockObject = new object();\n \n public event EventHandler? LogMessageGenerated;\n\n public LogService()\n {\n _logPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\",\n $\"Winhance_Log_{DateTime.Now:yyyyMMdd_HHmmss}.log\"\n );\n }\n\n public void Log(LogLevel level, string message, Exception? exception = null)\n {\n switch (level)\n {\n case LogLevel.Info:\n LogInformation(message);\n break;\n case LogLevel.Warning:\n LogWarning(message);\n break;\n case LogLevel.Error:\n LogError(message, exception);\n break;\n case LogLevel.Success:\n LogSuccess(message);\n break;\n default:\n LogInformation(message);\n break;\n }\n \n // Raise event for subscribers\n LogMessageGenerated?.Invoke(this, new LogMessageEventArgs(level, message, exception));\n }\n \n // This method should be removed, but it might still be used in some places\n // Redirecting to the standard method with correct parameter order\n public void Log(string message, LogLevel level)\n {\n Log(level, message);\n }\n\n public void StartLog()\n {\n try\n {\n // Ensure directory exists\n var logDirectory = Path.GetDirectoryName(_logPath);\n if (logDirectory != null)\n {\n Directory.CreateDirectory(logDirectory);\n }\n else\n {\n throw new InvalidOperationException(\"Log directory path is null.\");\n }\n\n // Create or overwrite log file\n _logWriter = new StreamWriter(_logPath, false, Encoding.UTF8)\n {\n AutoFlush = true\n };\n\n // Write initial log header\n LogInformation($\"==== Winhance Log Started ====\");\n LogInformation($\"Timestamp: {DateTime.Now}\");\n LogInformation($\"User: {Environment.UserName}\");\n LogInformation($\"Machine: {Environment.MachineName}\");\n LogInformation($\"OS Version: {Environment.OSVersion}\");\n LogInformation(\"===========================\");\n }\n catch (Exception ex)\n {\n // Fallback logging if file write fails\n Console.Error.WriteLine($\"Failed to start log: {ex.Message}\");\n }\n }\n\n public void StopLog()\n {\n lock (_lockObject)\n {\n try\n {\n LogInformation(\"==== Winhance Log Ended ====\");\n _logWriter?.Close();\n _logWriter?.Dispose();\n }\n catch (Exception ex)\n {\n Console.Error.WriteLine($\"Error stopping log: {ex.Message}\");\n }\n }\n }\n\n public void LogInformation(string message)\n {\n WriteLog(message, \"INFO\");\n }\n\n public void LogWarning(string message)\n {\n WriteLog(message, \"WARNING\");\n }\n\n public void LogError(string message, Exception? exception = null)\n {\n string fullMessage = exception != null\n ? $\"{message} - Exception: {exception.Message}\\n{exception.StackTrace}\"\n : message;\n WriteLog(fullMessage, \"ERROR\");\n }\n\n public void LogSuccess(string message)\n {\n WriteLog(message, \"SUCCESS\");\n }\n\n public string GetLogPath()\n {\n return _logPath;\n }\n\n private void WriteLog(string message, string level)\n {\n lock (_lockObject)\n {\n try\n {\n string logEntry = $\"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}\";\n\n // Write to file if log writer is available\n _logWriter?.WriteLine(logEntry);\n\n // Also write to console for immediate visibility\n Console.WriteLine(logEntry);\n }\n catch (Exception ex)\n {\n Console.Error.WriteLine($\"Logging failed: {ex.Message}\");\n }\n }\n }\n\n // Implement IDisposable pattern to ensure logs are stopped\n public void Dispose()\n {\n StopLog();\n GC.SuppressFinalize(this);\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/Methods/RegistryVerificationMethod.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Verification;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods\n{\n /// \n /// Verifies if a package is installed by checking the Windows Registry.\n /// This checks both 64-bit and 32-bit registry views.\n /// \n public class RegistryVerificationMethod : VerificationMethodBase\n {\n private const string UninstallKeyPath =\n @\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\";\n private const string UninstallKeyPathWow6432Node =\n @\"SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n public RegistryVerificationMethod()\n : base(\"Registry\", priority: 10) { }\n\n /// \n protected override async Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken = default\n )\n {\n return await Task.Run(\n () =>\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n // Check 64-bit registry view\n using (\n var baseKey = RegistryKey.OpenBaseKey(\n RegistryHive.LocalMachine,\n RegistryView.Registry64\n )\n )\n using (var uninstallKey = baseKey.OpenSubKey(UninstallKeyPath, writable: false))\n {\n var result = CheckRegistryKey(uninstallKey, packageId, null);\n if (result.IsVerified)\n {\n return result;\n }\n }\n\n // Check 32-bit registry view\n using (\n var baseKey = RegistryKey.OpenBaseKey(\n RegistryHive.LocalMachine,\n RegistryView.Registry32\n )\n )\n using (\n var uninstallKey = baseKey.OpenSubKey(\n UninstallKeyPathWow6432Node,\n writable: false\n )\n )\n {\n return CheckRegistryKey(uninstallKey, packageId, null);\n }\n },\n cancellationToken\n );\n }\n\n /// \n /// Checks a registry key for the presence of a package.\n /// \n /// The registry key to check.\n /// The package ID to look for.\n /// The version to check for, or null to check for any version.\n /// A indicating whether the package was found.\n private static VerificationResult CheckRegistryKey(\n RegistryKey uninstallKey,\n string packageId,\n string version\n )\n {\n if (uninstallKey == null)\n {\n return VerificationResult.Failure(\"Registry key not found\");\n }\n\n foreach (var subKeyName in uninstallKey.GetSubKeyNames())\n {\n using (var subKey = uninstallKey.OpenSubKey(subKeyName))\n {\n var displayName = subKey?.GetValue(\"DisplayName\") as string;\n if (string.IsNullOrEmpty(displayName))\n {\n continue;\n }\n\n // Check if the display name matches the package ID (case insensitive)\n if (displayName.IndexOf(packageId, StringComparison.OrdinalIgnoreCase) >= 0)\n {\n // If a version is specified, check if it matches\n if (version != null)\n {\n var displayVersion = subKey.GetValue(\"DisplayVersion\") as string;\n if (\n !string.Equals(\n displayVersion,\n version,\n StringComparison.OrdinalIgnoreCase\n )\n )\n {\n continue;\n }\n }\n\n var installLocation = subKey.GetValue(\"InstallLocation\") as string;\n var uninstallString = subKey.GetValue(\"UninstallString\") as string;\n var foundVersion = subKey.GetValue(\"DisplayVersion\") as string;\n\n return VerificationResult.Success(foundVersion);\n }\n }\n }\n\n return VerificationResult.Failure($\"Package '{packageId}' not found in registry\");\n }\n\n /// \n protected override async Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(version))\n {\n throw new ArgumentException(\n \"Version cannot be null or whitespace.\",\n nameof(version)\n );\n }\n\n return await VerifyPresenceAsync(packageId, cancellationToken).ConfigureAwait(false);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/TaskbarCustomizations.cs", "using Microsoft.Win32;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Enums;\nusing System;\nusing System.IO;\nusing System.Diagnostics;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Core.Features.Customize.Models;\n\npublic static class TaskbarCustomizations\n{\n /// \n /// Special handling for News and Interests (Widgets) toggle.\n /// This method temporarily disables the UCPD service before applying the settings.\n /// \n /// The registry service.\n /// The log service.\n /// The linked registry settings to apply.\n /// Whether to enable or disable the settings.\n /// True if the settings were applied successfully; otherwise, false.\n public static async Task ApplyNewsAndInterestsSettingsAsync(\n IRegistryService registryService,\n ILogService logService,\n LinkedRegistrySettings linkedSettings,\n bool enable)\n {\n // Path to the UCPD service Start value\n const string ucpdServiceKeyPath = @\"HKLM\\SYSTEM\\CurrentControlSet\\Services\\UCPD\";\n const string startValueName = \"Start\";\n \n // Get the current value of the UCPD service Start key\n object? originalStartValue = registryService.GetValue(ucpdServiceKeyPath, startValueName);\n \n try\n {\n // Set the UCPD service Start value to 4 (disabled)\n logService.LogInformation($\"Temporarily disabling UCPD service by setting {ucpdServiceKeyPath}\\\\{startValueName} to 4\");\n bool setResult = registryService.SetValue(ucpdServiceKeyPath, startValueName, 4, RegistryValueKind.DWord);\n \n if (!setResult)\n {\n logService.LogError(\"Failed to set UCPD service Start value to 4\");\n return false;\n }\n \n // Apply the News and Interests (Widgets) settings\n logService.LogInformation($\"Applying linked setting: News and Interests (Widgets) with {linkedSettings.Settings.Count} registry entries\");\n bool result = await registryService.ApplyLinkedSettingsAsync(linkedSettings, enable);\n \n if (!result)\n {\n logService.LogError(\"Failed to apply linked settings for News and Interests (Widgets)\");\n return false;\n }\n \n return true;\n }\n finally\n {\n // Restore the original UCPD service Start value\n if (originalStartValue != null)\n {\n logService.LogInformation($\"Restoring UCPD service Start value to {originalStartValue}\");\n registryService.SetValue(ucpdServiceKeyPath, startValueName, originalStartValue, RegistryValueKind.DWord);\n }\n }\n }\n /// \n /// Cleans the taskbar by unpinning all items except File Explorer.\n /// \n /// The system services.\n /// The log service.\n public static async Task CleanTaskbar(ISystemServices systemServices, ILogService logService)\n {\n try\n {\n logService.LogInformation(\"Task started: Cleaning taskbar...\");\n logService.LogInformation(\"Cleaning taskbar started\");\n \n // Delete taskband registry key using Registry API\n using (var key = Registry.CurrentUser.OpenSubKey(@\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\", true))\n {\n if (key != null)\n {\n key.DeleteSubKeyTree(\"Taskband\", false);\n }\n }\n \n // Create the Taskband key and set values directly\n using (var taskbandKey = Registry.CurrentUser.CreateSubKey(\n @\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Taskband\", true))\n {\n if (taskbandKey != null)\n {\n // Convert the hex string to a byte array\n // This is the same data that was in the .reg file\n byte[] favoritesData = new byte[] {\n 0x00, 0xaa, 0x01, 0x00, 0x00, 0x3a, 0x00, 0x1f, 0x80, 0xc8, 0x27, 0x34, 0x1f, 0x10, 0x5c, 0x10,\n 0x42, 0xaa, 0x03, 0x2e, 0xe4, 0x52, 0x87, 0xd6, 0x68, 0x26, 0x00, 0x01, 0x00, 0x26, 0x00, 0xef,\n 0xbe, 0x10, 0x00, 0x00, 0x00, 0xf4, 0x7e, 0x76, 0xfa, 0xde, 0x9d, 0xda, 0x01, 0x40, 0x61, 0x5d,\n 0x09, 0xdf, 0x9d, 0xda, 0x01, 0x19, 0xb8, 0x5f, 0x09, 0xdf, 0x9d, 0xda, 0x01, 0x14, 0x00, 0x56,\n 0x00, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x58, 0xa9, 0x26, 0x10, 0x00, 0x54, 0x61, 0x73,\n 0x6b, 0x42, 0x61, 0x72, 0x00, 0x40, 0x00, 0x09, 0x00, 0x04, 0x00, 0xef, 0xbe, 0xa4, 0x58, 0xa9,\n 0x26, 0xa4, 0x58, 0xa9, 0x26, 0x2e, 0x00, 0x00, 0x00, 0xde, 0x9c, 0x01, 0x00, 0x00, 0x00, 0x02,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c,\n 0xf4, 0x85, 0x00, 0x54, 0x00, 0x61, 0x00, 0x73, 0x00, 0x6b, 0x00, 0x42, 0x00, 0x61, 0x00, 0x72,\n 0x00, 0x00, 0x00, 0x16, 0x00, 0x18, 0x01, 0x32, 0x00, 0x8a, 0x04, 0x00, 0x00, 0xa4, 0x58, 0xb6,\n 0x26, 0x20, 0x00, 0x46, 0x49, 0x4c, 0x45, 0x45, 0x58, 0x7e, 0x31, 0x2e, 0x4c, 0x4e, 0x4b, 0x00,\n 0x00, 0x54, 0x00, 0x09, 0x00, 0x04, 0x00, 0xef, 0xbe, 0xa4, 0x58, 0xb6, 0x26, 0xa4, 0x58, 0xb6,\n 0x26, 0x2e, 0x00, 0x00, 0x00, 0xb7, 0xa8, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x5a, 0x1e, 0x01, 0x46,\n 0x00, 0x69, 0x00, 0x6c, 0x00, 0x65, 0x00, 0x20, 0x00, 0x45, 0x00, 0x78, 0x00, 0x70, 0x00, 0x6c,\n 0x00, 0x6f, 0x00, 0x72, 0x00, 0x65, 0x00, 0x72, 0x00, 0x2e, 0x00, 0x6c, 0x00, 0x6e, 0x00, 0x6b,\n 0x00, 0x00, 0x00, 0x1c, 0x00, 0x22, 0x00, 0x00, 0x00, 0x1e, 0x00, 0xef, 0xbe, 0x02, 0x00, 0x55,\n 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x50, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x6e, 0x00, 0x65,\n 0x00, 0x64, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x12, 0x00, 0x00, 0x00, 0x2b, 0x00, 0xef, 0xbe, 0x19,\n 0xb8, 0x5f, 0x09, 0xdf, 0x9d, 0xda, 0x01, 0x1c, 0x00, 0x74, 0x00, 0x00, 0x00, 0x1d, 0x00, 0xef,\n 0xbe, 0x02, 0x00, 0x7b, 0x00, 0x46, 0x00, 0x33, 0x00, 0x38, 0x00, 0x42, 0x00, 0x46, 0x00, 0x34,\n 0x00, 0x30, 0x00, 0x34, 0x00, 0x2d, 0x00, 0x31, 0x00, 0x44, 0x00, 0x34, 0x00, 0x33, 0x00, 0x2d,\n 0x00, 0x34, 0x00, 0x32, 0x00, 0x46, 0x00, 0x32, 0x00, 0x2d, 0x00, 0x39, 0x00, 0x33, 0x00, 0x30,\n 0x00, 0x35, 0x00, 0x2d, 0x00, 0x36, 0x00, 0x37, 0x00, 0x44, 0x00, 0x45, 0x00, 0x30, 0x00, 0x42,\n 0x00, 0x32, 0x00, 0x38, 0x00, 0x46, 0x00, 0x43, 0x00, 0x32, 0x00, 0x33, 0x00, 0x7d, 0x00, 0x5c,\n 0x00, 0x65, 0x00, 0x78, 0x00, 0x70, 0x00, 0x6c, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x65, 0x00, 0x72,\n 0x00, 0x2e, 0x00, 0x65, 0x00, 0x78, 0x00, 0x65, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0xff\n };\n \n // Set the binary value directly\n taskbandKey.SetValue(\"Favorites\", favoritesData, RegistryValueKind.Binary);\n }\n }\n \n // Wait for registry changes to take effect before refreshing Windows GUI\n logService.LogInformation(\"Registry changes applied, waiting for changes to take effect...\");\n await Task.Delay(2000);\n \n // Use the improved RefreshWindowsGUI method to restart Explorer and apply changes\n // This will ensure Explorer is restarted properly with retry logic and fallback\n var result = await systemServices.RefreshWindowsGUI(true);\n if (!result)\n {\n throw new Exception(\"Failed to refresh Windows GUI after cleaning taskbar\");\n }\n }\n catch (Exception ex)\n {\n throw new Exception($\"Error cleaning taskbar: {ex.Message}\", ex);\n }\n }\n\n public static CustomizationGroup GetTaskbarCustomizations()\n {\n return new CustomizationGroup\n {\n Name = \"Taskbar\",\n Category = CustomizationCategory.Taskbar,\n Settings = new List\n {\n new CustomizationSetting\n {\n Id = \"taskbar-chat-icon\",\n Name = \"Windows Chat Icon\",\n Description = \"Controls Windows Chat icon visibility and menu behavior in taskbar\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Icons\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\Windows Chat\",\n Name = \"ChatIcon\",\n RecommendedValue = 3, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, Chat icon is shown (0 = show)\n DisabledValue = 3, // When toggle is OFF, Chat icon is hidden (3 = hide)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls Windows Chat icon visibility in taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n },\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"TaskbarMn\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, taskbar menu is enabled\n DisabledValue = 0, // When toggle is OFF, taskbar menu is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls taskbar menu behavior for chat\",\n IsPrimary = false,\n AbsenceMeansEnabled = false\n }\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All\n },\n new CustomizationSetting\n {\n Id = \"taskbar-meet-now-group\",\n Name = \"Meet Now Button\",\n Description = \"Controls Meet Now button visibility in taskbar\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Icons\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\Explorer\",\n Name = \"HideSCAMeetNow\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, Meet Now button is shown\n DisabledValue = 1, // When toggle is OFF, Meet Now button is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Meet Now button visibility in taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n },\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\Explorer\",\n Name = \"HideSCAMeetNow\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, Meet Now button is shown (user level)\n DisabledValue = 1, // When toggle is OFF, Meet Now button is hidden (user level)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Meet Now button visibility (user level)\",\n IsPrimary = false,\n AbsenceMeansEnabled = true\n }\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All\n },\n new CustomizationSetting\n {\n Id = \"taskbar-search-box\",\n Name = \"Search in Taskbar\",\n Description = \"Controls search box visibility in taskbar\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Icons\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Search\",\n Name = \"SearchboxTaskbarMode\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 2, // When toggle is ON, search box is shown (2 = show search box)\n DisabledValue = 0, // When toggle is OFF, search box is hidden (0 = hide search box)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls search box visibility in taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new CustomizationSetting\n {\n Id = \"taskbar-copilot\",\n Name = \"Copilot Button\",\n Description = \"Controls Copilot button visibility in taskbar\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Icons\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowCopilotButton\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Copilot button is shown\n DisabledValue = 0, // When toggle is OFF, Copilot button is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls Copilot button visibility in taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new CustomizationSetting\n {\n Id = \"taskbar-left-align\",\n Name = \"Left Aligned Taskbar\",\n Description = \"Controls taskbar icons alignment\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Behavior\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"TaskbarAl\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, taskbar icons are left-aligned\n DisabledValue = 1, // When toggle is OFF, taskbar icons are center-aligned\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls taskbar icons alignment\",\n IsPrimary = true,\n AbsenceMeansEnabled = false\n }\n }\n },\n new CustomizationSetting\n {\n Id = \"taskbar-system-tray-icons\",\n Name = \"Show Hidden System Tray Icons (W10 Only)\",\n Description = \"Controls whether system tray icons are shown in the taskbar or hidden in the chevron menu\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"System Tray\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\",\n Name = \"EnableAutoTray\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls whether system tray icons are shown in the taskbar or hidden in the chevron menu\",\n IsPrimary = true,\n AbsenceMeansEnabled = false\n }\n }\n },\n new CustomizationSetting\n {\n Id = \"taskbar-task-view\",\n Name = \"Task View Button\",\n Description = \"Controls Task View button visibility in taskbar\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Icons\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowTaskViewButton\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Task View button is shown\n DisabledValue = 0, // When toggle is OFF, Task View button is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Task View button visibility in taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n }\n }\n };\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Resources/Theme/ThemeManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Reflection;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Media;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Properties;\n\nnamespace Winhance.WPF.Features.Common.Resources.Theme\n{\n public partial class ThemeManager : ObservableObject, IThemeManager, IDisposable\n {\n private bool _isDarkTheme = true;\n\n public bool IsDarkTheme\n {\n get => _isDarkTheme;\n set\n {\n if (_isDarkTheme != value)\n {\n _isDarkTheme = value;\n OnPropertyChanged(nameof(IsDarkTheme));\n\n // Update the application resource\n Application.Current.Resources[\"IsDarkTheme\"] = _isDarkTheme;\n }\n }\n }\n\n private readonly INavigationService _navigationService;\n\n // Dictionary with default color values for each theme\n private static readonly Dictionary DarkThemeColors = new()\n {\n { \"PrimaryTextColor\", Color.FromRgb(255, 255, 255) },\n { \"SecondaryTextColor\", Color.FromRgb(170, 170, 170) },\n { \"TertiaryTextColor\", Color.FromRgb(128, 128, 128) },\n { \"HelpIconColor\", Color.FromRgb(255, 255, 255) },\n { \"TooltipBackgroundColor\", Color.FromRgb(43, 45, 48) },\n { \"TooltipForegroundColor\", Color.FromRgb(255, 255, 255) },\n { \"TooltipBorderColor\", Color.FromRgb(255, 222, 0) },\n { \"ControlForegroundColor\", Color.FromRgb(255, 255, 255) },\n { \"ControlFillColor\", Color.FromRgb(255, 255, 255) },\n { \"ControlBorderColor\", Color.FromRgb(255, 222, 0) },\n { \"ToggleKnobColor\", Color.FromRgb(255, 255, 255) },\n { \"ToggleKnobCheckedColor\", Color.FromRgb(255, 222, 0) },\n { \"ContentSectionBorderColor\", Color.FromRgb(31, 32, 34) },\n { \"MainContainerBorderColor\", Color.FromRgb(43, 45, 48) },\n { \"PrimaryButtonForegroundColor\", Color.FromRgb(255, 255, 255) },\n { \"AccentColor\", Color.FromRgb(255, 222, 0) },\n { \"ButtonHoverTextColor\", Color.FromRgb(32, 33, 36) },\n { \"ButtonDisabledForegroundColor\", Color.FromRgb(153, 163, 164) },\n { \"ButtonDisabledBorderColor\", Color.FromRgb(43, 45, 48) },\n { \"NavigationButtonBackgroundColor\", Color.FromRgb(31, 32, 34) },\n { \"NavigationButtonForegroundColor\", Color.FromRgb(255, 255, 255) },\n { \"SliderTrackColor\", Color.FromRgb(64, 64, 64) },\n { \"BackgroundColor\", Color.FromRgb(32, 32, 32) },\n { \"ContentSectionBackgroundColor\", Color.FromRgb(31, 32, 34) },\n { \"ScrollBarThumbColor\", Color.FromRgb(255, 222, 0) },\n { \"ScrollBarThumbHoverColor\", Color.FromRgb(255, 233, 76) },\n { \"ScrollBarThumbPressedColor\", Color.FromRgb(255, 240, 102) },\n };\n\n private static readonly Dictionary LightThemeColors = new()\n {\n { \"PrimaryTextColor\", Color.FromRgb(32, 33, 36) },\n { \"SecondaryTextColor\", Color.FromRgb(102, 102, 102) },\n { \"TertiaryTextColor\", Color.FromRgb(153, 153, 153) },\n { \"HelpIconColor\", Color.FromRgb(32, 33, 36) },\n { \"TooltipBackgroundColor\", Color.FromRgb(255, 255, 255) },\n { \"TooltipForegroundColor\", Color.FromRgb(32, 33, 36) },\n { \"TooltipBorderColor\", Color.FromRgb(66, 66, 66) },\n { \"ControlForegroundColor\", Color.FromRgb(32, 33, 36) },\n { \"ControlFillColor\", Color.FromRgb(66, 66, 66) },\n { \"ControlBorderColor\", Color.FromRgb(66, 66, 66) },\n { \"ToggleKnobColor\", Color.FromRgb(255, 255, 255) },\n { \"ToggleKnobCheckedColor\", Color.FromRgb(66, 66, 66) },\n { \"ContentSectionBorderColor\", Color.FromRgb(246, 248, 252) },\n { \"MainContainerBorderColor\", Color.FromRgb(255, 255, 255) },\n { \"PrimaryButtonForegroundColor\", Color.FromRgb(32, 33, 36) },\n { \"AccentColor\", Color.FromRgb(66, 66, 66) },\n { \"ButtonHoverTextColor\", Color.FromRgb(255, 255, 255) },\n { \"ButtonDisabledForegroundColor\", Color.FromRgb(204, 204, 204) },\n { \"ButtonDisabledBorderColor\", Color.FromRgb(238, 238, 238) },\n { \"NavigationButtonBackgroundColor\", Color.FromRgb(255, 255, 255) },\n { \"NavigationButtonForegroundColor\", Color.FromRgb(32, 33, 36) },\n { \"SliderTrackColor\", Color.FromRgb(204, 204, 204) },\n { \"BackgroundColor\", Color.FromRgb(246, 248, 252) },\n { \"ContentSectionBackgroundColor\", Color.FromRgb(240, 240, 240) },\n { \"ScrollBarThumbColor\", Color.FromRgb(66, 66, 66) },\n { \"ScrollBarThumbHoverColor\", Color.FromRgb(102, 102, 102) },\n { \"ScrollBarThumbPressedColor\", Color.FromRgb(34, 34, 34) },\n };\n\n public ThemeManager(INavigationService navigationService)\n {\n _navigationService = navigationService ?? throw new ArgumentNullException(nameof(navigationService));\n\n // Subscribe to navigation events to update toggle switches when navigating between views\n _navigationService.Navigated += NavigationService_Navigated;\n\n LoadThemePreference();\n ApplyTheme();\n }\n\n private void NavigationService_Navigated(object sender, NavigationEventArgs e)\n {\n // We no longer need to update toggle switches on navigation\n // as they will automatically pick up the correct theme from the application resources\n }\n\n public void ToggleTheme()\n {\n IsDarkTheme = !IsDarkTheme;\n ApplyTheme();\n\n // Ensure the window icons are updated when toggling the theme\n NotifyWindowsOfThemeChange();\n }\n\n public void ApplyTheme()\n {\n try\n {\n var themeColors = IsDarkTheme ? DarkThemeColors : LightThemeColors;\n\n // We no longer need to explicitly update toggle switches\n // as they will automatically pick up the theme from application resources\n\n // Create brushes for all UI elements\n var brushes = new List<(string key, SolidColorBrush brush)>\n {\n (\"WindowBackground\", new SolidColorBrush(themeColors[\"BackgroundColor\"])),\n (\"PrimaryTextColor\", new SolidColorBrush(themeColors[\"PrimaryTextColor\"])),\n (\"SecondaryTextColor\", new SolidColorBrush(themeColors[\"SecondaryTextColor\"])),\n (\"TertiaryTextColor\", new SolidColorBrush(themeColors[\"TertiaryTextColor\"])),\n (\"SubTextColor\", new SolidColorBrush(themeColors[\"SecondaryTextColor\"])),\n (\"HelpIconForeground\", new SolidColorBrush(themeColors[\"HelpIconColor\"])),\n (\n \"ContentSectionBackground\",\n new SolidColorBrush(themeColors[\"ContentSectionBackgroundColor\"])\n ),\n (\n \"ContentSectionBorderBrush\",\n new SolidColorBrush(themeColors[\"ContentSectionBorderColor\"])\n ),\n (\n \"MainContainerBorderBrush\",\n new SolidColorBrush(themeColors[\"MainContainerBorderColor\"])\n ),\n (\n \"NavigationButtonBackground\",\n new SolidColorBrush(themeColors[\"NavigationButtonBackgroundColor\"])\n ),\n (\n \"NavigationButtonForeground\",\n new SolidColorBrush(themeColors[\"NavigationButtonForegroundColor\"])\n ),\n (\"ButtonBorderBrush\", new SolidColorBrush(themeColors[\"AccentColor\"])),\n (\"ButtonHoverBackground\", new SolidColorBrush(themeColors[\"AccentColor\"])),\n (\n \"ButtonHoverTextColor\",\n new SolidColorBrush(themeColors[\"ButtonHoverTextColor\"])\n ),\n (\n \"PrimaryButtonForeground\",\n new SolidColorBrush(themeColors[\"PrimaryButtonForegroundColor\"])\n ),\n (\n \"ButtonDisabledForeground\",\n new SolidColorBrush(themeColors[\"ButtonDisabledForegroundColor\"])\n ),\n (\n \"ButtonDisabledBorderBrush\",\n new SolidColorBrush(themeColors[\"ButtonDisabledBorderColor\"])\n ),\n (\n \"ButtonDisabledHoverBackground\",\n new SolidColorBrush(themeColors[\"ButtonDisabledBorderColor\"])\n ),\n (\n \"ButtonDisabledHoverForeground\",\n new SolidColorBrush(themeColors[\"ButtonDisabledForegroundColor\"])\n ),\n (\n \"TooltipBackground\",\n new SolidColorBrush(themeColors[\"TooltipBackgroundColor\"])\n ),\n (\n \"TooltipForeground\",\n new SolidColorBrush(themeColors[\"TooltipForegroundColor\"])\n ),\n (\"TooltipBorderBrush\", new SolidColorBrush(themeColors[\"TooltipBorderColor\"])),\n (\n \"ControlForeground\",\n new SolidColorBrush(themeColors[\"ControlForegroundColor\"])\n ),\n (\"ControlFillColor\", new SolidColorBrush(themeColors[\"ControlFillColor\"])),\n (\n \"ControlBorderBrush\",\n new SolidColorBrush(themeColors[\"ControlBorderColor\"])\n ),\n (\n \"ToggleKnobBrush\",\n new SolidColorBrush(themeColors[\"ToggleKnobColor\"])\n ),\n (\n \"ToggleKnobCheckedBrush\",\n new SolidColorBrush(themeColors[\"ToggleKnobCheckedColor\"])\n ),\n (\"SliderTrackBackground\", new SolidColorBrush(themeColors[\"SliderTrackColor\"])),\n // Special handling for slider thumb in light mode to make them more visible\n (\n \"SliderAccentColor\",\n new SolidColorBrush(\n IsDarkTheme ? themeColors[\"AccentColor\"] : Color.FromRgb(240, 240, 240)\n )\n ),\n (\"TickBarForeground\", new SolidColorBrush(themeColors[\"PrimaryTextColor\"])),\n (\n \"ScrollBarThumbBrush\",\n new SolidColorBrush(themeColors[\"ScrollBarThumbColor\"])\n ),\n (\n \"ScrollBarThumbHoverBrush\",\n new SolidColorBrush(themeColors[\"ScrollBarThumbHoverColor\"])\n ),\n (\n \"ScrollBarThumbPressedBrush\",\n new SolidColorBrush(themeColors[\"ScrollBarThumbPressedColor\"])\n ),\n };\n\n var resources = Application.Current.Resources;\n\n // Update all brushes in the application resources\n foreach (var (key, brush) in brushes)\n {\n // Freeze for better performance\n brush.Freeze();\n\n // Update in main resources dictionary\n resources[key] = brush;\n }\n\n // Notify the ViewNameToBackgroundConverter that the theme has changed\n try\n {\n Winhance.WPF.Features.Common.Converters.ViewNameToBackgroundConverter.Instance.NotifyThemeChanged();\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error notifying ViewNameToBackgroundConverter: {ex.Message}\");\n }\n\n // Attempt to force a visual refresh of the main window\n var mainWindow = Application.Current.MainWindow;\n if (mainWindow != null)\n {\n // Force a layout update\n mainWindow.InvalidateVisual();\n\n // Directly update the navigation buttons and toggle switches\n Application.Current.Dispatcher.Invoke(() =>\n {\n try\n {\n // Find the navigation buttons by name\n var softwareAppsButton = FindChildByName(\n mainWindow,\n \"SoftwareAppsButton\"\n );\n var optimizeButton = FindChildByName(mainWindow, \"OptimizeButton\");\n var customizeButton = FindChildByName(mainWindow, \"CustomizeButton\");\n var aboutButton = FindChildByName(mainWindow, \"AboutButton\");\n\n // Get the current view name from the main view model\n string currentViewName = string.Empty;\n if (mainWindow.DataContext != null)\n {\n var mainViewModel = mainWindow.DataContext as dynamic;\n currentViewName = mainViewModel.CurrentViewName;\n }\n\n // Update each button's background if not null\n if (softwareAppsButton != null)\n UpdateButtonBackground(\n softwareAppsButton,\n \"SoftwareApps\",\n currentViewName\n );\n if (optimizeButton != null)\n UpdateButtonBackground(optimizeButton, \"Optimize\", currentViewName);\n if (customizeButton != null)\n UpdateButtonBackground(\n customizeButton,\n \"Customize\",\n currentViewName\n );\n if (aboutButton != null)\n UpdateButtonBackground(aboutButton, \"About\", currentViewName);\n\n // We no longer need to explicitly update toggle switches\n // as they will automatically pick up the theme from application resources\n\n // Force a more thorough refresh of the UI\n mainWindow.UpdateLayout();\n\n // Update theme-dependent icons\n NotifyWindowsOfThemeChange();\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error updating UI elements: {ex.Message}\");\n }\n });\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error applying theme: {ex.Message}\");\n Debug.WriteLine(ex.StackTrace);\n }\n\n // Save theme preference\n SaveThemePreference();\n }\n\n private void SaveThemePreference()\n {\n try\n {\n Settings.Default.IsDarkTheme = IsDarkTheme;\n Settings.Default.Save();\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Failed to save theme preference: {ex.Message}\");\n }\n }\n\n public void LoadThemePreference()\n {\n try\n {\n IsDarkTheme = Settings.Default.IsDarkTheme;\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Failed to load theme preference: {ex.Message}\");\n // Keep default value if loading fails\n }\n }\n\n // Clean up event subscriptions\n public void Dispose()\n {\n try\n {\n if (_navigationService != null)\n {\n _navigationService.Navigated -= NavigationService_Navigated;\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error cleaning up ThemeManager: {ex.Message}\");\n }\n }\n\n public void ResetThemePreference()\n {\n try\n {\n Settings.Default.Reset();\n LoadThemePreference();\n ApplyTheme();\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Failed to reset theme preference: {ex.Message}\");\n }\n }\n\n // Helper method to find a child element by name\n private static System.Windows.Controls.Button? FindChildByName(\n DependencyObject parent,\n string name\n )\n {\n if (parent == null)\n return null;\n\n // Check if the current element is the one we're looking for\n if (\n parent is FrameworkElement element\n && element.Name == name\n && element is System.Windows.Controls.Button button\n )\n {\n return button;\n }\n\n // Get the number of children\n int childCount = VisualTreeHelper.GetChildrenCount(parent);\n\n // Recursively search through all children\n for (int i = 0; i < childCount; i++)\n {\n var child = VisualTreeHelper.GetChild(parent, i);\n var result = FindChildByName(child, name);\n if (result != null)\n {\n return result;\n }\n }\n\n return null;\n }\n\n // Helper method to update a button's background based on whether it's selected\n private void UpdateButtonBackground(\n System.Windows.Controls.Button button,\n string buttonViewName,\n string currentViewName\n )\n {\n if (button == null)\n return;\n\n var themeColors = IsDarkTheme ? DarkThemeColors : LightThemeColors;\n\n // Determine if this button is for the currently selected view\n bool isSelected = string.Equals(\n buttonViewName,\n currentViewName,\n StringComparison.OrdinalIgnoreCase\n );\n\n // Set the appropriate background color\n if (isSelected)\n {\n button.Background = new SolidColorBrush(themeColors[\"MainContainerBorderColor\"]);\n }\n else\n {\n button.Background = new SolidColorBrush(\n themeColors[\"NavigationButtonBackgroundColor\"]\n );\n }\n\n // Update the foreground color for the button's content\n button.Foreground = new SolidColorBrush(themeColors[\"NavigationButtonForegroundColor\"]);\n }\n\n // Method to update all toggle switches in all open windows\n private void UpdateAllToggleSwitches()\n {\n try\n {\n // Update toggle switches in all open windows\n foreach (Window window in Application.Current.Windows)\n {\n UpdateToggleSwitches(window);\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error updating toggle switches: {ex.Message}\");\n Debug.WriteLine(ex.StackTrace);\n }\n }\n\n // Method to notify windows about theme changes\n private void NotifyWindowsOfThemeChange()\n {\n try\n {\n Debug.WriteLine($\"NotifyWindowsOfThemeChange called. Current theme: {(IsDarkTheme ? \"Dark\" : \"Light\")}\");\n\n // Notify all open windows about theme changes\n foreach (Window window in Application.Current.Windows)\n {\n Debug.WriteLine($\"Processing window: {window.GetType().Name}\");\n\n // Check if the window is a MainWindow or LoadingWindow\n if (window is MainWindow mainWindow)\n {\n // Call the UpdateThemeIcon method using reflection\n try\n {\n Debug.WriteLine(\"Attempting to update MainWindow icon\");\n var method = mainWindow.GetType().GetMethod(\"UpdateThemeIcon\", BindingFlags.Instance | BindingFlags.NonPublic);\n if (method != null)\n {\n // Use the dispatcher to ensure UI updates happen on the UI thread\n mainWindow.Dispatcher.Invoke(() =>\n {\n method.Invoke(mainWindow, null);\n });\n Debug.WriteLine(\"Updated theme icon in MainWindow\");\n }\n else\n {\n Debug.WriteLine(\"UpdateThemeIcon method not found in MainWindow\");\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error updating theme icon in MainWindow: {ex.Message}\");\n Debug.WriteLine(ex.StackTrace);\n }\n }\n else if (window is LoadingWindow loadingWindow)\n {\n // Call the UpdateThemeIcon method using reflection\n try\n {\n Debug.WriteLine(\"Attempting to update LoadingWindow icon\");\n var method = loadingWindow.GetType().GetMethod(\"UpdateThemeIcon\", BindingFlags.Instance | BindingFlags.NonPublic);\n if (method != null)\n {\n // Use the dispatcher to ensure UI updates happen on the UI thread\n loadingWindow.Dispatcher.Invoke(() =>\n {\n method.Invoke(loadingWindow, null);\n });\n Debug.WriteLine(\"Updated theme icon in LoadingWindow\");\n }\n else\n {\n Debug.WriteLine(\"UpdateThemeIcon method not found in LoadingWindow\");\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error updating theme icon in LoadingWindow: {ex.Message}\");\n Debug.WriteLine(ex.StackTrace);\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error notifying windows of theme change: {ex.Message}\");\n Debug.WriteLine(ex.StackTrace);\n }\n }\n\n // Helper method to update all toggle switches in the visual tree\n private void UpdateToggleSwitches(DependencyObject parent)\n {\n if (parent == null)\n return;\n\n // Check if the current element is a ToggleButton\n if (parent is ToggleButton toggleButton)\n {\n try\n {\n // Always set the Tag property for all toggle buttons\n toggleButton.Tag = IsDarkTheme ? \"Dark\" : \"Light\";\n\n // Force a visual refresh for all toggle buttons\n toggleButton.InvalidateVisual();\n\n // Force a more thorough refresh\n if (toggleButton.Parent is FrameworkElement parentElement)\n {\n parentElement.InvalidateVisual();\n parentElement.UpdateLayout();\n }\n\n // Ensure the toggle button is enabled and clickable if it should be\n if (!toggleButton.IsEnabled && toggleButton.IsEnabled != false)\n {\n toggleButton.IsEnabled = true;\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error updating toggle button: {ex.Message}\");\n }\n }\n\n // Get the number of children\n int childCount = VisualTreeHelper.GetChildrenCount(parent);\n\n // Recursively search through all children\n for (int i = 0; i < childCount; i++)\n {\n var child = VisualTreeHelper.GetChild(parent, i);\n UpdateToggleSwitches(child);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScriptContentModifier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\n/// \n/// Implementation of IScriptContentModifier that provides methods for modifying script content.\n/// \npublic class ScriptContentModifier : IScriptContentModifier\n{\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public ScriptContentModifier(ILogService logService)\n {\n _logService = logService;\n }\n\n /// \n public string RemoveCapabilityFromScript(string scriptContent, string capabilityName)\n {\n // Find the capabilities array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$capabilities = @(\");\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $capabilities array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the capabilities array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find end of $capabilities array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the capabilities in the array\n var capabilities = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var capability = trimmedLine.Trim('\\'', '\"', ' ', ',');\n capabilities.Add(capability);\n }\n }\n\n // Check if the capability is in the array\n bool removed =\n capabilities.RemoveAll(c =>\n c.Equals(capabilityName, StringComparison.OrdinalIgnoreCase)\n ) > 0;\n\n if (!removed)\n {\n // Capability not found in the array\n return scriptContent;\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$capabilities = @(\");\n\n // Add capabilities without trailing comma on the last item\n for (int i = 0; i < capabilities.Count; i++)\n {\n string capability = capabilities[i];\n if (i < capabilities.Count - 1)\n {\n newArrayContent.AppendLine($\" '{capability}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{capability}'\");\n }\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n\n /// \n public string RemovePackageFromScript(string scriptContent, string packageName)\n {\n // Find the packages array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$packages = @(\");\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the packages array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find end of $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the packages in the array\n var packages = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var package = trimmedLine.Trim('\\'', '\"', ' ', ',');\n packages.Add(package);\n }\n }\n\n // Check if the package is in the array\n bool removed =\n packages.RemoveAll(p => p.Equals(packageName, StringComparison.OrdinalIgnoreCase)) > 0;\n\n if (!removed)\n {\n // Package not found in the array\n return scriptContent;\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$packages = @(\");\n\n // Add packages without trailing comma on the last item\n for (int i = 0; i < packages.Count; i++)\n {\n string package = packages[i];\n if (i < packages.Count - 1)\n {\n newArrayContent.AppendLine($\" '{package}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{package}'\");\n }\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n\n /// \n public string RemoveOptionalFeatureFromScript(string scriptContent, string featureName)\n {\n // Check if the optional features section exists\n int sectionStartIndex = scriptContent.IndexOf(\"# Disable Optional Features\");\n if (sectionStartIndex == -1)\n {\n // Optional features section doesn't exist, so nothing to remove\n return scriptContent;\n }\n\n // Find the optional features array\n int arrayStartIndex = scriptContent.IndexOf(\"$optionalFeatures = @(\", sectionStartIndex);\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $optionalFeatures array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the optional features array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\n \"Could not find end of $optionalFeatures array in BloatRemoval.ps1\"\n );\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the optional features in the array\n var optionalFeatures = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var feature = trimmedLine.Trim('\\'', '\"', ' ', ',');\n optionalFeatures.Add(feature);\n }\n }\n\n // Check if the feature is in the array\n bool removed =\n optionalFeatures.RemoveAll(f =>\n f.Equals(featureName, StringComparison.OrdinalIgnoreCase)\n ) > 0;\n\n if (!removed)\n {\n // Feature not found in the array\n return scriptContent;\n }\n\n // If the array is now empty, remove the entire optional features section\n if (optionalFeatures.Count == 0)\n {\n // Find the end of the optional features section\n int sectionEndIndex = scriptContent.IndexOf(\n \"foreach ($feature in $optionalFeatures) {\",\n arrayEndIndex\n );\n if (sectionEndIndex != -1)\n {\n sectionEndIndex = scriptContent.IndexOf(\"}\", sectionEndIndex);\n if (sectionEndIndex != -1)\n {\n sectionEndIndex = scriptContent.IndexOf('\\n', sectionEndIndex);\n if (sectionEndIndex != -1)\n {\n // Remove the entire section\n return scriptContent.Substring(0, sectionStartIndex)\n + scriptContent.Substring(sectionEndIndex + 1);\n }\n }\n }\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$optionalFeatures = @(\");\n\n // Add features without trailing comma on the last item\n for (int i = 0; i < optionalFeatures.Count; i++)\n {\n string feature = optionalFeatures[i];\n if (i < optionalFeatures.Count - 1)\n {\n newArrayContent.AppendLine($\" '{feature}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{feature}'\");\n }\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n\n /// \n public string RemoveAppRegistrySettingsFromScript(string scriptContent, string appName)\n {\n // Find the registry settings section\n int registrySection = scriptContent.IndexOf(\"# Registry settings\");\n if (registrySection == -1)\n {\n return scriptContent;\n }\n\n // Generate possible section headers for this app\n var possibleSectionHeaders = new List\n {\n $\"# Registry settings for {appName}\",\n $\"# Registry settings for Microsoft.{appName}\",\n };\n\n // Add variations without \"Microsoft.\" prefix if it already has it\n if (appName.StartsWith(\"Microsoft.\", StringComparison.OrdinalIgnoreCase))\n {\n string nameWithoutPrefix = appName.Substring(\"Microsoft.\".Length);\n possibleSectionHeaders.Add($\"# Registry settings for {nameWithoutPrefix}\");\n }\n\n // Add common variations\n possibleSectionHeaders.Add($\"# Registry settings for {appName}_8wekyb3d8bbwe\");\n\n // For Copilot specifically, add known variations\n if (appName.Contains(\"Copilot\", StringComparison.OrdinalIgnoreCase))\n {\n possibleSectionHeaders.Add(\"# Registry settings for Copilot\");\n possibleSectionHeaders.Add(\"# Registry settings for Microsoft.Copilot\");\n possibleSectionHeaders.Add(\"# Registry settings for Windows.Copilot\");\n }\n\n // For Xbox/GamingApp specifically, add known variations\n if (\n appName.Contains(\"Xbox\", StringComparison.OrdinalIgnoreCase)\n || appName.Equals(\"Microsoft.GamingApp\", StringComparison.OrdinalIgnoreCase)\n )\n {\n possibleSectionHeaders.Add(\"# Registry settings for Xbox\");\n possibleSectionHeaders.Add(\"# Registry settings for Microsoft.Xbox\");\n possibleSectionHeaders.Add(\"# Registry settings for GamingApp\");\n }\n\n // Find the earliest matching section header\n int appSection = -1;\n string matchedHeader = null;\n\n foreach (var header in possibleSectionHeaders)\n {\n int index = scriptContent.IndexOf(header, registrySection);\n if (index != -1 && (appSection == -1 || index < appSection))\n {\n appSection = index;\n matchedHeader = header;\n }\n }\n\n if (appSection == -1)\n {\n _logService.LogInformation($\"No registry settings found for {appName} in the script\");\n return scriptContent;\n }\n\n _logService.LogInformation(\n $\"Found registry settings for {appName} with header: {matchedHeader}\"\n );\n\n // Find the end of the app section (next section or end of file)\n int nextSection = scriptContent.IndexOf(\n \"# Registry settings for\",\n appSection + matchedHeader.Length\n );\n if (nextSection == -1)\n {\n // Look for the next major section\n nextSection = scriptContent.IndexOf(\"# Prevent apps from reinstalling\", appSection);\n if (nextSection == -1)\n {\n // If no next section, just return the original content\n _logService.LogWarning(\n $\"Could not find end of registry settings section for {appName}\"\n );\n return scriptContent;\n }\n }\n\n // Remove the app registry settings section\n _logService.LogInformation($\"Removing registry settings for {appName} from script\");\n return scriptContent.Substring(0, appSection) + scriptContent.Substring(nextSection);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/Views/CustomizeView.xaml.cs", "using System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing MaterialDesignThemes.Wpf;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Messages;\nusing Winhance.WPF.Features.Customize.ViewModels;\n\nnamespace Winhance.WPF.Features.Customize.Views\n{\n /// \n /// Interaction logic for CustomizeView.xaml\n /// \n public partial class CustomizeView : UserControl\n {\n private IMessengerService? _messengerService; // Changed from readonly to allow assignment\n \n public CustomizeView()\n {\n InitializeComponent();\n Loaded += CustomizeView_Loaded;\n \n // Get messenger service from DataContext when it's set\n DataContextChanged += (s, e) => \n {\n if (e.NewValue is CustomizeViewModel viewModel && \n viewModel.MessengerService is IMessengerService messengerService)\n {\n _messengerService = messengerService;\n SubscribeToMessages();\n }\n };\n }\n \n private void SubscribeToMessages()\n {\n if (_messengerService == null)\n return;\n \n // Subscribe to the message that signals resetting expansion states\n _messengerService.Register(this, OnResetExpansionState);\n }\n \n private void OnResetExpansionState(ResetExpansionStateMessage message)\n {\n // Reset all sections to be expanded\n ResetAllExpansionStates();\n }\n \n /// \n /// Resets all section expansion states to expanded\n /// \n private void ResetAllExpansionStates()\n {\n // Ensure all content is visible\n TaskbarContent.Visibility = Visibility.Visible;\n StartMenuContent.Visibility = Visibility.Visible;\n ExplorerContent.Visibility = Visibility.Visible;\n WindowsThemeContent.Visibility = Visibility.Visible;\n \n // Set all arrow icons to up (expanded state)\n TaskbarHeaderIcon.Kind = PackIconKind.ChevronUp;\n StartMenuHeaderIcon.Kind = PackIconKind.ChevronUp;\n ExplorerHeaderIcon.Kind = PackIconKind.ChevronUp;\n WindowsThemeHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n\n private void CustomizeView_Loaded(object sender, RoutedEventArgs e)\n {\n // Initialize sections to be expanded by default\n TaskbarContent.Visibility = Visibility.Visible;\n StartMenuContent.Visibility = Visibility.Visible;\n ExplorerContent.Visibility = Visibility.Visible;\n WindowsThemeContent.Visibility = Visibility.Visible;\n\n // Set arrow icons to up arrow\n TaskbarHeaderIcon.Kind = PackIconKind.ChevronUp; // Up arrow\n StartMenuHeaderIcon.Kind = PackIconKind.ChevronUp; // Up arrow\n ExplorerHeaderIcon.Kind = PackIconKind.ChevronUp; // Up arrow\n WindowsThemeHeaderIcon.Kind = PackIconKind.ChevronUp; // Up arrow\n\n // Remove all existing event handlers from all border elements\n foreach (var element in this.FindVisualChildren(this))\n {\n if (element?.Tag != null && element.Tag is string tag)\n {\n // Remove any existing MouseLeftButtonDown handlers\n element.MouseLeftButtonDown -= HeaderBorder_MouseLeftButtonDown;\n\n // Add our new handler\n element.PreviewMouseDown += Element_PreviewMouseDown;\n }\n }\n }\n\n private void Element_PreviewMouseDown(object sender, MouseButtonEventArgs e)\n {\n // If we clicked on a Button, don't handle it here\n if (e.OriginalSource is Button)\n {\n return;\n }\n\n if (sender is Border border && border.Tag is string tag)\n {\n try\n {\n // Toggle visibility and selection based on tag\n switch (tag)\n {\n case \"0\":\n ToggleSectionVisibility(TaskbarContent, TaskbarHeaderIcon);\n TaskbarToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n break;\n case \"1\":\n ToggleSectionVisibility(StartMenuContent, StartMenuHeaderIcon);\n StartMenuToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n break;\n case \"2\":\n ToggleSectionVisibility(ExplorerContent, ExplorerHeaderIcon);\n ExplorerToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n break;\n case \"3\":\n ToggleSectionVisibility(WindowsThemeContent, WindowsThemeHeaderIcon);\n WindowsThemeToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n break;\n }\n\n // Mark event as handled so it won't bubble up\n e.Handled = true;\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Error handling header click: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n }\n }\n }\n\n // This method is no longer needed since we're not checking for checkboxes anymore\n\n private void ToggleSectionVisibility(UIElement content, PackIcon icon)\n {\n if (content.Visibility == Visibility.Collapsed)\n {\n content.Visibility = Visibility.Visible;\n icon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n }\n else\n {\n content.Visibility = Visibility.Collapsed;\n icon.Kind = PackIconKind.ChevronDown; // Downward arrow for collapsed state\n }\n }\n\n // This is defined in the XAML, so we need to keep it to avoid errors\n private void HeaderBorder_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n // This no longer does anything because we're using PreviewMouseDown now\n // We'll just mark it as handled to prevent unexpected behavior\n e.Handled = true;\n }\n\n // Helper method to find visual children of a specific type\n private System.Collections.Generic.IEnumerable FindVisualChildren(DependencyObject parent) where T : DependencyObject\n {\n int childrenCount = VisualTreeHelper.GetChildrenCount(parent);\n for (int i = 0; i < childrenCount; i++)\n {\n DependencyObject child = VisualTreeHelper.GetChild(parent, i);\n\n if (child is T childOfType)\n yield return childOfType;\n\n foreach (T childOfChild in FindVisualChildren(child))\n yield return childOfChild;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/RegistryScriptModifier.cs", "using System;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Implementation of IRegistryScriptModifier that provides methods for modifying registry-related script content.\n /// \n public class RegistryScriptModifier : IRegistryScriptModifier\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public RegistryScriptModifier(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string RemoveAppRegistrySettingsFromScript(string scriptContent, string appName)\n {\n // Find the registry settings section\n int registrySection = scriptContent.IndexOf(\"# Registry settings\");\n if (registrySection == -1)\n {\n return scriptContent;\n }\n\n // Generate possible section headers for this app\n var possibleSectionHeaders = new List\n {\n $\"# Registry settings for {appName}\",\n $\"# Registry settings for Microsoft.{appName}\",\n };\n\n // Add variations without \"Microsoft.\" prefix if it already has it\n if (appName.StartsWith(\"Microsoft.\", StringComparison.OrdinalIgnoreCase))\n {\n string nameWithoutPrefix = appName.Substring(\"Microsoft.\".Length);\n possibleSectionHeaders.Add($\"# Registry settings for {nameWithoutPrefix}\");\n }\n\n // Add common variations\n possibleSectionHeaders.Add($\"# Registry settings for {appName}_8wekyb3d8bbwe\");\n\n // For Copilot specifically, add known variations\n if (appName.Contains(\"Copilot\", StringComparison.OrdinalIgnoreCase))\n {\n possibleSectionHeaders.Add(\"# Registry settings for Copilot\");\n possibleSectionHeaders.Add(\"# Registry settings for Microsoft.Copilot\");\n possibleSectionHeaders.Add(\"# Registry settings for Windows.Copilot\");\n }\n\n // For Xbox/GamingApp specifically, add known variations\n if (\n appName.Contains(\"Xbox\", StringComparison.OrdinalIgnoreCase)\n || appName.Equals(\"Microsoft.GamingApp\", StringComparison.OrdinalIgnoreCase)\n )\n {\n possibleSectionHeaders.Add(\"# Registry settings for Xbox\");\n possibleSectionHeaders.Add(\"# Registry settings for Microsoft.Xbox\");\n possibleSectionHeaders.Add(\"# Registry settings for GamingApp\");\n }\n\n // Find the earliest matching section header\n int appSection = -1;\n string matchedHeader = null;\n\n foreach (var header in possibleSectionHeaders)\n {\n int index = scriptContent.IndexOf(header, registrySection);\n if (index != -1 && (appSection == -1 || index < appSection))\n {\n appSection = index;\n matchedHeader = header;\n }\n }\n\n if (appSection == -1)\n {\n Console.WriteLine($\"No registry settings found for {appName} in the script\");\n return scriptContent;\n }\n\n Console.WriteLine($\"Found registry settings for {appName} with header: {matchedHeader}\");\n\n // Find the end of the app section (next section or end of file)\n int nextSection = scriptContent.IndexOf(\n \"# Registry settings for\",\n appSection + matchedHeader.Length\n );\n if (nextSection == -1)\n {\n // Look for the next major section\n nextSection = scriptContent.IndexOf(\"# Prevent apps from reinstalling\", appSection);\n if (nextSection == -1)\n {\n // If no next section, just return the original content\n Console.WriteLine($\"Could not find end of registry settings section for {appName}\");\n return scriptContent;\n }\n }\n\n // Remove the app registry settings section\n Console.WriteLine($\"Removing registry settings for {appName} from script\");\n return scriptContent.Substring(0, appSection) + scriptContent.Substring(nextSection);\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceTestMethods.cs", "using Microsoft.Win32;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n public partial class RegistryService\n {\n public async Task TestValue(string keyPath, string valueName, object expectedValue, RegistryValueKind valueKind)\n {\n var result = new RegistryTestResult\n {\n KeyPath = keyPath,\n ValueName = valueName,\n ExpectedValue = expectedValue,\n Category = \"Registry Test\"\n };\n\n try\n {\n if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n result.IsSuccess = false;\n result.Message = \"Registry operations are only supported on Windows\";\n return result;\n }\n\n _logService.LogInformation($\"Testing registry value: {keyPath}\\\\{valueName}\");\n\n // Check if the key exists\n var keyExists = KeyExists(keyPath); // Removed await\n if (!keyExists)\n {\n result.IsSuccess = false;\n result.Message = $\"Registry key not found: {keyPath}\";\n return result;\n }\n\n // Check if the value exists\n var valueExists = ValueExists(keyPath, valueName); // Removed await\n if (!valueExists)\n {\n result.IsSuccess = false;\n result.Message = $\"Registry value not found: {keyPath}\\\\{valueName}\";\n return result;\n }\n\n // Get the actual value\n var actualValue = GetValue(keyPath, valueName); // Removed await\n result.ActualValue = actualValue;\n\n // Check if the value kind matches\n // var actualValueKind = await GetValueKind(keyPath, valueName); // Method doesn't exist\n // if (actualValueKind != valueKind)\n // {\n // result.IsSuccess = false;\n // result.Message = $\"Value kind mismatch. Expected: {valueKind}, Actual: {actualValueKind}\";\n // return result;\n // }\n\n // Compare the values\n if (expectedValue is int expectedInt && actualValue is int actualInt)\n {\n result.IsSuccess = expectedInt == actualInt;\n }\n else if (expectedValue is string expectedString && actualValue is string actualString)\n {\n result.IsSuccess = string.Equals(expectedString, actualString, StringComparison.OrdinalIgnoreCase);\n }\n else if (expectedValue is byte[] expectedBytes && actualValue is byte[] actualBytes)\n {\n result.IsSuccess = expectedBytes.SequenceEqual(actualBytes);\n }\n else\n {\n // For other types, use Equals\n result.IsSuccess = expectedValue?.Equals(actualValue) ?? (actualValue == null);\n }\n\n if (!result.IsSuccess)\n {\n result.Message = $\"Value mismatch. Expected: {expectedValue}, Actual: {actualValue}\";\n }\n else\n {\n result.Message = \"Value matches expected value\";\n }\n\n return result;\n }\n catch (Exception ex)\n {\n result.IsSuccess = false;\n result.Message = $\"Error testing registry value: {ex.Message}\";\n _logService.LogError($\"Error testing registry value {keyPath}\\\\{valueName}\", ex);\n return result;\n }\n }\n\n public async Task> TestMultipleValues(IEnumerable settings)\n {\n var results = new List();\n\n try\n {\n if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n _logService.LogError(\"Registry operations are only supported on Windows\");\n return results;\n }\n\n _logService.LogInformation(\"Testing multiple registry values\");\n\n foreach (var setting in settings)\n {\n var keyPath = $\"{setting.Hive}\\\\{setting.SubKey}\";\n // Use EnabledValue if available, otherwise fall back to RecommendedValue for backward compatibility\n object valueToTest = setting.EnabledValue ?? setting.RecommendedValue;\n var result = await TestValue(keyPath, setting.Name, valueToTest, setting.ValueType);\n result.Category = setting.Category;\n result.Description = setting.Description;\n results.Add(result);\n }\n\n var passCount = results.Count(r => r.IsSuccess);\n _logService.LogInformation($\"Registry test results: {passCount}/{results.Count} passed\");\n\n return results;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error testing multiple registry values: {ex.Message}\", ex);\n return results;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/LoadingWindowViewModel.cs", "using System;\nusing System.ComponentModel;\nusing System.Runtime.CompilerServices;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n public class LoadingWindowViewModel : INotifyPropertyChanged\n {\n private readonly ITaskProgressService _progressService;\n\n // INotifyPropertyChanged implementation\n public event PropertyChangedEventHandler? PropertyChanged;\n\n protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n protected bool SetProperty(ref T field, T value, [CallerMemberName] string? propertyName = null)\n {\n if (Equals(field, value)) return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n\n // Progress properties\n private double _progress;\n public double Progress\n {\n get => _progress;\n set => SetProperty(ref _progress, value);\n }\n\n private string _progressText = string.Empty;\n public string ProgressText\n {\n get => _progressText;\n set => SetProperty(ref _progressText, value);\n }\n\n private bool _isIndeterminate = true;\n public bool IsIndeterminate\n {\n get => _isIndeterminate;\n set => SetProperty(ref _isIndeterminate, value);\n }\n\n private bool _showProgressText;\n public bool ShowProgressText\n {\n get => _showProgressText;\n set => SetProperty(ref _showProgressText, value);\n }\n\n // Additional properties for more detailed loading information\n private string _statusMessage = \"Initializing...\";\n public string StatusMessage\n {\n get => _statusMessage;\n set => SetProperty(ref _statusMessage, value);\n }\n\n private string _detailMessage = \"Please wait while the application loads...\";\n public string DetailMessage\n {\n get => _detailMessage;\n set => SetProperty(ref _detailMessage, value);\n }\n\n public LoadingWindowViewModel(ITaskProgressService progressService)\n {\n _progressService = progressService ?? throw new ArgumentNullException(nameof(progressService));\n \n // Subscribe to progress events\n _progressService.ProgressUpdated += ProgressService_ProgressUpdated;\n }\n\n private void ProgressService_ProgressUpdated(object? sender, TaskProgressDetail detail)\n {\n // Update UI properties based on progress events\n IsIndeterminate = detail.IsIndeterminate;\n Progress = detail.Progress ?? 0;\n \n // Update progress text with percentage and status\n ProgressText = detail.IsIndeterminate ? string.Empty : $\"{detail.Progress:F0}% - {detail.StatusText}\";\n ShowProgressText = !detail.IsIndeterminate && _progressService.IsTaskRunning;\n \n // Update status message with the current operation\n if (!string.IsNullOrEmpty(detail.StatusText))\n {\n StatusMessage = detail.StatusText;\n \n // Update detail message based on the current operation\n if (detail.StatusText.Contains(\"Loading installable apps\"))\n {\n DetailMessage = \"Discovering available applications...\";\n }\n else if (detail.StatusText.Contains(\"Loading removable apps\"))\n {\n DetailMessage = \"Identifying Windows applications...\";\n }\n else if (detail.StatusText.Contains(\"Checking installation status\"))\n {\n DetailMessage = \"Verifying which applications are installed...\";\n }\n else if (detail.StatusText.Contains(\"Organizing apps\"))\n {\n DetailMessage = \"Sorting applications for display...\";\n }\n else\n {\n DetailMessage = \"Please wait while the application loads...\";\n }\n }\n }\n\n public void Cleanup()\n {\n // Unsubscribe from events to prevent memory leaks\n _progressService.ProgressUpdated -= ProgressService_ProgressUpdated;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppService.cs", "using System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Unified service interface for app discovery, loading, and status management.\n /// \n public interface IAppService\n {\n #region App Discovery & Loading\n\n /// \n /// Gets all installable applications.\n /// \n /// A collection of installable applications.\n Task> GetInstallableAppsAsync();\n\n /// \n /// Gets all standard (built-in) applications.\n /// \n /// A collection of standard applications.\n Task> GetStandardAppsAsync();\n\n /// \n /// Gets all available Windows capabilities.\n /// \n /// A collection of Windows capabilities.\n Task> GetCapabilitiesAsync();\n\n /// \n /// Gets all available Windows optional features.\n /// \n /// A collection of Windows optional features.\n Task> GetOptionalFeaturesAsync();\n\n #endregion\n\n #region Status Management\n\n /// \n /// Checks if an application is installed.\n /// \n /// The package name to check.\n /// The cancellation token.\n /// True if the application is installed; otherwise, false.\n Task IsAppInstalledAsync(string packageName, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if Microsoft Edge is installed.\n /// \n /// True if Edge is installed; otherwise, false.\n Task IsEdgeInstalledAsync();\n\n /// \n /// Checks if OneDrive is installed.\n /// \n /// True if OneDrive is installed; otherwise, false.\n Task IsOneDriveInstalledAsync();\n\n /// \n /// Gets the installation status of an item.\n /// \n /// The item to check.\n /// True if the item is installed; otherwise, false.\n Task GetItemInstallStatusAsync(IInstallableItem item);\n\n /// \n /// Gets the installation status of multiple items by package ID.\n /// \n /// The package IDs to check.\n /// A dictionary mapping package IDs to installation status.\n Task> GetBatchInstallStatusAsync(IEnumerable packageIds);\n\n /// \n /// Gets detailed installation status of an app.\n /// \n /// The app ID to check.\n /// The detailed installation status.\n Task GetInstallStatusAsync(string appId);\n\n /// \n /// Refreshes the installation status of multiple items.\n /// \n /// The items to refresh.\n /// A task representing the asynchronous operation.\n Task RefreshInstallationStatusAsync(IEnumerable items);\n\n /// \n /// Sets the installation status of an app.\n /// \n /// The app ID to update.\n /// The new installation status.\n /// True if the status was updated successfully; otherwise, false.\n Task SetInstallStatusAsync(string appId, InstallStatus status);\n\n /// \n /// Clears the status cache.\n /// \n void ClearStatusCache();\n\n #endregion\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Extensions/SettingViewModelExtensions.cs", "using System;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Extensions\n{\n /// \n /// Extension methods for setting view models.\n /// \n public static class SettingViewModelExtensions\n {\n /// \n /// Safely converts an ApplicationSettingViewModel to an ApplicationSettingViewModel if possible.\n /// \n /// The setting to convert.\n /// The setting as an ApplicationSettingViewModel, or null if conversion is not possible.\n public static ApplicationSettingViewModel? AsApplicationSettingViewModel(this ApplicationSettingViewModel setting)\n {\n return setting;\n }\n \n /// \n /// Creates a new ApplicationSettingViewModel with properties copied from an ApplicationSettingViewModel.\n /// \n /// The setting to convert.\n /// The registry service.\n /// The dialog service.\n /// The log service.\n /// The dependency manager.\n /// The view model locator.\n /// The settings registry.\n /// A new ApplicationSettingViewModel with properties copied from the input setting.\n public static ApplicationSettingViewModel ToApplicationSettingViewModel(\n this ApplicationSettingViewModel setting,\n IRegistryService registryService,\n IDialogService? dialogService,\n ILogService logService,\n IDependencyManager? dependencyManager = null,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n {\n if (setting is ApplicationSettingViewModel applicationSetting)\n {\n return applicationSetting;\n }\n \n var result = new ApplicationSettingViewModel(\n registryService, \n dialogService, \n logService, \n dependencyManager)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsGroupHeader = setting.IsGroupHeader,\n IsGroupedSetting = setting.IsGroupedSetting,\n ControlType = setting.ControlType,\n SliderSteps = setting.SliderSteps,\n SliderValue = setting.SliderValue,\n Status = setting.Status,\n CurrentValue = setting.CurrentValue,\n StatusMessage = setting.StatusMessage,\n RegistrySetting = setting.RegistrySetting,\n LinkedRegistrySettings = setting.LinkedRegistrySettings,\n Dependencies = setting.Dependencies\n };\n \n // Copy child settings if any\n foreach (var child in setting.ChildSettings)\n {\n result.ChildSettings.Add(child.ToApplicationSettingViewModel(\n registryService, \n dialogService, \n logService, \n dependencyManager, \n viewModelLocator, \n settingsRegistry));\n }\n \n return result;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/DesignTimeDataService.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.WPF.Features.SoftwareApps.Models;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Implementation of the IDesignTimeDataService interface that provides\n /// realistic sample data for design-time visualization.\n /// \n public class DesignTimeDataService : IDesignTimeDataService\n {\n /// \n /// Gets a collection of sample third-party applications for design-time.\n /// \n /// A collection of ThirdPartyApp instances.\n public IEnumerable GetSampleThirdPartyApps()\n {\n return new List\n {\n new ThirdPartyApp\n {\n Name = \"Visual Studio Code\",\n Description = \"Lightweight code editor with powerful features\",\n PackageName = \"Microsoft.VisualStudioCode\",\n Category = \"Development\",\n IsInstalled = true,\n IsCustomInstall = false\n },\n new ThirdPartyApp\n {\n Name = \"Mozilla Firefox\",\n Description = \"Fast, private and secure web browser\",\n PackageName = \"Mozilla.Firefox\",\n Category = \"Web Browsers\",\n IsInstalled = false,\n IsCustomInstall = false\n },\n new ThirdPartyApp\n {\n Name = \"7-Zip\",\n Description = \"File archiver with high compression ratio\",\n PackageName = \"7zip.7zip\",\n Category = \"Utilities\",\n IsInstalled = true,\n IsCustomInstall = false\n },\n new ThirdPartyApp\n {\n Name = \"Adobe Photoshop\",\n Description = \"Professional image editing software\",\n PackageName = \"Adobe.Photoshop\",\n Category = \"Graphics & Design\",\n IsInstalled = false,\n IsCustomInstall = true\n }\n };\n }\n\n /// \n /// Gets a collection of sample Windows applications for design-time.\n /// \n /// A collection of WindowsApp instances.\n public IEnumerable GetSampleWindowsApps()\n {\n // Create sample AppInfo objects to use with the factory method\n var appInfos = new List\n {\n new AppInfo\n {\n Name = \"Microsoft Store\",\n Description = \"Microsoft's digital distribution platform\",\n PackageName = \"Microsoft.WindowsStore\",\n PackageID = \"9WZDNCRFJBMP\",\n Category = \"System\",\n IsInstalled = true,\n CanBeReinstalled = true,\n IsSystemProtected = false\n },\n new AppInfo\n {\n Name = \"Xbox\",\n Description = \"Xbox console companion app for Windows\",\n PackageName = \"Microsoft.XboxApp\",\n PackageID = \"9MV0B5HZVK9Z\",\n Category = \"Entertainment\",\n IsInstalled = true,\n CanBeReinstalled = true,\n IsSystemProtected = false\n },\n new AppInfo\n {\n Name = \"Microsoft Edge\",\n Description = \"Microsoft's web browser\",\n PackageName = \"Microsoft.MicrosoftEdge\",\n PackageID = \"9NBLGGH4M8RR\",\n Category = \"Web Browsers\",\n IsInstalled = true,\n RequiresSpecialHandling = true,\n SpecialHandlerType = \"Edge\",\n CanBeReinstalled = false,\n IsSystemProtected = true\n },\n new AppInfo\n {\n Name = \"OneDrive\",\n Description = \"Microsoft's cloud storage service\",\n PackageName = \"Microsoft.OneDrive\",\n PackageID = \"9WZDNCRFJ3PL\",\n Category = \"Cloud Storage\",\n IsInstalled = false,\n RequiresSpecialHandling = true,\n SpecialHandlerType = \"OneDrive\",\n CanBeReinstalled = true,\n IsSystemProtected = false\n }\n };\n\n // Use the factory method to create properly configured WindowsApp instances\n var windowsApps = new List();\n foreach (var appInfo in appInfos)\n {\n windowsApps.Add(WindowsApp.FromAppInfo(appInfo));\n }\n\n return windowsApps;\n }\n\n /// \n /// Gets a collection of sample Windows capabilities for design-time.\n /// \n /// A collection of WindowsApp instances configured as capabilities.\n public IEnumerable GetSampleWindowsCapabilities()\n {\n // Create sample CapabilityInfo objects to use with the factory method\n var capabilityInfos = new List\n {\n new CapabilityInfo\n {\n Name = \"Windows Media Player\",\n Description = \"Classic media player for Windows\",\n PackageName = \"Media.WindowsMediaPlayer\",\n Category = \"Media\",\n IsInstalled = true,\n CanBeReenabled = true,\n IsSystemProtected = false\n },\n new CapabilityInfo\n {\n Name = \"Internet Explorer\",\n Description = \"Legacy web browser\",\n PackageName = \"Browser.InternetExplorer\",\n Category = \"Web Browsers\",\n IsInstalled = false,\n CanBeReenabled = true,\n IsSystemProtected = false\n },\n new CapabilityInfo\n {\n Name = \"Windows Hello Face\",\n Description = \"Facial recognition authentication\",\n PackageName = \"Hello.Face\",\n Category = \"Security\",\n IsInstalled = true,\n CanBeReenabled = true,\n IsSystemProtected = true\n }\n };\n\n // Use the factory method to create properly configured WindowsApp instances\n var capabilities = new List();\n foreach (var capabilityInfo in capabilityInfos)\n {\n capabilities.Add(WindowsApp.FromCapabilityInfo(capabilityInfo));\n }\n\n return capabilities;\n }\n\n /// \n /// Gets a collection of sample Windows features for design-time.\n /// \n /// A collection of WindowsApp instances configured as features.\n public IEnumerable GetSampleWindowsFeatures()\n {\n // Create sample FeatureInfo objects to use with the factory method\n var featureInfos = new List\n {\n new FeatureInfo\n {\n Name = \"Windows Subsystem for Linux\",\n Description = \"Run Linux command-line tools on Windows\",\n PackageName = \"Microsoft-Windows-Subsystem-Linux\",\n Category = \"Development\",\n IsInstalled = true,\n CanBeReenabled = true,\n IsSystemProtected = false\n },\n new FeatureInfo\n {\n Name = \"Hyper-V\",\n Description = \"Windows virtualization platform\",\n PackageName = \"Microsoft-Hyper-V-All\",\n Category = \"Virtualization\",\n IsInstalled = false,\n CanBeReenabled = true,\n IsSystemProtected = false\n },\n new FeatureInfo\n {\n Name = \"Windows Sandbox\",\n Description = \"Isolated desktop environment for running applications\",\n PackageName = \"Containers-DisposableClientVM\",\n Category = \"Security\",\n IsInstalled = false,\n CanBeReenabled = true,\n IsSystemProtected = false\n }\n };\n\n // Use the factory method to create properly configured WindowsApp instances\n var features = new List();\n foreach (var featureInfo in featureInfos)\n {\n features.Add(WindowsApp.FromFeatureInfo(featureInfo));\n }\n\n return features;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/FeatureScriptModifier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Implementation of IFeatureScriptModifier that provides methods for modifying feature-related script content.\n /// \n public class FeatureScriptModifier : IFeatureScriptModifier\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public FeatureScriptModifier(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string RemoveOptionalFeatureFromScript(string scriptContent, string featureName)\n {\n // Check if the optional features section exists\n int sectionStartIndex = scriptContent.IndexOf(\"# Disable Optional Features\");\n if (sectionStartIndex == -1)\n {\n // Optional features section doesn't exist, so nothing to remove\n return scriptContent;\n }\n\n // Find the optional features array\n int arrayStartIndex = scriptContent.IndexOf(\"$optionalFeatures = @(\", sectionStartIndex);\n if (arrayStartIndex == -1)\n {\n Console.WriteLine(\"Could not find $optionalFeatures array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the optional features array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n Console.WriteLine(\"Could not find end of $optionalFeatures array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the optional features in the array\n var optionalFeatures = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var feature = trimmedLine.Trim('\\'', '\"', ' ', ',');\n optionalFeatures.Add(feature);\n }\n }\n\n // Check if the feature is in the array\n bool removed =\n optionalFeatures.RemoveAll(f =>\n f.Equals(featureName, StringComparison.OrdinalIgnoreCase)\n ) > 0;\n\n if (!removed)\n {\n // Feature not found in the array\n return scriptContent;\n }\n\n // If the array is now empty, remove the entire optional features section\n if (optionalFeatures.Count == 0)\n {\n // Find the end of the optional features section\n int sectionEndIndex = scriptContent.IndexOf(\n \"foreach ($feature in $optionalFeatures) {\",\n arrayEndIndex\n );\n if (sectionEndIndex != -1)\n {\n sectionEndIndex = scriptContent.IndexOf(\"}\", sectionEndIndex);\n if (sectionEndIndex != -1)\n {\n sectionEndIndex = scriptContent.IndexOf('\\n', sectionEndIndex);\n if (sectionEndIndex != -1)\n {\n // Remove the entire section\n return scriptContent.Substring(0, sectionStartIndex)\n + scriptContent.Substring(sectionEndIndex + 1);\n }\n }\n }\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$optionalFeatures = @(\");\n\n foreach (var feature in optionalFeatures)\n {\n newArrayContent.AppendLine($\" '{feature}'\");\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppInstallationService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for installing Windows applications.\n /// \n public interface IAppInstallationService : IInstallationService\n {\n /// \n /// Installs an application.\n /// \n /// The application to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n Task> InstallAppAsync(AppInfo app, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if an application can be installed.\n /// \n /// The application to check.\n /// An operation result indicating if the application can be installed, with error details if not.\n Task> CanInstallAppAsync(AppInfo app);\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Interfaces/IWinGetInstaller.cs", "using System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces\n{\n /// \n /// Defines the contract for WinGet package installation and management.\n /// \n public interface IWinGetInstaller\n {\n /// \n /// Installs a package using WinGet.\n /// \n /// The ID of the package to install.\n /// Optional installation options.\n /// The display name to use in progress reporting.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the installation result.\n Task InstallPackageAsync(\n string packageId, \n InstallationOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Upgrades a package using WinGet.\n /// \n /// The ID of the package to upgrade.\n /// Optional upgrade options.\n /// The display name to use in progress reporting.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the upgrade result.\n Task UpgradePackageAsync(\n string packageId, \n UpgradeOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Uninstalls a package using WinGet.\n /// \n /// The ID of the package to uninstall.\n /// Optional uninstallation options.\n /// The display name to use in progress reporting.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the uninstallation result.\n Task UninstallPackageAsync(\n string packageId, \n UninstallationOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Gets information about an installed package.\n /// \n /// The ID of the package to get information about.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the package information.\n Task GetPackageInfoAsync(\n string packageId, \n CancellationToken cancellationToken = default);\n\n /// \n /// Searches for packages matching the given query.\n /// \n /// The search query.\n /// Optional search options.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the search results.\n Task> SearchPackagesAsync(\n string query, \n SearchOptions options = null, \n CancellationToken cancellationToken = default);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Views/SoftwareAppsDialog.cs", "using System.Collections.Generic;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Views\n{\n public partial class SoftwareAppsDialog : Window\n {\n public int AppListColumns { get; set; } = 4;\n\n public SoftwareAppsDialog()\n {\n InitializeComponent();\n DataContext = this;\n }\n\n private void PrimaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = true;\n Close();\n }\n\n private void SecondaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = false;\n Close();\n }\n\n private void TertiaryButton_Click(object sender, RoutedEventArgs e)\n {\n // Explicitly set DialogResult to null for Cancel\n DialogResult = null;\n\n // Add debug logging\n System.Diagnostics.Debug.WriteLine(\n \"[DIALOG DEBUG] TertiaryButton (Cancel) clicked - DialogResult set to null\"\n );\n\n Close();\n }\n\n public static SoftwareAppsDialog CreateConfirmationDialog(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n var dialog = new SoftwareAppsDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"QuestionIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.AppList.ItemsSource = apps;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"Yes\";\n dialog.SecondaryButton.Content = \"No\";\n\n return dialog;\n }\n\n public static SoftwareAppsDialog CreateInformationDialog(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText,\n bool useMultiColumnLayout = false\n )\n {\n var dialog = new SoftwareAppsDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"InfoIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.AppList.ItemsSource = apps;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"OK\";\n dialog.SecondaryButton.Visibility = Visibility.Collapsed;\n\n return dialog;\n }\n\n public static bool? ShowConfirmationAsync(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n var dialog = CreateConfirmationDialog(title, headerText, apps, footerText);\n return dialog.ShowDialog();\n }\n\n public static void ShowInformationAsync(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n var dialog = CreateInformationDialog(title, headerText, apps, footerText);\n dialog.ShowDialog();\n }\n\n public static SoftwareAppsDialog CreateYesNoCancelDialog(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n var dialog = new SoftwareAppsDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"QuestionIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.AppList.ItemsSource = apps;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"Yes\";\n dialog.SecondaryButton.Content = \"No\";\n dialog.TertiaryButton.Content = \"Cancel\";\n\n // Ensure the Cancel button is visible and properly styled\n dialog.TertiaryButton.Visibility = Visibility.Visible;\n dialog.TertiaryButton.IsCancel = true;\n\n // Add debug logging for button visibility\n System.Diagnostics.Debug.WriteLine(\n $\"[DIALOG DEBUG] TertiaryButton Visibility: {dialog.TertiaryButton.Visibility}\"\n );\n System.Diagnostics.Debug.WriteLine(\n $\"[DIALOG DEBUG] TertiaryButton IsCancel: {dialog.TertiaryButton.IsCancel}\"\n );\n\n return dialog;\n }\n\n public static bool? ShowYesNoCancel(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n var dialog = CreateYesNoCancelDialog(title, headerText, apps, footerText);\n\n // Add event handler for the Closing event to ensure DialogResult is set correctly\n dialog.Closing += (sender, e) =>\n {\n // If DialogResult is not explicitly set (e.g., if the dialog is closed by clicking outside or pressing Escape),\n // set it to null to indicate Cancel\n if (dialog.DialogResult == null)\n {\n System.Diagnostics.Debug.WriteLine(\n \"[DIALOG DEBUG] Dialog closing without explicit DialogResult - setting to null (Cancel)\"\n );\n }\n };\n\n // Add event handler for the KeyDown event to handle Escape key\n dialog.KeyDown += (sender, e) =>\n {\n if (e.Key == System.Windows.Input.Key.Escape)\n {\n System.Diagnostics.Debug.WriteLine(\n \"[DIALOG DEBUG] Escape key pressed - setting DialogResult to null (Cancel)\"\n );\n dialog.DialogResult = null;\n dialog.Close();\n }\n };\n\n // Show the dialog and get the result\n var result = dialog.ShowDialog();\n\n // Log the result\n System.Diagnostics.Debug.WriteLine(\n $\"[DIALOG DEBUG] ShowYesNoCancel result: {(result == true ? \"Yes\" : result == false ? \"No\" : \"Cancel\")}\"\n );\n\n return result;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/WinGetModels.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents the result of a package installation operation.\n /// \n public class InstallationResult\n {\n /// \n /// Gets or sets a value indicating whether the installation was successful.\n /// \n public bool Success { get; set; }\n\n /// \n /// Gets or sets an optional message providing additional information about the result.\n /// \n public string Message { get; set; }\n\n /// \n /// Gets or sets the package ID that was installed.\n /// \n public string PackageId { get; set; }\n\n /// \n /// Gets or sets the version of the package that was installed.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets the exit code from the installation process.\n /// \n public int ExitCode { get; set; }\n\n /// \n /// Gets or sets the standard output from the installation process.\n /// \n public string Output { get; set; }\n\n /// \n /// Gets or sets the error output from the installation process.\n /// \n public string Error { get; set; }\n }\n\n \n /// \n /// Represents options for package installation.\n /// \n public class InstallationOptions\n {\n /// \n /// Gets or sets the version of the package to install. If null, the latest version is installed.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets the source to install the package from.\n /// \n public string Source { get; set; }\n\n /// \n /// Gets or sets a value indicating whether to accept package agreements automatically.\n /// \n public bool AcceptPackageAgreements { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether to accept source agreements automatically.\n /// \n public bool AcceptSourceAgreements { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether to run the installation in silent mode.\n /// \n public bool Silent { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether to force the installation even if the package is already installed.\n /// \n public bool Force { get; set; }\n\n /// \n /// Gets or sets the installation scope (user or machine).\n /// \n public PackageInstallScope Scope { get; set; } = PackageInstallScope.User;\n\n /// \n /// Gets or sets the installation location.\n /// \n public string Location { get; set; }\n }\n\n\n /// \n /// Represents the result of a package upgrade operation.\n /// \n public class UpgradeResult : InstallationResult\n {\n /// \n /// Gets or sets the version that was upgraded from.\n /// \n public string PreviousVersion { get; set; }\n }\n\n /// \n /// Represents options for package upgrades.\n /// \n public class UpgradeOptions : InstallationOptions\n {\n // Inherits all properties from InstallationOptions\n }\n\n /// \n /// Represents the result of a package uninstallation operation.\n /// \n public class UninstallationResult\n {\n /// \n /// Gets or sets a value indicating whether the uninstallation was successful.\n /// \n public bool Success { get; set; }\n\n /// \n /// Gets or sets an optional message providing additional information about the result.\n /// \n public string Message { get; set; }\n\n /// \n /// Gets or sets the package ID that was uninstalled.\n /// \n public string PackageId { get; set; }\n\n /// \n /// Gets or sets the version of the package that was uninstalled.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets the exit code from the uninstallation process.\n /// \n public int ExitCode { get; set; }\n\n /// \n /// Gets or sets the standard output from the uninstallation process.\n /// \n public string Output { get; set; }\n\n /// \n /// Gets or sets the error output from the uninstallation process.\n /// \n public string Error { get; set; }\n }\n\n\n /// \n /// Represents options for package uninstallation.\n /// \n public class UninstallationOptions\n {\n /// \n /// Gets or sets a value indicating whether to run the uninstallation in silent mode.\n /// \n public bool Silent { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether to force the uninstallation.\n /// \n public bool Force { get; set; }\n\n /// \n /// Gets or sets the installation scope (user or machine) to uninstall from.\n /// \n public PackageInstallScope Scope { get; set; } = PackageInstallScope.User;\n }\n\n /// \n /// Represents information about a package.\n /// \n public class PackageInfo\n {\n /// \n /// Gets or sets the package ID.\n /// \n public string Id { get; set; }\n\n /// \n /// Gets or sets the package name.\n /// \n public string Name { get; set; }\n\n /// \n /// Gets or sets the package version.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets the package source.\n /// \n public string Source { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the package is installed.\n /// \n public bool IsInstalled { get; set; }\n\n /// \n /// Gets or sets the installed version if different from the available version.\n /// \n public string InstalledVersion { get; set; }\n }\n\n\n /// \n /// Represents options for package search.\n /// \n public class SearchOptions\n {\n /// \n /// Gets or sets the maximum number of results to return.\n /// \n public int? Count { get; set; }\n\n /// \n /// Gets or sets the source to search in.\n /// \n public string Source { get; set; }\n\n /// \n /// Gets or sets a value indicating whether to include packages that are already installed.\n /// \n public bool IncludeInstalled { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether to include packages that are not installed.\n /// \n public bool IncludeAvailable { get; set; } = true;\n }\n\n /// \n /// Represents the installation scope for a package.\n /// \n public enum PackageInstallScope\n {\n /// \n /// Install for the current user only.\n /// \n User,\n\n /// \n /// Install for all users (requires elevation).\n /// \n Machine\n }\n\n /// \n /// Represents the progress of a package installation.\n /// \n public class InstallationProgress\n {\n /// \n /// Gets or sets the current progress percentage (0-100).\n /// \n public int Percentage { get; set; }\n\n /// \n /// Gets or sets the current status message.\n /// \n public string Status { get; set; }\n\n /// \n /// Gets or sets the current operation being performed.\n /// \n public string Operation { get; set; }\n\n /// \n /// Gets or sets the package ID being processed.\n /// \n public string PackageId { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the progress is indeterminate.\n /// \n public bool IsIndeterminate { get; set; }\n \n /// \n /// Gets or sets a value indicating whether the operation was cancelled.\n /// \n public bool IsCancelled { get; set; }\n \n /// \n /// Gets or sets a value indicating whether an error occurred during the operation.\n /// \n public bool IsError { get; set; }\n \n /// \n /// Gets or sets a value indicating whether the operation failed due to connectivity issues.\n /// \n public bool IsConnectivityIssue { get; set; }\n }\n\n /// \n /// Represents the progress of a package upgrade operation.\n /// \n public class UpgradeProgress\n {\n /// \n /// Gets or sets the percentage of completion (0-100).\n /// \n public int Percentage { get; set; }\n\n /// \n /// Gets or sets the status message.\n /// \n public string Status { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the progress is indeterminate.\n /// \n public bool IsIndeterminate { get; set; }\n\n /// \n /// Gets or sets the package ID being processed.\n /// \n public string PackageId { get; set; }\n }\n\n /// \n /// Represents the progress of a package uninstallation operation.\n /// \n public class UninstallationProgress\n {\n /// \n /// Gets or sets the percentage of completion (0-100).\n /// \n public int Percentage { get; set; }\n\n /// \n /// Gets or sets the status message.\n /// \n public string Status { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the progress is indeterminate.\n /// \n public bool IsIndeterminate { get; set; }\n\n /// \n /// Gets or sets the package ID being processed.\n /// \n public string PackageId { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppLoadingService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for loading application information and status.\n /// \n public interface IAppLoadingService\n {\n /// \n /// Loads applications and their installation status.\n /// \n /// An operation result containing a collection of applications with their installation status or error details.\n Task>> LoadAppsAsync();\n\n /// \n /// Refreshes the installation status of applications.\n /// \n /// The applications to refresh.\n /// An operation result indicating success or failure with error details.\n Task> RefreshInstallationStatusAsync(IEnumerable apps);\n\n /// \n /// Gets the installation status for an app by ID.\n /// \n /// The app ID.\n /// An operation result containing the installation status or error details.\n Task> GetInstallStatusAsync(string appId);\n\n /// \n /// Sets the installation status for an app.\n /// \n /// The app ID.\n /// The new status.\n /// An operation result indicating success or failure with error details.\n Task> SetInstallStatusAsync(string appId, InstallStatus status);\n\n /// \n /// Loads Windows capabilities.\n /// \n /// A collection of capability information.\n Task> LoadCapabilitiesAsync();\n\n /// \n /// Gets the installation status for an installable item.\n /// \n /// The installable item.\n /// True if the item is installed, false otherwise.\n Task GetItemInstallStatusAsync(IInstallableItem item);\n\n /// \n /// Gets the installation status for multiple package IDs.\n /// \n /// The package IDs to check.\n /// A dictionary mapping package IDs to their installation status.\n Task> GetBatchInstallStatusAsync(IEnumerable packageIds);\n\n /// \n /// Clears the status cache.\n /// \n void ClearStatusCache();\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Extensions/RegistrySettingExtensions.cs", "using Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Extensions\n{\n /// \n /// Extension methods for RegistrySetting.\n /// \n public static class RegistrySettingExtensions\n {\n /// \n /// Determines if the registry setting is for HttpAcceptLanguageOptOut.\n /// \n /// The registry setting to check.\n /// True if the setting is for HttpAcceptLanguageOptOut; otherwise, false.\n public static bool IsHttpAcceptLanguageOptOut(this RegistrySetting setting)\n {\n if (setting == null)\n return false;\n\n return setting.SubKey == \"Control Panel\\\\International\\\\User Profile\" &&\n setting.Name == \"HttpAcceptLanguageOptOut\";\n }\n\n /// \n /// Determines if the registry setting requires special handling.\n /// \n /// The registry setting to check.\n /// True if the setting requires special handling; otherwise, false.\n public static bool RequiresSpecialHandling(this RegistrySetting setting)\n {\n if (setting == null)\n return false;\n\n // Currently, only HttpAcceptLanguageOptOut requires special handling\n return IsHttpAcceptLanguageOptOut(setting);\n }\n\n /// \n /// Applies special handling for the registry setting.\n /// \n /// The registry setting to apply special handling for.\n /// The registry service to use.\n /// Whether the setting is being enabled or disabled.\n /// True if the special handling was applied successfully; otherwise, false.\n public static bool ApplySpecialHandling(this RegistrySetting setting, IRegistryService registryService, bool isEnabled)\n {\n if (setting == null || registryService == null)\n return false;\n\n if (IsHttpAcceptLanguageOptOut(setting) && isEnabled && setting.EnabledValue != null &&\n ((setting.EnabledValue is int intValue && intValue == 0) ||\n (setting.EnabledValue is string strValue && strValue == \"0\")))\n {\n // When enabling language list access, Windows deletes the key entirely\n string hiveString = GetRegistryHiveString(setting.Hive);\n return registryService.DeleteValue(\n $\"{hiveString}\\\\{setting.SubKey}\",\n setting.Name);\n }\n\n // No special handling needed or applicable\n return false;\n }\n\n /// \n /// Converts a RegistryHive enum to its string representation (HKCU, HKLM, etc.)\n /// \n /// The registry hive.\n /// The string representation of the registry hive.\n private static string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => throw new System.ArgumentException($\"Unsupported registry hive: {hive}\")\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/TaskProgressControl.xaml.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Markup;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.WPF.Features.Common.Models;\n\n[assembly: XmlnsDefinition(\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\", \"Winhance.WPF.Features.Common.Controls\")]\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// Interaction logic for TaskProgressControl.xaml\n /// \n public partial class TaskProgressControl : UserControl\n {\n #region Dependency Properties\n\n /// \n /// Gets or sets the progress value (0-100).\n /// \n public double Progress\n {\n get { return (double)GetValue(ProgressProperty); }\n set { SetValue(ProgressProperty, value); }\n }\n\n /// \n /// Identifies the Progress dependency property.\n /// \n public static readonly DependencyProperty ProgressProperty =\n DependencyProperty.Register(nameof(Progress), typeof(double), typeof(TaskProgressControl), \n new PropertyMetadata(0.0, OnProgressChanged));\n\n /// \n /// Gets or sets the status text.\n /// \n public string StatusText\n {\n get { return (string)GetValue(StatusTextProperty); }\n set { SetValue(StatusTextProperty, value); }\n }\n\n /// \n /// Identifies the StatusText dependency property.\n /// \n public static readonly DependencyProperty StatusTextProperty =\n DependencyProperty.Register(nameof(StatusText), typeof(string), typeof(TaskProgressControl), \n new PropertyMetadata(string.Empty));\n\n /// \n /// Gets or sets whether the progress is indeterminate.\n /// \n public bool IsIndeterminate\n {\n get { return (bool)GetValue(IsIndeterminateProperty); }\n set { SetValue(IsIndeterminateProperty, value); }\n }\n\n /// \n /// Identifies the IsIndeterminate dependency property.\n /// \n public static readonly DependencyProperty IsIndeterminateProperty =\n DependencyProperty.Register(nameof(IsIndeterminate), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets whether the control is visible.\n /// \n public new bool IsVisible\n {\n get { return (bool)GetValue(IsVisibleProperty); }\n set { SetValue(IsVisibleProperty, value); }\n }\n\n /// \n /// Identifies the IsVisible dependency property.\n /// \n public new static readonly DependencyProperty IsVisibleProperty =\n DependencyProperty.Register(nameof(IsVisible), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets the progress text (e.g., \"50%\").\n /// \n public string ProgressText\n {\n get { return (string)GetValue(ProgressTextProperty); }\n private set { SetValue(ProgressTextProperty, value); }\n }\n\n /// \n /// Identifies the ProgressText dependency property.\n /// \n public static readonly DependencyProperty ProgressTextProperty =\n DependencyProperty.Register(nameof(ProgressText), typeof(string), typeof(TaskProgressControl), \n new PropertyMetadata(string.Empty));\n\n /// \n /// Gets or sets whether the details are expanded.\n /// \n public bool AreDetailsExpanded\n {\n get { return (bool)GetValue(AreDetailsExpandedProperty); }\n set { SetValue(AreDetailsExpandedProperty, value); }\n }\n\n /// \n /// Identifies the AreDetailsExpanded dependency property.\n /// \n public static readonly DependencyProperty AreDetailsExpandedProperty =\n DependencyProperty.Register(nameof(AreDetailsExpanded), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets whether there are log messages.\n /// \n public bool HasLogMessages\n {\n get { return (bool)GetValue(HasLogMessagesProperty); }\n private set { SetValue(HasLogMessagesProperty, value); }\n }\n\n /// \n /// Identifies the HasLogMessages dependency property.\n /// \n public static readonly DependencyProperty HasLogMessagesProperty =\n DependencyProperty.Register(nameof(HasLogMessages), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets the log messages.\n /// \n public ObservableCollection LogMessages\n {\n get { return (ObservableCollection)GetValue(LogMessagesProperty); }\n private set { SetValue(LogMessagesProperty, value); }\n }\n\n /// \n /// Identifies the LogMessages dependency property.\n /// \n public static readonly DependencyProperty LogMessagesProperty =\n DependencyProperty.Register(nameof(LogMessages), typeof(ObservableCollection), \n typeof(TaskProgressControl), new PropertyMetadata(null));\n\n /// \n /// Gets or sets whether the operation can be cancelled.\n /// \n public bool CanCancel\n {\n get { return (bool)GetValue(CanCancelProperty); }\n set { SetValue(CanCancelProperty, value); }\n }\n\n /// \n /// Identifies the CanCancel dependency property.\n /// \n public static readonly DependencyProperty CanCancelProperty =\n DependencyProperty.Register(nameof(CanCancel), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets whether a task is running.\n /// \n public bool IsTaskRunning\n {\n get { return (bool)GetValue(IsTaskRunningProperty); }\n set { SetValue(IsTaskRunningProperty, value); }\n }\n\n /// \n /// Identifies the IsTaskRunning dependency property.\n /// \n public static readonly DependencyProperty IsTaskRunningProperty =\n DependencyProperty.Register(nameof(IsTaskRunning), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets the command to execute when the cancel button is clicked.\n /// \n public ICommand CancelCommand\n {\n get { return (ICommand)GetValue(CancelCommandProperty); }\n set { SetValue(CancelCommandProperty, value); }\n }\n\n /// \n /// Identifies the CancelCommand dependency property.\n /// \n public static readonly DependencyProperty CancelCommandProperty =\n DependencyProperty.Register(nameof(CancelCommand), typeof(ICommand), typeof(TaskProgressControl), \n new PropertyMetadata(null));\n\n #endregion\n\n /// \n /// Initializes a new instance of the class.\n /// \n public TaskProgressControl()\n {\n LogMessages = new ObservableCollection();\n InitializeComponent();\n UpdateProgressText();\n }\n\n private static void OnProgressChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is TaskProgressControl control)\n {\n control.UpdateProgressText();\n }\n }\n\n private void UpdateProgressText()\n {\n if (IsIndeterminate)\n {\n ProgressText = string.Empty;\n }\n else\n {\n ProgressText = $\"{Progress:F0}%\";\n }\n }\n\n /// \n /// Adds a log message to the control.\n /// \n /// The message content.\n /// The log level.\n public void AddLogMessage(string message, LogLevel level)\n {\n if (string.IsNullOrEmpty(message)) return;\n\n Application.Current.Dispatcher.Invoke(() =>\n {\n LogMessages.Add(new LogMessageViewModel\n {\n Message = message,\n Level = level,\n Timestamp = DateTime.Now\n });\n\n HasLogMessages = LogMessages.Count > 0;\n\n // Auto-expand details on error or warning\n if (level == LogLevel.Error || level == LogLevel.Warning)\n {\n AreDetailsExpanded = true;\n }\n });\n }\n\n /// \n /// Clears all log messages.\n /// \n public void ClearLogMessages()\n {\n Application.Current.Dispatcher.Invoke(() =>\n {\n LogMessages.Clear();\n HasLogMessages = false;\n });\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/MoreMenu.xaml.cs", "using System;\nusing System.IO;\nusing System.Windows;\nusing System.Windows.Controls;\nusing Winhance.WPF.Features.Common.Utilities;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// Interaction logic for MoreMenu.xaml\n /// \n public partial class MoreMenu : UserControl\n {\n public MoreMenu()\n {\n try\n {\n LogToStartupLog(\"MoreMenu constructor starting\");\n InitializeComponent();\n LogToStartupLog(\"MoreMenu constructor completed successfully\");\n }\n catch (Exception ex)\n {\n LogToStartupLog($\"ERROR in MoreMenu constructor: {ex.Message}\");\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n throw; // Re-throw to ensure the error is properly handled\n }\n }\n\n /// \n /// Logs a message directly to the WinhanceStartupLog.txt file\n /// \n private void LogToStartupLog(string message)\n {\n#if DEBUG\n try\n {\n string logsDir = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\"\n );\n string logFile = Path.Combine(logsDir, \"WinhanceStartupLog.txt\");\n\n // Ensure the logs directory exists\n if (!Directory.Exists(logsDir))\n {\n Directory.CreateDirectory(logsDir);\n }\n\n // Format the log message with timestamp\n string formattedMessage =\n $\"[{DateTime.Now:yyyy/MM/dd HH:mm:ss}] [MoreMenu] {message}\";\n\n // Append to the log file\n using (StreamWriter writer = File.AppendText(logFile))\n {\n writer.WriteLine(formattedMessage);\n }\n }\n catch\n {\n // Ignore errors in logging to avoid cascading issues\n }\n#endif\n }\n\n /// \n /// Shows the context menu at the specified placement target\n /// \n /// The UI element that the context menu should be positioned relative to\n public void ShowMenu(UIElement placementTarget)\n {\n try\n {\n LogToStartupLog(\"ShowMenu method called\");\n LogToStartupLog($\"placementTarget exists: {placementTarget != null}\");\n LogToStartupLog($\"DataContext exists: {DataContext != null}\");\n LogToStartupLog(\n $\"DataContext type: {(DataContext != null ? DataContext.GetType().FullName : \"null\")}\"\n );\n\n // Get the context menu from resources\n var contextMenu = Resources[\"MoreButtonContextMenu\"] as ContextMenu;\n LogToStartupLog($\"ContextMenu from resources exists: {contextMenu != null}\");\n\n if (contextMenu != null)\n {\n try\n {\n // Ensure the context menu has the same DataContext as the control\n LogToStartupLog(\"Setting context menu DataContext\");\n contextMenu.DataContext = this.DataContext;\n LogToStartupLog(\n $\"Context menu DataContext set: {contextMenu.DataContext != null}\"\n );\n\n // Add a handler to log when menu items are clicked\n foreach (var item in contextMenu.Items)\n {\n if (item is MenuItem menuItem)\n {\n LogToStartupLog(\n $\"Menu item: {menuItem.Header}, Command bound: {menuItem.Command != null}\"\n );\n\n // Add a Click handler to log when the item is clicked\n menuItem.Click += (s, e) =>\n {\n LogToStartupLog($\"Menu item clicked: {menuItem.Header}\");\n if (menuItem.Command != null)\n {\n LogToStartupLog(\n $\"Command can execute: {menuItem.Command.CanExecute(null)}\"\n );\n }\n };\n }\n }\n\n // Set the placement target\n LogToStartupLog(\"Setting placement target\");\n contextMenu.PlacementTarget = placementTarget;\n LogToStartupLog(\"Placement target set successfully\");\n\n // Set placement mode to Right to show menu to the right of the button\n LogToStartupLog(\"Setting placement mode\");\n contextMenu.Placement = System\n .Windows\n .Controls\n .Primitives\n .PlacementMode\n .Right;\n LogToStartupLog(\"Placement mode set successfully\");\n\n // No horizontal or vertical offset\n LogToStartupLog(\"Setting offset values\");\n contextMenu.HorizontalOffset = 0;\n contextMenu.VerticalOffset = 0;\n LogToStartupLog(\"Offset values set successfully\");\n\n // Open the context menu\n LogToStartupLog(\"About to open context menu\");\n contextMenu.IsOpen = true;\n LogToStartupLog(\"Context menu opened successfully\");\n }\n catch (Exception menuEx)\n {\n LogToStartupLog($\"ERROR configuring context menu: {menuEx.Message}\");\n LogToStartupLog($\"Stack trace: {menuEx.StackTrace}\");\n }\n }\n else\n {\n LogToStartupLog(\"ERROR: ContextMenu from resources is null, cannot show menu\");\n }\n }\n catch (Exception ex)\n {\n LogToStartupLog($\"ERROR in ShowMenu method: {ex.Message}\");\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Utilities/FileLogger.cs", "using System;\nusing System.IO;\nusing System.Threading;\n\nnamespace Winhance.WPF.Features.Common.Utilities\n{\n /// \n /// Utility class for direct file logging, used for diagnostic purposes.\n /// \n public static class FileLogger\n {\n private static readonly object _lockObject = new object();\n private const string LOG_FOLDER = \"DiagnosticLogs\";\n \n // Logging is disabled as CloseButtonDiagnostics.txt is no longer used\n private static readonly bool _loggingEnabled = false;\n\n /// \n /// Logs a message to the diagnostic log file.\n /// \n /// The source of the log message (e.g., class name)\n /// The message to log\n public static void Log(string source, string message)\n {\n // Early return if logging is disabled\n if (!_loggingEnabled)\n return;\n \n try\n {\n string logPath = GetLogFilePath();\n string timestamp = DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss.fff\");\n string threadId = Thread.CurrentThread.ManagedThreadId.ToString();\n string logMessage = $\"[{timestamp}] [Thread:{threadId}] [{source}] {message}\";\n\n lock (_lockObject)\n {\n // Ensure directory exists\n Directory.CreateDirectory(Path.GetDirectoryName(logPath));\n File.AppendAllText(logPath, logMessage + Environment.NewLine);\n }\n }\n catch\n {\n // Ignore errors in logging to avoid affecting the application\n }\n }\n\n /// \n /// Gets the full path to the log file.\n /// \n /// The full path to the log file\n public static string GetLogFilePath()\n {\n string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n string winhancePath = Path.Combine(appDataPath, \"Winhance\");\n string logFolderPath = Path.Combine(winhancePath, LOG_FOLDER);\n // Using a placeholder filename since logging is disabled\n return Path.Combine(logFolderPath, \"diagnostics.log\");\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/MessengerService.cs", "using System;\nusing System.Collections.Generic;\nusing CommunityToolkit.Mvvm.Messaging;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Implementation of IMessengerService that uses CommunityToolkit.Mvvm.Messenger\n /// \n public class MessengerService : IMessengerService\n {\n private readonly IMessenger _messenger;\n private readonly Dictionary> _recipientTokens;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public MessengerService()\n {\n _messenger = WeakReferenceMessenger.Default;\n _recipientTokens = new Dictionary>();\n }\n\n /// \n /// Initializes a new instance of the class with a specific messenger.\n /// \n /// The messenger to use.\n public MessengerService(IMessenger messenger)\n {\n _messenger = messenger ?? throw new ArgumentNullException(nameof(messenger));\n _recipientTokens = new Dictionary>();\n }\n\n /// \n void IMessengerService.Send(TMessage message)\n {\n // Only MessageBase objects can be sent with the messenger\n if (message is MessageBase msgBase)\n {\n _messenger.Send(msgBase);\n }\n }\n\n /// \n void IMessengerService.Register(object recipient, Action action)\n {\n // Only reference types can be registered with the messenger\n if (typeof(TMessage).IsClass && typeof(TMessage).IsAssignableTo(typeof(MessageBase)))\n {\n // We need to use dynamic here to handle the generic type constraints\n dynamic typedRecipient = recipient;\n dynamic typedAction = action;\n RegisterInternal(typedRecipient, typedAction);\n }\n }\n\n private void RegisterInternal(object recipient, Action action) \n where TMessage : MessageBase\n {\n // Register the recipient with the messenger\n _messenger.Register(recipient, (r, m) => action(m));\n \n // Create a token that will unregister the recipient when disposed\n var token = new RegistrationToken(() => _messenger.Unregister(recipient));\n\n // Keep track of the token for later cleanup\n if (!_recipientTokens.TryGetValue(recipient, out var tokens))\n {\n tokens = new List();\n _recipientTokens[recipient] = tokens;\n }\n\n tokens.Add(token);\n }\n\n /// \n /// A token that unregisters a recipient when disposed\n /// \n private class RegistrationToken : IDisposable\n {\n private readonly Action _unregisterAction;\n private bool _isDisposed;\n\n public RegistrationToken(Action unregisterAction)\n {\n _unregisterAction = unregisterAction;\n }\n\n public void Dispose()\n {\n if (!_isDisposed)\n {\n _unregisterAction();\n _isDisposed = true;\n }\n }\n }\n\n /// \n void IMessengerService.Unregister(object recipient)\n {\n if (_recipientTokens.TryGetValue(recipient, out var tokens))\n {\n foreach (var token in tokens)\n {\n token.Dispose();\n }\n\n _recipientTokens.Remove(recipient);\n }\n\n _messenger.UnregisterAll(recipient);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/OperationResult.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents the result of an operation, including success status, error details, and a result value.\n /// \n /// The type of the result value.\n public class OperationResult\n {\n /// \n /// Gets or sets a value indicating whether the operation was successful.\n /// \n public bool Success { get; set; }\n\n /// \n /// Gets or sets the result value of the operation.\n /// \n public T? Result { get; set; }\n\n /// \n /// Gets or sets the error message if the operation failed.\n /// \n public string? ErrorMessage { get; set; }\n\n /// \n /// Gets or sets the exception that occurred during the operation, if any.\n /// \n public Exception? Exception { get; set; }\n\n /// \n /// Gets or sets additional error details.\n /// \n public Dictionary? ErrorDetails { get; set; }\n\n /// \n /// Creates a successful operation result with the specified result value.\n /// \n /// The result value.\n /// A successful operation result.\n public static OperationResult CreateSuccess(T result)\n {\n return new OperationResult\n {\n Success = true,\n Result = result\n };\n }\n\n /// \n /// Creates a failed operation result with the specified error message.\n /// \n /// The error message.\n /// A failed operation result.\n public static OperationResult CreateFailure(string errorMessage)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = errorMessage\n };\n }\n\n /// \n /// Creates a failed operation result with the specified exception.\n /// \n /// The exception that occurred.\n /// A failed operation result.\n public static OperationResult CreateFailure(Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = exception.Message,\n Exception = exception\n };\n }\n\n /// \n /// Creates a failed operation result with the specified error message and exception.\n /// \n /// The error message.\n /// The exception that occurred.\n /// A failed operation result.\n public static OperationResult CreateFailure(string errorMessage, Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = errorMessage,\n Exception = exception\n };\n }\n\n /// \n /// Checks if the operation was successful.\n /// \n /// True if the operation was successful; otherwise, false.\n public bool Succeeded()\n {\n return Success;\n }\n\n /// \n /// Creates a successful operation result with the specified message.\n /// \n /// The message.\n /// A successful operation result.\n public static OperationResult Succeeded(string message)\n {\n return new OperationResult\n {\n Success = true,\n ErrorMessage = message\n };\n }\n\n /// \n /// Creates a successful operation result with the specified result value.\n /// \n /// The result value.\n /// A successful operation result.\n public static OperationResult Succeeded(T result)\n {\n return new OperationResult\n {\n Success = true,\n Result = result\n };\n }\n\n /// \n /// Checks if the operation failed.\n /// \n /// True if the operation failed; otherwise, false.\n public bool Failed()\n {\n return !Success;\n }\n\n /// \n /// Creates a failed operation result with the specified message.\n /// \n /// The message.\n /// A failed operation result.\n public static OperationResult Failed(string message)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = message\n };\n }\n\n /// \n /// Creates a failed operation result with the specified message and exception.\n /// \n /// The message.\n /// The exception.\n /// A failed operation result.\n public static OperationResult Failed(string message, Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = message,\n Exception = exception\n };\n }\n\n /// \n /// Creates a failed operation result with the specified message and result value.\n /// \n /// The error message.\n /// The result value to set even though the operation failed.\n /// A failed operation result with the specified result value.\n public static OperationResult Failed(string message, T result)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = message,\n Result = result\n };\n }\n }\n\n /// \n /// Represents the result of an operation, including success status and error details.\n /// \n public class OperationResult\n {\n /// \n /// Gets or sets a value indicating whether the operation was successful.\n /// \n public bool Success { get; set; }\n\n /// \n /// Gets or sets the error message if the operation failed.\n /// \n public string? ErrorMessage { get; set; }\n\n /// \n /// Gets or sets the exception that occurred during the operation, if any.\n /// \n public Exception? Exception { get; set; }\n\n /// \n /// Gets or sets additional error details.\n /// \n public Dictionary? ErrorDetails { get; set; }\n\n /// \n /// Creates a successful operation result.\n /// \n /// A successful operation result.\n public static OperationResult CreateSuccess()\n {\n return new OperationResult\n {\n Success = true\n };\n }\n\n /// \n /// Creates a failed operation result with the specified error message.\n /// \n /// The error message.\n /// A failed operation result.\n public static OperationResult CreateFailure(string errorMessage)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = errorMessage\n };\n }\n\n /// \n /// Creates a failed operation result with the specified exception.\n /// \n /// The exception that occurred.\n /// A failed operation result.\n public static OperationResult CreateFailure(Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = exception.Message,\n Exception = exception\n };\n }\n\n /// \n /// Creates a failed operation result with the specified error message and exception.\n /// \n /// The error message.\n /// The exception that occurred.\n /// A failed operation result.\n public static OperationResult CreateFailure(string errorMessage, Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = errorMessage,\n Exception = exception\n };\n }\n\n /// \n /// Checks if the operation was successful.\n /// \n /// True if the operation was successful; otherwise, false.\n public bool Succeeded()\n {\n return Success;\n }\n\n /// \n /// Creates a successful operation result with the specified message.\n /// \n /// The message.\n /// A successful operation result.\n public static OperationResult Succeeded(string message)\n {\n return new OperationResult\n {\n Success = true,\n ErrorMessage = message\n };\n }\n\n /// \n /// Checks if the operation failed.\n /// \n /// True if the operation failed; otherwise, false.\n public bool Failed()\n {\n return !Success;\n }\n\n /// \n /// Creates a failed operation result with the specified message.\n /// \n /// The message.\n /// A failed operation result.\n public static OperationResult Failed(string message)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = message\n };\n }\n\n /// \n /// Creates a failed operation result with the specified message and exception.\n /// \n /// The message.\n /// The exception.\n /// A failed operation result.\n public static OperationResult Failed(string message, Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = message,\n Exception = exception\n };\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Services/SettingsRegistry.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Core.Features.Common.Services\n{\n /// \n /// Registry for settings.\n /// \n public class SettingsRegistry : ISettingsRegistry\n {\n private readonly ILogService _logService;\n private readonly List _settings = new List();\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public SettingsRegistry(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Registers a setting in the registry.\n /// \n /// The setting to register.\n public void RegisterSetting(ISettingItem setting)\n {\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot register null setting\");\n return;\n }\n\n if (string.IsNullOrEmpty(setting.Id))\n {\n _logService.Log(LogLevel.Warning, \"Cannot register setting with null or empty ID\");\n return;\n }\n\n lock (_settings)\n {\n // Check if the setting is already registered\n if (_settings.Any(s => s.Id == setting.Id))\n {\n _logService.Log(LogLevel.Info, $\"Setting with ID '{setting.Id}' is already registered\");\n return;\n }\n\n _settings.Add(setting);\n _logService.Log(LogLevel.Info, $\"Registered setting {setting.Id} in global settings collection\");\n }\n }\n\n /// \n /// Gets a setting by its ID.\n /// \n /// The ID of the setting to get.\n /// The setting if found, otherwise null.\n public ISettingItem? GetSettingById(string id)\n {\n if (string.IsNullOrEmpty(id))\n {\n _logService.Log(LogLevel.Warning, \"Cannot get setting with null or empty ID\");\n return null;\n }\n\n lock (_settings)\n {\n return _settings.FirstOrDefault(s => s.Id == id);\n }\n }\n\n /// \n /// Gets all settings in the registry.\n /// \n /// A list of all settings.\n public List GetAllSettings()\n {\n lock (_settings)\n {\n return new List(_settings);\n }\n }\n\n /// \n /// Gets all settings of a specific type.\n /// \n /// The type of settings to get.\n /// A list of settings of the specified type.\n public List GetSettingsByType() where T : ISettingItem\n {\n lock (_settings)\n {\n return _settings.OfType().Cast().ToList();\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/UnifiedConfigurationDialogViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// ViewModel for the UnifiedConfigurationDialog.\n /// \n public class UnifiedConfigurationDialogViewModel : ObservableObject\n {\n private string _title;\n private string _description;\n private bool _isSaveDialog;\n\n /// \n /// Gets or sets the title of the dialog.\n /// \n public string Title\n {\n get => _title;\n set => SetProperty(ref _title, value);\n }\n\n /// \n /// Gets or sets the description of the dialog.\n /// \n public string Description\n {\n get => _description;\n set => SetProperty(ref _description, value);\n }\n\n /// \n /// Gets a value indicating whether this is a save dialog.\n /// \n public bool IsSaveDialog => _isSaveDialog;\n\n /// \n /// Gets the collection of configuration sections.\n /// \n public ObservableCollection Sections { get; } = new ObservableCollection();\n\n /// \n /// Gets or sets the command to confirm the selection.\n /// \n public ICommand OkCommand { get; set; }\n\n /// \n /// Gets or sets the command to cancel the selection.\n /// \n public ICommand CancelCommand { get; set; }\n\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The title of the dialog.\n /// The description of the dialog.\n /// The dictionary of section names, their availability, and item counts.\n /// Whether this is a save dialog (true) or an import dialog (false).\n public UnifiedConfigurationDialogViewModel(\n string title, \n string description, \n Dictionary sections,\n bool isSaveDialog)\n {\n Title = title;\n Description = description;\n _isSaveDialog = isSaveDialog;\n\n // Create section view models\n foreach (var section in sections)\n {\n Sections.Add(new UnifiedConfigurationSectionViewModel\n {\n Name = GetSectionDisplayName(section.Key),\n Description = GetSectionDescription(section.Key),\n IsSelected = section.Value.IsSelected,\n IsAvailable = section.Value.IsAvailable,\n ItemCount = section.Value.ItemCount,\n SectionKey = section.Key\n });\n }\n\n // Commands will be set by the dialog\n OkCommand = null;\n CancelCommand = null;\n }\n\n /// \n /// Gets the result of the dialog as a dictionary of section names and their selection state.\n /// \n /// A dictionary of section names and their selection state.\n public Dictionary GetResult()\n {\n var result = new Dictionary();\n\n foreach (var section in Sections)\n {\n result[section.SectionKey] = section.IsSelected;\n }\n\n return result;\n }\n\n\n private string GetSectionDisplayName(string sectionKey)\n {\n return sectionKey switch\n {\n \"WindowsApps\" => \"Windows Apps\",\n \"ExternalApps\" => \"External Apps\",\n \"Customize\" => \"Customization Settings\",\n \"Optimize\" => \"Optimization Settings\",\n _ => sectionKey\n };\n }\n\n private string GetSectionDescription(string sectionKey)\n {\n return sectionKey switch\n {\n \"WindowsApps\" => \"Settings for Windows built-in applications\",\n \"ExternalApps\" => \"Settings for third-party applications\",\n \"Customize\" => \"Windows UI customization settings\",\n \"Optimize\" => \"Windows optimization settings\",\n _ => string.Empty\n };\n }\n }\n\n /// \n /// ViewModel for a unified configuration section.\n /// \n public class UnifiedConfigurationSectionViewModel : ObservableObject\n {\n private string _name;\n private string _description;\n private bool _isSelected;\n private bool _isAvailable;\n private int _itemCount;\n private string _sectionKey;\n\n /// \n /// Gets or sets the name of the section.\n /// \n public string Name\n {\n get => _name;\n set => SetProperty(ref _name, value);\n }\n\n /// \n /// Gets or sets the description of the section.\n /// \n public string Description\n {\n get => _description;\n set => SetProperty(ref _description, value);\n }\n\n /// \n /// Gets or sets a value indicating whether the section is selected.\n /// \n public bool IsSelected\n {\n get => _isSelected;\n set => SetProperty(ref _isSelected, value);\n }\n\n /// \n /// Gets or sets a value indicating whether the section is available.\n /// \n public bool IsAvailable\n {\n get => _isAvailable;\n set => SetProperty(ref _isAvailable, value);\n }\n\n /// \n /// Gets or sets the number of items in the section.\n /// \n public int ItemCount\n {\n get => _itemCount;\n set => SetProperty(ref _itemCount, value);\n }\n\n /// \n /// Gets or sets the section key.\n /// \n public string SectionKey\n {\n get => _sectionKey;\n set => SetProperty(ref _sectionKey, value);\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/CapabilityScriptModifier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Implementation of ICapabilityScriptModifier that provides methods for modifying capability-related script content.\n /// \n public class CapabilityScriptModifier : ICapabilityScriptModifier\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public CapabilityScriptModifier(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string RemoveCapabilityFromScript(string scriptContent, string capabilityName)\n {\n // Find the capabilities array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$capabilities = @(\");\n if (arrayStartIndex == -1)\n {\n Console.WriteLine(\"Could not find $capabilities array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the capabilities array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n Console.WriteLine(\"Could not find end of $capabilities array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the capabilities in the array\n var capabilities = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var capability = trimmedLine.Trim('\\'', '\"', ' ', ',');\n capabilities.Add(capability);\n }\n }\n\n // Check if the capability is in the array\n bool removed =\n capabilities.RemoveAll(c =>\n c.Equals(capabilityName, StringComparison.OrdinalIgnoreCase)\n ) > 0;\n\n if (!removed)\n {\n // Capability not found in the array\n return scriptContent;\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$capabilities = @(\");\n\n foreach (var capability in capabilities)\n {\n newArrayContent.AppendLine($\" '{capability}'\");\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/JsonParameterSerializer.cs", "using System;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Text;\nusing System.Text.Json;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n public class JsonParameterSerializer : IParameterSerializer\n {\n private readonly JsonSerializerOptions _options = new()\n {\n PropertyNameCaseInsensitive = true,\n WriteIndented = false\n };\n\n public int MaxParameterSize { get; set; } = 1024 * 1024; // 1MB default\n public bool UseCompression { get; set; } = true;\n\n public string Serialize(object parameter)\n {\n if (parameter == null) return null;\n \n var json = JsonSerializer.Serialize(parameter, _options);\n \n if (UseCompression && json.Length > 1024) // Compress if over 1KB\n {\n var bytes = Encoding.UTF8.GetBytes(json);\n using var output = new MemoryStream();\n using (var gzip = new GZipStream(output, CompressionMode.Compress))\n {\n gzip.Write(bytes, 0, bytes.Length);\n }\n return Convert.ToBase64String(output.ToArray());\n }\n \n return json;\n }\n\n // Corrected signature to match IParameterSerializer\n public object Deserialize(Type targetType, string value)\n {\n if (string.IsNullOrWhiteSpace(value)) return null;\n\n try\n {\n if (IsCompressed(value)) // Use 'value' parameter\n {\n var bytes = Convert.FromBase64String(value); // Use 'value' parameter\n using var input = new MemoryStream(bytes);\n using var output = new MemoryStream();\n using (var gzip = new GZipStream(input, CompressionMode.Decompress))\n {\n gzip.CopyTo(output);\n }\n var json = Encoding.UTF8.GetString(output.ToArray());\n return JsonSerializer.Deserialize(json, targetType, _options);\n }\n\n return JsonSerializer.Deserialize(value, targetType, _options); // Use 'value' parameter\n }\n catch (JsonException ex)\n {\n throw new InvalidOperationException(\"Failed to deserialize parameter\", ex);\n }\n catch (Exception ex) when (ex is FormatException || ex is InvalidDataException)\n {\n throw new InvalidOperationException(\"Invalid compressed parameter format\", ex);\n }\n }\n\n public T Deserialize(string serialized)\n {\n if (string.IsNullOrWhiteSpace(serialized)) return default;\n\n try\n {\n if (IsCompressed(serialized))\n {\n var bytes = Convert.FromBase64String(serialized);\n using var input = new MemoryStream(bytes);\n using var output = new MemoryStream();\n using (var gzip = new GZipStream(input, CompressionMode.Decompress))\n {\n gzip.CopyTo(output);\n }\n var json = Encoding.UTF8.GetString(output.ToArray());\n return JsonSerializer.Deserialize(json, _options);\n }\n \n return JsonSerializer.Deserialize(serialized, _options);\n }\n catch (JsonException ex)\n {\n throw new InvalidOperationException($\"Failed to deserialize parameter to type {typeof(T).Name}\", ex);\n }\n catch (Exception ex) when (ex is FormatException || ex is InvalidDataException)\n {\n throw new InvalidOperationException(\"Invalid compressed parameter format\", ex);\n }\n }\n\n private bool IsCompressed(string input)\n {\n if (string.IsNullOrEmpty(input)) return false;\n try\n {\n // Simple check - compressed data is base64 and starts with H4sI (GZip magic number)\n return input.Length > 4 && \n input.StartsWith(\"H4sI\") && \n input.Length % 4 == 0;\n }\n catch\n {\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/CapabilityCatalog.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a catalog of Windows capabilities that can be enabled or disabled.\n/// \npublic class CapabilityCatalog\n{\n /// \n /// Gets or sets the collection of Windows capabilities.\n /// \n public IReadOnlyList Capabilities { get; init; } = new List();\n\n /// \n /// Creates a default capability catalog with predefined Windows capabilities.\n /// \n /// A new CapabilityCatalog instance with default capabilities.\n public static CapabilityCatalog CreateDefault()\n {\n return new CapabilityCatalog { Capabilities = CreateDefaultCapabilities() };\n }\n\n private static IReadOnlyList CreateDefaultCapabilities()\n {\n return new List\n {\n // Browser capabilities\n new CapabilityInfo\n {\n Name = \"Internet Explorer\",\n Description = \"Legacy web browser\",\n PackageName = \"Browser.InternetExplorer\",\n Category = \"Browser\",\n CanBeReenabled = false,\n },\n // Development capabilities\n new CapabilityInfo\n {\n Name = \"PowerShell ISE\",\n Description = \"PowerShell Integrated Scripting Environment\",\n PackageName = \"Microsoft.Windows.PowerShell.ISE\",\n Category = \"Development\",\n CanBeReenabled = true,\n },\n // System capabilities\n new CapabilityInfo\n {\n Name = \"Quick Assist\",\n Description = \"Remote assistance app\",\n PackageName = \"App.Support.QuickAssist\",\n Category = \"System\",\n CanBeReenabled = false,\n },\n // Utilities capabilities\n new CapabilityInfo\n {\n Name = \"Steps Recorder\",\n Description = \"Screen recording tool\",\n PackageName = \"App.StepsRecorder\",\n Category = \"Utilities\",\n CanBeReenabled = true,\n },\n // Media capabilities\n new CapabilityInfo\n {\n Name = \"Windows Media Player\",\n Description = \"Classic media player\",\n PackageName = \"Media.WindowsMediaPlayer\",\n Category = \"Media\",\n CanBeReenabled = true,\n },\n // Productivity capabilities\n new CapabilityInfo\n {\n Name = \"WordPad\",\n Description = \"Rich text editor\",\n PackageName = \"Microsoft.Windows.WordPad\",\n Category = \"Productivity\",\n CanBeReenabled = false,\n },\n new CapabilityInfo\n {\n Name = \"Paint (Legacy)\",\n Description = \"Classic Paint app\",\n PackageName = \"Microsoft.Windows.MSPaint\",\n Category = \"Graphics\",\n CanBeReenabled = false,\n },\n // OpenSSH capabilities\n new CapabilityInfo\n {\n Name = \"OpenSSH Client\",\n Description = \"Secure Shell client for remote connections\",\n PackageName = \"OpenSSH.Client\",\n Category = \"Networking\",\n IsSystemProtected = false,\n CanBeReenabled = true,\n },\n new CapabilityInfo\n {\n Name = \"OpenSSH Server\",\n Description = \"Secure Shell server for remote connections\",\n PackageName = \"OpenSSH.Server\",\n Category = \"Networking\",\n IsSystemProtected = false,\n CanBeReenabled = true,\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Exceptions/InstallationException.cs", "using System;\nusing Winhance.Core.Features.SoftwareApps.Enums;\n\nnamespace Winhance.Core.Features.SoftwareApps.Exceptions\n{\n /// \n /// Exception thrown when there is an error with installation operations.\n /// \n public class InstallationException : Exception\n {\n /// \n /// Gets the type of installation error.\n /// \n public InstallationErrorType ErrorType { get; }\n \n /// \n /// Initializes a new instance of the class.\n /// \n public InstallationException() : base()\n {\n ErrorType = InstallationErrorType.UnknownError;\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message.\n /// \n /// The message that describes the error.\n public InstallationException(string message) : base(message)\n {\n ErrorType = InstallationErrorType.UnknownError;\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message\n /// and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception.\n public InstallationException(string message, Exception innerException) : base(message, innerException)\n {\n ErrorType = InstallationErrorType.UnknownError;\n }\n \n /// \n /// Initializes a new instance of the class with a specified error message,\n /// error type, and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception.\n /// The type of installation error.\n public InstallationException(string message, Exception innerException, InstallationErrorType errorType)\n : base(message, innerException)\n {\n ErrorType = errorType;\n }\n\n /// \n /// Initializes a new instance of the class with a specified item name, error message,\n /// a flag indicating whether the error is critical, and a reference to the inner exception that is the cause of this exception.\n /// \n /// The name of the item that failed to be installed.\n /// The error message.\n /// A flag indicating whether the error is critical.\n /// The exception that is the cause of the current exception.\n public InstallationException(string itemName, string errorMessage, bool isCritical, Exception innerException)\n : base($\"Failed to install {itemName}: {errorMessage}\", innerException)\n {\n ItemName = itemName;\n IsCritical = isCritical;\n ErrorType = InstallationErrorType.UnknownError;\n }\n \n /// \n /// Initializes a new instance of the class with a specified item name, error message,\n /// a flag indicating whether the error is critical, the error type, and a reference to the inner exception that is the cause of this exception.\n /// \n /// The name of the item that failed to be installed.\n /// The error message.\n /// A flag indicating whether the error is critical.\n /// The type of installation error.\n /// The exception that is the cause of the current exception.\n public InstallationException(string itemName, string errorMessage, bool isCritical, InstallationErrorType errorType, Exception innerException)\n : base($\"Failed to install {itemName}: {errorMessage}\", innerException)\n {\n ItemName = itemName;\n IsCritical = isCritical;\n ErrorType = errorType;\n }\n\n /// \n /// Gets the name of the item that failed to be installed.\n /// \n public string? ItemName { get; }\n\n /// \n /// Gets a value indicating whether the error is critical.\n /// \n public bool IsCritical { get; }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/PackageScriptModifier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Implementation of IPackageScriptModifier that provides methods for modifying package-related script content.\n /// \n public class PackageScriptModifier : IPackageScriptModifier\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public PackageScriptModifier(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string RemovePackageFromScript(string scriptContent, string packageName)\n {\n // Find the packages array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$packages = @(\");\n if (arrayStartIndex == -1)\n {\n Console.WriteLine(\"Could not find $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the packages array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n Console.WriteLine(\"Could not find end of $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the packages in the array\n var packages = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var package = trimmedLine.Trim('\\'', '\"', ' ', ',');\n packages.Add(package);\n }\n }\n\n // Check if the package is in the array\n bool removed =\n packages.RemoveAll(p => p.Equals(packageName, StringComparison.OrdinalIgnoreCase)) > 0;\n\n if (!removed)\n {\n // Package not found in the array\n return scriptContent;\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$packages = @(\");\n\n foreach (var package in packages)\n {\n newArrayContent.AppendLine($\" '{package}'\");\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ITaskProgressService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides functionality for tracking task progress.\n /// \n public interface ITaskProgressService\n {\n /// \n /// Gets a value indicating whether a task is currently running.\n /// \n bool IsTaskRunning { get; }\n\n /// \n /// Gets the current progress value (0-100).\n /// \n int CurrentProgress { get; }\n\n /// \n /// Gets the current status text.\n /// \n string CurrentStatusText { get; }\n\n /// \n /// Gets a value indicating whether the current task progress is indeterminate.\n /// \n bool IsIndeterminate { get; }\n\n /// \n /// Gets the cancellation token source for the current task.\n /// \n CancellationTokenSource? CurrentTaskCancellationSource { get; }\n\n /// \n /// Starts a new task.\n /// \n /// The name of the task.\n /// Whether the task progress is indeterminate.\n /// A cancellation token source for the task.\n CancellationTokenSource StartTask(string taskName, bool isIndeterminate = false);\n\n /// \n /// Updates the progress of the current task.\n /// \n /// The progress percentage (0-100).\n /// The status text.\n void UpdateProgress(int progressPercentage, string? statusText = null);\n\n /// \n /// Updates the progress of the current task with detailed information.\n /// \n /// The detailed progress information.\n void UpdateDetailedProgress(TaskProgressDetail detail);\n\n /// \n /// Completes the current task.\n /// \n void CompleteTask();\n\n /// \n /// Adds a log message to the task progress.\n /// \n /// The log message.\n void AddLogMessage(string message);\n\n /// \n /// Cancels the current task.\n /// \n void CancelCurrentTask();\n\n /// \n /// Creates a progress reporter for detailed progress.\n /// \n /// The progress reporter.\n IProgress CreateDetailedProgress();\n\n /// \n /// Creates a progress reporter for PowerShell progress.\n /// \n /// The progress reporter.\n IProgress CreatePowerShellProgress();\n\n /// \n /// Event raised when progress is updated.\n /// \n event EventHandler? ProgressUpdated;\n \n /// \n /// Event raised when progress is updated (legacy compatibility).\n /// \n event EventHandler? ProgressChanged;\n\n /// \n /// Event raised when a log message is added.\n /// \n event EventHandler? LogMessageAdded;\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Verification/VerificationMethodBase.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Verification\n{\n /// \n /// Base class for verification methods that check if a package is installed.\n /// \n public abstract class VerificationMethodBase\n {\n /// \n /// Gets the name of the verification method.\n /// \n public string Name { get; }\n\n /// \n /// Gets the priority of this verification method. Lower values mean higher priority.\n /// \n public int Priority { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The name of the verification method.\n /// The priority of the verification method. Lower values mean higher priority.\n protected VerificationMethodBase(string name, int priority)\n {\n Name = name ?? throw new System.ArgumentNullException(nameof(name));\n Priority = priority;\n }\n\n /// \n /// Verifies if a package is installed.\n /// \n /// The ID of the package to verify.\n /// The version of the package to verify, or null to check for any version.\n /// A cancellation token that can be used to cancel the operation.\n /// A task that represents the asynchronous operation. The task result contains the verification result.\n public async Task VerifyAsync(\n string packageId,\n string version = null,\n CancellationToken cancellationToken = default)\n {\n if (string.IsNullOrWhiteSpace(packageId))\n {\n throw new System.ArgumentException(\"Package ID cannot be null or whitespace.\", nameof(packageId));\n }\n\n return version == null\n ? await VerifyPresenceAsync(packageId, cancellationToken).ConfigureAwait(false)\n : await VerifyVersionAsync(packageId, version, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// When overridden in a derived class, verifies if a package is installed, regardless of version.\n /// \n /// The ID of the package to verify.\n /// A cancellation token that can be used to cancel the operation.\n /// A task that represents the asynchronous operation. The task result contains the verification result.\n protected abstract Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken);\n\n /// \n /// When overridden in a derived class, verifies if a specific version of a package is installed.\n /// \n /// The ID of the package to verify.\n /// The version of the package to verify.\n /// A cancellation token that can be used to cancel the operation.\n /// A task that represents the asynchronous operation. The task result contains the verification result.\n protected abstract Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken);\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/UI/Services/NotificationService.cs", "using System;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.UI.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.UI.Services\n{\n /// \n /// Implementation of the notification service that shows toast notifications.\n /// \n public class NotificationService : INotificationService\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public NotificationService(ILogService logService)\n {\n _logService = logService;\n }\n\n /// \n public void ShowToast(string title, string message, ToastType type)\n {\n // Log the notification\n switch (type)\n {\n case ToastType.Information:\n _logService.LogInformation($\"Toast Notification - {title}: {message}\");\n break;\n case ToastType.Success:\n _logService.LogSuccess($\"Toast Notification - {title}: {message}\");\n break;\n case ToastType.Warning:\n _logService.LogWarning($\"Toast Notification - {title}: {message}\");\n break;\n case ToastType.Error:\n _logService.LogError($\"Toast Notification - {title}: {message}\");\n break;\n default:\n _logService.LogInformation($\"Toast Notification - {title}: {message}\");\n break;\n }\n\n // In a real implementation, this would show a toast notification in the UI\n // For now, we're just logging the notification\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/FileSystemService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading.Tasks;\nusing Winhance.Core.Interfaces.Services;\n\nnamespace Winhance.Infrastructure.FileSystem\n{\n /// \n /// Implementation of IFileSystem that wraps the System.IO operations.\n /// \n public class FileSystemService : IFileSystemService\n {\n /// \n /// Determines whether the specified file exists.\n /// \n /// The file to check.\n /// True if the file exists; otherwise, false.\n public bool FileExists(string path)\n {\n return File.Exists(path);\n }\n\n /// \n /// Determines whether the specified directory exists.\n /// \n /// The directory to check.\n /// True if the directory exists; otherwise, false.\n public bool DirectoryExists(string path)\n {\n return Directory.Exists(path);\n }\n\n /// \n /// Creates a directory if it doesn't exist.\n /// \n /// The directory to create.\n /// True if the directory was created or already exists; otherwise, false.\n public bool CreateDirectory(string path)\n {\n try\n {\n if (!Directory.Exists(path))\n {\n Directory.CreateDirectory(path);\n }\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n /// Reads all text from a file.\n /// \n /// The file to read from.\n /// The text read from the file.\n public string ReadAllText(string path)\n {\n return File.ReadAllText(path);\n }\n\n /// \n /// Reads all text from a file asynchronously.\n /// \n /// The file to read from.\n /// A task that represents the asynchronous read operation and wraps the text read from the file.\n public async Task ReadAllTextAsync(string path)\n {\n using var reader = new StreamReader(path);\n return await reader.ReadToEndAsync();\n }\n\n /// \n /// Reads all bytes from a file.\n /// \n /// The file to read from.\n /// The bytes read from the file.\n public byte[] ReadAllBytes(string path)\n {\n return File.ReadAllBytes(path);\n }\n\n /// \n /// Reads all bytes from a file asynchronously.\n /// \n /// The file to read from.\n /// A task that represents the asynchronous read operation and wraps the bytes read from the file.\n public async Task ReadAllBytesAsync(string path)\n {\n return await File.ReadAllBytesAsync(path);\n }\n\n /// \n /// Writes text to a file.\n /// \n /// The file to write to.\n /// The text to write to the file.\n /// True if the text was written successfully; otherwise, false.\n public bool WriteAllText(string path, string contents)\n {\n try\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n File.WriteAllText(path, contents);\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n /// Writes text to a file asynchronously.\n /// \n /// The file to write to.\n /// The text to write to the file.\n /// A task that represents the asynchronous write operation.\n public async Task WriteAllTextAsync(string path, string contents)\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n await File.WriteAllTextAsync(path, contents);\n }\n \n /// \n /// Appends text to a file.\n /// \n /// The file to append to.\n /// The text to append to the file.\n public void AppendAllText(string path, string contents)\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n File.AppendAllText(path, contents);\n }\n \n /// \n /// Appends text to a file asynchronously.\n /// \n /// The file to append to.\n /// The text to append to the file.\n /// A task that represents the asynchronous append operation.\n public async Task AppendAllTextAsync(string path, string contents)\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n await File.AppendAllTextAsync(path, contents);\n }\n\n /// \n /// Writes bytes to a file.\n /// \n /// The file to write to.\n /// The bytes to write to the file.\n public void WriteAllBytes(string path, byte[] bytes)\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n File.WriteAllBytes(path, bytes);\n }\n\n /// \n /// Writes bytes to a file asynchronously.\n /// \n /// The file to write to.\n /// The bytes to write to the file.\n /// A task that represents the asynchronous write operation.\n public async Task WriteAllBytesAsync(string path, byte[] bytes)\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n await File.WriteAllBytesAsync(path, bytes);\n }\n\n /// \n /// Deletes a file.\n /// \n /// The file to delete.\n /// True if the file was deleted or didn't exist; otherwise, false.\n public bool DeleteFile(string path)\n {\n try\n {\n if (File.Exists(path))\n {\n File.Delete(path);\n }\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n /// Deletes a directory.\n /// \n /// The directory to delete.\n /// True to delete subdirectories and files; otherwise, false.\n public void DeleteDirectory(string path, bool recursive)\n {\n if (Directory.Exists(path))\n {\n Directory.Delete(path, recursive);\n }\n }\n\n /// \n /// Gets all files in a directory that match the specified pattern.\n /// \n /// The directory to search.\n /// The search pattern.\n /// Whether to search subdirectories.\n /// A collection of file paths.\n public IEnumerable GetFiles(string path, string pattern, bool recursive)\n {\n return Directory.GetFiles(path, pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);\n }\n\n /// \n /// Gets all directories in a directory that match the specified pattern.\n /// \n /// The directory to search.\n /// The search pattern.\n /// Whether to search subdirectories.\n /// A collection of directory paths.\n public IEnumerable GetDirectories(string path, string pattern, bool recursive)\n {\n return Directory.GetDirectories(path, pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);\n }\n \n /// \n /// Gets the path to a special folder, such as AppData, ProgramFiles, etc.\n /// \n /// The name of the special folder.\n /// The path to the special folder.\n public string GetSpecialFolderPath(string specialFolder)\n {\n if (Enum.TryParse(specialFolder, out var folder))\n {\n return Environment.GetFolderPath(folder);\n }\n return string.Empty;\n }\n \n /// \n /// Combines multiple paths into a single path.\n /// \n /// The paths to combine.\n /// The combined path.\n public string CombinePaths(params string[] paths)\n {\n return Path.Combine(paths);\n }\n \n /// \n /// Gets the current directory of the application.\n /// \n /// The current directory path.\n public string GetCurrentDirectory()\n {\n return Directory.GetCurrentDirectory();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/VerificationResult.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents the result of a verification operation.\n /// \n public class VerificationResult\n {\n /// \n /// Gets or sets a value indicating whether the verification was successful.\n /// \n public bool IsVerified { get; set; }\n\n /// \n /// Gets or sets the version that was verified, if applicable.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets an optional message providing additional information about the verification.\n /// \n public string Message { get; set; }\n\n /// \n /// Gets or sets the name of the verification method that was used.\n /// \n public string MethodUsed { get; set; }\n\n /// \n /// Gets or sets additional information about the verification result.\n /// This can be any object containing relevant details.\n /// \n public object AdditionalInfo { get; set; }\n\n /// \n /// Creates a successful verification result.\n /// \n /// The version that was verified.\n /// The name of the verification method that was used.\n /// Additional information about the verification result.\n /// A successful verification result.\n public static VerificationResult Success(string version = null, string methodUsed = null, object additionalInfo = null)\n {\n return new VerificationResult\n {\n IsVerified = true,\n Version = version,\n MethodUsed = methodUsed,\n AdditionalInfo = additionalInfo\n };\n }\n\n /// \n /// Creates a failed verification result.\n /// \n /// An optional message explaining why the verification failed.\n /// The name of the verification method that was used.\n /// Additional information about the verification result.\n /// A failed verification result.\n public static VerificationResult Failure(string message = null, string methodUsed = null, object additionalInfo = null)\n {\n return new VerificationResult\n {\n IsVerified = false,\n Message = message,\n MethodUsed = methodUsed,\n AdditionalInfo = additionalInfo\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IScriptGenerationService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for generating scripts for application removal and management.\n /// \n public interface IScriptGenerationService\n {\n /// \n /// Creates a batch removal script for applications.\n /// \n /// The application names to generate a removal script for.\n /// Dictionary mapping app names to registry settings.\n /// A removal script object.\n Task CreateBatchRemovalScriptAsync(\n List appNames,\n Dictionary> appsWithRegistry);\n\n /// \n /// Creates a batch removal script for a single application.\n /// \n /// The path where the script should be saved.\n /// The application to generate a removal script for.\n /// True if the script was created successfully; otherwise, false.\n Task CreateBatchRemovalScriptAsync(string scriptPath, AppInfo app);\n\n /// \n /// Updates the bloat removal script for an installed application.\n /// \n /// The application to update the script for.\n /// True if the script was updated successfully; otherwise, false.\n Task UpdateBloatRemovalScriptForInstalledAppAsync(AppInfo app);\n\n /// \n /// Registers a removal task in the Windows Task Scheduler.\n /// \n /// The script to register.\n /// A task representing the asynchronous operation.\n Task RegisterRemovalTaskAsync(RemovalScript script);\n\n /// \n /// Registers a removal task in the Windows Task Scheduler.\n /// \n /// The name of the task.\n /// The path to the script.\n /// True if the task was registered successfully; otherwise, false.\n Task RegisterRemovalTaskAsync(string taskName, string scriptPath);\n\n /// \n /// Saves a script to a file.\n /// \n /// The script to save.\n /// A task representing the asynchronous operation.\n Task SaveScriptAsync(RemovalScript script);\n\n /// \n /// Saves a script to a file.\n /// \n /// The path where the script should be saved.\n /// The content of the script.\n /// True if the script was saved successfully; otherwise, false.\n Task SaveScriptAsync(string scriptPath, string scriptContent);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/ExternalAppCatalog.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a catalog of external applications that can be installed.\n/// \npublic class ExternalAppCatalog\n{\n /// \n /// Gets or sets the collection of installable external applications.\n /// \n public IReadOnlyList ExternalApps { get; init; } = new List();\n\n /// \n /// Creates a default external app catalog with predefined installable apps.\n /// \n /// A new ExternalAppCatalog instance with default apps.\n public static ExternalAppCatalog CreateDefault()\n {\n return new ExternalAppCatalog { ExternalApps = CreateDefaultExternalApps() };\n }\n\n private static IReadOnlyList CreateDefaultExternalApps()\n {\n return new List\n {\n // Browsers\n new AppInfo\n {\n Name = \"Microsoft Edge WebView\",\n Description = \"WebView2 runtime for Windows applications\",\n PackageName = \"Microsoft.EdgeWebView2Runtime\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Thorium\",\n Description = \"Chromium-based browser with enhanced privacy features\",\n PackageName = \"Alex313031.Thorium\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Thorium AVX2\",\n Description = \"Chromium-based browser with enhanced privacy features\",\n PackageName = \"Alex313031.Thorium.AVX2\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Mercury\",\n Description = \"Compiler optimized, private Firefox fork\",\n PackageName = \"Alex313031.Mercury\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Firefox\",\n Description = \"Popular web browser known for privacy and customization\",\n PackageName = \"Mozilla.Firefox\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Chrome\",\n Description = \"Google's web browser with sync and extension support\",\n PackageName = \"Google.Chrome\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Ungoogled Chromium\",\n Description = \"Chromium-based browser with privacy enhancements\",\n PackageName = \"Eloston.Ungoogled-Chromium\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Brave\",\n Description = \"Privacy-focused browser with built-in ad blocking\",\n PackageName = \"Brave.Brave\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Opera\",\n Description = \"Feature-rich web browser with built-in VPN and ad blocker\",\n PackageName = \"Opera.Opera\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Opera GX\",\n Description = \"Gaming-oriented version of Opera with unique features\",\n PackageName = \"Opera.OperaGX\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Arc Browser\",\n Description = \"Innovative browser with a focus on design and user experience\",\n PackageName = \"TheBrowserCompany.Arc\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Tor Browser\",\n Description = \"Privacy-focused browser that routes traffic through the Tor network\",\n PackageName = \"TorProject.TorBrowser\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Vivaldi\",\n Description = \"Highly customizable browser with a focus on user control\",\n PackageName = \"Vivaldi.Vivaldi\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Waterfox\",\n Description = \"Firefox-based browser with a focus on privacy and customization\",\n PackageName = \"Waterfox.Waterfox\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Zen Browser\",\n Description = \"Privacy-focused browser with built-in ad blocking\",\n PackageName = \"Zen-Team.Zen-Browser\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Mullvad Browser\",\n Description =\n \"Privacy-focused browser designed to minimize tracking and fingerprints\",\n PackageName = \"MullvadVPN.MullvadBrowser\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Pale Moon Browser\",\n Description =\n \"Open Source, Goanna-based web browser focusing on efficiency and customization\",\n PackageName = \"MoonchildProductions.PaleMoon\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Maxthon Browser\",\n Description = \"Privacy focused browser with built-in ad blocking and VPN\",\n PackageName = \"Maxthon.Maxthon\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Floorp\",\n Description = \"Privacy focused browser with strong tracking protection\",\n PackageName = \"Ablaze.Floorp\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"DuckDuckGo\",\n Description = \"Privacy-focused search engine with a browser extension\",\n PackageName = \"DuckDuckGo.DesktopBrowser\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Document Viewers\n new AppInfo\n {\n Name = \"LibreOffice\",\n Description = \"Free and open-source office suite\",\n PackageName = \"TheDocumentFoundation.LibreOffice\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"ONLYOFFICE Desktop Editors\",\n Description = \"100% open-source free alternative to Microsoft Office\",\n PackageName = \"ONLYOFFICE.DesktopEditors\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Foxit Reader\",\n Description = \"Lightweight PDF reader with advanced features\",\n PackageName = \"Foxit.FoxitReader\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"SumatraPDF\",\n Description =\n \"PDF, eBook (epub, mobi), comic book (cbz/cbr), DjVu, XPS, CHM, image viewer for Windows\",\n PackageName = \"SumatraPDF.SumatraPDF\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"OpenOffice\",\n Description =\n \"Discontinued open-source office suite. Active successor projects is LibreOffice\",\n PackageName = \"Apache.OpenOffice\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Adobe Acrobat Reader DC\",\n Description = \"PDF reader and editor\",\n PackageName = \"XPDP273C0XHQH2\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Evernote\",\n Description = \"Note-taking app\",\n PackageName = \"Evernote.Evernote\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Online Storage\n new AppInfo\n {\n Name = \"Google Drive\",\n Description = \"Cloud storage and file synchronization service\",\n PackageName = \"Google.GoogleDrive\",\n Category = \"Online Storage\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Dropbox\",\n Description =\n \"File hosting service that offers cloud storage, file synchronization, personal cloud\",\n PackageName = \"Dropbox.Dropbox\",\n Category = \"Online Storage\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"SugarSync\",\n Description =\n \"Automatically access and share your photos, videos, and files in any folder\",\n PackageName = \"IPVanish.SugarSync\",\n Category = \"Online Storage\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"NextCloud\",\n Description =\n \"Access, share and protect your files, calendars, contacts, communication & more at home and in your organization\",\n PackageName = \"Nextcloud.NextcloudDesktop\",\n Category = \"Online Storage\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Proton Drive\",\n Description = \"Secure cloud storage with end-to-end encryption\",\n PackageName = \"Proton.ProtonDrive\",\n Category = \"Online Storage\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Development Apps\n new AppInfo\n {\n Name = \"Python 3.13\",\n Description = \"Python programming language\",\n PackageName = \"Python.Python.3.13\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Notepad++\",\n Description = \"Free source code editor and Notepad replacement\",\n PackageName = \"Notepad++.Notepad++\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"WinSCP\",\n Description = \"Free SFTP, SCP, Amazon S3, WebDAV, and FTP client\",\n PackageName = \"WinSCP.WinSCP\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"PuTTY\",\n Description = \"Free SSH and telnet client\",\n PackageName = \"PuTTY.PuTTY\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"WinMerge\",\n Description = \"Open source differencing and merging tool\",\n PackageName = \"WinMerge.WinMerge\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Eclipse\",\n Description = \"Java IDE and development platform\",\n PackageName = \"EclipseFoundation.EclipseIDEforJavaDevelopers\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Visual Studio Code\",\n Description = \"Code editor with support for development operations\",\n PackageName = \"Microsoft.VisualStudioCode\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Git\",\n Description = \"Distributed version control system\",\n PackageName = \"Git.Git\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"GitHub Desktop\",\n Description = \"GitHub desktop client\",\n PackageName = \"GitHub.GitHubDesktop\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"AutoHotkey\",\n Description = \"Scripting language for desktop automation\",\n PackageName = \"AutoHotkey.AutoHotkey\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Windsurf\",\n Description = \"AI Code Editor\",\n PackageName = \"Codeium.Windsurf\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Cursor\",\n Description = \"AI Code Editor\",\n PackageName = \"Anysphere.Cursor\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Multimedia (Audio & Video)\n new AppInfo\n {\n Name = \"VLC\",\n Description = \"Open-source multimedia player and framework\",\n PackageName = \"VideoLAN.VLC\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"iTunes\",\n Description = \"Media player and library\",\n PackageName = \"Apple.iTunes\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"AIMP\",\n Description = \"Audio player with support for various formats\",\n PackageName = \"AIMP.AIMP\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"foobar2000\",\n Description = \"Advanced audio player for Windows\",\n PackageName = \"PeterPawlowski.foobar2000\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"MusicBee\",\n Description = \"Music manager and player\",\n PackageName = \"9P4CLT2RJ1RS\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Audacity\",\n Description = \"Audio editor and recorder\",\n PackageName = \"Audacity.Audacity\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"GOM\",\n Description = \"Media player for Windows\",\n PackageName = \"GOMLab.GOMPlayer\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Spotify\",\n Description = \"Music streaming service\",\n PackageName = \"Spotify.Spotify\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"MediaMonkey\",\n Description = \"Media manager and player\",\n PackageName = \"VentisMedia.MediaMonkey.5\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"HandBrake\",\n Description = \"Open-source video transcoder\",\n PackageName = \"HandBrake.HandBrake\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"OBS Studio\",\n Description =\n \"Free and open source software for video recording and live streaming\",\n PackageName = \"OBSProject.OBSStudio\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Streamlabs OBS\",\n Description = \"Streaming software built on OBS with additional features for streamers\",\n PackageName = \"Streamlabs.StreamlabsOBS\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"MPC-BE\",\n Description = \"Media Player Classic - Black Edition\",\n PackageName = \"MPC-BE.MPC-BE\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"K-Lite Codec Pack (Mega)\",\n Description = \"Collection of codecs and related tools\",\n PackageName = \"CodecGuide.K-LiteCodecPack.Mega\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"CapCut\",\n Description = \"Video editor\",\n PackageName = \"ByteDance.CapCut\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"PotPlayer\",\n Description = \"Comprehensive multimedia player for Windows\",\n PackageName = \"Daum.PotPlayer\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Imaging\n new AppInfo\n {\n Name = \"IrfanView\",\n Description = \"Fast and compact image viewer and converter\",\n PackageName = \"IrfanSkiljan.IrfanView\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Krita\",\n Description = \"Digital painting and illustration software\",\n PackageName = \"KDE.Krita\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Blender\",\n Description = \"3D creation suite\",\n PackageName = \"BlenderFoundation.Blender\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Paint.NET\",\n Description = \"Image and photo editing software\",\n PackageName = \"dotPDN.PaintDotNet\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"GIMP\",\n Description = \"GNU Image Manipulation Program\",\n PackageName = \"GIMP.GIMP.3\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"XnViewMP\",\n Description = \"Image viewer, browser and converter\",\n PackageName = \"XnSoft.XnViewMP\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"XnView Classic\",\n Description = \"Image viewer, browser and converter (Classic Version)\",\n PackageName = \"XnSoft.XnView.Classic\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Inkscape\",\n Description = \"Vector graphics editor\",\n PackageName = \"Inkscape.Inkscape\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Greenshot\",\n Description = \"Screenshot tool with annotation features\",\n PackageName = \"Greenshot.Greenshot\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"ShareX\",\n Description = \"Screen capture, file sharing and productivity tool\",\n PackageName = \"ShareX.ShareX\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Flameshot\",\n Description = \"Powerful yet simple to use screenshot software\",\n PackageName = \"Flameshot.Flameshot\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"FastStone\",\n Description = \"Image browser, converter and editor\",\n PackageName = \"FastStone.Viewer\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Compression\n new AppInfo\n {\n Name = \"7-Zip\",\n Description = \"Open-source file archiver with a high compression ratio\",\n PackageName = \"7zip.7zip\",\n Category = \"Compression\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"WinRAR\",\n Description = \"File archiver with a high compression ratio\",\n PackageName = \"RARLab.WinRAR\",\n Category = \"Compression\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"PeaZip\",\n Description =\n \"Free file archiver utility. Open and extract RAR, TAR, ZIP files and more\",\n PackageName = \"Giorgiotani.Peazip\",\n Category = \"Compression\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"NanaZip\",\n Description =\n \"Open source fork of 7-zip intended for the modern Windows experience\",\n PackageName = \"M2Team.NanaZip\",\n Category = \"Compression\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Messaging, Email & Calendar\n new AppInfo\n {\n Name = \"Telegram\",\n Description = \"Instant messaging and voice calling app\",\n PackageName = \"Telegram.TelegramDesktop\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Whatsapp\",\n Description = \"Instant messaging and voice calling app\",\n PackageName = \"9NKSQGP7F2NH\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Zoom\",\n Description = \"Video conferencing and messaging platform\",\n PackageName = \"Zoom.Zoom\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Discord\",\n Description = \"Voice, video and text communication service\",\n PackageName = \"Discord.Discord\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Pidgin\",\n Description = \"Multi-protocol instant messaging client\",\n PackageName = \"Pidgin.Pidgin\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Thunderbird\",\n Description = \"Free email application\",\n PackageName = \"Mozilla.Thunderbird\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"eMClient\",\n Description = \"Email client with calendar, tasks, and chat\",\n PackageName = \"eMClient.eMClient\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Proton Mail\",\n Description = \"Secure email service with end-to-end encryption\",\n PackageName = \"Proton.ProtonMail\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Trillian\",\n Description = \"Instant messaging application\",\n PackageName = \"CeruleanStudios.Trillian\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // File & Disk Management\n new AppInfo\n {\n Name = \"WinDirStat\",\n Description = \"Disk usage statistics viewer and cleanup tool\",\n PackageName = \"WinDirStat.WinDirStat\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"WizTree\",\n Description = \"Disk space analyzer with extremely fast scanning\",\n PackageName = \"AntibodySoftware.WizTree\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"TreeSize Free\",\n Description = \"Disk space manager\",\n PackageName = \"JAMSoftware.TreeSize.Free\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Everything\",\n Description = \"Locate files and folders by name instantly\",\n PackageName = \"voidtools.Everything\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"TeraCopy\",\n Description = \"Copy files faster and more securely\",\n PackageName = \"CodeSector.TeraCopy\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"File Converter\",\n Description = \"Batch file converter for Windows\",\n PackageName = \"AdrienAllard.FileConverter\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Crystal Disk Info\",\n Description = \"Hard drive health monitoring utility\",\n PackageName = \"WsSolInfor.CrystalDiskInfo\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Bulk Rename Utility\",\n Description = \"File renaming software for Windows\",\n PackageName = \"TGRMNSoftware.BulkRenameUtility\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"IObit Unlocker\",\n Description = \"Tool to unlock files that are in use by other processes\",\n PackageName = \"IObit.IObitUnlocker\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Ventoy\",\n Description = \"Open source tool to create bootable USB drive for ISO files\",\n PackageName = \"Ventoy.Ventoy\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Volume2\",\n Description = \"Advanced Windows volume control\",\n PackageName = \"irzyxa.Volume2Portable\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Remote Access\n new AppInfo\n {\n Name = \"RustDesk\",\n Description = \"Fast Open-Source Remote Access and Support Software\",\n PackageName = \"RustDesk.RustDesk\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Input Leap\",\n Description = \"Open-source KVM software for sharing mouse and keyboard between computers\",\n PackageName = \"input-leap.input-leap\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"AnyDesk\",\n Description = \"Remote desktop software for remote access and support\",\n PackageName = \"AnyDesk.AnyDesk\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"TeamViewer 15\",\n Description =\n \"Remote control, desktop sharing, online meetings, web conferencing and file transfer\",\n PackageName = \"TeamViewer.TeamViewer\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"RealVNC Server\",\n Description = \"Remote access software\",\n PackageName = \"RealVNC.VNCServer\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"RealVNC Viewer\",\n Description = \"Remote access software\",\n PackageName = \"RealVNC.VNCViewer\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Chrome Remote Desktop Host\",\n Description = \"Remote access to your computer through Chrome browser\",\n PackageName = \"Google.ChromeRemoteDesktopHost\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Optical Disc Tools\n new AppInfo\n {\n Name = \"CDBurnerXP\",\n Description = \"Application to burn CDs and DVDs\",\n PackageName = \"\",\n Category = \"Optical Disc Tools\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"ImgBurn\",\n Description = \"Lightweight CD / DVD / HD DVD / Blu-ray burning application\",\n PackageName = \"LIGHTNINGUK.ImgBurn\",\n Category = \"Optical Disc Tools\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"AnyBurn\",\n Description = \"Lightweight CD/DVD/Blu-ray burning software\",\n PackageName = \"PowerSoftware.AnyBurn\",\n Category = \"Optical Disc Tools\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Other Utilities\n new AppInfo\n {\n Name = \"Snappy Driver Installer Origin\",\n Description = \"Driver installer and updater\",\n PackageName = \"GlennDelahoy.SnappyDriverInstallerOrigin\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Wise Registry Cleaner\",\n Description = \"Registry cleaning and optimization tool\",\n PackageName = \"XPDLS1XBTXVPP4\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"UniGetUI\",\n Description =\n \"Universal package manager interface supporting WinGet, Chocolatey, and more\",\n PackageName = \"MartiCliment.UniGetUI\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Google Earth\",\n Description = \"3D representation of Earth based on satellite imagery\",\n PackageName = \"Google.GoogleEarthPro\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"NV Access\",\n Description = \"Screen reader for blind and vision impaired users\",\n PackageName = \"NVAccess.NVDA\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Revo Uninstaller\",\n Description = \"Uninstaller with advanced features\",\n PackageName = \"RevoUninstaller.RevoUninstaller\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Bulk Crap Uninstaller\",\n Description = \"Free and open-source program uninstaller with advanced features\",\n PackageName = \"Klocman.BulkCrapUninstaller\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Text Grab\",\n Description = \"Tool for extracting text from images and screenshots\",\n PackageName = \"JosephFinney.Text-Grab\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Glary Utilities\",\n Description = \"All-in-one PC care utility\",\n PackageName = \"Glarysoft.GlaryUtilities\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Buzz\",\n Description = \"AI video & audio transcription tool\",\n PackageName = \"ChidiWilliams.Buzz\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"PowerToys\",\n Description = \"Windows system utilities to maximize productivity\",\n PackageName = \"Microsoft.PowerToys\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Customization Utilities\n new AppInfo\n {\n Name = \"Nilesoft Shell\",\n Description = \"Windows context menu customization tool\",\n PackageName = \"Nilesoft.Shell\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"StartAllBack\",\n Description = \"Windows 11 Start menu and taskbar customization\",\n PackageName = \"StartIsBack.StartAllBack\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Open-Shell\",\n Description = \"Classic style Start Menu for Windows\",\n PackageName = \"Open-Shell.Open-Shell-Menu\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Windhawk\",\n Description = \"Customization platform for Windows\",\n PackageName = \"RamenSoftware.Windhawk\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Lively Wallpaper\",\n Description = \"Free and open-source animated desktop wallpaper application\",\n PackageName = \"rocksdanister.LivelyWallpaper\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Sucrose Wallpaper Engine\",\n Description = \"Free and open-source animated desktop wallpaper application\",\n PackageName = \"Taiizor.SucroseWallpaperEngine\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Rainmeter\",\n Description = \"Desktop customization tool for Windows\",\n PackageName = \"Rainmeter.Rainmeter\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"ExplorerPatcher\",\n Description = \"Utility that enhances the Windows Explorer experience\",\n PackageName = \"valinet.ExplorerPatcher\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Gaming\n new AppInfo\n {\n Name = \"Steam\",\n Description = \"Digital distribution platform for PC gaming\",\n PackageName = \"Valve.Steam\",\n Category = \"Gaming\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Epic Games Launcher\",\n Description = \"Digital distribution platform for PC gaming\",\n PackageName = \"EpicGames.EpicGamesLauncher\",\n Category = \"Gaming\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"EA Desktop App\",\n Description = \"Digital distribution platform for PC gaming\",\n PackageName = \"ElectronicArts.EADesktop\",\n Category = \"Gaming\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Ubisoft Connect\",\n Description = \"Digital distribution platform for PC gaming\",\n PackageName = \"Ubisoft.Connect\",\n Category = \"Gaming\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Battle.net\",\n Description = \"Digital distribution platform for PC gaming\",\n PackageName = \"Blizzard.BattleNet\",\n Category = \"Gaming\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Privacy & Security\n new AppInfo\n {\n Name = \"Malwarebytes\",\n Description = \"Anti-malware software for Windows\",\n PackageName = \"Malwarebytes.Malwarebytes\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Malwarebytes AdwCleaner\",\n Description = \"Adware removal tool for Windows\",\n PackageName = \"Malwarebytes.AdwCleaner\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"SUPERAntiSpyware\",\n Description = \"Anti-spyware software for Windows\",\n PackageName = \"SUPERAntiSpyware.SUPERAntiSpyware\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"ProtonVPN\",\n Description = \"Secure and private VPN service\",\n PackageName = \"Proton.ProtonVPN\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"KeePass 2\",\n Description = \"Free, open source, light-weight password manager\",\n PackageName = \"DominikReichl.KeePass\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Proton Pass\",\n Description = \"Secure password manager with end-to-end encryption\",\n PackageName = \"Proton.ProtonPass\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Bitwarden\",\n Description = \"Open source password manager\",\n PackageName = \"Bitwarden.Bitwarden\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"KeePassXC\",\n Description = \"Cross-platform secure password manager\",\n PackageName = \"KeePassXCTeam.KeePassXC\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Tailscale\",\n Description = \"Zero config VPN for building secure networks\",\n PackageName = \"Tailscale.Tailscale\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/CustomDialog.xaml.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n public partial class CustomDialog : Window\n {\n\n public CustomDialog()\n {\n InitializeComponent();\n DataContext = this;\n }\n\n private void PrimaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = true;\n Close();\n }\n\n private void SecondaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = false;\n Close();\n }\n\n private void TertiaryButton_Click(object sender, RoutedEventArgs e)\n {\n // Explicitly set DialogResult to null for Cancel\n DialogResult = null;\n\n Close();\n }\n\n public static CustomDialog CreateConfirmationDialog(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = new CustomDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"QuestionIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.MessageContent.Text = message;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"Yes\";\n dialog.SecondaryButton.Content = \"No\";\n\n return dialog;\n }\n\n public static CustomDialog CreateConfirmationDialog(\n string title,\n string headerText,\n IEnumerable items,\n string footerText\n )\n {\n string message = items != null ? string.Join(Environment.NewLine, items) : string.Empty;\n return CreateConfirmationDialog(title, headerText, message, footerText);\n }\n\n public static CustomDialog CreateInformationDialog(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = new CustomDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"InfoIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.MessageContent.Text = message;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"OK\";\n dialog.SecondaryButton.Visibility = Visibility.Collapsed;\n\n return dialog;\n }\n\n public static CustomDialog CreateInformationDialog(\n string title,\n string headerText,\n IEnumerable items,\n string footerText,\n bool useMultiColumnLayout = false\n )\n {\n string message = items != null ? string.Join(Environment.NewLine, items) : string.Empty;\n return CreateInformationDialog(title, headerText, message, footerText);\n }\n\n public static bool? ShowConfirmation(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = CreateConfirmationDialog(title, headerText, message, footerText);\n return dialog.ShowDialog();\n }\n\n public static bool? ShowConfirmation(\n string title,\n string headerText,\n IEnumerable items,\n string footerText\n )\n {\n var dialog = CreateConfirmationDialog(title, headerText, items, footerText);\n return dialog.ShowDialog();\n }\n\n public static void ShowInformation(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = CreateInformationDialog(title, headerText, message, footerText);\n dialog.ShowDialog();\n }\n\n public static void ShowInformation(\n string title,\n string headerText,\n IEnumerable items,\n string footerText\n )\n {\n var dialog = CreateInformationDialog(title, headerText, items, footerText);\n dialog.ShowDialog();\n }\n\n public static CustomDialog CreateYesNoCancelDialog(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = new CustomDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"QuestionIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.MessageContent.Text = message;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"Yes\";\n dialog.SecondaryButton.Content = \"No\";\n dialog.TertiaryButton.Content = \"Cancel\";\n\n // Ensure the Cancel button is visible and properly styled\n dialog.TertiaryButton.Visibility = Visibility.Visible;\n dialog.TertiaryButton.IsCancel = true;\n\n return dialog;\n }\n\n public static CustomDialog CreateYesNoCancelDialog(\n string title,\n string headerText,\n IEnumerable items,\n string footerText\n )\n {\n string message = items != null ? string.Join(Environment.NewLine, items) : string.Empty;\n return CreateYesNoCancelDialog(title, headerText, message, footerText);\n }\n\n public static bool? ShowYesNoCancel(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = CreateYesNoCancelDialog(title, headerText, message, footerText);\n\n // Add event handler for the Closing event to ensure DialogResult is set correctly\n dialog.Closing += (sender, e) =>\n {\n // If DialogResult is not explicitly set (e.g., if the dialog is closed by clicking outside or pressing Escape),\n // set it to null to indicate Cancel\n if (dialog.DialogResult == null) { }\n };\n\n // Add event handler for the KeyDown event to handle Escape key\n dialog.KeyDown += (sender, e) =>\n {\n if (e.Key == System.Windows.Input.Key.Escape)\n {\n dialog.DialogResult = null;\n dialog.Close();\n }\n };\n\n // Show the dialog and get the result\n var result = dialog.ShowDialog();\n\n return result;\n }\n\n public static bool? ShowYesNoCancel(\n string title,\n string headerText,\n IEnumerable items,\n string footerText\n )\n {\n var dialog = CreateYesNoCancelDialog(title, headerText, items, footerText);\n\n // Add event handler for the Closing event to ensure DialogResult is set correctly\n dialog.Closing += (sender, e) =>\n {\n // If DialogResult is not explicitly set (e.g., if the dialog is closed by clicking outside or pressing Escape),\n // set it to null to indicate Cancel\n if (dialog.DialogResult == null) { }\n };\n\n // Add event handler for the KeyDown event to handle Escape key\n dialog.KeyDown += (sender, e) =>\n {\n if (e.Key == System.Windows.Input.Key.Escape)\n {\n dialog.DialogResult = null;\n dialog.Close();\n }\n };\n\n // Show the dialog and get the result\n var result = dialog.ShowDialog();\n\n return result;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/TaskProgressEventArgs.cs", "using System;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Event arguments for task progress events.\n /// \n public class TaskProgressEventArgs : EventArgs\n {\n /// \n /// Gets the progress value (0-100), or null if not applicable.\n /// \n public double Progress { get; }\n \n /// \n /// Gets the status text.\n /// \n public string StatusText { get; }\n \n /// \n /// Gets a detailed message about the current operation.\n /// \n public string DetailedMessage { get; }\n \n /// \n /// Gets the log level for the detailed message.\n /// \n public LogLevel LogLevel { get; }\n \n /// \n /// Gets whether the progress is indeterminate.\n /// \n public bool IsIndeterminate { get; }\n \n /// \n /// Gets whether a task is currently running.\n /// \n public bool IsTaskRunning { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The progress value.\n /// The status text.\n /// The detailed message.\n /// The log level.\n /// Whether the progress is indeterminate.\n /// Whether a task is running.\n public TaskProgressEventArgs(double progress, string statusText, string detailedMessage = \"\", LogLevel logLevel = LogLevel.Info, bool isIndeterminate = false, bool isTaskRunning = true)\n {\n Progress = progress;\n StatusText = statusText;\n DetailedMessage = detailedMessage;\n LogLevel = logLevel;\n IsIndeterminate = isIndeterminate;\n IsTaskRunning = isTaskRunning;\n }\n\n /// \n /// Creates a TaskProgressEventArgs instance from a TaskProgressDetail.\n /// \n /// The progress detail.\n /// Whether a task is running.\n /// A new TaskProgressEventArgs instance.\n public static TaskProgressEventArgs FromTaskProgressDetail(TaskProgressDetail detail, bool isTaskRunning = true)\n {\n return new TaskProgressEventArgs(\n detail.Progress ?? 0,\n detail.StatusText ?? string.Empty,\n detail.DetailedMessage ?? string.Empty,\n detail.LogLevel,\n detail.IsIndeterminate,\n isTaskRunning);\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Models/ThirdPartyApp.cs", "using CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Models\n{\n /// \n /// Represents a third-party application that can be installed through package managers like winget.\n /// These are applications not built into Windows but available for installation.\n /// \n public partial class ThirdPartyApp : ObservableObject\n {\n [ObservableProperty]\n private string _name = string.Empty;\n\n [ObservableProperty]\n private string _description = string.Empty;\n\n [ObservableProperty]\n private string _packageName = string.Empty;\n \n [ObservableProperty]\n private string _category = string.Empty;\n\n [ObservableProperty]\n private bool _isInstalled;\n\n [ObservableProperty]\n private bool _isCustomInstall;\n\n /// \n /// Determines if the app has a description that should be displayed.\n /// \n public bool HasDescription => !string.IsNullOrEmpty(Description);\n\n public static ThirdPartyApp FromAppInfo(AppInfo appInfo)\n {\n return new ThirdPartyApp\n {\n Name = appInfo.Name,\n Description = appInfo.Description,\n PackageName = appInfo.PackageName,\n Category = appInfo.Category,\n IsInstalled = appInfo.IsInstalled,\n IsCustomInstall = appInfo.IsCustomInstall\n };\n }\n\n /// \n /// Converts this ThirdPartyApp to an AppInfo object.\n /// \n /// An AppInfo object representing this ThirdPartyApp.\n public AppInfo ToAppInfo()\n {\n return new AppInfo\n {\n Name = Name,\n Description = Description,\n PackageName = PackageName,\n Category = Category,\n IsInstalled = IsInstalled,\n IsCustomInstall = IsCustomInstall\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppRemovalService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for removing Windows applications.\n /// \n public interface IAppRemovalService\n {\n /// \n /// Removes an application.\n /// \n /// The application to remove.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n Task> RemoveAppAsync(AppInfo app, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Generates a removal script for an application.\n /// \n /// The application to generate a removal script for.\n /// An operation result containing the removal script or error details.\n Task> GenerateRemovalScriptAsync(AppInfo app);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IFeatureInstallationService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for installing Windows optional features.\n /// \n public interface IFeatureInstallationService : IInstallationService\n {\n /// \n /// Installs a feature.\n /// \n /// The feature to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n Task> InstallFeatureAsync(FeatureInfo feature, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if a feature can be installed.\n /// \n /// The feature to check.\n /// An operation result indicating if the feature can be installed, with error details if not.\n Task> CanInstallFeatureAsync(FeatureInfo feature);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Services/ModelMapper.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\nnamespace Winhance.Core.Features.Common.Services\n{\n /// \n /// Interface for mapping between different model types.\n /// \n public interface IModelMapper\n {\n /// \n /// Maps a source object to a destination type.\n /// \n /// The source type.\n /// The destination type.\n /// The source object.\n /// The mapped destination object.\n TDestination Map(TSource source) where TDestination : new();\n\n /// \n /// Maps a collection of source objects to a collection of destination objects.\n /// \n /// The source type.\n /// The destination type.\n /// The collection of source objects.\n /// The collection of mapped destination objects.\n IEnumerable MapCollection(IEnumerable source) where TDestination : new();\n }\n\n /// \n /// Service for mapping between different model types.\n /// \n public class ModelMapper : IModelMapper\n {\n /// \n public TDestination Map(TSource source) where TDestination : new()\n {\n if (source == null)\n {\n throw new ArgumentNullException(nameof(source));\n }\n\n var destination = new TDestination();\n MapProperties(source, destination);\n return destination;\n }\n\n /// \n public IEnumerable MapCollection(IEnumerable source) where TDestination : new()\n {\n if (source == null)\n {\n throw new ArgumentNullException(nameof(source));\n }\n\n return source.Select(item => Map(item));\n }\n\n private static void MapProperties(TSource source, TDestination destination)\n {\n var sourceProperties = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);\n var destinationProperties = typeof(TDestination).GetProperties(BindingFlags.Public | BindingFlags.Instance)\n .ToDictionary(p => p.Name, p => p);\n\n foreach (var sourceProperty in sourceProperties)\n {\n if (destinationProperties.TryGetValue(sourceProperty.Name, out var destinationProperty))\n {\n if (destinationProperty.CanWrite && \n (destinationProperty.PropertyType == sourceProperty.PropertyType || \n IsAssignableOrConvertible(sourceProperty.PropertyType, destinationProperty.PropertyType)))\n {\n var value = sourceProperty.GetValue(source);\n \n if (value != null && sourceProperty.PropertyType != destinationProperty.PropertyType)\n {\n value = Convert.ChangeType(value, destinationProperty.PropertyType);\n }\n \n destinationProperty.SetValue(destination, value);\n }\n }\n }\n }\n\n private static bool IsAssignableOrConvertible(Type sourceType, Type destinationType)\n {\n return destinationType.IsAssignableFrom(sourceType) || \n (sourceType.IsPrimitive && destinationType.IsPrimitive) ||\n (sourceType == typeof(string) && destinationType.IsPrimitive) ||\n (destinationType == typeof(string) && sourceType.IsPrimitive);\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/ICapabilityInstallationService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for installing Windows capabilities.\n /// \n public interface ICapabilityInstallationService : IInstallationService\n {\n /// \n /// Installs a capability.\n /// \n /// The capability to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n Task> InstallCapabilityAsync(CapabilityInfo capability, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if a capability can be installed.\n /// \n /// The capability to check.\n /// An operation result indicating if the capability can be installed, with error details if not.\n Task> CanInstallCapabilityAsync(CapabilityInfo capability);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/SpecialAppHandler.cs", "using System;\nusing System.IO;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a handler for special applications that require custom removal processes.\n/// \npublic class SpecialAppHandler\n{\n /// \n /// Gets or sets the unique identifier for the special handler type.\n /// \n public string HandlerType { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the display name of the application.\n /// \n public string DisplayName { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the description of the application.\n /// \n public string Description { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the script content for removing the application.\n /// \n public string RemovalScriptContent { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the name of the scheduled task to create for preventing reinstallation.\n /// \n public string ScheduledTaskName { get; init; } = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether the application is currently installed.\n /// \n public bool IsInstalled { get; set; }\n\n /// \n /// Gets the path where the removal script will be saved.\n /// \n public string ScriptPath => Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n \"Winhance\",\n \"Scripts\",\n $\"{HandlerType}Removal.ps1\");\n\n /// \n /// Gets a collection of predefined special app handlers.\n /// \n /// A collection of special app handlers.\n public static SpecialAppHandler[] GetPredefinedHandlers()\n {\n return new[]\n {\n new SpecialAppHandler\n {\n HandlerType = \"Edge\",\n DisplayName = \"Microsoft Edge\",\n Description = \"Microsoft's web browser (requires special removal process)\",\n RemovalScriptContent = GetEdgeRemovalScript(),\n ScheduledTaskName = \"Winhance\\\\EdgeRemoval\"\n },\n new SpecialAppHandler\n {\n HandlerType = \"OneDrive\",\n DisplayName = \"OneDrive\",\n Description = \"Microsoft's cloud storage service (requires special removal process)\",\n RemovalScriptContent = GetOneDriveRemovalScript(),\n ScheduledTaskName = \"Winhance\\\\OneDriveRemoval\"\n },\n new SpecialAppHandler\n {\n HandlerType = \"OneNote\",\n DisplayName = \"Microsoft OneNote\",\n Description = \"Microsoft's note-taking application (requires special removal process)\",\n RemovalScriptContent = GetOneNoteRemovalScript(),\n ScheduledTaskName = \"Winhance\\\\OneNoteRemoval\"\n },\n };\n }\n\n private static string GetEdgeRemovalScript()\n {\n return @\"\n# EdgeRemoval.ps1\n# Standalone script to remove Microsoft Edge\n# Source: Winhance (https://github.com/memstechtips/Winhance)\n\n# stop edge running\n$stop = \"\"MicrosoftEdgeUpdate\"\", \"\"OneDrive\"\", \"\"WidgetService\"\", \"\"Widgets\"\", \"\"msedge\"\", \"\"msedgewebview2\"\"\n$stop | ForEach-Object { Stop-Process -Name $_ -Force -ErrorAction SilentlyContinue }\n# uninstall copilot\nGet-AppxPackage -allusers *Microsoft.Windows.Ai.Copilot.Provider* | Remove-AppxPackage\n# disable edge updates regedit\nreg add \"\"HKLM\\SOFTWARE\\Microsoft\\EdgeUpdate\"\" /v \"\"DoNotUpdateToEdgeWithChromium\"\" /t REG_DWORD /d \"\"1\"\" /f | Out-Null\n# allow edge uninstall regedit\nreg add \"\"HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\EdgeUpdateDev\"\" /v \"\"AllowUninstall\"\" /t REG_SZ /f | Out-Null\n# new folder to uninstall edge\nNew-Item -Path \"\"$env:SystemRoot\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\"\" -ItemType Directory -ErrorAction SilentlyContinue | Out-Null\n# new file to uninstall edge\nNew-Item -Path \"\"$env:SystemRoot\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\"\" -ItemType File -Name \"\"MicrosoftEdge.exe\"\" -ErrorAction SilentlyContinue | Out-Null\n# find edge uninstall string\n$regview = [Microsoft.Win32.RegistryView]::Registry32\n$microsoft = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $regview).\nOpenSubKey(\"\"SOFTWARE\\Microsoft\"\", $true)\n$uninstallregkey = $microsoft.OpenSubKey(\"\"Windows\\CurrentVersion\\Uninstall\\Microsoft Edge\"\")\ntry {\n $uninstallstring = $uninstallregkey.GetValue(\"\"UninstallString\"\") + \"\" --force-uninstall\"\"\n}\ncatch {\n}\n# uninstall edge\nStart-Process cmd.exe \"\"/c $uninstallstring\"\" -WindowStyle Hidden -Wait\n# remove folder file\nRemove-Item -Recurse -Force \"\"$env:SystemRoot\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\"\" -ErrorAction SilentlyContinue | Out-Null\n# find edgeupdate.exe\n$edgeupdate = @(); \"\"LocalApplicationData\"\", \"\"ProgramFilesX86\"\", \"\"ProgramFiles\"\" | ForEach-Object {\n $folder = [Environment]::GetFolderPath($_)\n $edgeupdate += Get-ChildItem \"\"$folder\\Microsoft\\EdgeUpdate\\*.*.*.*\\MicrosoftEdgeUpdate.exe\"\" -rec -ea 0\n}\n# find edgeupdate & allow uninstall regedit\n$global:REG = \"\"HKCU:\\SOFTWARE\"\", \"\"HKLM:\\SOFTWARE\"\", \"\"HKCU:\\SOFTWARE\\Policies\"\", \"\"HKLM:\\SOFTWARE\\Policies\"\", \"\"HKCU:\\SOFTWARE\\WOW6432Node\"\", \"\"HKLM:\\SOFTWARE\\WOW6432Node\"\", \"\"HKCU:\\SOFTWARE\\WOW6432Node\\Policies\"\", \"\"HKLM:\\SOFTWARE\\WOW6432Node\\Policies\"\"\nforeach ($location in $REG) { Remove-Item \"\"$location\\Microsoft\\EdgeUpdate\"\" -recurse -force -ErrorAction SilentlyContinue }\n# uninstall edgeupdate\nforeach ($path in $edgeupdate) {\n if (Test-Path $path) { Start-Process -Wait $path -Args \"\"/unregsvc\"\" | Out-Null }\n do { Start-Sleep 3 } while ((Get-Process -Name \"\"setup\"\", \"\"MicrosoftEdge*\"\" -ErrorAction SilentlyContinue).Path -like \"\"*\\Microsoft\\Edge*\"\")\n if (Test-Path $path) { Start-Process -Wait $path -Args \"\"/uninstall\"\" | Out-Null }\n do { Start-Sleep 3 } while ((Get-Process -Name \"\"setup\"\", \"\"MicrosoftEdge*\"\" -ErrorAction SilentlyContinue).Path -like \"\"*\\Microsoft\\Edge*\"\")\n}\n# remove edgewebview regedit\ncmd /c \"\"reg delete `\"\"HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Microsoft EdgeWebView`\"\" /f >nul 2>&1\"\"\ncmd /c \"\"reg delete `\"\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Microsoft EdgeWebView`\"\" /f >nul 2>&1\"\"\n# remove folders edge edgecore edgeupdate edgewebview temp\nRemove-Item -Recurse -Force \"\"$env:SystemDrive\\Program Files (x86)\\Microsoft\"\" -ErrorAction SilentlyContinue | Out-Null\n# remove edge shortcuts\nRemove-Item -Recurse -Force \"\"$env:SystemDrive\\Windows\\System32\\config\\systemprofile\\AppData\\Roaming\\Microsoft\\Internet Explorer\\Quick Launch\\Microsoft Edge.lnk\"\" -ErrorAction SilentlyContinue | Out-Null\nRemove-Item -Recurse -Force \"\"$env:ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Edge.lnk\"\" -ErrorAction SilentlyContinue | Out-Null\n\n$fileSystemProfiles = Get-ChildItem -Path \"\"C:\\Users\"\" -Directory | Where-Object { \n $_.Name -notin @('Public', 'Default', 'Default User', 'All Users') -and \n (Test-Path -Path \"\"$($_.FullName)\\NTUSER.DAT\"\")\n}\n\n# Loop through each user profile and clean up Edge shortcuts\nforeach ($profile in $fileSystemProfiles) {\n $userProfilePath = $profile.FullName\n \n # Define user-specific paths to clean\n $edgeShortcutPaths = @(\n \"\"$userProfilePath\\AppData\\Roaming\\Microsoft\\Internet Explorer\\Quick Launch\\Microsoft Edge.lnk\"\",\n \"\"$userProfilePath\\Desktop\\Microsoft Edge.lnk\"\",\n \"\"$userProfilePath\\AppData\\Roaming\\Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar\\Microsoft Edge.lnk\"\",\n \"\"$userProfilePath\\AppData\\Roaming\\Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar\\Tombstones\\Microsoft Edge.lnk\"\",\n \"\"$userProfilePath\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Edge.lnk\"\"\n )\n\n # Remove Edge shortcuts for each user\n foreach ($path in $edgeShortcutPaths) {\n if (Test-Path -Path $path -PathType Leaf) {\n Remove-Item -Path $path -Force -ErrorAction SilentlyContinue\n }\n }\n}\n\n# Clean up common locations\n$commonShortcutPaths = @(\n \"\"$env:PUBLIC\\Desktop\\Microsoft Edge.lnk\"\",\n \"\"$env:ALLUSERSPROFILE\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Edge.lnk\"\",\n \"\"C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Edge.lnk\"\"\n)\n\nforeach ($path in $commonShortcutPaths) {\n if (Test-Path -Path $path -PathType Leaf) {\n Remove-Item -Path $path -Force -ErrorAction SilentlyContinue\n }\n}\n\n# Removes Edge in Task Manager Startup Apps for All Users\n# Get all user profiles on the system\n$userProfiles = Get-CimInstance -ClassName Win32_UserProfile | \nWhere-Object { -not $_.Special -and $_.SID -notmatch 'S-1-5-18|S-1-5-19|S-1-5-20' }\n\nforeach ($profile in $userProfiles) {\n $sid = $profile.SID\n $hiveLoaded = $false\n\n if (-not (Test-Path \"\"Registry::HKEY_USERS\\$sid\"\")) {\n $userRegPath = Join-Path $profile.LocalPath \"\"NTUSER.DAT\"\"\n if (Test-Path $userRegPath) {\n reg load \"\"HKU\\$sid\"\" $userRegPath | Out-Null\n $hiveLoaded = $true\n Start-Sleep -Seconds 2\n }\n }\n\n $runKeyPath = \"\"Registry::HKEY_USERS\\$sid\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\"\"\n\n if (Test-Path $runKeyPath) {\n $properties = Get-ItemProperty -Path $runKeyPath\n $edgeEntries = $properties.PSObject.Properties | \n Where-Object { $_.Name -like 'MicrosoftEdgeAutoLaunch*' }\n\n foreach ($entry in $edgeEntries) {\n Remove-ItemProperty -Path $runKeyPath -Name $entry.Name -Force\n }\n }\n\n if ($hiveLoaded) {\n [gc]::Collect()\n Start-Sleep -Seconds 2\n reg unload \"\"HKU\\$sid\"\" | Out-Null\n }\n}\n\";\n }\n\n private static string GetOneNoteRemovalScript()\n {\n return @\"# OneNoteRemoval.ps1\n# Standalone script to remove Microsoft OneNote\n# Source: Winhance (https://github.com/memstechtips/Winhance)\n\ntry {\n # Stop OneNote processes\n $processesToStop = @(\"\"OneNote\"\", \"\"ONENOTE\"\", \"\"ONENOTEM\"\")\n foreach ($processName in $processesToStop) { \n Get-Process -Name $processName -ErrorAction SilentlyContinue | \n Stop-Process -Force -ErrorAction SilentlyContinue\n }\n Start-Sleep -Seconds 1\n}\ncatch {\n # Continue if process stopping fails\n}\n\n# Remove OneNote AppX package (Windows 10 version)\nGet-AppxPackage -AllUsers *OneNote* | Remove-AppxPackage\n\n# Check and execute uninstall strings from registry (Windows 11 version)\n$registryPaths = @(\n \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneNote*\"\",\n \"\"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneNote*\"\",\n \"\"HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneNote*\"\"\n)\n\nforeach ($regPathPattern in $registryPaths) {\n try {\n $regPaths = Get-ChildItem -Path $regPathPattern -ErrorAction SilentlyContinue\n foreach ($regPath in $regPaths) {\n $uninstallString = (Get-ItemProperty -Path $regPath.PSPath -ErrorAction SilentlyContinue).UninstallString\n if ($uninstallString) {\n if ($uninstallString -match '^\\\"\"([^\\\"\"]+)\\\"\"(.*)$') {\n $exePath = $matches[1]\n $args = $matches[2].Trim()\n Start-Process -FilePath $exePath -ArgumentList $args -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n else {\n Start-Process -FilePath $uninstallString -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n }\n }\n }\n catch {\n # Continue if registry operation fails\n continue\n }\n}\n\n# Try to uninstall using the Office setup\n$officeUninstallPaths = @(\n \"\"$env:ProgramFiles\\Microsoft Office\\Office16\\setup.exe\"\",\n \"\"$env:ProgramFiles\\Microsoft Office\\root\\Office16\\setup.exe\"\",\n \"\"$env:ProgramFiles(x86)\\Microsoft Office\\Office16\\setup.exe\"\",\n \"\"$env:ProgramFiles(x86)\\Microsoft Office\\root\\Office16\\setup.exe\"\"\n)\n\nforeach ($path in $officeUninstallPaths) {\n try {\n if (Test-Path $path) {\n Start-Process -FilePath $path -ArgumentList \"\"/uninstall OneNote /config OneNoteRemoval.xml\"\" -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if uninstall fails\n continue\n }\n}\n\n# Remove OneNote scheduled tasks\ntry {\n Get-ScheduledTask -ErrorAction SilentlyContinue | \n Where-Object { $_.TaskName -match 'OneNote' -and $_.TaskName -ne 'OneNoteRemoval' } | \n ForEach-Object { \n Unregister-ScheduledTask -TaskName $_.TaskName -Confirm:$false -ErrorAction SilentlyContinue \n }\n}\ncatch {\n # Continue if task removal fails\n}\n\n# Remove OneNote from startup\ntry {\n Remove-ItemProperty -Path \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\"\" -Name \"\"OneNote*\"\" -ErrorAction SilentlyContinue\n}\ncatch {\n # Continue if registry operations fail\n}\n\n# Files to remove (single items)\n$filesToRemove = @(\n \"\"$env:ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\OneNote.lnk\"\",\n \"\"$env:PUBLIC\\Desktop\\OneNote.lnk\"\"\n)\n\n# Remove single files\nforeach ($file in $filesToRemove) {\n try {\n if (Test-Path $file) {\n Remove-Item $file -Force -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if file removal fails\n continue\n }\n}\n\n# Folders that need special handling\n$foldersToRemove = @(\n \"\"$env:ProgramFiles\\Microsoft\\OneNote\"\",\n \"\"$env:ProgramFiles(x86)\\Microsoft\\OneNote\"\",\n \"\"$env:LOCALAPPDATA\\Microsoft\\OneNote\"\"\n)\n\n# Remove folders\nforeach ($folder in $foldersToRemove) {\n try {\n if (Test-Path $folder) {\n Remove-Item -Path $folder -Force -Recurse -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if folder removal fails\n continue\n }\n}\n\n# Clean up per-user OneNote shortcuts\n$userProfiles = Get-ChildItem -Path \"\"C:\\Users\"\" -Directory | Where-Object { \n $_.Name -notin @('Public', 'Default', 'Default User', 'All Users') -and \n (Test-Path -Path \"\"$($_.FullName)\\NTUSER.DAT\"\")\n}\n\nforeach ($profile in $userProfiles) {\n $userProfilePath = $profile.FullName\n \n # Define user-specific paths to clean\n $oneNoteShortcutPaths = @(\n \"\"$userProfilePath\\Desktop\\OneNote.lnk\"\",\n \"\"$userProfilePath\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\OneNote.lnk\"\"\n )\n\n # Remove OneNote shortcuts for each user\n foreach ($path in $oneNoteShortcutPaths) {\n if (Test-Path -Path $path -PathType Leaf) {\n Remove-Item -Path $path -Force -ErrorAction SilentlyContinue\n }\n }\n}\n\";\n }\n\n private static string GetOneDriveRemovalScript()\n {\n return @\"\n# OneDriveRemoval.ps1\n# Standalone script to remove Microsoft OneDrive\n# Source: Winhance (https://github.com/memstechtips/Winhance)\n\ntry {\n # Stop OneDrive processes\n $processesToStop = @(\"\"OneDrive\"\", \"\"FileCoAuth\"\", \"\"FileSyncHelper\"\")\n foreach ($processName in $processesToStop) { \n Get-Process -Name $processName -ErrorAction SilentlyContinue | \n Stop-Process -Force -ErrorAction SilentlyContinue\n }\n Start-Sleep -Seconds 1\n}\ncatch {\n # Continue if process stopping fails\n}\n\n# Check and execute uninstall strings from registry\n$registryPaths = @(\n \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneDriveSetup.exe\"\",\n \"\"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneDriveSetup.exe\"\"\n)\n\nforeach ($regPath in $registryPaths) {\n try {\n if (Test-Path $regPath) {\n $uninstallString = (Get-ItemProperty -Path $regPath -ErrorAction Stop).UninstallString\n if ($uninstallString) {\n if ($uninstallString -match '^\"\"([^\"\"]+)\"\"(.*)$') {\n $exePath = $matches[1]\n $args = $matches[2].Trim()\n Start-Process -FilePath $exePath -ArgumentList $args -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n else {\n Start-Process -FilePath $uninstallString -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n }\n }\n }\n catch {\n # Continue if registry operation fails\n continue\n }\n}\n\ntry {\n # Remove OneDrive AppX package\n Get-AppxPackage -Name \"\"*OneDrive*\"\" -ErrorAction SilentlyContinue | \n Remove-AppxPackage -ErrorAction SilentlyContinue\n}\ncatch {\n # Continue if AppX removal fails\n}\n\n# Uninstall OneDrive using setup files\n$oneDrivePaths = @(\n \"\"$env:SystemRoot\\SysWOW64\\OneDriveSetup.exe\"\",\n \"\"$env:SystemRoot\\System32\\OneDriveSetup.exe\"\",\n \"\"$env:LOCALAPPDATA\\Microsoft\\OneDrive\\OneDrive.exe\"\"\n)\n\nforeach ($path in $oneDrivePaths) {\n try {\n if (Test-Path $path) {\n Start-Process -FilePath $path -ArgumentList \"\"/uninstall\"\" -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if uninstall fails\n continue\n }\n}\n\ntry {\n # Remove OneDrive scheduled tasks\n Get-ScheduledTask -ErrorAction SilentlyContinue | \n Where-Object { $_.TaskName -match 'OneDrive' -and $_.TaskName -ne 'OneDriveRemoval' } | \n ForEach-Object { \n Unregister-ScheduledTask -TaskName $_.TaskName -Confirm:$false -ErrorAction SilentlyContinue \n }\n}\ncatch {\n # Continue if task removal fails\n}\n\ntry {\n # Configure registry settings\n $regPath = \"\"HKLM:\\SOFTWARE\\Policies\\Microsoft\\OneDrive\"\"\n if (-not (Test-Path $regPath)) {\n New-Item -Path $regPath -Force -ErrorAction SilentlyContinue | Out-Null\n }\n Set-ItemProperty -Path $regPath -Name \"\"KFMBlockOptIn\"\" -Value 1 -Type DWord -Force -ErrorAction SilentlyContinue\n \n # Remove OneDrive from startup\n Remove-ItemProperty -Path \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\"\" -Name \"\"OneDriveSetup\"\" -ErrorAction SilentlyContinue\n \n # Remove OneDrive from Navigation Pane\n Remove-Item -Path \"\"Registry::HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Desktop\\NameSpace\\{018D5C66-4533-4307-9B53-224DE2ED1FE6}\"\" -Recurse -Force -ErrorAction SilentlyContinue\n}\ncatch {\n # Continue if registry operations fail\n}\n\n# Function to handle robust folder removal\nfunction Remove-OneDriveFolder {\n param ([string]$folderPath)\n \n if (-not (Test-Path $folderPath)) {\n return\n }\n \n try {\n # Stop OneDrive processes if they're running\n Get-Process -Name \"\"OneDrive\"\" -ErrorAction SilentlyContinue | \n Stop-Process -Force -ErrorAction SilentlyContinue\n \n # Take ownership and grant permissions\n $null = Start-Process \"\"takeown.exe\"\" -ArgumentList \"\"/F `\"\"$folderPath`\"\" /R /A /D Y\"\" -Wait -NoNewWindow -PassThru -ErrorAction SilentlyContinue\n $null = Start-Process \"\"icacls.exe\"\" -ArgumentList \"\"`\"\"$folderPath`\"\" /grant administrators:F /T\"\" -Wait -NoNewWindow -PassThru -ErrorAction SilentlyContinue\n \n # Try direct removal\n Remove-Item -Path $folderPath -Force -Recurse -ErrorAction SilentlyContinue\n }\n catch {\n try {\n # If direct removal fails, create and execute a cleanup batch file\n $batchPath = \"\"$env:TEMP\\RemoveOneDrive_$(Get-Random).bat\"\"\n $batchContent = @\"\"\n@echo off\ntimeout /t 2 /nobreak > nul\ntakeown /F \"\"$folderPath\"\" /R /A /D Y\nicacls \"\"$folderPath\"\" /grant administrators:F /T\nrd /s /q \"\"$folderPath\"\"\ndel /F /Q \"\"%~f0\"\"\n\"\"@\n Set-Content -Path $batchPath -Value $batchContent -Force -ErrorAction SilentlyContinue\n Start-Process \"\"cmd.exe\"\" -ArgumentList \"\"/c $batchPath\"\" -WindowStyle Hidden -ErrorAction SilentlyContinue\n }\n catch {\n # Continue if batch file cleanup fails\n }\n }\n}\n\n# Files to remove (single items)\n$filesToRemove = @(\n \"\"$env:ALLUSERSPROFILE\\Users\\Default\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\OneDrive.lnk\"\",\n \"\"$env:ALLUSERSPROFILE\\Users\\Default\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\OneDrive.exe\"\",\n \"\"$env:PUBLIC\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\OneDrive.lnk\"\",\n \"\"$env:PUBLIC\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\OneDrive.exe\"\",\n \"\"$env:SystemRoot\\System32\\OneDriveSetup.exe\"\",\n \"\"$env:SystemRoot\\SysWOW64\\OneDriveSetup.exe\"\",\n \"\"$env:LOCALAPPDATA\\Microsoft\\OneDrive\\OneDrive.exe\"\",\n \"\"$env:ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\OneDrive.lnk\"\"\n)\n\n# Remove single files\nforeach ($file in $filesToRemove) {\n try {\n if (Test-Path $file) {\n Remove-Item $file -Force -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if file removal fails\n continue\n }\n}\n\n# Folders that need special handling\n$foldersToRemove = @(\n \"\"$env:ProgramFiles\\Microsoft\\OneDrive\"\",\n \"\"$env:ProgramFiles\\Microsoft OneDrive\"\",\n \"\"$env:LOCALAPPDATA\\Microsoft\\OneDrive\"\"\n)\n\n# Remove folders with robust method\nforeach ($folder in $foldersToRemove) {\n try {\n Remove-OneDriveFolder -folderPath $folder\n }\n catch {\n # Continue if folder removal fails\n continue\n }\n}\n\n# Additional cleanup for stubborn setup files\n$setupFiles = @(\n \"\"$env:SystemRoot\\System32\\OneDriveSetup.exe\"\",\n \"\"$env:SystemRoot\\SysWOW64\\OneDriveSetup.exe\"\"\n)\n\nforeach ($file in $setupFiles) {\n if (Test-Path $file) {\n try {\n # Take ownership and grant full permissions\n $null = Start-Process \"\"takeown.exe\"\" -ArgumentList \"\"/F `\"\"$file`\"\"\"\" -Wait -NoNewWindow -PassThru -ErrorAction SilentlyContinue\n $null = Start-Process \"\"icacls.exe\"\" -ArgumentList \"\"`\"\"$file`\"\" /grant administrators:F\"\" -Wait -NoNewWindow -PassThru -ErrorAction SilentlyContinue\n \n # Attempt direct removal\n Remove-Item -Path $file -Force -ErrorAction SilentlyContinue\n \n # If file still exists, schedule it for deletion on next reboot\n if (Test-Path $file) {\n $pendingRename = \"\"$file.pending\"\"\n Move-Item -Path $file -Destination $pendingRename -Force -ErrorAction SilentlyContinue\n Start-Process \"\"cmd.exe\"\" -ArgumentList \"\"/c del /F /Q `\"\"$pendingRename`\"\"\"\" -WindowStyle Hidden -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if cleanup fails\n continue\n }\n }\n}\n\";\n }\n\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IInstallationService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Generic interface for installation services.\n /// \n /// The type of item to install, which must implement IInstallableItem.\n public interface IInstallationService where T : IInstallableItem\n {\n /// \n /// Installs an item.\n /// \n /// The item to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n Task> InstallAsync(\n T item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Checks if an item can be installed.\n /// \n /// The item to check.\n /// An operation result indicating if the item can be installed, with error details if not.\n Task> CanInstallAsync(T item);\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/PowerShellScriptTemplateProvider.cs", "using System;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Provides PowerShell script templates with OS-specific adjustments.\n /// \n public class PowerShellScriptTemplateProvider : IScriptTemplateProvider\n {\n private readonly ISystemServices _systemService;\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The system service.\n /// The logging service.\n public PowerShellScriptTemplateProvider(\n ISystemServices systemService,\n ILogService logService)\n {\n _systemService = systemService ?? throw new ArgumentNullException(nameof(systemService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string GetPackageRemovalTemplate()\n {\n // Windows 10 compatibility: Don't use -AllUsers with Remove-AppxPackage\n return @\"Get-AppxPackage -Name \"\"{0}\"\" | Remove-AppxPackage -ErrorAction SilentlyContinue\nGet-AppxProvisionedPackage -Online | Where-Object {{ $_.DisplayName -eq \"\"{0}\"\" }} | Remove-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue\";\n }\n\n /// \n public string GetCapabilityRemovalTemplate()\n {\n return @\"Get-WindowsCapability -Online | Where-Object {{ $_.Name -like \"\"{0}*\"\" }} | Remove-WindowsCapability -Online\";\n }\n\n /// \n public string GetFeatureRemovalTemplate()\n {\n return @\"Write-Host \"\"Disabling optional feature: {0}\"\" -ForegroundColor Yellow\nDisable-WindowsOptionalFeature -Online -FeatureName \"\"{0}\"\" -NoRestart | Out-Null\";\n }\n\n /// \n public string GetRegistrySettingTemplate(bool isDelete)\n {\n if (isDelete)\n {\n return @\"reg delete \"\"{0}\"\" /v {1} /f | Out-Null\";\n }\n else\n {\n return @\"reg add \"\"{0}\"\" /v {1} /t REG_{2} /d {3} /f | Out-Null\";\n }\n }\n\n /// \n public string GetScriptHeader(string scriptName)\n {\n return $@\"# {scriptName}.ps1\n# This script removes Windows bloatware apps and prevents them from reinstalling\n# Source: Winhance (https://github.com/memstechtips/Winhance)\n# Generated by Winhance on {DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\")}\n\n\";\n }\n\n /// \n public string GetScriptFooter()\n {\n return @\"\n# Prevent apps from reinstalling\nreg add \"\"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\CloudContent\"\" /v DisableWindowsConsumerFeatures /t REG_DWORD /d 1 /f | Out-Null\n\nWrite-Host \"\"=== Script Completed ===\"\" -ForegroundColor Green\n\";\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Services/LoggingService.cs", "using Microsoft.Extensions.Hosting;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System;\n\nnamespace Winhance.Core.Features.Common.Services\n{\n public class LoggingService : ILogService, IHostedService, IDisposable\n {\n private readonly ILogService _logService;\n \n public event EventHandler? LogMessageGenerated;\n\n public LoggingService(ILogService logService)\n {\n _logService = logService;\n \n // Subscribe to the inner log service events and forward them\n _logService.LogMessageGenerated += (sender, args) => \n {\n LogMessageGenerated?.Invoke(this, args);\n };\n }\n\n public void StartLog()\n {\n _logService.StartLog();\n }\n\n public void StopLog()\n {\n _logService.StopLog();\n }\n\n public Task StartAsync(CancellationToken cancellationToken)\n {\n _logService.StartLog();\n return Task.CompletedTask;\n }\n\n public Task StopAsync(CancellationToken cancellationToken)\n {\n _logService.StopLog();\n return Task.CompletedTask;\n }\n\n public void LogInformation(string message)\n {\n _logService.LogInformation(message);\n }\n\n public void LogWarning(string message)\n {\n _logService.LogWarning(message);\n }\n\n public void LogError(string message, Exception? exception)\n {\n _logService.LogError(message, exception);\n }\n\n public void LogSuccess(string message)\n {\n _logService.LogSuccess(message);\n }\n\n public void Log(LogLevel level, string message, Exception? exception = null)\n {\n _logService.Log(level, message, exception);\n }\n \n // Removed the incorrectly ordered Log method to fix the parameter order error\n // This was causing CS1503 errors with parameter type mismatches\n\n public string GetLogPath()\n {\n return _logService.GetLogPath();\n }\n\n public void Dispose()\n {\n if (_logService is IDisposable disposable)\n {\n disposable.Dispose();\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/SearchService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service for handling search operations across different types of items.\n /// \n public class SearchService : ISearchService\n {\n /// \n /// Filters a collection of items based on a search term.\n /// \n /// The type of items to filter.\n /// The collection of items to filter.\n /// The search term to filter by.\n /// A filtered collection of items that match the search term.\n public IEnumerable FilterItems(IEnumerable items, string searchTerm) where T : ISearchable\n {\n // Add console logging for debugging\n Console.WriteLine($\"SearchService.FilterItems: Filtering with search term '{searchTerm}'\");\n \n if (string.IsNullOrWhiteSpace(searchTerm))\n {\n Console.WriteLine($\"SearchService.FilterItems: Search term is empty, returning all {items.Count()} items\");\n return items;\n }\n\n // Just trim the search term, but don't convert to lowercase\n // We'll handle case insensitivity in the MatchesSearch method\n searchTerm = searchTerm.Trim();\n Console.WriteLine($\"SearchService.FilterItems: Normalized search term '{searchTerm}'\");\n Console.WriteLine($\"SearchService.FilterItems: Starting search with term '{searchTerm}'\");\n \n // Log items before filtering\n int totalItems = items.Count();\n Console.WriteLine($\"SearchService.FilterItems: Total items before filtering: {totalItems}\");\n \n // Apply filtering and log results\n var filteredItems = items.Where(item => {\n bool matches = item.MatchesSearch(searchTerm);\n \n // Log details for all items to help diagnose search issues\n var itemName = item.GetType().GetProperty(\"Name\")?.GetValue(item)?.ToString();\n var itemGroupName = item.GetType().GetProperty(\"GroupName\")?.GetValue(item)?.ToString();\n \n // Log all items for better debugging\n Console.WriteLine($\"SearchService.FilterItems: Checking item '{itemName}' (Group: '{itemGroupName}') - matches: {matches}\");\n \n return matches;\n }).ToList();\n \n Console.WriteLine($\"SearchService.FilterItems: Found {filteredItems.Count} matching items out of {totalItems}\");\n \n return filteredItems;\n }\n\n /// \n /// Asynchronously filters a collection of items based on a search term.\n /// \n /// The type of items to filter.\n /// The collection of items to filter.\n /// The search term to filter by.\n /// A task that represents the asynchronous operation. The task result contains a filtered collection of items that match the search term.\n public Task> FilterItemsAsync(IEnumerable items, string searchTerm) where T : ISearchable\n {\n return Task.FromResult(FilterItems(items, searchTerm));\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IWinGetInstallationService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces;\n\n/// \n/// Interface for services that handle WinGet-related installation operations.\n/// \npublic interface IWinGetInstallationService\n{\n /// \n /// Installs a package using WinGet.\n /// \n /// The package name or ID to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// The display name of the package for progress reporting.\n /// True if installation was successful; otherwise, false.\n Task InstallWithWingetAsync(\n string packageName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default,\n string? displayName = null);\n\n /// \n /// Installs WinGet if not already installed.\n /// \n Task InstallWinGetAsync(IProgress? progress = null);\n\n /// \n /// Checks if WinGet is installed on the system.\n /// \n /// True if WinGet is installed, false otherwise\n Task IsWinGetInstalledAsync();\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ISystemServices.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Models.Enums;\nusing Winhance.Core.Features.Customize.Enums;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for system-level services that interact with the Windows operating system.\n /// \n public interface ISystemServices\n {\n /// \n /// Gets the registry service.\n /// \n IRegistryService RegistryService { get; }\n\n /// \n /// Restarts the Windows Explorer process.\n /// \n void RestartExplorer();\n\n /// \n /// Checks if the current user is an administrator.\n /// \n /// True if the current user is an administrator; otherwise, false.\n bool IsAdministrator();\n\n /// \n /// Gets the Windows version.\n /// \n /// A string representing the Windows version.\n string GetWindowsVersion();\n\n /// \n /// Refreshes the desktop.\n /// \n void RefreshDesktop();\n\n /// \n /// Checks if a process is running.\n /// \n /// The name of the process to check.\n /// True if the process is running; otherwise, false.\n bool IsProcessRunning(string processName);\n\n /// \n /// Kills a process.\n /// \n /// The name of the process to kill.\n void KillProcess(string processName);\n\n /// \n /// Checks if the operating system is Windows 11.\n /// \n /// True if the operating system is Windows 11; otherwise, false.\n bool IsWindows11();\n\n /// \n /// Requires administrator privileges.\n /// \n /// True if the application is running with administrator privileges; otherwise, false.\n bool RequireAdministrator();\n\n /// \n /// Checks if dark mode is enabled.\n /// \n /// True if dark mode is enabled; otherwise, false.\n bool IsDarkModeEnabled();\n\n /// \n /// Sets dark mode.\n /// \n /// True to enable dark mode; false to disable it.\n void SetDarkMode(bool enabled);\n\n /// \n /// Sets the UAC level.\n /// \n /// The UAC level to set.\n void SetUacLevel(Winhance.Core.Models.Enums.UacLevel level);\n\n /// \n /// Gets the UAC level.\n /// \n /// The current UAC level.\n Winhance.Core.Models.Enums.UacLevel GetUacLevel();\n\n /// \n /// Refreshes the Windows GUI.\n /// \n /// A task that represents the asynchronous operation. The task result contains a value indicating whether the operation succeeded.\n Task RefreshWindowsGUI();\n\n /// \n /// Refreshes the Windows GUI.\n /// \n /// True to kill the Explorer process; otherwise, false.\n /// A task that represents the asynchronous operation. The task result contains a value indicating whether the operation succeeded.\n Task RefreshWindowsGUI(bool killExplorer);\n\n /// \n /// Checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// True if internet is connected, false otherwise.\n bool IsInternetConnected(bool forceCheck = false);\n\n /// \n /// Asynchronously checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// Cancellation token for the operation.\n /// True if internet is connected, false otherwise.\n Task IsInternetConnectedAsync(bool forceCheck = false, CancellationToken cancellationToken = default, bool userInitiatedCancellation = false);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToThemeConverter.cs", "using System;\nusing System.Globalization;\nusing System.Linq;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean value to a theme string (\"Dark\" or \"Light\") or theme-specific colors\n /// \n public class BooleanToThemeConverter : IValueConverter, IMultiValueConverter\n {\n // Default track colors\n private static readonly Color DarkTrackColor = Color.FromRgb(68, 68, 68);\n private static readonly Color LightTrackColor = Color.FromRgb(204, 204, 204);\n \n // Checked track colors\n private static readonly Color DarkCheckedTrackColor = Color.FromRgb(85, 85, 85);\n private static readonly Color LightCheckedTrackColor = Color.FromRgb(66, 66, 66);\n \n // Knob colors\n private static readonly Color DefaultKnobColor = Color.FromRgb(255, 255, 255); // White for unchecked\n private static readonly Color DarkCheckedKnobColor = Color.FromRgb(255, 222, 0); // Yellow for dark theme checked\n private static readonly Color LightCheckedKnobColor = Color.FromRgb(66, 66, 66); // Gray for light theme checked\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n bool isDarkTheme = false;\n bool isChecked = false;\n \n // Handle different input types for theme\n if (value is bool boolValue)\n {\n isDarkTheme = boolValue;\n }\n else if (value is string stringValue)\n {\n isDarkTheme = stringValue.Equals(\"Dark\", StringComparison.OrdinalIgnoreCase);\n }\n \n // Extract checked state from parameter if provided\n if (parameter is string paramString)\n {\n string[] parts = paramString.Split(':');\n string elementType = parts[0];\n \n // Check if we have checked state information\n if (parts.Length > 1)\n {\n isChecked = parts[1].Equals(\"Checked\", StringComparison.OrdinalIgnoreCase);\n }\n \n if (targetType == typeof(Brush) || targetType == typeof(SolidColorBrush))\n {\n if (elementType.Equals(\"Track\", StringComparison.OrdinalIgnoreCase))\n {\n if (isChecked)\n {\n return new SolidColorBrush(isDarkTheme ? DarkCheckedTrackColor : LightCheckedTrackColor);\n }\n else\n {\n return new SolidColorBrush(isDarkTheme ? DarkTrackColor : LightTrackColor);\n }\n }\n else if (elementType.Equals(\"Knob\", StringComparison.OrdinalIgnoreCase))\n {\n if (isChecked)\n {\n // Use the hardcoded colors for better reliability\n return new SolidColorBrush(isDarkTheme ? DarkCheckedKnobColor : LightCheckedKnobColor);\n }\n else\n {\n // Use white for unchecked knobs in both themes\n return new SolidColorBrush(DefaultKnobColor);\n }\n }\n }\n }\n \n // Default behavior - return theme string\n return isDarkTheme ? \"Dark\" : \"Light\";\n }\n \n // Implementation for IMultiValueConverter\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length < 2)\n return Binding.DoNothing;\n \n bool isDarkTheme = false;\n bool isChecked = false;\n \n // First value is the theme\n if (values[0] is bool themeBool)\n {\n isDarkTheme = themeBool;\n }\n else if (values[0] is string themeString)\n {\n isDarkTheme = themeString.Equals(\"Dark\", StringComparison.OrdinalIgnoreCase);\n }\n \n // Second value is the checked state\n if (values[1] is bool checkedBool)\n {\n isChecked = checkedBool;\n }\n \n // Determine which element we're styling based on parameter\n string elementType = parameter as string ?? \"Track\";\n \n if (targetType == typeof(Brush) || targetType == typeof(SolidColorBrush))\n {\n if (elementType.Equals(\"Track\", StringComparison.OrdinalIgnoreCase))\n {\n if (isChecked)\n {\n return new SolidColorBrush(isDarkTheme ? DarkCheckedTrackColor : LightCheckedTrackColor);\n }\n else\n {\n return new SolidColorBrush(isDarkTheme ? DarkTrackColor : LightTrackColor);\n }\n }\n else if (elementType.Equals(\"Knob\", StringComparison.OrdinalIgnoreCase))\n {\n if (isChecked)\n {\n // Use the hardcoded colors for better reliability\n return new SolidColorBrush(isDarkTheme ? DarkCheckedKnobColor : LightCheckedKnobColor);\n }\n else\n {\n // Use white for unchecked knobs in both themes\n return new SolidColorBrush(DefaultKnobColor);\n }\n }\n }\n \n return Binding.DoNothing;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is string themeString)\n {\n return themeString.Equals(\"Dark\", StringComparison.OrdinalIgnoreCase);\n }\n \n return false; // Default to Light theme (false) if value is not a string\n }\n \n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n // We don't need to implement this for our use case\n return targetTypes.Select(t => Binding.DoNothing).ToArray();\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/PrivacyOptimizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class PrivacyOptimizations\n{\n public static OptimizationGroup GetPrivacyOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Privacy\",\n Category = OptimizationCategory.Privacy,\n Settings = new List\n {\n // Activity History\n new OptimizationSetting\n {\n Id = \"privacy-activity-history\",\n Name = \"Activity History\",\n Description = \"Controls activity history tracking\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Activity History\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\System\",\n Name = \"PublishUserActivities\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, Activity History is enabled\n DisabledValue = 0, // When toggle is OFF, Activity History is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls activity history tracking\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Personalized Ads (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-advertising-id\",\n Name = \"Personalized Ads\",\n Description = \"Controls personalized ads using advertising ID\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Advertising\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\AdvertisingInfo\",\n Name = \"Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, advertising ID is enabled\n DisabledValue = 0, // When toggle is OFF, advertising ID is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls advertising ID for personalized ads\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\AdvertisingInfo\",\n Name = \"DisabledByGroupPolicy\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, advertising is NOT disabled by policy\n DisabledValue = 1, // When toggle is OFF, advertising is disabled by policy\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls advertising ID for personalized ads\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Language List Access\n new OptimizationSetting\n {\n Id = \"privacy-language-list\",\n Name = \"Allow Websites Access to Language List\",\n Description =\n \"Let websites show me locally relevant content by accessing my language list\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"General\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\International\\\\User Profile\",\n Name = \"HttpAcceptLanguageOptOut\",\n RecommendedValue = 0,\n EnabledValue = 0, // When toggle is ON, language list access is enabled\n DisabledValue = 1, // When toggle is OFF, language list access is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls language list access for websites\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // App Launch Tracking\n new OptimizationSetting\n {\n Id = \"privacy-app-launch-tracking\",\n Name = \"App Launch Tracking\",\n Description =\n \"Let Windows improve Start and search results by tracking app launches\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"General\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"Start_TrackProgs\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, app launch tracking is enabled\n DisabledValue = 0, // When toggle is OFF, app launch tracking is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description =\n \"Controls app launch tracking for improved Start and search results\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Show Suggested Content in Settings (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-settings-content\",\n Name = \"Show Suggested Content in Settings\",\n Description = \"Controls suggested content in the Settings app\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Settings App\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ContentDeliveryManager\",\n Name = \"SubscribedContent-338393Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, suggested content is enabled\n DisabledValue = 0, // When toggle is OFF, suggested content is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls suggested content in the Settings app\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ContentDeliveryManager\",\n Name = \"SubscribedContent-353694Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, suggested content is enabled\n DisabledValue = 0, // When toggle is OFF, suggested content is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls suggested content in the Settings app\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ContentDeliveryManager\",\n Name = \"SubscribedContent-353696Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, suggested content is enabled\n DisabledValue = 0, // When toggle is OFF, suggested content is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls suggested content in the Settings app\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Settings App Notifications\n new OptimizationSetting\n {\n Id = \"privacy-settings-notifications\",\n Name = \"Settings App Notifications\",\n Description =\n \"Controls notifications in the Settings app and immersive control panel\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Settings App\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\SystemSettings\\\\AccountNotifications\",\n Name = \"EnableAccountNotifications\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, account notifications are enabled\n DisabledValue = 0, // When toggle is OFF, account notifications are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description =\n \"Controls notifications in the Settings app and immersive control panel\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Online Speech Recognition (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-speech-recognition\",\n Name = \"Online Speech Recognition\",\n Description = \"Controls online speech recognition\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Speech\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Speech_OneCore\\\\Settings\\\\OnlineSpeechPrivacy\",\n Name = \"HasAccepted\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, online speech recognition is enabled\n DisabledValue = 0, // When toggle is OFF, online speech recognition is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls online speech recognition\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\InputPersonalization\",\n Name = \"AllowInputPersonalization\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, input personalization is allowed\n DisabledValue = 0, // When toggle is OFF, input personalization is not allowed\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls input personalization for speech recognition\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Custom Inking and Typing Dictionary (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-inking-typing-dictionary\",\n Name = \"Custom Inking and Typing Dictionary\",\n Description =\n \"Controls custom inking and typing dictionary (turning off will clear all words in your custom dictionary)\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Inking and Typing\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CPSS\\\\Store\\\\InkingAndTypingPersonalization\",\n Name = \"Value\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, custom dictionary is enabled\n DisabledValue = 0, // When toggle is OFF, custom dictionary is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls custom inking and typing dictionary\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Personalization\\\\Settings\",\n Name = \"AcceptedPrivacyPolicy\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, privacy policy is accepted\n DisabledValue = 0, // When toggle is OFF, privacy policy is not accepted\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls custom inking and typing dictionary\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\InputPersonalization\",\n Name = \"RestrictImplicitTextCollection\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, text collection is not restricted\n DisabledValue = 1, // When toggle is OFF, text collection is restricted\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls custom inking and typing dictionary\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\InputPersonalization\\\\TrainedDataStore\",\n Name = \"HarvestContacts\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, contacts harvesting is enabled\n DisabledValue = 0, // When toggle is OFF, contacts harvesting is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls custom inking and typing dictionary\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Send Diagnostic Data (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-diagnostics\",\n Name = \"Send Diagnostic Data\",\n Description = \"Controls diagnostic data collection level\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Diagnostics & Feedback\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Diagnostics\\\\DiagTrack\",\n Name = \"ShowedToastAtLevel\",\n RecommendedValue = 1,\n EnabledValue = 3, // When toggle is ON, full diagnostic data is enabled\n DisabledValue = 1, // When toggle is OFF, basic diagnostic data is enabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls diagnostic data collection level\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\DataCollection\",\n Name = \"AllowTelemetry\",\n RecommendedValue = 1,\n EnabledValue = 3, // When toggle is ON, full telemetry is allowed\n DisabledValue = 1, // When toggle is OFF, basic telemetry is allowed\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls telemetry data collection\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\DataCollection\",\n Name = \"MaxTelemetryAllowed\",\n RecommendedValue = 1,\n EnabledValue = 3, // When toggle is ON, full telemetry is allowed\n DisabledValue = 1, // When toggle is OFF, basic telemetry is allowed\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls telemetry data collection\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\DataCollection\",\n Name = \"AllowTelemetry\",\n RecommendedValue = 1,\n EnabledValue = 3, // When toggle is ON, telemetry is allowed by policy\n DisabledValue = 0, // When toggle is OFF, telemetry is not allowed by policy\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls telemetry data collection\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Improve Inking and Typing (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-improve-inking-typing\",\n Name = \"Improve Inking and Typing\",\n Description = \"Controls inking and typing data collection\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Diagnostics & Feedback\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n Dependencies = new List\n {\n new SettingDependency\n {\n DependencyType = SettingDependencyType.RequiresEnabled,\n DependentSettingId = \"privacy-improve-inking-typing\",\n RequiredSettingId = \"privacy-diagnostics\",\n },\n },\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Input\\\\TIPC\",\n Name = \"Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, inking and typing improvement is enabled\n DisabledValue = 0, // When toggle is OFF, inking and typing improvement is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls inking and typing data collection\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CPSS\\\\Store\\\\ImproveInkingAndTyping\",\n Name = \"Value\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, linguistic data collection is allowed\n DisabledValue = 0, // When toggle is OFF, linguistic data collection is not allowed\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls inking and typing data collection\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Tailored Experiences (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-tailored-experiences\",\n Name = \"Tailored Experiences\",\n Description = \"Controls personalized experiences with diagnostic data\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Diagnostics & Feedback\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Privacy\",\n Name = \"TailoredExperiencesWithDiagnosticDataEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, tailored experiences are enabled\n DisabledValue = 0, // When toggle is OFF, tailored experiences are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls personalized experiences with diagnostic data\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Policies\\\\Microsoft\\\\Windows\\\\CloudContent\",\n Name = \"DisableTailoredExperiencesWithDiagnosticData\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, tailored experiences are not disabled by policy\n DisabledValue = 1, // When toggle is OFF, tailored experiences are disabled by policy\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls personalized experiences with diagnostic data\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Location Services (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-location-services\",\n Name = \"Location Services\",\n Description = \"Controls location services\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"App Permissions\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\location\",\n Name = \"Value\",\n RecommendedValue = \"Deny\",\n EnabledValue = \"Allow\", // When toggle is ON, location services are allowed\n DisabledValue = \"Deny\", // When toggle is OFF, location services are denied\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Allow\", // Default value when registry key exists but no value is set\n Description = \"Controls location services\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\LocationAndSensors\",\n Name = \"DisableLocation\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, location is not disabled by policy\n DisabledValue = 1, // When toggle is OFF, location is disabled by policy\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls location services\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Camera Access\n new OptimizationSetting\n {\n Id = \"privacy-camera-access\",\n Name = \"Camera Access\",\n Description = \"Controls camera access\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"App Permissions\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\webcam\",\n Name = \"Value\",\n RecommendedValue = \"Deny\",\n EnabledValue = \"Allow\", // When toggle is ON, camera access is allowed\n DisabledValue = \"Deny\", // When toggle is OFF, camera access is denied\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Allow\", // Default value when registry key exists but no value is set\n Description = \"Controls camera access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Microphone Access\n new OptimizationSetting\n {\n Id = \"privacy-microphone-access\",\n Name = \"Microphone Access\",\n Description = \"Controls microphone access\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"App Permissions\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\microphone\",\n Name = \"Value\",\n RecommendedValue = \"Deny\",\n EnabledValue = \"Allow\", // When toggle is ON, microphone access is allowed\n DisabledValue = \"Deny\", // When toggle is OFF, microphone access is denied\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Allow\", // Default value when registry key exists but no value is set\n Description = \"Controls microphone access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Account Info Access\n new OptimizationSetting\n {\n Id = \"privacy-account-info-access\",\n Name = \"Account Info Access\",\n Description = \"Controls account information access\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"App Permissions\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\userAccountInformation\",\n Name = \"Value\",\n RecommendedValue = \"Deny\",\n EnabledValue = \"Allow\", // When toggle is ON, account info access is allowed\n DisabledValue = \"Deny\", // When toggle is OFF, account info access is denied\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Allow\", // Default value when registry key exists but no value is set\n Description = \"Controls account information access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // App Diagnostic Access\n new OptimizationSetting\n {\n Id = \"privacy-app-diagnostic-access\",\n Name = \"App Diagnostic Access\",\n Description = \"Controls app diagnostic access\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"App Permissions\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\appDiagnostics\",\n Name = \"Value\",\n RecommendedValue = \"Deny\",\n EnabledValue = \"Allow\", // When toggle is ON, app diagnostic access is allowed\n DisabledValue = \"Deny\", // When toggle is OFF, app diagnostic access is denied\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Allow\", // Default value when registry key exists but no value is set\n Description = \"Controls app diagnostic access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Cloud Content Search for Microsoft Account\n new OptimizationSetting\n {\n Id = \"privacy-search-msa-cloud\",\n Name = \"Cloud Content Search (Microsoft Account)\",\n Description = \"Controls cloud content search for Microsoft account\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Search\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\SearchSettings\",\n Name = \"IsMSACloudSearchEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, cloud search is enabled\n DisabledValue = 0, // When toggle is OFF, cloud search is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls cloud content search for Microsoft account\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Cloud Content Search for Work or School Account\n new OptimizationSetting\n {\n Id = \"privacy-search-aad-cloud\",\n Name = \"Cloud Content Search (Work/School Acc)\",\n Description = \"Controls cloud content search for work or school account\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Search\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\SearchSettings\",\n Name = \"IsAADCloudSearchEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, cloud search is enabled\n DisabledValue = 0, // When toggle is OFF, cloud search is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description =\n \"Controls cloud content search for work or school account\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Web Search\n new OptimizationSetting\n {\n Id = \"privacy-web-search\",\n Name = \"Web Search\",\n Description = \"Controls web search in Start menu and taskbar\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Search\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Search\",\n Name = \"BingSearchEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, web search is enabled\n DisabledValue = 0, // When toggle is OFF, web search is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls web search in Start menu and taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IInstallationOrchestrator.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Orchestrates high-level installation and removal operations across different types of items.\n /// \n /// \n /// This is a higher-level service that coordinates operations across different specific services.\n /// \n public interface IInstallationOrchestrator\n {\n /// \n /// Installs an installable item based on its type.\n /// \n /// The item to install.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the asynchronous operation.\n Task InstallAsync(\n IInstallableItem item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Removes an installable item based on its type.\n /// \n /// The item to remove.\n /// A task representing the asynchronous operation.\n Task RemoveAsync(IInstallableItem item);\n\n /// \n /// Installs multiple items in batch.\n /// \n /// The items to install.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the asynchronous operation.\n Task InstallBatchAsync(\n IEnumerable items,\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Removes multiple items in batch.\n /// \n /// The items to remove.\n /// A list of results indicating success or failure for each item.\n Task> RemoveBatchAsync(\n IEnumerable items);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/UacOptimizations.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Models.Enums;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class UacOptimizations\n{\n public const string RegistryPath = @\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\";\n public const string ConsentPromptName = \"ConsentPromptBehaviorAdmin\";\n public const string SecureDesktopName = \"PromptOnSecureDesktop\";\n public static readonly RegistryValueKind ValueKind = RegistryValueKind.DWord;\n\n // UAC settings require two registry values working together\n // ConsentPromptBehaviorAdmin controls the behavior type\n // PromptOnSecureDesktop controls whether the desktop is dimmed\n\n // Map from UacLevel enum to ConsentPromptBehaviorAdmin registry values\n public static readonly Dictionary UacLevelToConsentPromptValue = new()\n {\n { UacLevel.NeverNotify, 0 }, // Never notify\n { UacLevel.NotifyNoDesktopDim, 5 }, // Notify without dimming desktop\n { UacLevel.NotifyChangesOnly, 5 }, // Notify only for changes (default)\n { UacLevel.AlwaysNotify, 2 }, // Always notify\n };\n\n // Map from UacLevel enum to PromptOnSecureDesktop registry values\n public static readonly Dictionary UacLevelToSecureDesktopValue = new()\n {\n { UacLevel.NeverNotify, 0 }, // Secure desktop disabled\n { UacLevel.NotifyNoDesktopDim, 0 }, // Secure desktop disabled\n { UacLevel.NotifyChangesOnly, 1 }, // Secure desktop enabled\n { UacLevel.AlwaysNotify, 1 }, // Secure desktop enabled\n };\n\n // User-friendly names for each UAC level\n public static readonly Dictionary UacLevelNames = new()\n {\n { UacLevel.AlwaysNotify, \"Always notify\" },\n { UacLevel.NotifyChangesOnly, \"Notify when apps try to make changes\" },\n { UacLevel.NotifyNoDesktopDim, \"Notify when apps try to make changes (no dim)\" },\n { UacLevel.NeverNotify, \"Never notify\" },\n { UacLevel.Custom, \"Custom UAC Setting\" },\n };\n\n /// \n /// Helper method to get UacLevel from both registry values\n /// \n /// The ConsentPromptBehaviorAdmin registry value\n /// The PromptOnSecureDesktop registry value\n /// Optional UAC settings service to save custom values\n /// The corresponding UacLevel\n public static UacLevel GetUacLevelFromRegistryValues(\n int consentPromptValue,\n int secureDesktopValue,\n IUacSettingsService uacSettingsService = null\n )\n {\n // Check for exact matches of both values\n foreach (var level in UacLevelToConsentPromptValue.Keys)\n {\n if (\n UacLevelToConsentPromptValue[level] == consentPromptValue\n && UacLevelToSecureDesktopValue[level] == secureDesktopValue\n )\n {\n return level;\n }\n }\n\n // If no exact match, determine if it's one of the common non-standard combinations\n if (consentPromptValue == 0)\n {\n return UacLevel.NeverNotify; // ConsentPrompt=0 always means Never Notify\n }\n else if (consentPromptValue == 5)\n {\n // ConsentPrompt=5 with SecureDesktop determines dimming\n return secureDesktopValue == 0\n ? UacLevel.NotifyNoDesktopDim\n : UacLevel.NotifyChangesOnly;\n }\n else if (consentPromptValue == 2)\n {\n return UacLevel.AlwaysNotify; // ConsentPrompt=2 is Always Notify\n }\n\n // If we get here, we have a custom UAC setting\n // Save the custom values if we have a service\n if (uacSettingsService != null)\n {\n // Save asynchronously - fire and forget\n _ = Task.Run(() => uacSettingsService.SaveCustomUacSettingsAsync(consentPromptValue, secureDesktopValue));\n }\n \n return UacLevel.Custom;\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceCore.cs", "using Microsoft.Win32;\nusing System;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Core implementation of the registry service.\n /// \n [SupportedOSPlatform(\"windows\")]\n public partial class RegistryService : IRegistryService\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public RegistryService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Checks if the current platform is Windows.\n /// \n /// True if the platform is Windows; otherwise, logs an error and returns false.\n private bool CheckWindowsPlatform()\n {\n if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n return true;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/ViewNameToBackgroundConverter.cs", "using System;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing System.Windows.Threading;\nusing Winhance.WPF.Features.Common.Resources.Theme;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class ViewNameToBackgroundConverter : IValueConverter, INotifyPropertyChanged\n {\n private static ViewNameToBackgroundConverter? _instance;\n \n public static ViewNameToBackgroundConverter Instance \n {\n get \n {\n if (_instance == null)\n {\n _instance = new ViewNameToBackgroundConverter();\n }\n return _instance;\n }\n }\n \n public event PropertyChangedEventHandler? PropertyChanged;\n \n // This method will be called when the theme changes\n public void NotifyThemeChanged()\n {\n // Force a refresh of all bindings that use this converter\n Application.Current.Dispatcher.Invoke(() =>\n {\n // Notify all properties to force binding refresh\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(string.Empty));\n \n // Also notify specific properties to ensure all binding scenarios are covered\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(\"ThemeChanged\"));\n \n // Force WPF to update all bindings\n if (Application.Current.MainWindow != null)\n {\n Application.Current.MainWindow.UpdateLayout();\n }\n }, DispatcherPriority.Render);\n }\n \n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n try\n {\n var currentViewName = value as string;\n var buttonViewName = parameter as string;\n \n if (string.Equals(currentViewName, buttonViewName, StringComparison.OrdinalIgnoreCase))\n {\n // Return the main content background color for selected buttons\n var brush = Application.Current.Resources[\"MainContainerBorderBrush\"] as SolidColorBrush;\n return brush?.Color ?? Colors.Transparent;\n }\n \n // Return the default navigation button background color\n var defaultBrush = Application.Current.Resources[\"NavigationButtonBackground\"] as SolidColorBrush;\n return defaultBrush?.Color ?? Colors.Transparent;\n }\n catch\n {\n var defaultBrush = Application.Current.Resources[\"NavigationButtonBackground\"] as SolidColorBrush;\n return defaultBrush?.Color ?? Colors.Transparent;\n }\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Behaviors/ResponsiveLayoutBehavior.cs", "using System.Windows;\nusing System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Common.Behaviors\n{\n /// \n /// Provides attached properties and behaviors for responsive layouts\n /// \n public static class ResponsiveLayoutBehavior\n {\n #region ItemWidth Attached Property\n\n /// \n /// Gets the ItemWidth value\n /// \n public static double GetItemWidth(DependencyObject obj)\n {\n return (double)obj.GetValue(ItemWidthProperty);\n }\n\n /// \n /// Sets the ItemWidth value\n /// \n public static void SetItemWidth(DependencyObject obj, double value)\n {\n obj.SetValue(ItemWidthProperty, value);\n }\n\n /// \n /// ItemWidth Attached Dependency Property\n /// \n public static readonly DependencyProperty ItemWidthProperty =\n DependencyProperty.RegisterAttached(\n \"ItemWidth\",\n typeof(double),\n typeof(ResponsiveLayoutBehavior),\n new PropertyMetadata(200.0, OnItemWidthChanged));\n\n /// \n /// Called when ItemWidth is changed\n /// \n private static void OnItemWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is FrameworkElement element)\n {\n element.Width = (double)e.NewValue;\n }\n }\n\n #endregion\n\n #region MinItemWidth Attached Property\n\n /// \n /// Gets the MinItemWidth value\n /// \n public static double GetMinItemWidth(DependencyObject obj)\n {\n return (double)obj.GetValue(MinItemWidthProperty);\n }\n\n /// \n /// Sets the MinItemWidth value\n /// \n public static void SetMinItemWidth(DependencyObject obj, double value)\n {\n obj.SetValue(MinItemWidthProperty, value);\n }\n\n /// \n /// MinItemWidth Attached Dependency Property\n /// \n public static readonly DependencyProperty MinItemWidthProperty =\n DependencyProperty.RegisterAttached(\n \"MinItemWidth\",\n typeof(double),\n typeof(ResponsiveLayoutBehavior),\n new PropertyMetadata(150.0, OnMinItemWidthChanged));\n\n /// \n /// Called when MinItemWidth is changed\n /// \n private static void OnMinItemWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is FrameworkElement element)\n {\n element.MinWidth = (double)e.NewValue;\n }\n }\n\n #endregion\n\n #region WrapPanelMaxWidth Attached Property\n\n /// \n /// Gets the WrapPanelMaxWidth value\n /// \n public static double GetWrapPanelMaxWidth(DependencyObject obj)\n {\n return (double)obj.GetValue(WrapPanelMaxWidthProperty);\n }\n\n /// \n /// Sets the WrapPanelMaxWidth value\n /// \n public static void SetWrapPanelMaxWidth(DependencyObject obj, double value)\n {\n obj.SetValue(WrapPanelMaxWidthProperty, value);\n }\n\n /// \n /// WrapPanelMaxWidth Attached Dependency Property\n /// \n public static readonly DependencyProperty WrapPanelMaxWidthProperty =\n DependencyProperty.RegisterAttached(\n \"WrapPanelMaxWidth\",\n typeof(double),\n typeof(ResponsiveLayoutBehavior),\n new PropertyMetadata(1000.0));\n\n #endregion\n\n #region MaxItemWidth Attached Property\n\n /// \n /// Gets the MaxItemWidth value\n /// \n public static double GetMaxItemWidth(DependencyObject obj)\n {\n return (double)obj.GetValue(MaxItemWidthProperty);\n }\n\n /// \n /// Sets the MaxItemWidth value\n /// \n public static void SetMaxItemWidth(DependencyObject obj, double value)\n {\n obj.SetValue(MaxItemWidthProperty, value);\n }\n\n /// \n /// MaxItemWidth Attached Dependency Property\n /// \n public static readonly DependencyProperty MaxItemWidthProperty =\n DependencyProperty.RegisterAttached(\n \"MaxItemWidth\",\n typeof(double),\n typeof(ResponsiveLayoutBehavior),\n new PropertyMetadata(400.0, OnMaxItemWidthChanged));\n\n /// \n /// Called when MaxItemWidth is changed\n /// \n private static void OnMaxItemWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is FrameworkElement element)\n {\n element.MaxWidth = (double)e.NewValue;\n }\n }\n\n #endregion\n\n #region UseWrapPanel Attached Property\n\n /// \n /// Gets the UseWrapPanel value\n /// \n public static bool GetUseWrapPanel(DependencyObject obj)\n {\n return (bool)obj.GetValue(UseWrapPanelProperty);\n }\n\n /// \n /// Sets the UseWrapPanel value\n /// \n public static void SetUseWrapPanel(DependencyObject obj, bool value)\n {\n obj.SetValue(UseWrapPanelProperty, value);\n }\n\n /// \n /// UseWrapPanel Attached Dependency Property\n /// \n public static readonly DependencyProperty UseWrapPanelProperty =\n DependencyProperty.RegisterAttached(\n \"UseWrapPanel\",\n typeof(bool),\n typeof(ResponsiveLayoutBehavior),\n new PropertyMetadata(false, OnUseWrapPanelChanged));\n\n /// \n /// Called when UseWrapPanel is changed\n /// \n private static void OnUseWrapPanelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is ItemsControl itemsControl && (bool)e.NewValue)\n {\n // Get the WrapPanelMaxWidth value or use the default\n double maxWidth = GetWrapPanelMaxWidth(itemsControl);\n\n // Create a WrapPanel for the ItemsPanel\n var wrapPanel = new WrapPanel\n {\n Orientation = Orientation.Horizontal,\n MaxWidth = maxWidth,\n HorizontalAlignment = HorizontalAlignment.Left\n };\n \n // Add resources to the WrapPanel\n var wrapPanelStyle = new Style(typeof(ContentPresenter));\n wrapPanelStyle.Setters.Add(new Setter(FrameworkElement.MarginProperty, new Thickness(0, 5, 10, 5)));\n wrapPanel.Resources.Add(typeof(ContentPresenter), wrapPanelStyle);\n\n // Set the ItemsPanel template\n var template = new ItemsPanelTemplate();\n template.VisualTree = new FrameworkElementFactory(typeof(WrapPanel));\n template.VisualTree.SetValue(WrapPanel.OrientationProperty, Orientation.Horizontal);\n template.VisualTree.SetValue(WrapPanel.MaxWidthProperty, maxWidth);\n template.VisualTree.SetValue(WrapPanel.HorizontalAlignmentProperty, HorizontalAlignment.Left);\n \n // Add resources to the template\n var resourceDictionary = new ResourceDictionary();\n var contentPresenterStyle = new Style(typeof(ContentPresenter));\n contentPresenterStyle.Setters.Add(new Setter(FrameworkElement.MarginProperty, new Thickness(0, 5, 10, 5)));\n resourceDictionary.Add(typeof(ContentPresenter), contentPresenterStyle);\n template.Resources = resourceDictionary;\n \n // Set item spacing through the ItemContainerStyle\n var style = new Style(typeof(ContentPresenter));\n style.Setters.Add(new Setter(FrameworkElement.MarginProperty, new Thickness(0, 5, 10, 5)));\n style.Setters.Add(new Setter(FrameworkElement.WidthProperty, 250.0));\n style.Setters.Add(new Setter(FrameworkElement.MinWidthProperty, 250.0));\n style.Setters.Add(new Setter(FrameworkElement.MaxWidthProperty, 250.0));\n \n if (itemsControl.ItemContainerStyle == null)\n {\n itemsControl.ItemContainerStyle = style;\n }\n\n itemsControl.ItemsPanel = template;\n }\n }\n\n #endregion\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Theme/FontLoader.cs", "using System;\nusing System.IO;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Theme\n{\n public static class FontLoader\n {\n [DllImport(\"gdi32.dll\")]\n private static extern int AddFontResource(string lpFilename);\n\n [DllImport(\"gdi32.dll\")]\n private static extern int RemoveFontResource(string lpFilename);\n\n private static string? _tempFontPath;\n\n public static bool LoadFont(string resourcePath)\n {\n try\n {\n // Extract the font to a temporary file\n var fontUri = new Uri(resourcePath);\n var streamResourceInfo = Application.GetResourceStream(fontUri);\n\n if (streamResourceInfo == null)\n {\n return false;\n }\n\n // Create a temporary file for the font\n _tempFontPath = Path.Combine(\n Path.GetTempPath(),\n $\"MaterialSymbols_{Guid.NewGuid()}.ttf\"\n );\n\n using (var fileStream = File.Create(_tempFontPath))\n using (var resourceStream = streamResourceInfo.Stream)\n {\n resourceStream.CopyTo(fileStream);\n }\n\n // Load the font using the Win32 API\n int result = AddFontResource(_tempFontPath);\n\n // Force a redraw of all text elements\n foreach (Window window in Application.Current.Windows)\n {\n window.InvalidateVisual();\n }\n\n return result > 0;\n }\n catch (Exception)\n {\n return false;\n }\n }\n\n public static void UnloadFont()\n {\n if (!string.IsNullOrEmpty(_tempFontPath) && File.Exists(_tempFontPath))\n {\n RemoveFontResource(_tempFontPath);\n try\n {\n File.Delete(_tempFontPath);\n }\n catch\n {\n // Ignore errors when deleting the temporary file\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/ConfigurationItem.cs", "using System;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents an item in a configuration file.\n /// \n public class ConfigurationItem\n {\n /// \n /// Gets or sets the name of the item.\n /// \n public string Name { get; set; }\n\n /// \n /// Gets or sets the package name of the item.\n /// \n public string PackageName { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the item is selected.\n /// \n public bool IsSelected { get; set; }\n \n /// \n /// Gets or sets the type of control used for this item.\n /// \n public ControlType ControlType { get; set; } = ControlType.BinaryToggle;\n \n /// \n /// Gets or sets the selected value for ComboBox controls.\n /// This is used when ControlType is ComboBox.\n /// \n public string SelectedValue { get; set; }\n \n /// \n /// Gets or sets additional properties for the item.\n /// This can be used to store custom properties like wallpaper change preference.\n /// \n public Dictionary CustomProperties { get; set; } = new Dictionary();\n \n /// \n /// Ensures that SelectedValue is set for ComboBox controls based on SliderValue and available options.\n /// \n public void EnsureSelectedValueIsSet()\n {\n // Only process ComboBox controls with null SelectedValue\n if (ControlType == ControlType.ComboBox && string.IsNullOrEmpty(SelectedValue))\n {\n // For Power Plan\n if (Name?.Contains(\"Power Plan\") == true ||\n (CustomProperties.TryGetValue(\"Id\", out var id) && id?.ToString() == \"PowerPlanComboBox\"))\n {\n // Try to get the value from PowerPlanOptions if available\n if (CustomProperties.TryGetValue(\"PowerPlanOptions\", out var options) &&\n options is List powerPlanOptions &&\n powerPlanOptions.Count > 0 &&\n CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int index = Convert.ToInt32(sliderValue);\n if (index >= 0 && index < powerPlanOptions.Count)\n {\n SelectedValue = powerPlanOptions[index];\n }\n }\n // If PowerPlanOptions is not available, use default values\n else if (CustomProperties.TryGetValue(\"SliderValue\", out var sv))\n {\n int index = Convert.ToInt32(sv);\n string[] defaultOptions = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n if (index >= 0 && index < defaultOptions.Length)\n {\n SelectedValue = defaultOptions[index];\n }\n }\n \n // If we still don't have a SelectedValue, add PowerPlanOptions\n if (string.IsNullOrEmpty(SelectedValue) && CustomProperties.TryGetValue(\"SliderValue\", out var sv2))\n {\n int index = Convert.ToInt32(sv2);\n string[] defaultOptions = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n if (index >= 0 && index < defaultOptions.Length)\n {\n SelectedValue = defaultOptions[index];\n CustomProperties[\"PowerPlanOptions\"] = new List(defaultOptions);\n }\n }\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/AppInfo.cs", "// This contains the model for standard application information\n\nusing System;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models\n{\n /// \n /// Defines the type of application.\n /// \n public enum AppType\n {\n /// \n /// Standard application.\n /// \n StandardApp,\n\n /// \n /// Windows capability.\n /// \n Capability,\n\n /// \n /// Windows optional feature.\n /// \n OptionalFeature,\n }\n\n /// \n /// Represents information about a standard application.\n /// \n public class AppInfo : IInstallableItem\n {\n string IInstallableItem.PackageId => PackageID;\n string IInstallableItem.DisplayName => Name;\n InstallItemType IInstallableItem.ItemType =>\n Type switch\n {\n AppType.Capability => InstallItemType.Capability,\n AppType.OptionalFeature => InstallItemType.Feature,\n _ => InstallItemType.WindowsApp,\n };\n bool IInstallableItem.RequiresRestart => false;\n\n /// \n /// Gets or sets the name of the application.\n /// \n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description of the application.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the package name of the application.\n /// \n public string PackageName { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the package ID of the application.\n /// \n public string PackageID { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the category of the application.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether the application is installed.\n /// \n public bool IsInstalled { get; set; }\n\n /// \n /// Gets or sets the type of application.\n /// \n public AppType Type { get; set; } = AppType.StandardApp;\n\n /// \n /// Gets or sets a value indicating whether the application requires a custom installation process.\n /// \n public bool IsCustomInstall { get; set; }\n\n /// \n /// Gets or sets the sub-packages associated with this application.\n /// \n public string[]? SubPackages { get; set; }\n\n /// \n /// Gets or sets the registry settings associated with this application.\n /// \n public AppRegistrySetting[]? RegistrySettings { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the application requires special handling.\n /// \n public bool RequiresSpecialHandling { get; set; }\n\n /// \n /// Gets or sets the special handler type for this application.\n /// \n public string? SpecialHandlerType { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the application is protected by the system.\n /// \n public bool IsSystemProtected { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the application can be reinstalled after removal.\n /// \n public bool CanBeReinstalled { get; set; } = true;\n\n /// \n /// Gets or sets the version of the application.\n /// \n public string Version { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the last operation error message, if any.\n /// \n public string? LastOperationError { get; set; }\n }\n\n /// \n /// Represents a registry setting for an application.\n /// \n public class AppRegistrySetting\n {\n /// \n /// Gets or sets the registry path.\n /// \n public string Path { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the registry value name.\n /// \n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the registry value.\n /// \n public object? Value { get; set; }\n\n /// \n /// Gets or sets the registry value kind.\n /// \n public Microsoft.Win32.RegistryValueKind ValueKind { get; set; }\n\n /// \n /// Gets or sets the description of the registry setting.\n /// \n public string? Description { get; set; }\n }\n\n /// \n /// Represents a package removal script.\n /// \n public class PackageRemovalScript\n {\n /// \n /// Gets or sets the name of the script.\n /// \n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the content of the script.\n /// \n public string Content { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the target scheduled task name.\n /// \n public string? TargetScheduledTaskName { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the script should run on startup.\n /// \n public bool RunOnStartup { get; set; }\n }\n\n /// \n /// Defines the types of special app handlers.\n /// \n public enum AppHandlerType\n {\n /// \n /// No special handling required.\n /// \n None,\n\n /// \n /// Microsoft Edge browser.\n /// \n Edge,\n\n /// \n /// Microsoft OneDrive.\n /// \n OneDrive,\n\n /// \n /// Microsoft Copilot.\n /// \n Copilot,\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/IScriptUpdateService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\n/// \n/// Provides methods for updating script content.\n/// \npublic interface IScriptUpdateService\n{\n /// \n /// Updates an existing BloatRemoval script with new entries.\n /// \n /// The names of the applications to add or remove.\n /// Dictionary mapping app names to their registry settings.\n /// Dictionary mapping app names to their subpackages.\n /// True if this is an install operation (remove from script), false if it's a removal operation (add to script).\n /// The updated removal script.\n Task UpdateExistingBloatRemovalScriptAsync(\n List appNames,\n Dictionary> appsWithRegistry,\n Dictionary appSubPackages,\n bool isInstallOperation = false);\n\n /// \n /// Updates the capabilities array in the script by adding or removing capabilities.\n /// \n /// The script content.\n /// The capabilities to add or remove.\n /// True if this is an install operation (remove from script), false if it's a removal operation (add to script).\n /// The updated script content.\n string UpdateCapabilitiesArrayInScript(string scriptContent, List capabilities, bool isInstallOperation = false);\n\n /// \n /// Updates the packages array in the script by adding or removing packages.\n /// \n /// The script content.\n /// The packages to add or remove.\n /// True if this is an install operation (remove from script), false if it's a removal operation (add to script).\n /// The updated script content.\n string UpdatePackagesArrayInScript(string scriptContent, List packages, bool isInstallOperation = false);\n\n /// \n /// Updates the optional features in the script by adding or removing features.\n /// \n /// The script content.\n /// The features to add or remove.\n /// True if this is an install operation (remove from script), false if it's a removal operation (add to script).\n /// The updated script content.\n string UpdateOptionalFeaturesInScript(string scriptContent, List features, bool isInstallOperation = false);\n\n /// \n /// Updates the registry settings in the script by adding new settings.\n /// \n /// The script content.\n /// Dictionary mapping app names to their registry settings.\n /// The updated script content.\n string UpdateRegistrySettingsInScript(string scriptContent, Dictionary> appsWithRegistry);\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/ExplorerCustomizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Enums;\n\nnamespace Winhance.Core.Features.Customize.Models;\n\npublic static class ExplorerCustomizations\n{\n public static CustomizationGroup GetExplorerCustomizations()\n {\n return new CustomizationGroup\n {\n Name = \"Explorer\",\n Category = CustomizationCategory.Explorer,\n Settings = new List\n {\n new CustomizationSetting\n {\n Id = \"explorer-3d-objects\",\n Name = \"3D Objects\",\n Description = \"Controls 3D Objects folder visibility in This PC\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\MyComputer\\\\NameSpace\",\n Name = \"{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}\",\n RecommendedValue = null,\n EnabledValue = null, // When toggle is ON, 3D Objects folder is shown (key exists)\n DisabledValue = null, // When toggle is OFF, 3D Objects folder is hidden (key removed)\n ValueType = RegistryValueKind.None,\n DefaultValue = null,\n Description = \"Controls 3D Objects folder visibility in This PC\",\n ActionType = RegistryActionType.Remove,\n },\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\MyComputer\\\\NameSpace\\\\WOW64\",\n Name = \"{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}\",\n RecommendedValue = null,\n EnabledValue = null, // When toggle is ON, 3D Objects folder is shown (key exists)\n DisabledValue = null, // When toggle is OFF, 3D Objects folder is hidden (key removed)\n ValueType = RegistryValueKind.None,\n DefaultValue = null,\n Description =\n \"Controls 3D Objects folder visibility in This PC (WOW64)\",\n ActionType = RegistryActionType.Remove,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new CustomizationSetting\n {\n Id = \"explorer-home-folder\",\n Name = \"Home Folder in Navigation Pane\",\n Description = \"Controls Home Folder visibility in Navigation Pane\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Desktop\\\\NameSpace\",\n Name = \"{f874310e-b6b7-47dc-bc84-b9e6b38f5903}\",\n RecommendedValue = null,\n EnabledValue = null, // When toggle is ON, Home Folder is shown (key exists)\n DisabledValue = null, // When toggle is OFF, Home Folder is hidden (key removed)\n ValueType = RegistryValueKind.None,\n DefaultValue = null,\n Description = \"Controls Home Folder visibility in Navigation Pane\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n ActionType = RegistryActionType.Remove,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-launch-to\",\n Name = \"Launch to This PC\",\n Description = \"Controls where File Explorer opens by default\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"LaunchTo\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, File Explorer opens to 'This PC'\n DisabledValue = 2, // When toggle is OFF, File Explorer opens to 'Quick access'\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls where File Explorer opens by default\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-show-file-ext\",\n Name = \"Show File Extensions\",\n Description = \"Controls visibility of file name extensions\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"HideFileExt\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, file extensions are shown\n DisabledValue = 1, // When toggle is OFF, file extensions are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls visibility of file name extensions\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-show-hidden-files\",\n Name = \"Show Hidden Files, Folders & Drives\",\n Description = \"Controls visibility of hidden files and folders\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"Hidden\",\n RecommendedValue = 1,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls visibility of hidden files, folders and drives\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-hide-protected-files\",\n Name = \"Hide Protected Operating System Files\",\n Description = \"Controls visibility of protected operating system files\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowSuperHidden\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls visibility of protected operating system files\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-folder-tips\",\n Name = \"Folder Tips\",\n Description = \"Controls file size information in folder tips\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"FolderContentsInfoTip\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, folder tips are enabled\n DisabledValue = 0, // When toggle is OFF, folder tips are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls file size information in folder tips\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-popup-descriptions\",\n Name = \"Pop-up Descriptions\",\n Description = \"Controls pop-up descriptions for folder and desktop items\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowInfoTip\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, pop-up descriptions are shown\n DisabledValue = 0, // When toggle is OFF, pop-up descriptions are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description =\n \"Controls pop-up descriptions for folder and desktop items\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-preview-handlers\",\n Name = \"Preview Handlers\",\n Description = \"Controls preview handlers in preview pane\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowPreviewHandlers\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, preview handlers are enabled\n DisabledValue = 0, // When toggle is OFF, preview handlers are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls preview handlers in preview pane\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-status-bar\",\n Name = \"Status Bar\",\n Description = \"Controls status bar visibility in File Explorer\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowStatusBar\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, status bar is shown\n DisabledValue = 0, // When toggle is OFF, status bar is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls status bar visibility in File Explorer\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-show-thumbnails\",\n Name = \"Show Thumbnails\",\n Description = \"Controls whether to show thumbnails or icons\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"IconsOnly\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, thumbnails are shown\n DisabledValue = 1, // When toggle is OFF, icons are shown\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls whether to show thumbnails or icons\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-translucent-selection\",\n Name = \"Translucent Selection\",\n Description = \"Controls translucent selection rectangle\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ListviewAlphaSelect\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, translucent selection is enabled\n DisabledValue = 0, // When toggle is OFF, translucent selection is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls translucent selection rectangle\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-drop-shadows\",\n Name = \"Drop Shadows\",\n Description = \"Controls drop shadows for icon labels\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ListviewShadow\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, drop shadows are enabled\n DisabledValue = 0, // When toggle is OFF, drop shadows are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls drop shadows for icon labels\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-full-path\",\n Name = \"Full Path in Title Bar\",\n Description = \"Controls full path display in the title bar\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\CabinetState\",\n Name = \"FullPath\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, full path is shown\n DisabledValue = 0, // When toggle is OFF, full path is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls full path display in the title bar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-font-smoothing\",\n Name = \"Font Smoothing\",\n Description = \"Controls smooth edges of screen fonts\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"FontSmoothing\",\n RecommendedValue = \"2\",\n EnabledValue = \"2\", // When toggle is ON, font smoothing is enabled\n DisabledValue = \"0\", // When toggle is OFF, font smoothing is disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = \"0\", // Default value when registry key exists but no value is set\n Description = \"Controls smooth edges of screen fonts\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-dpi-scaling\",\n Name = \"DPI Scaling (100%)\",\n Description = \"Controls DPI scaling setting\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"LogPixels\",\n RecommendedValue = 96,\n EnabledValue = 96, // When toggle is ON, DPI scaling is set to 100%\n DisabledValue = 120, // When toggle is OFF, DPI scaling is set to 125%\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 120, // Default value when registry key exists but no value is set\n Description = \"Controls DPI scaling setting\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-per-process-dpi\",\n Name = \"Per-Process DPI\",\n Description = \"Controls per-process system DPI\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"EnablePerProcessSystemDPI\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, per-process DPI is enabled\n DisabledValue = 0, // When toggle is OFF, per-process DPI is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls per-process system DPI\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-lock-screen\",\n Name = \"Lock Screen\",\n Description = \"Controls lock screen visibility\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\Personalization\",\n Name = \"NoLockScreen\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls lock screen visibility\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-gallery\",\n Name = \"Gallery in Navigation Pane\",\n Description = \"Controls gallery visibility in navigation pane\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Desktop\\\\NameSpace\",\n Name = \"{e88865ea-0e1c-4e20-9aa6-edcd0212c87c}\",\n RecommendedValue = null,\n EnabledValue = null, // When toggle is ON, gallery is shown (key exists)\n DisabledValue = null, // When toggle is OFF, gallery is hidden (key removed)\n ValueType = RegistryValueKind.None,\n DefaultValue = null,\n Description = \"Controls gallery visibility in navigation pane\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n ActionType = RegistryActionType.Remove,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-context-menu\",\n Name = \"Classic Context Menu\",\n Description = \"Controls context menu style (classic or modern)\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Classes\\\\CLSID\\\\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\\\\InprocServer32\",\n Name = \"\",\n RecommendedValue = \"\",\n EnabledValue = null, // When toggle is ON, classic context menu is used (value is deleted)\n DisabledValue = \"\", // When toggle is OFF, modern context menu is used (empty value is set)\n ValueType = RegistryValueKind.String,\n DefaultValue = \"\", // Default value when registry key exists but no value is set\n Description = \"Controls context menu style (classic or modern)\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/VersionInfo.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n public class VersionInfo\n {\n public string Version { get; set; } = string.Empty;\n public DateTime ReleaseDate { get; set; }\n public string DownloadUrl { get; set; } = string.Empty;\n public bool IsUpdateAvailable { get; set; }\n \n public static VersionInfo FromTag(string tag)\n {\n // Parse version tag in format v25.05.02\n if (string.IsNullOrEmpty(tag) || !tag.StartsWith(\"v\"))\n return new VersionInfo();\n \n string versionString = tag.Substring(1); // Remove 'v' prefix\n string[] parts = versionString.Split('.');\n \n if (parts.Length != 3)\n return new VersionInfo();\n \n if (!int.TryParse(parts[0], out int year) || \n !int.TryParse(parts[1], out int month) || \n !int.TryParse(parts[2], out int day))\n return new VersionInfo();\n \n // Construct a date from the version components\n DateTime releaseDate;\n try\n {\n releaseDate = new DateTime(2000 + year, month, day);\n }\n catch\n {\n // Invalid date components\n return new VersionInfo();\n }\n \n return new VersionInfo\n {\n Version = tag,\n ReleaseDate = releaseDate\n };\n }\n \n public bool IsNewerThan(VersionInfo other)\n {\n if (other == null)\n return true;\n \n return ReleaseDate > other.ReleaseDate;\n }\n \n public override string ToString()\n {\n return Version;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/CancellationReason.cs", "namespace Winhance.Core.Features.Common.Enums\n{\n /// \n /// Represents the reason for a cancellation operation.\n /// \n public enum CancellationReason\n {\n /// \n /// No cancellation occurred.\n /// \n None = 0,\n\n /// \n /// Cancellation was initiated by the user.\n /// \n UserCancelled = 1,\n\n /// \n /// Cancellation occurred due to internet connectivity issues.\n /// \n InternetConnectivityLost = 2,\n\n /// \n /// Cancellation occurred due to a system error.\n /// \n SystemError = 3\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/ScriptDetectionService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Implementation of the IScriptDetectionService interface.\n /// \n public class ScriptDetectionService : IScriptDetectionService\n {\n private const string ScriptsDirectory = @\"C:\\Program Files\\Winhance\\Scripts\";\n \n private static readonly Dictionary ScriptDescriptions = new Dictionary(StringComparer.OrdinalIgnoreCase)\n {\n { \"BloatRemoval.ps1\", \"Multiple items removed via BloatRemoval.ps1\" },\n { \"EdgeRemoval.ps1\", \"Microsoft Edge Removed via EdgeRemoval.ps1\" },\n { \"OneDriveRemoval.ps1\", \"OneDrive Removed via OneDriveRemoval.ps1\" }\n };\n \n /// \n public bool AreRemovalScriptsPresent()\n {\n if (!Directory.Exists(ScriptsDirectory))\n {\n return false;\n }\n \n return GetScriptFiles().Any();\n }\n \n /// \n public IEnumerable GetActiveScripts()\n {\n if (!Directory.Exists(ScriptsDirectory))\n {\n return Enumerable.Empty();\n }\n \n var scriptFiles = GetScriptFiles();\n \n return scriptFiles.Select(file => new ScriptInfo\n {\n Name = Path.GetFileName(file),\n Description = GetScriptDescription(Path.GetFileName(file)),\n FilePath = file\n });\n }\n \n private IEnumerable GetScriptFiles()\n {\n if (!Directory.Exists(ScriptsDirectory))\n {\n return Enumerable.Empty();\n }\n \n return Directory.GetFiles(ScriptsDirectory, \"*.ps1\")\n .Where(file => ScriptDescriptions.ContainsKey(Path.GetFileName(file)));\n }\n \n private string GetScriptDescription(string fileName)\n {\n return ScriptDescriptions.TryGetValue(fileName, out var description)\n ? description\n : $\"Unknown script: {fileName}\";\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IFeatureRemovalService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for removing Windows optional features.\n /// \n public interface IFeatureRemovalService\n {\n /// \n /// Removes a feature.\n /// \n /// The feature to remove.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// True if the removal was successful; otherwise, false.\n Task RemoveFeatureAsync(FeatureInfo feature, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if a feature can be removed.\n /// \n /// The feature to check.\n /// True if the feature can be removed; otherwise, false.\n Task CanRemoveFeatureAsync(FeatureInfo feature);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/ICapabilityRemovalService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for removing Windows capabilities.\n /// \n public interface ICapabilityRemovalService\n {\n /// \n /// Removes a capability.\n /// \n /// The capability to remove.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// True if the removal was successful; otherwise, false.\n Task RemoveCapabilityAsync(CapabilityInfo capability, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if a capability can be removed.\n /// \n /// The capability to check.\n /// True if the capability can be removed; otherwise, false.\n Task CanRemoveCapabilityAsync(CapabilityInfo capability);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Views/SoftwareAppsView.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing MaterialDesignThemes.Wpf;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Views\n{\n /// \n /// Interaction logic for SoftwareAppsView.xaml\n /// \n public partial class SoftwareAppsView : UserControl\n {\n public SoftwareAppsView()\n {\n InitializeComponent();\n Loaded += SoftwareAppsView_Loaded;\n\n // Set up the expandable sections\n WindowsAppsContent.Visibility = Visibility.Collapsed;\n ExternalAppsContent.Visibility = Visibility.Collapsed;\n\n // Add click handlers\n WindowsAppsHeaderBorder.MouseDown += WindowsAppsHeader_MouseDown;\n ExternalAppsHeaderBorder.MouseDown += ExternalAppsHeader_MouseDown;\n }\n\n private async void SoftwareAppsView_Loaded(object sender, RoutedEventArgs e)\n {\n if (DataContext is SoftwareAppsViewModel viewModel)\n {\n try\n {\n // Initialize the view model\n await viewModel.InitializeCommand.ExecuteAsync(null);\n \n // Expand the first section by default after initialization is complete\n WindowsAppsContent.Visibility = Visibility.Visible;\n WindowsAppsHeaderIcon.Kind = PackIconKind.ChevronUp; // Up arrow\n }\n catch (System.Exception ex)\n {\n MessageBox.Show($\"Error initializing Software Apps view: {ex.Message}\",\n \"Initialization Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error);\n }\n }\n }\n\n private void WindowsAppsHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n ToggleSection(WindowsAppsContent, WindowsAppsHeaderIcon);\n }\n\n private void ExternalAppsHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n ToggleSection(ExternalAppsContent, ExternalAppsHeaderIcon);\n }\n\n private void ToggleSection(UIElement content, PackIcon icon)\n {\n if (content.Visibility == Visibility.Collapsed)\n {\n content.Visibility = Visibility.Visible;\n icon.Kind = PackIconKind.ChevronUp; // Up arrow (section expanded)\n }\n else\n {\n content.Visibility = Visibility.Collapsed;\n icon.Kind = PackIconKind.ChevronDown; // Down arrow (section collapsed)\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/FeatureCatalog.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a catalog of Windows optional features that can be enabled or disabled.\n/// \npublic class FeatureCatalog\n{\n /// \n /// Gets or sets the collection of Windows optional features.\n /// \n public IReadOnlyList Features { get; init; } = new List();\n\n /// \n /// Creates a default feature catalog with predefined Windows optional features.\n /// \n /// A new FeatureCatalog instance with default features.\n public static FeatureCatalog CreateDefault()\n {\n return new FeatureCatalog { Features = CreateDefaultFeatures() };\n }\n\n private static IReadOnlyList CreateDefaultFeatures()\n {\n return new List\n {\n // Windows Subsystems\n new FeatureInfo\n {\n Name = \"Subsystem for Linux\",\n Description = \"Allows running Linux binary executables natively on Windows\",\n PackageName = \"Microsoft-Windows-Subsystem-Linux\",\n Category = \"Development\",\n RequiresReboot = true,\n CanBeReenabled = true,\n },\n // Virtualization\n new FeatureInfo\n {\n Name = \"Windows Hypervisor Platform\",\n Description = \"Core virtualization platform without Hyper-V management tools\",\n PackageName = \"Microsoft-Hyper-V-Hypervisor\",\n Category = \"Virtualization\",\n RequiresReboot = true,\n CanBeReenabled = true,\n },\n // Hyper-V\n new FeatureInfo\n {\n Name = \"Hyper-V\",\n Description = \"Virtualization platform for running multiple operating systems\",\n PackageName = \"Microsoft-Hyper-V-All\",\n Category = \"Virtualization\",\n RequiresReboot = true,\n CanBeReenabled = true,\n },\n new FeatureInfo\n {\n Name = \"Hyper-V Management Tools\",\n Description = \"Tools for managing Hyper-V virtual machines\",\n PackageName = \"Microsoft-Hyper-V-Tools-All\",\n Category = \"Virtualization\",\n RequiresReboot = false,\n CanBeReenabled = true,\n },\n // .NET Framework\n new FeatureInfo\n {\n Name = \".NET Framework 3.5\",\n Description = \"Legacy .NET Framework for older applications\",\n PackageName = \"NetFx3\",\n Category = \"Development\",\n RequiresReboot = true,\n CanBeReenabled = true,\n },\n // Windows Features\n new FeatureInfo\n {\n Name = \"Windows Sandbox\",\n Description = \"Isolated desktop environment for running applications\",\n PackageName = \"Containers-DisposableClientVM\",\n Category = \"Security\",\n RequiresReboot = true,\n CanBeReenabled = true,\n },\n new FeatureInfo\n {\n Name = \"Recall\",\n Description = \"Windows 11 feature that records user activity\",\n PackageName = \"Recall\",\n Category = \"System\",\n RequiresReboot = false,\n CanBeReenabled = true,\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/INavigationService.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for navigating between views in the application.\n /// \n public interface INavigationService\n {\n /// \n /// Navigates to a view.\n /// \n /// The name of the view to navigate to.\n /// True if navigation was successful; otherwise, false.\n bool NavigateTo(string viewName);\n\n /// \n /// Navigates to a view with parameters.\n /// \n /// The name of the view to navigate to.\n /// The navigation parameter.\n /// True if navigation was successful; otherwise, false.\n bool NavigateTo(string viewName, object parameter);\n\n /// \n /// Navigates back to the previous view.\n /// \n /// True if navigation was successful; otherwise, false.\n bool NavigateBack();\n\n /// \n /// Gets the current view name.\n /// \n string CurrentView { get; }\n\n /// \n /// Event raised when navigation occurs.\n /// \n event EventHandler? Navigated;\n\n /// \n /// Event raised before navigation occurs.\n /// \n event EventHandler? Navigating;\n\n /// \n /// Event raised when navigation fails.\n /// \n event EventHandler? NavigationFailed;\n }\n\n /// \n /// Event arguments for navigation events.\n /// \n public class NavigationEventArgs : EventArgs\n {\n /// \n /// Gets the source view name.\n /// \n public string SourceView { get; }\n\n /// \n /// Gets the target view name.\n /// \n public string TargetView { get; }\n\n /// \n /// Gets the navigation route (same as TargetView).\n /// \n public string Route => TargetView;\n\n /// \n /// Gets the view model type associated with the navigation.\n /// \n public Type? ViewModelType => Parameter?.GetType();\n\n /// \n /// Gets the navigation parameter.\n /// \n public object? Parameter { get; }\n\n /// \n /// Gets a value indicating whether the navigation can be canceled.\n /// \n public bool CanCancel { get; }\n\n /// \n /// Gets or sets a value indicating whether the navigation should be canceled.\n /// \n public bool Cancel { get; set; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The source view name.\n /// The target view name.\n /// The navigation parameter.\n /// Whether the navigation can be canceled.\n public NavigationEventArgs(\n string sourceView,\n string targetView,\n object? parameter = null,\n bool canCancel = false\n )\n {\n SourceView = sourceView;\n TargetView = targetView;\n Parameter = parameter;\n CanCancel = canCancel;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/UpdateOptimizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class UpdateOptimizations\n{\n public static OptimizationGroup GetUpdateOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Windows Updates\",\n Category = OptimizationCategory.Updates,\n Settings = new List\n {\n new OptimizationSetting\n {\n Id = \"updates-auto-update\",\n Name = \"Automatic Windows Updates\",\n Description = \"Controls automatic Windows updates behavior\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Windows Update Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\\\\AU\",\n Name = \"NoAutoUpdate\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, automatic updates are enabled\n DisabledValue = 1, // When toggle is OFF, automatic updates are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls automatic Windows updates\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\\\\AU\",\n Name = \"AUOptions\",\n RecommendedValue = 2,\n EnabledValue = 4, // When toggle is ON, auto download and schedule install (4)\n DisabledValue = 2, // When toggle is OFF, notify before download (2)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls automatic update behavior\",\n },\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\\\\AU\",\n Name = \"AutoInstallMinorUpdates\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, minor updates are installed automatically\n DisabledValue = 0, // When toggle is OFF, minor updates are not installed automatically\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls automatic installation of minor updates\",\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"updates-defer-feature-updates\",\n Name = \"Delay Feature Updates for 365 Days\",\n Description = \"Delays major Windows feature updates for 365 days\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Windows Update Policies\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"DeferFeatureUpdates\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, feature updates are deferred\n DisabledValue = 0, // When toggle is OFF, feature updates are not deferred\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Enables deferral of feature updates\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"DeferFeatureUpdatesPeriodInDays\",\n RecommendedValue = 365,\n EnabledValue = 365, // When toggle is ON, feature updates are deferred for 365 days\n DisabledValue = 0, // When toggle is OFF, feature updates are not deferred\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Sets the deferral period for feature updates to 365 days\",\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"updates-defer-quality-updates\",\n Name = \"Delay Security Updates for 7 Days\",\n Description = \"Delays Windows security and quality updates for 7 days\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Windows Update Policies\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"DeferQualityUpdates\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, quality updates are deferred\n DisabledValue = 0, // When toggle is OFF, quality updates are not deferred\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Enables deferral of security and quality updates\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"DeferQualityUpdatesPeriodInDays\",\n RecommendedValue = 7,\n EnabledValue = 7, // When toggle is ON, quality updates are deferred for 7 days\n DisabledValue = 0, // When toggle is OFF, quality updates are not deferred\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Sets the deferral period for security and quality updates to 7 days\",\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"updates-delivery-optimization\",\n Name = \"Delivery Optimization (LAN)\",\n Description = \"Controls peer-to-peer update distribution\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Delivery Optimization\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\DeliveryOptimization\",\n Name = \"DODownloadMode\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, peer-to-peer update distribution is enabled (LAN only)\n DisabledValue = 0, // When toggle is OFF, peer-to-peer update distribution is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls peer-to-peer update distribution\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-store-auto-download\",\n Name = \"Auto Update Microsoft Store Apps\",\n Description = \"Controls automatic updates for Microsoft Store apps\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Microsoft Store\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\WindowsStore\",\n Name = \"AutoDownload\",\n RecommendedValue = 2,\n EnabledValue = 4, // When toggle is ON, automatic updates for Microsoft Store apps are enabled\n DisabledValue = 2, // When toggle is OFF, automatic updates for Microsoft Store apps are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls automatic updates for Microsoft Store apps\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-app-archiving\",\n Name = \"Automatic Archiving of Unused Apps\",\n Description = \"Controls automatic archiving of unused apps\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Microsoft Store\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\Appx\",\n Name = \"AllowAutomaticAppArchiving\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, automatic archiving of unused apps is enabled\n DisabledValue = 0, // When toggle is OFF, automatic archiving of unused apps is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls automatic archiving of unused apps\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-restart-options\",\n Name = \"Prevent Automatic Restarts\",\n Description =\n \"Prevents automatic restarts after installing updates when users are logged on\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Update Behavior\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\\\\AU\",\n Name = \"NoAutoRebootWithLoggedOnUsers\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, automatic restarts are prevented\n DisabledValue = 1, // When toggle is OFF, automatic restarts are allowed\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls automatic restart behavior after updates\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-driver-controls\",\n Name = \"Do Not Include Drivers with Updates\",\n Description = \"Does not include driver updates with Windows quality updates\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Update Content\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"ExcludeWUDriversInQualityUpdate\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, driver updates are included\n DisabledValue = 1, // When toggle is OFF, driver updates are excluded\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Controls whether driver updates are included in Windows quality updates\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-notification-level\",\n Name = \"Update Notifications\",\n Description = \"Controls the visibility of update notifications\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Update Behavior\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"SetUpdateNotificationLevel\",\n RecommendedValue = 1,\n EnabledValue = 2, // When toggle is ON, show all notifications (2 = default)\n DisabledValue = 1, // When toggle is OFF, show only restart required notifications (1 = reduced)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls the visibility level of update notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-metered-connection\",\n Name = \"Updates on Metered Connections\",\n Description =\n \"Controls whether updates are downloaded over metered connections\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Update Behavior\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\WindowsUpdate\\\\UX\\\\Settings\",\n Name = \"AllowAutoWindowsUpdateDownloadOverMeteredNetwork\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, updates are downloaded over metered connections\n DisabledValue = 0, // When toggle is OFF, updates are not downloaded over metered connections\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Controls update download behavior on metered connections\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Views/ExternalAppsView.xaml.cs", "using System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Views\n{\n public partial class ExternalAppsView : UserControl\n {\n public ExternalAppsView()\n {\n InitializeComponent();\n Loaded += ExternalAppsView_Loaded;\n }\n\n private void ExternalAppsView_Loaded(object sender, RoutedEventArgs e)\n {\n // Find all category header borders and attach click handlers\n foreach (var border in FindVisualChildren(this))\n {\n if (border?.Tag != null && border.Tag is string)\n {\n // Add click handler to toggle category expansion\n border.MouseLeftButtonDown += CategoryHeader_MouseLeftButtonDown;\n }\n }\n }\n\n private void CategoryHeader_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n try\n {\n if (sender is Border border && border.DataContext is ExternalAppsCategoryViewModel category)\n {\n // Toggle the IsExpanded property\n category.IsExpanded = !category.IsExpanded;\n e.Handled = true;\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Error handling category click: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n }\n }\n\n // Helper method to find visual children of a specific type\n private System.Collections.Generic.IEnumerable FindVisualChildren(DependencyObject parent) where T : DependencyObject\n {\n int childrenCount = VisualTreeHelper.GetChildrenCount(parent);\n for (int i = 0; i < childrenCount; i++)\n {\n DependencyObject child = VisualTreeHelper.GetChild(parent, i);\n \n if (child is T childOfType)\n yield return childOfType;\n \n foreach (T childOfChild in FindVisualChildren(child))\n yield return childOfChild;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/CategoryToIconConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing MaterialDesignThemes.Wpf;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a category name to an appropriate Material Design icon.\n /// \n public class CategoryToIconConverter : IValueConverter\n {\n public static CategoryToIconConverter Instance { get; } = new CategoryToIconConverter();\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is string categoryName)\n {\n // Convert category name to lowercase for case-insensitive comparison\n string category = categoryName.ToLowerInvariant();\n\n // Map category names to appropriate Material Design icons\n return category switch\n {\n // Browser related categories\n var c when c.Contains(\"browser\") => PackIconKind.Web,\n \n // Compression related categories\n var c when c.Contains(\"compression\") => PackIconKind.ZipBox,\n var c when c.Contains(\"zip\") => PackIconKind.ZipBox,\n var c when c.Contains(\"archive\") => PackIconKind.Archive,\n \n // Customization related categories\n var c when c.Contains(\"customization\") => PackIconKind.Palette,\n var c when c.Contains(\"utilities\") => PackIconKind.Tools,\n var c when c.Contains(\"shell\") => PackIconKind.Console,\n \n // Development related categories\n var c when c.Contains(\"development\") => PackIconKind.CodeBraces,\n var c when c.Contains(\"programming\") => PackIconKind.CodeBraces,\n var c when c.Contains(\"code\") => PackIconKind.CodeBraces,\n \n // Document related categories\n var c when c.Contains(\"document\") => PackIconKind.FileDocument,\n var c when c.Contains(\"pdf\") => PackIconKind.File,\n var c when c.Contains(\"office\") => PackIconKind.FileDocument,\n var c when c.Contains(\"viewer\") => PackIconKind.FileDocument,\n \n // Media related categories\n var c when c.Contains(\"media\") => PackIconKind.Play,\n var c when c.Contains(\"video\") => PackIconKind.Video,\n var c when c.Contains(\"audio\") => PackIconKind.Music,\n var c when c.Contains(\"player\") => PackIconKind.Play,\n var c when c.Contains(\"multimedia\") => PackIconKind.Play,\n \n // Communication related categories\n var c when c.Contains(\"communication\") => PackIconKind.Message,\n var c when c.Contains(\"chat\") => PackIconKind.Chat,\n var c when c.Contains(\"email\") => PackIconKind.Email,\n var c when c.Contains(\"messaging\") => PackIconKind.Message,\n var c when c.Contains(\"calendar\") => PackIconKind.Calendar,\n \n // Security related categories\n var c when c.Contains(\"security\") => PackIconKind.Shield,\n var c when c.Contains(\"antivirus\") => PackIconKind.ShieldOutline,\n var c when c.Contains(\"firewall\") => PackIconKind.Fire,\n var c when c.Contains(\"privacy\") => PackIconKind.Lock,\n \n // File & Disk Management\n var c when c.Contains(\"file\") => PackIconKind.Folder,\n var c when c.Contains(\"disk\") => PackIconKind.Database,\n \n // Gaming\n var c when c.Contains(\"gaming\") => PackIconKind.GamepadVariant,\n var c when c.Contains(\"game\") => PackIconKind.GamepadVariant,\n \n // Imaging\n var c when c.Contains(\"imaging\") => PackIconKind.Image,\n var c when c.Contains(\"image\") => PackIconKind.Image,\n \n // Online Storage\n var c when c.Contains(\"storage\") => PackIconKind.Cloud,\n var c when c.Contains(\"cloud\") => PackIconKind.Cloud,\n \n // Remote Access\n var c when c.Contains(\"remote\") => PackIconKind.Remote,\n var c when c.Contains(\"access\") => PackIconKind.Remote,\n \n // Optical Disc Utilities\n var c when c.Contains(\"optical\") => PackIconKind.Album,\n var c when c.Contains(\"disc\") => PackIconKind.Album,\n var c when c.Contains(\"dvd\") => PackIconKind.Album,\n var c when c.Contains(\"cd\") => PackIconKind.Album,\n \n // Default icon for unknown categories\n _ => PackIconKind.Apps\n };\n }\n \n // Default to Apps icon if value is not a string\n return PackIconKind.Apps;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // This converter doesn't support converting back\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IOneDriveInstallationService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces;\n\n/// \n/// Interface for services that handle OneDrive installation.\n/// \npublic interface IOneDriveInstallationService\n{\n /// \n /// Installs OneDrive from the Microsoft download link.\n /// \n /// Optional progress reporter.\n /// Optional cancellation token.\n /// True if installation was successful; otherwise, false.\n Task InstallOneDriveAsync(\n IProgress? progress,\n CancellationToken cancellationToken);\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Interfaces/IInstallationVerifier.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces\n{\n /// \n /// Defines the contract for verifying software installations.\n /// \n public interface IInstallationVerifier\n {\n /// \n /// Verifies if a package is installed.\n /// \n /// The ID of the package to verify.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the verification result.\n Task VerifyInstallationAsync(\n string packageId, \n CancellationToken cancellationToken = default);\n\n /// \n /// Verifies if a package is installed with the specified version.\n /// \n /// The ID of the package to verify.\n /// The expected version of the package.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the verification result.\n Task VerifyInstallationAsync(\n string packageId, \n string version, \n CancellationToken cancellationToken = default);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToThemeIconConverter.cs", "using System;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Media.Imaging;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean value (IsDarkTheme) to the appropriate themed icon path\n /// \n public class BooleanToThemeIconConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n bool isDarkTheme = false;\n\n // Handle different input types for theme\n if (value is bool boolValue)\n {\n isDarkTheme = boolValue;\n Debug.WriteLine($\"BooleanToThemeIconConverter: isDarkTheme = {isDarkTheme} (from bool)\");\n }\n else if (value is string stringValue)\n {\n isDarkTheme = stringValue.Equals(\"Dark\", StringComparison.OrdinalIgnoreCase);\n Debug.WriteLine($\"BooleanToThemeIconConverter: isDarkTheme = {isDarkTheme} (from string '{stringValue}')\");\n }\n else\n {\n Debug.WriteLine($\"BooleanToThemeIconConverter: value is {(value == null ? \"null\" : value.GetType().Name)}\");\n }\n\n // Parameter should be in format \"darkIconPath|lightIconPath\"\n if (parameter is string paramString)\n {\n string[] iconPaths = paramString.Split('|');\n if (iconPaths.Length >= 2)\n {\n string darkIconPath = iconPaths[0];\n string lightIconPath = iconPaths[1];\n\n string selectedPath = isDarkTheme ? darkIconPath : lightIconPath;\n Debug.WriteLine($\"BooleanToThemeIconConverter: Selected path = {selectedPath}\");\n\n // If the target type is BitmapImage, create and return it\n if (targetType == typeof(BitmapImage))\n {\n return new BitmapImage(new Uri(selectedPath, UriKind.Relative));\n }\n\n // Otherwise return the path string\n return selectedPath;\n }\n }\n\n // Default fallback icon path\n Debug.WriteLine(\"BooleanToThemeIconConverter: Using fallback icon path\");\n return \"/Resources/AppIcons/winhance-rocket.ico\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // This converter doesn't support converting back\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/SoundOptimizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class SoundOptimizations\n{\n public static OptimizationGroup GetSoundOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Sound\",\n Category = OptimizationCategory.Sound,\n Settings = new List\n {\n new OptimizationSetting\n {\n Id = \"sound-startup\",\n Name = \"Startup Sound During Boot\",\n Description = \"Controls the startup sound during boot and for the user\",\n Category = OptimizationCategory.Sound,\n GroupName = \"System Sounds\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Authentication\\\\LogonUI\\\\BootAnimation\",\n Name = \"DisableStartupSound\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, startup sound is enabled\n DisabledValue = 1, // When toggle is OFF, startup sound is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls the startup sound during boot\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\EditionOverrides\",\n Name = \"UserSetting_DisableStartupSound\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, user startup sound is enabled\n DisabledValue = 1, // When toggle is OFF, user startup sound is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls the startup sound for the user\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"sound-communication-ducking\",\n Name = \"Sound Ducking Preference\",\n Description = \"Controls sound behavior by reducing the volume of other sounds\",\n Category = OptimizationCategory.Sound,\n GroupName = \"System Sounds\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Multimedia\\\\Audio\",\n Name = \"UserDuckingPreference\",\n RecommendedValue = 3, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, sound ducking is enabled (1 = reduce other sounds by 80%)\n DisabledValue = 3, // When toggle is OFF, sound ducking is disabled (3 = do nothing)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls sound communications behavior\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"sound-voice-activation\",\n Name = \"Voice Activation for Apps\",\n Description = \"Controls voice activation for all apps\",\n Category = OptimizationCategory.Sound,\n GroupName = \"System Sounds\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\SpeechOneCore\\\\Settings\",\n Name = \"AgentActivationEnabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, voice activation is enabled\n DisabledValue = 0, // When toggle is OFF, voice activation is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls voice activation for all apps\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"sound-voice-activation-last-used\",\n Name = \"Last Used Voice Activation Setting\",\n Description = \"Controls the last used voice activation setting\",\n Category = OptimizationCategory.Sound,\n GroupName = \"System Sounds\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\SpeechOneCore\\\\Settings\",\n Name = \"AgentActivationLastUsed\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, last used voice activation is enabled\n DisabledValue = 0, // When toggle is OFF, last used voice activation is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls the last used voice activation setting\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"sound-effects-enhancements\",\n Name = \"Sound Effects and Enhancements\",\n Description = \"Controls audio enhancements for playback devices\",\n Category = OptimizationCategory.Sound,\n GroupName = \"Audio Enhancements\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Multimedia\\\\Audio\\\\DeviceFx\",\n Name = \"EnableDeviceEffects\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, audio enhancements are enabled\n DisabledValue = 0, // When toggle is OFF, audio enhancements are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls audio enhancements for playback devices\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"sound-spatial-audio\",\n Name = \"Spatial Sound Settings\",\n Description = \"Controls Windows Sonic and spatial sound features\",\n Category = OptimizationCategory.Sound,\n GroupName = \"Audio Enhancements\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Audio\",\n Name = \"EnableSpatialSound\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, spatial sound is enabled\n DisabledValue = 0, // When toggle is OFF, spatial sound is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Windows Sonic and spatial sound features\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/ScriptStatusToColorConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean script status to a color.\n /// \n public class ScriptStatusToColorConverter : IValueConverter\n {\n /// \n /// Converts a boolean value to a color.\n /// \n /// The boolean value indicating if scripts are active.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// A color based on the script status.\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isActive)\n {\n // Return green if scripts are active, gray if not\n return isActive \n ? new SolidColorBrush(Color.FromRgb(0, 200, 83)) // Green for active\n : new SolidColorBrush(Color.FromRgb(150, 150, 150)); // Gray for inactive\n }\n \n return new SolidColorBrush(Colors.Gray);\n }\n \n /// \n /// Converts a color back to a boolean value.\n /// \n /// The color to convert back.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// A boolean value based on the color.\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IDialogService.cs", "using System.Threading.Tasks;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides functionality for displaying dialog boxes to the user.\n /// \n public interface IDialogService\n {\n /// \n /// Displays a message to the user.\n /// \n /// The message to display.\n /// The title of the dialog box.\n void ShowMessage(string message, string title = \"\");\n\n /// \n /// Displays a confirmation dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// The text for the OK button.\n /// The text for the Cancel button.\n /// True if the user confirmed; otherwise, false.\n Task ShowConfirmationAsync(string message, string title = \"\", string okButtonText = \"OK\", string cancelButtonText = \"Cancel\");\n\n /// \n /// Displays an information dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// The text for the button.\n /// A task representing the asynchronous operation.\n Task ShowInformationAsync(string message, string title = \"Information\", string buttonText = \"OK\");\n\n /// \n /// Displays a warning dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// The text for the button.\n /// A task representing the asynchronous operation.\n Task ShowWarningAsync(string message, string title = \"Warning\", string buttonText = \"OK\");\n\n /// \n /// Displays an error dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// The text for the button.\n /// A task representing the asynchronous operation.\n Task ShowErrorAsync(string message, string title = \"Error\", string buttonText = \"OK\");\n\n /// \n /// Displays an input dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// The default value for the input.\n /// The value entered by the user, or null if the user canceled.\n Task ShowInputAsync(string message, string title = \"\", string defaultValue = \"\");\n\n /// \n /// Displays a Yes/No/Cancel dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// True if the user clicked Yes, false if the user clicked No, null if the user clicked Cancel.\n Task ShowYesNoCancelAsync(string message, string title = \"\");\n\n /// \n /// Displays a unified configuration save dialog.\n /// \n /// The title of the dialog box.\n /// The description of the dialog.\n /// A dictionary of section names, their availability, and item counts.\n /// A dictionary of section names and their final selection state, or null if the user canceled.\n Task> ShowUnifiedConfigurationSaveDialogAsync(string title, string description, Dictionary sections);\n\n /// \n /// Displays a unified configuration import dialog.\n /// \n /// The title of the dialog box.\n /// The description of the dialog.\n /// A dictionary of section names, their availability, and item counts.\n /// A dictionary of section names and their final selection state, or null if the user canceled.\n Task> ShowUnifiedConfigurationImportDialogAsync(string title, string description, Dictionary sections);\n\n /// \n /// Displays a donation dialog.\n /// \n /// The title of the dialog box.\n /// The support message to display.\n /// The footer text.\n /// A task representing the asynchronous operation, with a tuple containing the dialog result (whether the user clicked Yes or No) and whether the \"Don't show again\" checkbox was checked.\n Task<(bool? Result, bool DontShowAgain)> ShowDonationDialogAsync(string title, string supportMessage, string footerText);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Exceptions/InstallationStatusException.cs", "using System;\n\nnamespace Winhance.Core.Features.SoftwareApps.Exceptions\n{\n /// \n /// Exception thrown when there is an error with installation status operations.\n /// \n public class InstallationStatusException : Exception\n {\n /// \n /// Initializes a new instance of the class.\n /// \n public InstallationStatusException() : base()\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message.\n /// \n /// The message that describes the error.\n public InstallationStatusException(string message) : base(message)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message\n /// and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception.\n public InstallationStatusException(string message, Exception innerException) : base(message, innerException)\n {\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IScriptFactory.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Factory for creating script objects.\n /// \n public interface IScriptFactory\n {\n /// \n /// Creates a batch removal script.\n /// \n /// The names of the applications to remove.\n /// Dictionary mapping app names to registry settings.\n /// Dictionary mapping app names to their subpackages.\n /// A removal script object.\n RemovalScript CreateBatchRemovalScript(\n List appNames,\n Dictionary> appsWithRegistry,\n Dictionary appSubPackages = null);\n\n /// \n /// Creates a single app removal script.\n /// \n /// The app to remove.\n /// A removal script object.\n RemovalScript CreateSingleAppRemovalScript(AppInfo app);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/LogLevelToColorConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a LogLevel to a color for display in the UI.\n /// \n public class LogLevelToColorConverter : IValueConverter\n {\n /// \n /// Converts a LogLevel to a color.\n /// \n /// The LogLevel value.\n /// The target type.\n /// The converter parameter.\n /// The culture information.\n /// A color brush based on the log level.\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is LogLevel level)\n {\n switch (level)\n {\n case LogLevel.Error:\n return new SolidColorBrush(Colors.Red);\n case LogLevel.Warning:\n return new SolidColorBrush(Colors.Orange);\n case LogLevel.Debug:\n return new SolidColorBrush(Colors.Gray);\n default:\n return new SolidColorBrush(Colors.White);\n }\n }\n return new SolidColorBrush(Colors.White);\n }\n\n /// \n /// Converts a color back to a LogLevel (not implemented).\n /// \n /// The color value.\n /// The target type.\n /// The converter parameter.\n /// The culture information.\n /// Not implemented.\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/GamingandPerformanceOptimizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class GamingandPerformanceOptimizations\n{\n public static OptimizationGroup GetGamingandPerformanceOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Gaming and Performance\",\n Category = OptimizationCategory.GamingandPerformance,\n Settings = new List\n {\n new OptimizationSetting\n {\n Id = \"gaming-xbox-game-dvr\",\n Name = \"Xbox Game DVR\",\n Description = \"Controls Xbox Game DVR functionality\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Game Recording\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"System\\\\GameConfigStore\",\n Name = \"GameDVR_Enabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Game DVR is enabled\n DisabledValue = 0, // When toggle is OFF, Game DVR is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Game Bar and Game DVR functionality\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\GameConfigStore\",\n Name = \"AllowGameDVR\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Xbox Game DVR is enabled\n DisabledValue = 0, // When toggle is OFF, Xbox Game DVR is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Xbox GameDVR functionality\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"gaming-game-bar-controller\",\n Name = \"Game Bar Controller Access\",\n Description = \"Allow your controller to open Game Bar\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Game Bar\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\GameBar\",\n Name = \"UseNexusForGameBarEnabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, controller access is enabled\n DisabledValue = 0, // When toggle is OFF, controller access is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Xbox Game Bar access via game controller\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-game-mode\",\n Name = \"Game Mode\",\n Description = \"Controls Game Mode for optimized gaming performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Game Mode\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\GameBar\",\n Name = \"AutoGameModeEnabled\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Game Mode is enabled\n DisabledValue = 0, // When toggle is OFF, Game Mode is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Game Mode for optimized gaming performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-directx-optimizations\",\n Name = \"DirectX Optimizations\",\n Description = \"Changes DirectX settings for optimal gaming performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"DirectX\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\DirectX\\\\UserGpuPreferences\",\n Name = \"DirectXUserGlobalSettings\",\n RecommendedValue = \"SwapEffectUpgradeEnable=1;VRROptimizeEnable=0;\", // For backward compatibility\n EnabledValue = \"SwapEffectUpgradeEnable=1;VRROptimizeEnable=0;\", // When toggle is ON, optimizations are enabled\n DisabledValue = \"\", // When toggle is OFF, use default settings\n ValueType = RegistryValueKind.String,\n DefaultValue = \"SwapEffectUpgradeEnable=1;VRROptimizeEnable=0;\", // Default value when registry key exists but no value is set\n Description =\n \"Controls DirectX settings for optimal gaming performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-nvidia-sharpening\",\n Name = \"Old Nvidia Sharpening\",\n Description = \"Controls Nvidia sharpening for image quality\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Nvidia\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"Software\\\\NVIDIA Corporation\\\\Global\\\\FTS\",\n Name = \"EnableGR535\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, old Nvidia sharpening is enabled (0 = enabled for this setting)\n DisabledValue = 1, // When toggle is OFF, old Nvidia sharpening is disabled (1 = disabled for this setting)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Nvidia sharpening for image quality\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-high-precision-event-timer\",\n Name = \"High Precision Event Timer\",\n Description = \"Controls the High Precision Event Timer (HPET) for improved system performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CommandSettings = new List\n {\n new CommandSetting\n {\n Id = \"hpet-platform-clock\",\n Category = \"Gaming\",\n Description = \"Controls the platform clock setting for HPET\",\n EnabledCommand = \"bcdedit /set useplatformclock true\",\n DisabledCommand = \"bcdedit /deletevalue useplatformclock\",\n RequiresElevation = true,\n IsPrimary = true\n },\n new CommandSetting\n {\n Id = \"hpet-dynamic-tick\",\n Category = \"Gaming\",\n Description = \"Controls the dynamic tick setting for HPET\",\n EnabledCommand = \"bcdedit /set disabledynamictick no\",\n DisabledCommand = \"bcdedit /set disabledynamictick yes\",\n RequiresElevation = true,\n IsPrimary = false\n }\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"gaming-system-responsiveness\",\n Name = \"System Responsiveness for Games\",\n Description = \"Controls system responsiveness for multimedia applications\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Multimedia\\\\SystemProfile\",\n Name = \"SystemResponsiveness\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, system responsiveness is optimized for games (0 = prioritize foreground)\n DisabledValue = 10, // When toggle is OFF, system responsiveness is balanced (10 = default Windows value)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 10, // Default value when registry key exists but no value is set\n Description =\n \"Controls system responsiveness for multimedia applications\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-network-throttling\",\n Name = \"Network Throttling for Gaming\",\n Description = \"Controls network throttling for optimal gaming performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Multimedia\\\\SystemProfile\",\n Name = \"NetworkThrottlingIndex\",\n RecommendedValue = 10, // For backward compatibility\n EnabledValue = 10, // When toggle is ON, network throttling is disabled (10 = disabled)\n DisabledValue = 5, // When toggle is OFF, network throttling is enabled (default Windows value)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 5, // Default value when registry key exists but no value is set\n Description =\n \"Controls network throttling for optimal gaming performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-gpu-priority\",\n Name = \"GPU Priority for Gaming\",\n Description = \"Controls GPU priority for gaming performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Multimedia\\\\SystemProfile\\\\Tasks\\\\Games\",\n Name = \"GPU Priority\",\n RecommendedValue = 8, // For backward compatibility\n EnabledValue = 8, // When toggle is ON, GPU priority is high (8 = high priority)\n DisabledValue = 2, // When toggle is OFF, GPU priority is normal (default Windows value)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls GPU priority for gaming performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-cpu-priority\",\n Name = \"CPU Priority for Gaming\",\n Description = \"Controls CPU priority for gaming performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Multimedia\\\\SystemProfile\\\\Tasks\\\\Games\",\n Name = \"Priority\",\n RecommendedValue = 6, // For backward compatibility\n EnabledValue = 6, // When toggle is ON, CPU priority is high (6 = high priority)\n DisabledValue = 2, // When toggle is OFF, CPU priority is normal (default Windows value)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls CPU priority for gaming performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-scheduling-category\",\n Name = \"High Scheduling Category for Gaming\",\n Description = \"Controls scheduling category for games\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Multimedia\\\\SystemProfile\\\\Tasks\\\\Games\",\n Name = \"Scheduling Category\",\n RecommendedValue = \"High\", // For backward compatibility\n EnabledValue = \"High\", // When toggle is ON, scheduling category is high\n DisabledValue = \"Medium\", // When toggle is OFF, scheduling category is medium (default Windows value)\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Medium\", // Default value when registry key exists but no value is set\n Description = \"Controls scheduling category for games\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-gpu-scheduling\",\n Name = \"Hardware-Accelerated GPU Scheduling\",\n Description = \"Controls hardware-accelerated GPU scheduling\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"System\\\\CurrentControlSet\\\\Control\\\\GraphicsDrivers\",\n Name = \"HwSchMode\",\n RecommendedValue = 2, // For backward compatibility\n EnabledValue = 2, // When toggle is ON, hardware-accelerated GPU scheduling is enabled\n DisabledValue = 1, // When toggle is OFF, hardware-accelerated GPU scheduling is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls hardware-accelerated GPU scheduling\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-win32-priority\",\n Name = \"Win32 Priority Separation\",\n Description = \"Controls Win32 priority separation for program performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"System\\\\CurrentControlSet\\\\Control\\\\PriorityControl\",\n Name = \"Win32PrioritySeparation\",\n RecommendedValue = 38, // For backward compatibility\n EnabledValue = 38, // When toggle is ON, priority is set for best performance of programs\n DisabledValue = 2, // When toggle is OFF, priority is set to default Windows value\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description =\n \"Controls Win32 priority separation for program performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-storage-sense\",\n Name = \"Storage Sense\",\n Description = \"Controls Storage Sense functionality\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\StorageSense\",\n Name = \"AllowStorageSenseGlobal\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Storage Sense is enabled\n DisabledValue = 0, // When toggle is OFF, Storage Sense is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Storage Sense functionality\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-animations\",\n Name = \"UI Animations\",\n Description = \"Controls UI animations for improved performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Visual Effects\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\\\\WindowMetrics\",\n Name = \"MinAnimate\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, animations are enabled\n DisabledValue = 0, // When toggle is OFF, animations are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls UI animations for improved performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-autostart-delay\",\n Name = \"Startup Delay for Apps\",\n Description = \"Controls startup delay for applications\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Startup\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Serialize\",\n Name = \"StartupDelayInMSec\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 10000, // When toggle is ON, startup delay is enabled (10 seconds)\n DisabledValue = 0, // When toggle is OFF, startup delay is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls startup delay for applications\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-background-services\",\n Name = \"Optimize Background Services\",\n Description = \"Controls background services for better performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Services\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\",\n Name = \"ServicesPipeTimeout\",\n RecommendedValue = 60000, // For backward compatibility\n EnabledValue = 30000, // When toggle is ON, services timeout is reduced (30 seconds)\n DisabledValue = 60000, // When toggle is OFF, services timeout is default (60 seconds)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 60000, // Default value when registry key exists but no value is set\n Description = \"Controls background services for better performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-desktop-composition\",\n Name = \"Desktop Composition Effects\",\n Description = \"Controls desktop composition effects\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Visual Effects\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\DWM\",\n Name = \"CompositionPolicy\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, desktop composition is enabled\n DisabledValue = 0, // When toggle is OFF, desktop composition is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls desktop composition effects\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-fast-startup\",\n Name = \"Fast Startup\",\n Description = \"Controls fast startup feature\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Startup\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Power\",\n Name = \"HiberbootEnabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, fast startup is enabled\n DisabledValue = 0, // When toggle is OFF, fast startup is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls fast startup feature\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-explorer-search\",\n Name = \"Optimize File Explorer Search\",\n Description = \"Controls file explorer search indexing\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Search\\\\Preferences\",\n Name = \"WholeFileSystem\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, search includes whole file system\n DisabledValue = 0, // When toggle is OFF, search is limited to indexed locations\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls file explorer search indexing\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-menu-animations\",\n Name = \"Menu Animations\",\n Description = \"Controls menu animations\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Visual Effects\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"MenuShowDelay\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 400, // When toggle is ON, menu animations are enabled (default delay)\n DisabledValue = 0, // When toggle is OFF, menu animations are disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = 400, // Default value when registry key exists but no value is set\n Description = \"Controls menu animations\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-prefetch\",\n Name = \"Prefetch Feature\",\n Description = \"Controls Windows prefetch feature\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Memory Management\\\\PrefetchParameters\",\n Name = \"EnablePrefetcher\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 3, // When toggle is ON, prefetch is enabled (3 = both application and boot prefetching)\n DisabledValue = 0, // When toggle is OFF, prefetch is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls Windows prefetch feature\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-remote-assistance\",\n Name = \"Remote Assistance\",\n Description = \"Controls remote assistance feature\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Services\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Remote Assistance\",\n Name = \"fAllowToGetHelp\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, remote assistance is enabled\n DisabledValue = 0, // When toggle is OFF, remote assistance is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls remote assistance feature\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-superfetch\",\n Name = \"Superfetch Service\",\n Description = \"Controls superfetch/SysMain service\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Memory Management\\\\PrefetchParameters\",\n Name = \"EnableSuperfetch\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 3, // When toggle is ON, superfetch is enabled (3 = full functionality)\n DisabledValue = 0, // When toggle is OFF, superfetch is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls superfetch/SysMain service\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-visual-effects\",\n Name = \"Optimize Visual Effects\",\n Description = \"Controls visual effects for best performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Visual Effects\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\VisualEffects\",\n Name = \"VisualFXSetting\",\n RecommendedValue = 2, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, visual effects are set to \"best appearance\" (1)\n DisabledValue = 2, // When toggle is OFF, visual effects are set to \"best performance\" (2)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls visual effects for best performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-mouse-precision\",\n Name = \"Enhanced Pointer Precision\",\n Description = \"Controls enhanced pointer precision (mouse acceleration)\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Mouse Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"MouseSpeed\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, enhanced pointer precision is enabled\n DisabledValue = 0, // When toggle is OFF, enhanced pointer precision is disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Controls enhanced pointer precision (mouse acceleration)\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-mouse-threshold1\",\n Name = \"Mouse Acceleration Threshold 1\",\n Description = \"Controls mouse acceleration threshold 1\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Mouse Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"MouseThreshold1\",\n RecommendedValue = 0,\n EnabledValue = 6, // When toggle is ON, mouse threshold 1 is enabled (default value)\n DisabledValue = 0, // When toggle is OFF, mouse threshold 1 is disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls mouse acceleration threshold 1\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-mouse-threshold2\",\n Name = \"Mouse Acceleration Threshold 2\",\n Description = \"Controls mouse acceleration threshold 2\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Mouse Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"MouseThreshold2\",\n RecommendedValue = 0,\n EnabledValue = 10, // When toggle is ON, mouse threshold 2 is enabled (default value)\n DisabledValue = 0, // When toggle is OFF, mouse threshold 2 is disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls mouse acceleration threshold 2\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-set-mouse-sensitivity\",\n Name = \"Set Mouse Sensitivity\",\n Description = \"Sets mouse sensitivity to 10\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"MouseSensitivity\",\n RecommendedValue = 10,\n EnabledValue = 10,\n DisabledValue = \"\", // Sets to default\n ValueType = RegistryValueKind.String,\n DefaultValue = \"\", // Default value when registry key exists but no value is set\n Description = \"Sets mouse sensitivity to 10\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-set-smooth-mouse-x-curve\",\n Name = \"Set Smooth Mouse X Curve\",\n Description = \"Sets SmoothMouseXCurve\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"SmoothMouseXCurve\",\n RecommendedValue = new byte[]\n {\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xC0,\n 0xCC,\n 0x0C,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x80,\n 0x99,\n 0x19,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x40,\n 0x66,\n 0x26,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x33,\n 0x33,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n },\n ValueType = RegistryValueKind.Binary,\n DefaultValue = new byte[]\n {\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xC0,\n 0xCC,\n 0x0C,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x80,\n 0x99,\n 0x19,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x40,\n 0x66,\n 0x26,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x33,\n 0x33,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n },\n Description = \"Sets SmoothMouseXCurve\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-set-smooth-mouse-y-curve\",\n Name = \"Set Smooth Mouse Y Curve\",\n Description = \"Sets SmoothMouseYCurve\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"SmoothMouseYCurve\",\n RecommendedValue = new byte[]\n {\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x38,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x70,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xA8,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xE0,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n },\n ValueType = RegistryValueKind.Binary,\n DefaultValue = new byte[]\n {\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x38,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x70,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xA8,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xE0,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n },\n Description = \"Sets SmoothMouseYCurve\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-animations\",\n Name = \"System Animations\",\n Description = \"Controls animations and visual effects\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"UserPreferencesMask\",\n RecommendedValue = new byte[]\n {\n 0x90,\n 0x12,\n 0x03,\n 0x80,\n 0x10,\n 0x00,\n 0x00,\n 0x00,\n },\n EnabledValue = new byte[]\n {\n 0x9E,\n 0x3E,\n 0x07,\n 0x80,\n 0x12,\n 0x00,\n 0x00,\n 0x00,\n }, // When toggle is ON, animations are enabled\n DisabledValue = new byte[]\n {\n 0x90,\n 0x12,\n 0x03,\n 0x80,\n 0x10,\n 0x00,\n 0x00,\n 0x00,\n }, // When toggle is OFF, animations are disabled\n ValueType = RegistryValueKind.Binary,\n DefaultValue = new byte[]\n {\n 0x90,\n 0x12,\n 0x03,\n 0x80,\n 0x10,\n 0x00,\n 0x00,\n 0x00,\n },\n Description = \"Controls animations and visual effects\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-menu-show-delay\",\n Name = \"Menu Show Delay\",\n Description = \"Controls menu show delay\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"MenuShowDelay\",\n RecommendedValue = 0,\n EnabledValue = 400, // When toggle is ON, menu show delay is enabled (default value)\n DisabledValue = 0, // When toggle is OFF, menu show delay is disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = 400, // Default value when registry key exists but no value is set\n Description = \"Controls menu show delay\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-set-visual-effects\",\n Name = \"Set Visual Effects\",\n Description = \"Sets appearance options to custom\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\VisualEffects\",\n Name = \"VisualFXSetting\",\n RecommendedValue = 3,\n EnabledValue = 3,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Sets appearance options to custom\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-taskbar-animations\",\n Name = \"Taskbar Animations\",\n Description = \"Controls taskbar animations\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"TaskbarAnimations\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, taskbar animations are enabled\n DisabledValue = 0, // When toggle is OFF, taskbar animations are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls taskbar animations\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"background-apps\",\n Name = \"Let Apps Run in Background\",\n Description = \"Controls whether apps can run in the background\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Background Apps\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\AppPrivacy\",\n Name = \"LetAppsRunInBackground\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, background apps are enabled\n DisabledValue = 0, // When toggle is OFF, background apps are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls whether apps can run in the background\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-alt-tab-filter\",\n Name = \"Alt+Tab Filter\",\n Description = \"Sets Alt+Tab to show open windows only\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"MultiTaskingAltTabFilter\",\n RecommendedValue = 3,\n EnabledValue = 3,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Sets Alt+Tab to show open windows only\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IScriptBuilderService.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for building script content.\n /// \n public interface IScriptBuilderService\n {\n /// \n /// Builds a script for removing packages.\n /// \n /// The names of the packages to remove.\n /// The script content.\n string BuildPackageRemovalScript(IEnumerable packageNames);\n\n /// \n /// Builds a script for removing capabilities.\n /// \n /// The names of the capabilities to remove.\n /// The script content.\n string BuildCapabilityRemovalScript(IEnumerable capabilityNames);\n\n /// \n /// Builds a script for removing features.\n /// \n /// The names of the features to remove.\n /// The script content.\n string BuildFeatureRemovalScript(IEnumerable featureNames);\n\n /// \n /// Builds a script for registry operations.\n /// \n /// Dictionary mapping app names to registry settings.\n /// The script content.\n string BuildRegistryScript(Dictionary> registrySettings);\n\n /// \n /// Builds a complete removal script.\n /// \n /// The names of the packages to remove.\n /// The names of the capabilities to remove.\n /// The names of the features to remove.\n /// Dictionary mapping app names to registry settings.\n /// Dictionary mapping app names to their subpackages.\n /// The script content.\n string BuildCompleteRemovalScript(\n IEnumerable packageNames,\n IEnumerable capabilityNames,\n IEnumerable featureNames,\n Dictionary> registrySettings,\n Dictionary subPackages);\n\n /// \n /// Builds a script for removing a single app.\n /// \n /// The app to remove.\n /// The script content.\n string BuildSingleAppRemovalScript(AppInfo app);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Exceptions/InstallationException.cs", "using System;\n\nnamespace Winhance.Core.Models.Exceptions\n{\n public class InstallationException : Exception \n {\n public bool IsRecoverable { get; }\n public string ItemName { get; }\n \n public InstallationException(string itemName, string message, \n bool isRecoverable = false, Exception? inner = null)\n : base(message, inner)\n {\n ItemName = itemName;\n IsRecoverable = isRecoverable;\n }\n }\n\n public class InstallationCancelledException : InstallationException\n {\n public InstallationCancelledException(string itemName)\n : base(itemName, $\"Installation cancelled for {itemName}\", true) { }\n }\n\n public class DependencyInstallationException : InstallationException\n {\n public string DependencyName { get; }\n\n public DependencyInstallationException(string itemName, string dependencyName)\n : base(itemName, $\"Dependency {dependencyName} failed to install for {itemName}\", true)\n {\n DependencyName = dependencyName;\n }\n }\n\n public class ItemOperationException : InstallationException\n {\n public ItemOperationException(string itemName, string operation, string message, \n bool isRecoverable = false, Exception? inner = null)\n : base(itemName, $\"{operation} failed for {itemName}: {message}\", isRecoverable, inner) { }\n }\n\n public class RemovalException : ItemOperationException\n {\n public RemovalException(string itemName, string message, \n bool isRecoverable = false, Exception? inner = null)\n : base(itemName, \"removal\", message, isRecoverable, inner) { }\n }\n\n public class BatchOperationException : InstallationException\n {\n public int FailedCount { get; }\n public string OperationType { get; }\n\n public BatchOperationException(string operationType, int failedCount, int totalCount)\n : base(\"multiple items\", \n $\"{operationType} failed for {failedCount} of {totalCount} items\", \n true)\n {\n OperationType = operationType;\n FailedCount = failedCount;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Models/ExternalAppSettingItem.cs", "using System.Collections.Generic;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Models\n{\n /// \n /// Adapter class that wraps an ExternalApp and implements ISettingItem.\n /// \n public class ExternalAppSettingItem : ISettingItem\n {\n private readonly ExternalApp _externalApp;\n \n public ExternalAppSettingItem(ExternalApp externalApp)\n {\n _externalApp = externalApp;\n \n // Initialize properties required by ISettingItem\n Id = externalApp.PackageName;\n Name = externalApp.Name;\n Description = externalApp.Description;\n IsSelected = externalApp.IsSelected;\n GroupName = externalApp.Category;\n IsVisible = true;\n ControlType = ControlType.BinaryToggle;\n Dependencies = new List();\n \n // Create a command that does nothing (placeholder)\n ApplySettingCommand = new RelayCommand(() => { });\n }\n \n // ISettingItem implementation\n public string Id { get; set; }\n public string Name { get; set; }\n public string Description { get; set; }\n public bool IsSelected { get; set; }\n public string GroupName { get; set; }\n public bool IsVisible { get; set; }\n public ControlType ControlType { get; set; }\n public List Dependencies { get; set; }\n public bool IsUpdatingFromCode { get; set; }\n public ICommand ApplySettingCommand { get; }\n \n // Method to convert back to ExternalApp\n public ExternalApp ToExternalApp()\n {\n // Update the original ExternalApp with any changes\n _externalApp.IsSelected = IsSelected;\n return _externalApp;\n }\n \n // Static method to convert a collection of ExternalApps to ExternalAppSettingItems\n public static IEnumerable FromExternalApps(IEnumerable externalApps)\n {\n foreach (var app in externalApps)\n {\n yield return new ExternalAppSettingItem(app);\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/ScriptStatusToTextConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean script status to a descriptive text.\n /// \n public class ScriptStatusToTextConverter : IValueConverter\n {\n /// \n /// Converts a boolean value to a descriptive text.\n /// \n /// The boolean value indicating if scripts are active.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// A descriptive text based on the script status.\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isActive)\n {\n return isActive \n ? \"Winhance Removing Apps\" \n : \"No Active Removals\";\n }\n \n return \"Unknown Status\";\n }\n \n /// \n /// Converts a descriptive text back to a boolean value.\n /// \n /// The text to convert back.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// A boolean value based on the text.\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/ResponsiveScrollViewer.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// A custom ScrollViewer that handles mouse wheel events regardless of cursor position\n /// and provides enhanced scrolling speed\n /// \n public class ResponsiveScrollViewer : ScrollViewer\n {\n #region Dependency Properties\n\n /// \n /// Dependency property for ScrollSpeedMultiplier\n /// \n public static readonly DependencyProperty ScrollSpeedMultiplierProperty =\n DependencyProperty.RegisterAttached(\n \"ScrollSpeedMultiplier\",\n typeof(double),\n typeof(ResponsiveScrollViewer),\n new PropertyMetadata(10.0));\n\n /// \n /// Gets the scroll speed multiplier for a ScrollViewer\n /// \n public static double GetScrollSpeedMultiplier(DependencyObject obj)\n {\n return (double)obj.GetValue(ScrollSpeedMultiplierProperty);\n }\n\n /// \n /// Sets the scroll speed multiplier for a ScrollViewer\n /// \n public static void SetScrollSpeedMultiplier(DependencyObject obj, double value)\n {\n obj.SetValue(ScrollSpeedMultiplierProperty, value);\n }\n\n #endregion\n\n /// \n /// Static constructor to register event handlers for all ScrollViewers\n /// \n static ResponsiveScrollViewer()\n {\n // Register class handler for the PreviewMouseWheel event\n EventManager.RegisterClassHandler(\n typeof(ScrollViewer),\n UIElement.PreviewMouseWheelEvent,\n new MouseWheelEventHandler(OnPreviewMouseWheel),\n true);\n }\n\n /// \n /// Constructor\n /// \n public ResponsiveScrollViewer()\n {\n // No need to register for the event here anymore as we're using a class handler\n }\n\n /// \n /// Handles the PreviewMouseWheel event for all ScrollViewers\n /// \n private static void OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)\n {\n if (sender is ScrollViewer scrollViewer)\n {\n // Get the current vertical offset\n double currentOffset = scrollViewer.VerticalOffset;\n\n // Get the scroll speed multiplier (use default value if not set)\n double speedMultiplier = GetScrollSpeedMultiplier(scrollViewer);\n\n // Calculate the scroll amount based on the mouse wheel delta and speed multiplier\n double scrollAmount = (SystemParameters.WheelScrollLines * speedMultiplier);\n\n if (e.Delta < 0)\n {\n // Scroll down when the mouse wheel is rotated down\n scrollViewer.ScrollToVerticalOffset(currentOffset + scrollAmount);\n }\n else\n {\n // Scroll up when the mouse wheel is rotated up\n scrollViewer.ScrollToVerticalOffset(currentOffset - scrollAmount);\n }\n\n // Mark the event as handled to prevent it from bubbling up\n e.Handled = true;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Interfaces/IVerificationMethod.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces\n{\n /// \n /// Defines the contract for different verification methods to check if a package is installed.\n /// \n public interface IVerificationMethod\n {\n /// \n /// Gets the name of the verification method.\n /// \n string Name { get; }\n\n /// \n /// Gets the priority of this verification method. Lower numbers indicate higher priority.\n /// \n int Priority { get; }\n\n /// \n /// Verifies if a package is installed using this verification method.\n /// \n /// The ID of the package to verify.\n /// Optional version to verify. If null, only the presence is checked.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the verification result.\n Task VerifyAsync(\n string packageId, \n string version = null, \n CancellationToken cancellationToken = default);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IRegistryService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides access to the Windows registry.\n /// \n public interface IRegistryService\n {\n /// \n /// Sets a value in the registry.\n /// \n /// The registry key path.\n /// The name of the value to set.\n /// The value to set.\n /// The type of the value.\n /// True if the operation succeeded; otherwise, false.\n bool SetValue(string keyPath, string valueName, object value, Microsoft.Win32.RegistryValueKind valueKind);\n\n /// \n /// Gets a value from the registry.\n /// \n /// The registry key path.\n /// The name of the value to get.\n /// The value from the registry, or null if it doesn't exist.\n object? GetValue(string keyPath, string valueName);\n\n /// \n /// Deletes a value from the registry.\n /// \n /// The registry key path.\n /// The name of the value to delete.\n /// True if the operation succeeded; otherwise, false.\n bool DeleteValue(string keyPath, string valueName);\n\n /// \n /// Deletes a value from the registry using hive and subkey.\n /// \n /// The registry hive.\n /// The registry subkey.\n /// The name of the value to delete.\n /// True if the operation succeeded; otherwise, false.\n Task DeleteValue(RegistryHive hive, string subKey, string valueName);\n\n /// \n /// Exports a registry key to a string.\n /// \n /// The registry key path to export.\n /// Whether to include subkeys in the export.\n /// The exported registry key as a string.\n Task ExportKey(string keyPath, bool includeSubKeys);\n\n /// \n /// Gets the status of a registry setting.\n /// \n /// The registry setting to check.\n /// The status of the registry setting.\n Task GetSettingStatusAsync(RegistrySetting setting);\n\n /// \n /// Gets the current value of a registry setting.\n /// \n /// The registry setting to check.\n /// The current value of the registry setting, or null if it doesn't exist.\n Task GetCurrentValueAsync(RegistrySetting setting);\n\n /// \n /// Determines whether a registry key exists.\n /// \n /// The registry key path.\n /// True if the key exists; otherwise, false.\n bool KeyExists(string keyPath);\n\n /// \n /// Creates a registry key.\n /// \n /// The registry key path.\n /// True if the operation succeeded; otherwise, false.\n bool CreateKey(string keyPath);\n\n /// \n /// Creates a registry key if it doesn't exist.\n /// \n /// The full path to the registry key.\n /// True if the key exists or was created successfully; otherwise, false.\n bool CreateKeyIfNotExists(string keyPath);\n\n /// \n /// Determines whether a registry value exists.\n /// \n /// The registry key path.\n /// The name of the value to check.\n /// True if the value exists; otherwise, false.\n bool ValueExists(string keyPath, string valueName);\n\n /// \n /// Deletes a registry key and all its values.\n /// \n /// The full path to the registry key to delete.\n /// True if the key was successfully deleted, false otherwise.\n bool DeleteKey(string keyPath);\n\n /// \n /// Deletes a registry key and all its values.\n /// \n /// The registry hive.\n /// The subkey path.\n /// True if the key was successfully deleted, false otherwise.\n Task DeleteKey(RegistryHive hive, string subKey);\n\n /// \n /// Tests a registry setting.\n /// \n /// The registry key path.\n /// The name of the value to test.\n /// The desired value.\n /// The status of the registry setting.\n RegistrySettingStatus TestRegistrySetting(string keyPath, string valueName, object desiredValue);\n\n /// \n /// Backs up the Windows registry.\n /// \n /// The path where the backup should be stored.\n /// True if the operation succeeded; otherwise, false.\n Task BackupRegistry(string backupPath);\n\n /// \n /// Restores the Windows registry from a backup.\n /// \n /// The path to the backup file.\n /// True if the operation succeeded; otherwise, false.\n Task RestoreRegistry(string backupPath);\n\n /// \n /// Applies customization settings to the registry.\n /// \n /// The settings to apply.\n /// True if all settings were applied successfully; otherwise, false.\n Task ApplyCustomizations(List settings);\n\n /// \n /// Restores customization settings to their default values.\n /// \n /// The settings to restore.\n /// True if all settings were restored successfully; otherwise, false.\n Task RestoreCustomizationDefaults(List settings);\n\n /// \n /// Applies power plan settings to the registry.\n /// \n /// The settings to apply.\n /// True if all settings were applied successfully; otherwise, false.\n Task ApplyPowerPlanSettings(List settings);\n\n /// \n /// Restores power plan settings to their default values.\n /// \n /// True if all settings were restored successfully; otherwise, false.\n Task RestoreDefaultPowerSettings();\n\n /// \n /// Gets the status of linked registry settings.\n /// \n /// The linked registry settings to check.\n /// The combined status of the linked registry settings.\n Task GetLinkedSettingsStatusAsync(LinkedRegistrySettings linkedSettings);\n\n /// \n /// Applies linked registry settings.\n /// \n /// The linked registry settings to apply.\n /// Whether to enable or disable the settings.\n /// True if all settings were applied successfully; otherwise, false.\n Task ApplyLinkedSettingsAsync(LinkedRegistrySettings linkedSettings, bool enable);\n\n /// \n /// Clears all registry caches to ensure fresh reads\n /// \n void ClearRegistryCaches();\n\n /// \n /// Gets the status of an optimization setting that may contain multiple registry settings.\n /// \n /// The optimization setting to check.\n /// The combined status of the optimization setting.\n Task GetOptimizationSettingStatusAsync(Winhance.Core.Features.Optimize.Models.OptimizationSetting setting);\n\n /// \n /// Applies an optimization setting that may contain multiple registry settings.\n /// \n /// The optimization setting to apply.\n /// Whether to enable or disable the setting.\n /// True if the setting was applied successfully; otherwise, false.\n Task ApplyOptimizationSettingAsync(Winhance.Core.Features.Optimize.Models.OptimizationSetting setting, bool enable);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/ExplorerOptimizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class ExplorerOptimizations\n{\n public static OptimizationGroup GetExplorerOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Explorer\",\n Category = OptimizationCategory.Explorer,\n Settings = new List\n {\n new OptimizationSetting\n {\n Id = \"explorer-long-paths-enabled\",\n Name = \"Long Paths Enabled\",\n Description = \"Controls support for long file paths (up to 32,767 characters)\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\FileSystem\",\n Name = \"LongPathsEnabled\",\n RecommendedValue = 1,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description =\n \"Controls support for long file paths (up to 32,767 characters)\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-block-aad-workplace-join\",\n Name = \"Block AAD Workplace Join\",\n Description = \"Controls 'Allow my organization to manage my device' pop-up\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\System\",\n Name = \"BlockAADWorkplaceJoin\",\n RecommendedValue = 1,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description =\n \"Controls 'Allow my organization to manage my device' pop-up\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-disable-sync-provider-notifications\",\n Name = \"Sync Provider Notifications\",\n Description = \"Controls sync provider notifications visibility\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowSyncProviderNotifications\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls sync provider notifications visibility\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-tablet-mode\",\n Name = \"Tablet Mode\",\n Description = \"Controls Tablet Mode\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"System Interface\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ImmersiveShell\",\n Name = \"TabletMode\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, tablet mode is enabled\n DisabledValue = 0, // When toggle is OFF, tablet mode is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls Tablet Mode\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-desktop-mode-signin\",\n Name = \"Desktop Mode on Sign-in\",\n Description = \"Controls whether the system goes to desktop mode on sign-in\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"System Interface\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ImmersiveShell\",\n Name = \"SignInMode\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, system goes to desktop mode on sign-in\n DisabledValue = 0, // When toggle is OFF, system uses default behavior\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description =\n \"Controls whether the system goes to desktop mode on sign-in\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-voice-typing\",\n Name = \"Voice Typing Button\",\n Description = \"Controls voice typing microphone button\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"Input Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\InputSettings\",\n Name = \"IsVoiceTypingKeyEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, voice typing is enabled\n DisabledValue = 0, // When toggle is OFF, voice typing is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls voice typing microphone button\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-typing-insights\",\n Name = \"Typing Insights\",\n Description = \"Controls typing insights and suggestions\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"Input Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\InputSettings\",\n Name = \"InsightsEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, typing insights are enabled\n DisabledValue = 0, // When toggle is OFF, typing insights are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls typing insights and suggestions\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-suggested-actions\",\n Name = \"Clipboard Suggested Actions\",\n Description = \"Controls suggested actions for clipboard content\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"System Interface\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\SmartActionPlatform\\\\SmartClipboard\",\n Name = \"Disabled\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, suggested actions are enabled\n DisabledValue = 1, // When toggle is OFF, suggested actions are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls suggested actions for clipboard content\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-windows-manage-printer\",\n Name = \"Default Printer Management\",\n Description = \"Controls Windows managing default printer\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"Printer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Windows\",\n Name = \"LegacyDefaultPrinterMode\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, Windows manages default printer\n DisabledValue = 1, // When toggle is OFF, Windows does not manage default printer\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls Windows managing default printer\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-disable-snap-assist\",\n Name = \"Snap Assist\",\n Description = \"Controls Snap Assist feature\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"SnapAssist\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls Snap Assist feature\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-frequent-folders\",\n Name = \"Frequent Folders in Quick Access\",\n Description = \"Controls display of frequent folders in Quick Access\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\",\n Name = \"ShowFrequent\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, frequent folders are shown\n DisabledValue = 0, // When toggle is OFF, frequent folders are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls display of frequent folders in Quick Access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"compress-desktop-wallpaper\",\n Name = \"Compress Desktop Wallpaper\",\n Description = \"Controls compression of desktop wallpaper\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"Desktop Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"JPEGImportQuality\",\n RecommendedValue = 100,\n EnabledValue = 0,\n DisabledValue = 100,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls compression of desktop wallpaper\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-office-files\",\n Name = \"Office Files in Quick Access\",\n Description = \"Controls display of files from Office.com in Quick Access\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\",\n Name = \"ShowCloudFilesInQuickAccess\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, Office.com files are shown\n DisabledValue = 0, // When toggle is OFF, Office.com files are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description =\n \"Controls display of files from Office.com in Quick Access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/PowerOptimizations.cs", "using System;\nusing System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\n/// \n/// Represents a PowerCfg command setting.\n/// \npublic class PowerCfgSetting\n{\n /// \n /// Gets or sets the command to execute.\n /// \n public string Command { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description of the command.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the value to use when the setting is enabled.\n /// \n public string EnabledValue { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the value to use when the setting is disabled.\n /// \n public string DisabledValue { get; set; } = string.Empty;\n}\n\npublic static class PowerOptimizations\n{\n /// \n /// Gets all power optimizations as an OptimizationGroup.\n /// \n /// An OptimizationGroup containing all power settings.\n public static OptimizationGroup GetPowerOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Power\",\n Category = OptimizationCategory.Power,\n Settings = new List\n {\n // Hibernate Settings\n new OptimizationSetting\n {\n Id = \"power-hibernate-enabled\",\n Name = \"Hibernate\",\n Description = \"Controls whether hibernate is enabled\",\n Category = OptimizationCategory.Power,\n GroupName = \"Power Management\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Power\",\n Name = \"HibernateEnabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, hibernate is enabled\n DisabledValue = 0, // When toggle is OFF, hibernate is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls whether hibernate is enabled\",\n IsPrimary = true, // Mark as primary for linked settings\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Power\",\n Name = \"HibernateEnabledDefault\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, hibernate is enabled\n DisabledValue = 0, // When toggle is OFF, hibernate is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls whether hibernate is enabled by default\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.Primary,\n },\n // Video Settings\n new OptimizationSetting\n {\n Id = \"power-video-quality\",\n Name = \"High Video Quality on Battery\",\n Description = \"Controls video quality when running on battery power\",\n Category = OptimizationCategory.Power,\n GroupName = \"Display & Graphics\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\VideoSettings\",\n Name = \"VideoQualityOnBattery\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 1, // High quality (from Recommended)\n DisabledValue = 0, // Lower quality (from Default)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls video quality when running on battery power\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n // Performance Settings\n new OptimizationSetting\n {\n Id = \"power-fast-boot\",\n Name = \"Fast Boot\",\n Description = \"Controls whether fast boot (hybrid boot) is enabled\",\n Category = OptimizationCategory.Power,\n GroupName = \"Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Power\",\n Name = \"HiberbootEnabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // Enable fast boot\n DisabledValue = 0, // Disable fast boot\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls whether fast boot (hybrid boot) is enabled\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Sleep Settings\n new OptimizationSetting\n {\n Id = \"power-sleep-settings\",\n Name = \"Sleep & Hibernate\",\n Description =\n \"When enabled, prevents your computer from going to sleep or hibernating\",\n Category = OptimizationCategory.Power,\n GroupName = \"Sleep & Hibernate\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command = \"powercfg /hibernate off\",\n Description = \"Disable hibernate\",\n EnabledValue = \"/hibernate off\",\n DisabledValue = \"/hibernate on\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n Description = \"Set sleep timeout (AC) to never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n DisabledValue =\n \"/setactive 381b4222-f694-41f0-9685-ff5bb260df2e\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n Description = \"Set sleep timeout (DC) to never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n DisabledValue =\n \"/setactive 381b4222-f694-41f0-9685-ff5bb260df2e\",\n },\n }\n },\n },\n },\n // Display Settings\n new OptimizationSetting\n {\n Id = \"power-display-settings\",\n Name = \"Display Always On\",\n Description =\n \"When enabled, prevents your display from turning off and sets maximum brightness\",\n Category = OptimizationCategory.Power,\n GroupName = \"Display & Graphics\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\",\n Description = \"Set display timeout (AC) to never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000258\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\",\n Description = \"Set display timeout (DC) to never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000258\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 aded5e82-b909-4619-9949-f5d71dac0bcb 0x00000064\",\n Description = \"Set display brightness (AC) to 100%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 aded5e82-b909-4619-9949-f5d71dac0bcb 0x00000064\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 aded5e82-b909-4619-9949-f5d71dac0bcb 0x00000032\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\",\n Description = \"Disable adaptive brightness (AC)\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\",\n Description = \"Disable adaptive brightness (DC)\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 001\",\n },\n }\n },\n },\n },\n // Processor Settings\n new OptimizationSetting\n {\n Id = \"power-processor-settings\",\n Name = \"CPU Performance\",\n Description =\n \"When enabled, sets processor to run at 100% power with active cooling\",\n Category = OptimizationCategory.Power,\n GroupName = \"Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 893dee8e-2bef-41e0-89c6-b55d0929964c 0x00000064\",\n Description = \"Set processor minimum state (AC) to 100%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 893dee8e-2bef-41e0-89c6-b55d0929964c 0x00000064\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 893dee8e-2bef-41e0-89c6-b55d0929964c 0x00000005\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 bc5038f7-23e0-4960-96da-33abaf5935ec 0x00000064\",\n Description = \"Set processor maximum state (AC) to 100%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 bc5038f7-23e0-4960-96da-33abaf5935ec 0x00000064\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 bc5038f7-23e0-4960-96da-33abaf5935ec 0x00000064\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 94d3a615-a899-4ac5-ae2b-e4d8f634367f 001\",\n Description = \"Set cooling policy (AC) to active\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 94d3a615-a899-4ac5-ae2b-e4d8f634367f 001\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 94d3a615-a899-4ac5-ae2b-e4d8f634367f 000\",\n },\n }\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"power-cpu-unpark\",\n Name = \"CPU Core Unparking\",\n Description = \"Controls CPU core parking for better performance\",\n Category = OptimizationCategory.Power,\n GroupName = \"Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SYSTEM\\\\ControlSet001\\\\Control\\\\Power\\\\PowerSettings\\\\54533251-82be-4824-96c1-47b60b740d00\\\\0cc5b647-c1df-4637-891a-dec35c318583\",\n Name = \"ValueMax\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // Unpark CPU cores (from Recommended)\n DisabledValue = 1, // Allow CPU core parking (from Default)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls CPU core parking for better performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"power-throttling\",\n Name = \"Power Throttling\",\n Description = \"Controls power throttling for better performance\",\n Category = OptimizationCategory.Power,\n GroupName = \"Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Power\\\\PowerThrottling\",\n Name = \"PowerThrottlingOff\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 0, // Enable power throttling\n DisabledValue = 1, // Disable power throttling\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls power throttling for better performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Storage Settings\n new OptimizationSetting\n {\n Id = \"power-hard-disk-settings\",\n Name = \"Hard Disks Always On\",\n Description =\n \"When enabled, prevents hard disks from turning off to improve performance\",\n Category = OptimizationCategory.Power,\n GroupName = \"Storage\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\",\n Description = \"Set hard disk timeout (AC) to never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000258\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\",\n Description = \"Set hard disk timeout (DC) to never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000258\",\n },\n }\n },\n },\n },\n // Desktop & Display Settings\n new OptimizationSetting\n {\n Id = \"power-desktop-slideshow-settings\",\n Name = \"Desktop Slideshow\",\n Description =\n \"When enabled, allows desktop background slideshow to run even on battery power\",\n Category = OptimizationCategory.Power,\n GroupName = \"Desktop & Display\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 000\",\n Description =\n \"Desktop slideshow (AC) - Value 0 means Available\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 000\",\n Description =\n \"Desktop slideshow (DC) - Value 0 means Available\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 001\",\n },\n }\n },\n },\n },\n // Network Settings\n new OptimizationSetting\n {\n Id = \"power-wireless-adapter-settings\",\n Name = \"Wi-Fi Performance\",\n Description = \"When enabled, sets wireless adapter to maximum performance mode\",\n Category = OptimizationCategory.Power,\n GroupName = \"Network\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\",\n Description =\n \"Wireless adapter power saving mode (AC) - Maximum performance\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\",\n Description =\n \"Wireless adapter power saving mode (DC) - Maximum performance\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 001\",\n },\n }\n },\n },\n },\n // Sleep & Hibernate Settings\n new OptimizationSetting\n {\n Id = \"power-sleep-hibernate-settings\",\n Name = \"All Sleep Features\",\n Description =\n \"When enabled, disables sleep, hybrid sleep, hibernate, and wake timers\",\n Category = OptimizationCategory.Power,\n GroupName = \"Sleep & Hibernate\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n Description = \"Sleep timeout (AC) - Never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000384\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n Description = \"Sleep timeout (DC) - Never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000384\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\",\n Description = \"Hybrid sleep (AC) - Off\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\",\n Description = \"Hybrid sleep (DC) - Off\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\",\n Description = \"Hibernate timeout (AC) - Never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000384\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\",\n Description = \"Hibernate timeout (DC) - Never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000384\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\",\n Description = \"Wake timers (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\",\n Description = \"Wake timers (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 001\",\n },\n }\n },\n },\n },\n // USB Settings\n new OptimizationSetting\n {\n Id = \"power-usb-settings\",\n Name = \"USB Devices Always On\",\n Description =\n \"When enabled, prevents USB devices from being powered down to save energy\",\n Category = OptimizationCategory.Power,\n GroupName = \"USB\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\",\n Description = \"USB hub timeout (AC) - Never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000258\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\",\n Description = \"USB hub timeout (DC) - Never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000258\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\",\n Description = \"USB selective suspend (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\",\n Description = \"USB selective suspend (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\",\n Description = \"USB 3.0 link power management (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\",\n Description = \"USB 3.0 link power management (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 001\",\n },\n }\n },\n },\n },\n // Power Button Settings\n new OptimizationSetting\n {\n Id = \"power-button-settings\",\n Name = \"Power Button Shutdown\",\n Description =\n \"When enabled, sets power button to immediately shut down your computer\",\n Category = OptimizationCategory.Power,\n GroupName = \"Power Buttons\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\",\n Description = \"Power button action (AC) - Shut down\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\",\n Description = \"Power button action (DC) - Shut down\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 000\",\n },\n }\n },\n },\n },\n // PCI Express Settings\n new OptimizationSetting\n {\n Id = \"power-pci-express-settings\",\n Name = \"PCI Express Performance\",\n Description =\n \"When enabled, disables power saving features for PCI Express devices\",\n Category = OptimizationCategory.Power,\n GroupName = \"PCI Express\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\",\n Description = \"PCI Express power management (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\",\n Description = \"PCI Express power management (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 001\",\n },\n }\n },\n },\n },\n // Video Playback Settings\n new OptimizationSetting\n {\n Id = \"power-video-playback-settings\",\n Name = \"Video Playback Quality\",\n Description =\n \"When enabled, ensures maximum video quality even when on battery power\",\n Category = OptimizationCategory.Power,\n GroupName = \"Video Playback\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\",\n Description =\n \"Video playback quality (AC) - Optimized for performance\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\",\n Description =\n \"Video playback quality (DC) - Optimized for performance\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\",\n Description =\n \"Video quality reduction on battery (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\",\n Description =\n \"Video quality reduction on battery (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 001\",\n },\n }\n },\n },\n },\n // Graphics Settings\n new OptimizationSetting\n {\n Id = \"power-graphics-settings\",\n Name = \"GPU Performance\",\n Description = \"When enabled, sets graphics cards to run at maximum performance\",\n Category = OptimizationCategory.Power,\n GroupName = \"Graphics\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\",\n Description = \"Intel graphics power (AC) - Maximum performance\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\",\n Description = \"Intel graphics power (DC) - Maximum performance\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\",\n Description = \"AMD power slider (AC) - Maximum performance\",\n EnabledValue =\n \"/setacvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\",\n DisabledValue =\n \"/setacvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\",\n Description = \"AMD power slider (DC) - Maximum performance\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\",\n Description = \"ATI PowerPlay (AC) - Enabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\",\n DisabledValue =\n \"/setacvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\",\n Description = \"ATI PowerPlay (DC) - Enabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\",\n Description = \"Switchable graphics (AC) - Maximum performance\",\n EnabledValue =\n \"/setacvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\",\n DisabledValue =\n \"/setacvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\",\n Description = \"Switchable graphics (DC) - Maximum performance\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 000\",\n },\n }\n },\n },\n },\n // Battery Settings\n new OptimizationSetting\n {\n Id = \"power-battery-settings\",\n Name = \"Battery Notifications\",\n Description =\n \"When enabled, turns off low battery and critical battery notifications\",\n Category = OptimizationCategory.Power,\n GroupName = \"Battery\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\",\n Description = \"Critical battery notification (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\",\n Description = \"Critical battery notification (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\",\n Description = \"Critical battery action (AC) - Do nothing\",\n EnabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\",\n Description = \"Critical battery action (DC) - Do nothing\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\",\n Description = \"Low battery level (AC) - 0%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x0000000A\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\",\n Description = \"Low battery level (DC) - 0%\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x0000000A\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\",\n Description = \"Low battery notification (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\",\n Description = \"Low battery notification (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 001\",\n },\n }\n },\n },\n },\n // Battery Saver Settings\n new OptimizationSetting\n {\n Id = \"power-battery-saver-settings\",\n Name = \"Battery Saver\",\n Description =\n \"When enabled, prevents battery saver from activating at any battery level\",\n Category = OptimizationCategory.Power,\n GroupName = \"Battery Saver\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\",\n Description = \"Battery saver brightness (AC) - 100%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\",\n DisabledValue =\n \"/setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000032\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\",\n Description = \"Battery saver brightness (DC) - 100%\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000032\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\",\n Description = \"Battery saver threshold (AC) - 0%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000032\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\",\n Description = \"Battery saver threshold (DC) - 0%\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000032\",\n },\n }\n },\n },\n },\n },\n };\n }\n\n /// \n /// Contains all the powercfg commands for the Ultimate Performance Power Plan.\n /// \n public static class UltimatePerformancePowerPlan\n {\n public static readonly Dictionary PowerCfgCommands = new()\n {\n // Create and set the Ultimate Performance power plan\n {\n \"CreateUltimatePlan\",\n \"/duplicatescheme e9a42b02-d5df-448d-aa00-03f14749eb61 99999999-9999-9999-9999-999999999999\"\n },\n { \"SetActivePlan\", \"/SETACTIVE 99999999-9999-9999-9999-999999999999\" },\n // Hard disk settings\n {\n \"HardDiskTimeout_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\"\n },\n {\n \"HardDiskTimeout_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\"\n },\n // Desktop background slideshow\n {\n \"DesktopSlideshow_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 001\"\n },\n {\n \"DesktopSlideshow_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 001\"\n },\n // Wireless adapter settings\n {\n \"WirelessAdapter_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\"\n },\n {\n \"WirelessAdapter_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\"\n },\n // Sleep settings\n {\n \"SleepTimeout_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\"\n },\n {\n \"SleepTimeout_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\"\n },\n {\n \"HybridSleep_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\"\n },\n {\n \"HybridSleep_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\"\n },\n {\n \"HibernateTimeout_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\"\n },\n {\n \"HibernateTimeout_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\"\n },\n {\n \"WakeTimers_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\"\n },\n {\n \"WakeTimers_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\"\n },\n // USB settings\n {\n \"UsbHubTimeout_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\"\n },\n {\n \"UsbHubTimeout_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\"\n },\n {\n \"UsbSelectiveSuspend_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\"\n },\n {\n \"UsbSelectiveSuspend_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\"\n },\n {\n \"Usb3LinkPower_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\"\n },\n {\n \"Usb3LinkPower_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\"\n },\n // Power button action\n {\n \"PowerButtonAction_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\"\n },\n {\n \"PowerButtonAction_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\"\n },\n // PCI Express\n {\n \"PciExpressPower_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\"\n },\n {\n \"PciExpressPower_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\"\n },\n // Processor settings\n {\n \"ProcessorMinState_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 893dee8e-2bef-41e0-89c6-b55d0929964c 0x00000064\"\n },\n {\n \"ProcessorMinState_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 893dee8e-2bef-41e0-89c6-b55d0929964c 0x00000064\"\n },\n {\n \"CoolingPolicy_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 94d3a615-a899-4ac5-ae2b-e4d8f634367f 001\"\n },\n {\n \"CoolingPolicy_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 94d3a615-a899-4ac5-ae2b-e4d8f634367f 001\"\n },\n {\n \"ProcessorMaxState_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 bc5038f7-23e0-4960-96da-33abaf5935ec 0x00000064\"\n },\n {\n \"ProcessorMaxState_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 bc5038f7-23e0-4960-96da-33abaf5935ec 0x00000064\"\n },\n // Display settings\n {\n \"DisplayTimeout_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\"\n },\n {\n \"DisplayTimeout_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\"\n },\n {\n \"DisplayBrightness_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 aded5e82-b909-4619-9949-f5d71dac0bcb 0x00000064\"\n },\n {\n \"DisplayBrightness_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 aded5e82-b909-4619-9949-f5d71dac0bcb 0x00000064\"\n },\n {\n \"DimmedBrightness_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 f1fbfde2-a960-4165-9f88-50667911ce96 0x00000064\"\n },\n {\n \"DimmedBrightness_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 f1fbfde2-a960-4165-9f88-50667911ce96 0x00000064\"\n },\n {\n \"AdaptiveBrightness_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\"\n },\n {\n \"AdaptiveBrightness_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\"\n },\n // Video playback settings\n {\n \"VideoPlaybackQuality_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\"\n },\n {\n \"VideoPlaybackQuality_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\"\n },\n {\n \"VideoPlaybackQualityOnBattery_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\"\n },\n {\n \"VideoPlaybackQualityOnBattery_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\"\n },\n // Graphics settings\n {\n \"IntelGraphicsPower_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\"\n },\n {\n \"IntelGraphicsPower_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\"\n },\n {\n \"AmdPowerSlider_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\"\n },\n {\n \"AmdPowerSlider_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\"\n },\n {\n \"AtiPowerPlay_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\"\n },\n {\n \"AtiPowerPlay_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\"\n },\n {\n \"SwitchableGraphics_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\"\n },\n {\n \"SwitchableGraphics_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\"\n },\n // Battery settings\n {\n \"CriticalBatteryNotification_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\"\n },\n {\n \"CriticalBatteryNotification_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\"\n },\n {\n \"CriticalBatteryAction_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\"\n },\n {\n \"CriticalBatteryAction_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\"\n },\n {\n \"LowBatteryLevel_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\"\n },\n {\n \"LowBatteryLevel_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\"\n },\n {\n \"CriticalBatteryLevel_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 9a66d8d7-4ff7-4ef9-b5a2-5a326ca2a469 0x00000000\"\n },\n {\n \"CriticalBatteryLevel_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 9a66d8d7-4ff7-4ef9-b5a2-5a326ca2a469 0x00000000\"\n },\n {\n \"LowBatteryNotification_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\"\n },\n {\n \"LowBatteryNotification_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\"\n },\n {\n \"LowBatteryAction_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f d8742dcb-3e6a-4b3c-b3fe-374623cdcf06 000\"\n },\n {\n \"LowBatteryAction_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f d8742dcb-3e6a-4b3c-b3fe-374623cdcf06 000\"\n },\n {\n \"ReserveBatteryLevel_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f f3c5027d-cd16-4930-aa6b-90db844a8f00 0x00000000\"\n },\n {\n \"ReserveBatteryLevel_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f f3c5027d-cd16-4930-aa6b-90db844a8f00 0x00000000\"\n },\n // Battery Saver settings\n {\n \"BatterySaverBrightness_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\"\n },\n {\n \"BatterySaverBrightness_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\"\n },\n {\n \"BatterySaverThreshold_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\"\n },\n {\n \"BatterySaverThreshold_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\"\n },\n };\n }\n\n /// \n /// Provides access to all available power plans.\n /// \n public static class PowerPlans\n {\n /// \n /// The Balanced power plan.\n /// \n public static readonly PowerPlan Balanced = new PowerPlan\n {\n Name = \"Balanced\",\n Guid = \"381b4222-f694-41f0-9685-ff5bb260df2e\",\n Description =\n \"Automatically balances performance with energy consumption on capable hardware.\",\n };\n\n /// \n /// The High Performance power plan.\n /// \n public static readonly PowerPlan HighPerformance = new PowerPlan\n {\n Name = \"High Performance\",\n Guid = \"8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c\",\n Description = \"Favors performance, but may use more energy.\",\n };\n\n /// \n /// The Ultimate Performance power plan.\n /// \n public static readonly PowerPlan UltimatePerformance = new PowerPlan\n {\n Name = \"Ultimate Performance\",\n // This GUID is a placeholder and will be updated at runtime by PowerPlanService\n Guid = \"e9a42b02-d5df-448d-aa00-03f14749eb61\",\n Description = \"Provides ultimate performance on Windows.\",\n };\n\n /// \n /// Gets a list of all available power plans.\n /// \n /// A list of all power plans.\n public static List GetAllPowerPlans()\n {\n return new List { Balanced, HighPerformance, UltimatePerformance };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Models/WindowsAppSettingItem.cs", "using System.Collections.Generic;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Models\n{\n /// \n /// Adapter class that wraps a WindowsApp and implements ISettingItem.\n /// \n public class WindowsAppSettingItem : ISettingItem\n {\n private readonly WindowsApp _windowsApp;\n \n public WindowsAppSettingItem(WindowsApp windowsApp)\n {\n _windowsApp = windowsApp;\n \n // Initialize properties required by ISettingItem\n Id = windowsApp.PackageId;\n Name = windowsApp.DisplayName;\n Description = windowsApp.Description;\n IsSelected = windowsApp.IsSelected;\n GroupName = windowsApp.Category;\n IsVisible = true;\n ControlType = ControlType.BinaryToggle;\n Dependencies = new List();\n \n // Create a command that does nothing (placeholder)\n ApplySettingCommand = new RelayCommand(() => { });\n }\n \n // ISettingItem implementation\n public string Id { get; set; }\n public string Name { get; set; }\n public string Description { get; set; }\n public bool IsSelected { get; set; }\n public string GroupName { get; set; }\n public bool IsVisible { get; set; }\n public ControlType ControlType { get; set; }\n public List Dependencies { get; set; }\n public bool IsUpdatingFromCode { get; set; }\n public ICommand ApplySettingCommand { get; }\n \n // Method to convert back to WindowsApp\n public WindowsApp ToWindowsApp()\n {\n // Update the original WindowsApp with any changes\n _windowsApp.IsSelected = IsSelected;\n return _windowsApp;\n }\n \n // Static method to convert a collection of WindowsApps to WindowsAppSettingItems\n public static IEnumerable FromWindowsApps(IEnumerable windowsApps)\n {\n foreach (var app in windowsApps)\n {\n yield return new WindowsAppSettingItem(app);\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/LinkedRegistrySettings.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents a collection of registry settings that should be treated as a single logical setting.\n /// This allows multiple registry keys to be controlled by a single toggle in the UI.\n /// \n public class LinkedRegistrySettings\n {\n /// \n /// Gets or sets the list of registry settings that are linked together.\n /// \n public List Settings { get; set; } = new List();\n\n /// \n /// Gets or sets the category for all linked settings.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description for all linked settings.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the logic to use when determining the status of linked settings.\n /// Default is Any, which means if any setting is applied, the entire setting is considered applied.\n /// \n public LinkedSettingsLogic Logic { get; set; } = LinkedSettingsLogic.Any;\n\n /// \n /// Creates a new instance of the LinkedRegistrySettings class.\n /// \n public LinkedRegistrySettings()\n {\n }\n\n /// \n /// Creates a new instance of the LinkedRegistrySettings class with a single registry setting.\n /// \n /// The registry setting to include.\n public LinkedRegistrySettings(RegistrySetting registrySetting)\n {\n if (registrySetting != null)\n {\n Settings.Add(registrySetting);\n Category = registrySetting.Category;\n Description = registrySetting.Description;\n }\n }\n\n /// \n /// Creates a new instance of the LinkedRegistrySettings class with a specific logic type.\n /// \n /// The logic to use when determining the status of linked settings.\n public LinkedRegistrySettings(LinkedSettingsLogic logic)\n {\n Logic = logic;\n }\n\n /// \n /// Adds a registry setting to the linked collection.\n /// \n /// The registry setting to add.\n public void AddSetting(RegistrySetting registrySetting)\n {\n if (registrySetting != null)\n {\n Settings.Add(registrySetting);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/StatusToColorConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class StatusToColorConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // Handle RegistrySettingStatus\n if (value is RegistrySettingStatus status)\n {\n return status switch\n {\n RegistrySettingStatus.Applied => new SolidColorBrush(Color.FromRgb(0, 255, 60)), // Electric Green (#00FF3C)\n RegistrySettingStatus.NotApplied => new SolidColorBrush(Color.FromRgb(255, 40, 0)), // Ferrari Red (#FF2800)\n RegistrySettingStatus.Modified => new SolidColorBrush(Colors.Orange),\n RegistrySettingStatus.Error => new SolidColorBrush(Colors.Gray),\n _ => new SolidColorBrush(Colors.Gray)\n };\n }\n \n // Handle boolean for reinstallability status\n if (value is bool canBeReinstalled)\n {\n return canBeReinstalled \n ? new SolidColorBrush(Color.FromRgb(0, 165, 255)) // Blue (#00A5FF)\n : new SolidColorBrush(Color.FromRgb(255, 40, 0)); // Ferrari Red (#FF2800)\n }\n\n return new SolidColorBrush(Colors.Gray);\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/NotificationOptimizations.cs", "using Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class NotificationOptimizations\n{\n public static OptimizationGroup GetNotificationOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Notifications\",\n Category = OptimizationCategory.Notifications,\n Settings = new List\n {\n new OptimizationSetting\n {\n Id = \"notifications-toast\",\n Name = \"Windows Notifications\",\n Description = \"Controls toast notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\PushNotifications\",\n Name = \"ToastEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls toast notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-sound\",\n Name = \"Notification Sounds\",\n Description = \"Controls notification sounds\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\",\n Name = \"NOC_GLOBAL_SETTING_ALLOW_NOTIFICATION_SOUND\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls notification sounds\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-toast-above-lock\",\n Name = \"Notifications On Lock Screen\",\n Description = \"Controls notifications above lock screen\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\",\n Name = \"NOC_GLOBAL_SETTING_ALLOW_TOASTS_ABOVE_LOCK\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls notifications on lock screen\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n },\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\PushNotifications\",\n Name = \"LockScreenToastEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls notifications on lock screen\",\n IsPrimary = false,\n AbsenceMeansEnabled = true\n }\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All\n },\n new OptimizationSetting\n {\n Id = \"notifications-critical-toast-above-lock\",\n Name = \"Show Reminders and VoIP Calls Notifications\",\n Description = \"Controls critical notifications above lock screen\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\",\n Name = \"NOC_GLOBAL_SETTING_ALLOW_CRITICAL_TOASTS_ABOVE_LOCK\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls critical notifications above lock screen\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-security-maintenance\",\n Name = \"Security and Maintenance Notifications\",\n Description = \"Controls security and maintenance notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\\\\Windows.SystemToast.SecurityAndMaintenance\",\n Name = \"Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls security and maintenance notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-capability-access\",\n Name = \"Capability Access Notifications\",\n Description = \"Controls capability access notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\\\\Windows.SystemToast.CapabilityAccess\",\n Name = \"Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls capability access notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-startup-app\",\n Name = \"Startup App Notifications\",\n Description = \"Controls startup app notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\\\\Windows.SystemToast.StartupApp\",\n Name = \"Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls startup app notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-system-setting-engagement\",\n Name = \"System Setting Engagement Notifications\",\n Description = \"Controls system setting engagement notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\UserProfileEngagement\",\n Name = \"ScoobeSystemSettingEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls system setting engagement notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-app-location-request\",\n Name = \"Notify when apps request location\",\n Description = \"Controls wheter notifications are shown for location requests\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"Privacy Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\location\",\n Name = \"ShowGlobalPrompts\",\n RecommendedValue = 1,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls wheter notifications are shown for location requests\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-windows-security\",\n Name = \"Windows Security Notifications\",\n Description = \"Controls whether Windows Security notifications are shown\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"Security Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows Defender Security Center\\\\Notifications\",\n Name = \"DisableNotifications\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls whether Windows Security Center notifications are shown\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n },\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows Defender Security Center\\\\Notifications\",\n Name = \"DisableNotifications\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls whether Windows Defender Security Center notifications are shown\",\n IsPrimary = false,\n AbsenceMeansEnabled = true\n },\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows Defender Security Center\\\\Notifications\",\n Name = \"DisableEnhancedNotifications\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls whether Windows Defender Security Center notifications are shown\",\n IsPrimary = false,\n AbsenceMeansEnabled = true\n }\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All\n },\n new OptimizationSetting\n {\n Id = \"notifications-clock-change\",\n Name = \"Clock Change Notifications\",\n Description = \"Controls clock change notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"DstNotification\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls clock change notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n }\n }\n };\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/RegistryValueStatusConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class RegistryValueStatusConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null)\n return DependencyProperty.UnsetValue;\n\n if (value is RegistrySettingStatus status)\n {\n return status switch\n {\n RegistrySettingStatus.NotApplied => \"Not Applied\",\n RegistrySettingStatus.Applied => \"Applied\",\n RegistrySettingStatus.Modified => \"Modified\",\n RegistrySettingStatus.Error => \"Error\",\n RegistrySettingStatus.Unknown => \"Unknown\",\n _ => \"Unknown\"\n };\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n\n public class RegistryValueStatusToColorConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null)\n return DependencyProperty.UnsetValue;\n\n if (value is RegistrySettingStatus status)\n {\n return status switch\n {\n RegistrySettingStatus.NotApplied => new SolidColorBrush(Colors.Gray),\n RegistrySettingStatus.Applied => new SolidColorBrush(Colors.Green),\n RegistrySettingStatus.Modified => new SolidColorBrush(Colors.Orange),\n RegistrySettingStatus.Error => new SolidColorBrush(Colors.Red),\n RegistrySettingStatus.Unknown => new SolidColorBrush(Colors.Gray),\n _ => new SolidColorBrush(Colors.Gray)\n };\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n\n public class RegistryValueStatusToIconConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null)\n return DependencyProperty.UnsetValue;\n\n if (value is RegistrySettingStatus status)\n {\n return status switch\n {\n RegistrySettingStatus.NotApplied => \"⚪\", // Empty circle\n RegistrySettingStatus.Applied => \"✅\", // Green checkmark\n RegistrySettingStatus.Modified => \"⚠️\", // Warning\n RegistrySettingStatus.Error => \"❌\", // Red X\n RegistrySettingStatus.Unknown => \"❓\", // Question mark\n _ => \"❓\"\n };\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Exceptions/RemovalException.cs", "using System;\n\nnamespace Winhance.Core.Features.SoftwareApps.Exceptions\n{\n /// \n /// Exception thrown when there is an error with removal operations.\n /// \n public class RemovalException : Exception\n {\n /// \n /// Initializes a new instance of the class.\n /// \n public RemovalException() : base()\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message.\n /// \n /// The message that describes the error.\n public RemovalException(string message) : base(message)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message\n /// and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception.\n public RemovalException(string message, Exception innerException) : base(message, innerException)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified item name, error message,\n /// a flag indicating whether the error is critical, and a reference to the inner exception that is the cause of this exception.\n /// \n /// The name of the item that failed to be removed.\n /// The error message.\n /// A flag indicating whether the error is critical.\n /// The exception that is the cause of the current exception.\n public RemovalException(string itemName, string errorMessage, bool isCritical, Exception innerException)\n : base($\"Failed to remove {itemName}: {errorMessage}\", innerException)\n {\n ItemName = itemName;\n IsCritical = isCritical;\n }\n\n /// \n /// Gets the name of the item that failed to be removed.\n /// \n public string? ItemName { get; }\n\n /// \n /// Gets a value indicating whether the error is critical.\n /// \n public bool IsCritical { get; }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IUnifiedConfigurationService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for managing unified configuration operations across the application.\n /// \n public interface IUnifiedConfigurationService\n {\n /// \n /// Creates a unified configuration file containing settings from all view models.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file.\n Task CreateUnifiedConfigurationAsync();\n\n /// \n /// Saves a unified configuration file.\n /// \n /// The unified configuration to save.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile config);\n\n /// \n /// Loads a unified configuration file.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file if successful, null otherwise.\n Task LoadUnifiedConfigurationAsync();\n\n /// \n /// Shows the unified configuration dialog to let the user select which sections to include.\n /// \n /// The unified configuration file.\n /// Whether this is a save dialog (true) or an import dialog (false).\n /// A dictionary of section names and their selection state.\n Task> ShowUnifiedConfigurationDialogAsync(UnifiedConfigurationFile config, bool isSaveDialog);\n\n /// \n /// Applies a unified configuration to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task ApplyUnifiedConfigurationAsync(UnifiedConfigurationFile config, IEnumerable selectedSections);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/AppListViewModel.cs", "using System.Collections.ObjectModel;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.SoftwareApps.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n public abstract partial class AppListViewModel : BaseViewModel where T : class\n {\n protected readonly IPackageManager? _packageManager;\n protected readonly ITaskProgressService _progressService;\n \n [ObservableProperty]\n private bool _isLoading;\n\n public ObservableCollection Items { get; } = new();\n\n protected AppListViewModel(ITaskProgressService progressService, IPackageManager? packageManager) \n : base(progressService)\n {\n _packageManager = packageManager;\n _progressService = progressService;\n }\n\n public abstract Task LoadItemsAsync();\n public abstract Task CheckInstallationStatusAsync();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IPowerShellExecutionService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides functionality for executing PowerShell scripts.\n /// \n public interface IPowerShellExecutionService\n {\n /// \n /// Executes a PowerShell script.\n /// \n /// The script to execute.\n /// The progress reporter.\n /// The cancellation token.\n /// The output of the script.\n Task ExecuteScriptAsync(\n string script,\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Executes a PowerShell script file.\n /// \n /// The path to the script file.\n /// The arguments to pass to the script.\n /// The progress reporter.\n /// The cancellation token.\n /// The output of the script.\n Task ExecuteScriptFileAsync(\n string scriptPath,\n string arguments = \"\",\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/ApplicationSetting.cs", "using Microsoft.Win32;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Base class for all application settings that can modify registry values.\n /// \n public abstract record ApplicationSetting\n {\n /// \n /// Gets or sets the unique identifier for this setting.\n /// \n public required string Id { get; init; }\n\n /// \n /// Gets or sets the user-friendly name for this setting.\n /// \n public required string Name { get; init; }\n\n /// \n /// Gets or sets the description for this setting.\n /// \n public required string Description { get; init; }\n\n /// \n /// Gets or sets the group name for this setting.\n /// \n public required string GroupName { get; init; }\n\n /// \n /// Gets or sets the collection of registry settings associated with this application setting.\n /// \n public List RegistrySettings { get; init; } = new List();\n\n /// \n /// Gets or sets the collection of command settings associated with this application setting.\n /// \n public List CommandSettings { get; init; } = new List();\n\n /// \n /// Gets or sets the logic to use when determining the status of linked registry settings.\n /// \n public LinkedSettingsLogic LinkedSettingsLogic { get; init; } = LinkedSettingsLogic.Any;\n\n /// \n /// Gets or sets the dependencies between settings.\n /// \n public List Dependencies { get; init; } = new List();\n\n /// \n /// Gets or sets the control type for the UI.\n /// \n public ControlType ControlType { get; init; } = ControlType.BinaryToggle;\n\n /// \n /// Gets or sets the number of steps for a slider control.\n /// \n public int? SliderSteps { get; init; }\n\n /// \n /// Gets or sets a value indicating whether this setting is enabled.\n /// \n public bool IsEnabled { get; init; }\n\n /// \n /// Creates a LinkedRegistrySettings object from the RegistrySettings collection.\n /// \n /// A LinkedRegistrySettings object.\n public LinkedRegistrySettings CreateLinkedRegistrySettings()\n {\n if (RegistrySettings.Count == 0)\n {\n return new LinkedRegistrySettings();\n }\n\n var linkedSettings = new LinkedRegistrySettings\n {\n Category = RegistrySettings[0].Category,\n Description = Description,\n Logic = LinkedSettingsLogic\n };\n\n foreach (var registrySetting in RegistrySettings)\n {\n linkedSettings.AddSetting(registrySetting);\n }\n\n return linkedSettings;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/LogMessageEventArgs.cs", "using System;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Event arguments for log message events.\n /// \n public class LogMessageEventArgs : EventArgs\n {\n /// \n /// Gets the message content.\n /// \n public string Message { get; }\n \n /// \n /// Gets the log level.\n /// \n public LogLevel Level { get; }\n \n /// \n /// Gets the timestamp when the message was created.\n /// \n public DateTime Timestamp { get; }\n \n /// \n /// Gets the exception associated with the log message, if any.\n /// \n public Exception? Exception { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The message content.\n /// The log level.\n public LogMessageEventArgs(string message, LogLevel level)\n {\n Message = message ?? throw new ArgumentNullException(nameof(message));\n Level = level;\n Timestamp = DateTime.Now;\n Exception = null;\n }\n \n /// \n /// Initializes a new instance of the class.\n /// \n /// The log level.\n /// The message content.\n /// The exception associated with the message, if any.\n public LogMessageEventArgs(LogLevel level, string message, Exception? exception)\n {\n Message = message ?? throw new ArgumentNullException(nameof(message));\n Level = level;\n Timestamp = DateTime.Now;\n Exception = exception;\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/CompositeScriptContentModifier.cs", "using System;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Implementation of IScriptContentModifier that delegates to specialized modifiers.\n /// \n public class CompositeScriptContentModifier : IScriptContentModifier\n {\n private readonly IPackageScriptModifier _packageModifier;\n private readonly ICapabilityScriptModifier _capabilityModifier;\n private readonly IFeatureScriptModifier _featureModifier;\n private readonly IRegistryScriptModifier _registryModifier;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The package script modifier.\n /// The capability script modifier.\n /// The feature script modifier.\n /// The registry script modifier.\n public CompositeScriptContentModifier(\n IPackageScriptModifier packageModifier,\n ICapabilityScriptModifier capabilityModifier,\n IFeatureScriptModifier featureModifier,\n IRegistryScriptModifier registryModifier)\n {\n _packageModifier = packageModifier ?? throw new ArgumentNullException(nameof(packageModifier));\n _capabilityModifier = capabilityModifier ?? throw new ArgumentNullException(nameof(capabilityModifier));\n _featureModifier = featureModifier ?? throw new ArgumentNullException(nameof(featureModifier));\n _registryModifier = registryModifier ?? throw new ArgumentNullException(nameof(registryModifier));\n }\n\n /// \n public string RemoveCapabilityFromScript(string scriptContent, string capabilityName)\n {\n return _capabilityModifier.RemoveCapabilityFromScript(scriptContent, capabilityName);\n }\n\n /// \n public string RemovePackageFromScript(string scriptContent, string packageName)\n {\n return _packageModifier.RemovePackageFromScript(scriptContent, packageName);\n }\n\n /// \n public string RemoveOptionalFeatureFromScript(string scriptContent, string featureName)\n {\n return _featureModifier.RemoveOptionalFeatureFromScript(scriptContent, featureName);\n }\n\n /// \n public string RemoveAppRegistrySettingsFromScript(string scriptContent, string appName)\n {\n return _registryModifier.RemoveAppRegistrySettingsFromScript(scriptContent, appName);\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/OptimizationModels.cs", "using Microsoft.Win32;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Core.Features.Common.Models;\n\n// This class is deprecated. Use Winhance.Core.Features.Optimize.Models.OptimizationSetting instead.\n[System.Obsolete(\"This class is deprecated. Use Winhance.Core.Features.Optimize.Models.OptimizationSetting instead.\")]\npublic record OptimizationSetting\n{\n public required string Id { get; init; } // Unique identifier\n public required string Name { get; init; } // User-friendly name\n public required string Description { get; init; }\n public required OptimizationCategory Category { get; init; }\n public required string GroupName { get; init; } // Sub-group within category\n\n // Single registry setting (for backward compatibility)\n public RegistrySetting? RegistrySetting { get; init; }\n\n // Multiple registry settings (new approach)\n private LinkedRegistrySettings? _linkedRegistrySettings;\n public LinkedRegistrySettings LinkedRegistrySettings\n {\n get\n {\n // If LinkedRegistrySettings is null but RegistrySetting is not, create a new LinkedRegistrySettings with the single RegistrySetting\n if (_linkedRegistrySettings == null && RegistrySetting != null)\n {\n _linkedRegistrySettings = new LinkedRegistrySettings(RegistrySetting);\n }\n return _linkedRegistrySettings ?? new LinkedRegistrySettings();\n }\n init { _linkedRegistrySettings = value; }\n }\n\n // New approach: Use a collection of registry settings directly\n public List RegistrySettings { get; init; } = new List();\n \n // Linked settings configuration\n public LinkedSettingsLogic LinkedSettingsLogic { get; init; } = LinkedSettingsLogic.Any;\n\n // Dependencies between settings\n public List Dependencies { get; init; } = new List();\n\n public ControlType ControlType { get; init; } = ControlType.BinaryToggle; // Default to binary toggle\n public int? SliderSteps { get; init; } // For discrete sliders (null for binary toggles)\n public bool IsEnabled { get; init; } // Current state\n}\n\npublic record OptimizationGroup\n{\n public required string Name { get; init; }\n public required OptimizationCategory Category { get; init; }\n public required IReadOnlyList Settings { get; init; }\n}\n\n/// \n/// Represents a dependency between two settings.\n/// \n/// \n/// For example, \"Improve Inking and Typing\" requires \"Send Diagnostic Data\" to be enabled.\n/// \n/// \n/// new SettingDependency\n/// {\n/// DependencyType = SettingDependencyType.RequiresEnabled,\n/// DependentSettingId = \"privacy-improve-inking-typing-user\",\n/// RequiredSettingId = \"privacy-diagnostics-policy\"\n/// }\n/// \npublic record SettingDependency\n{\n /// \n /// The type of dependency.\n /// \n public SettingDependencyType DependencyType { get; init; }\n\n /// \n /// The ID of the setting that depends on another setting.\n /// \n public required string DependentSettingId { get; init; }\n\n /// \n /// The ID of the setting that is required by the dependent setting.\n /// \n public required string RequiredSettingId { get; init; }\n}\n\n/// \n/// The type of dependency between two settings.\n/// \npublic enum SettingDependencyType\n{\n /// \n /// The dependent setting requires the required setting to be enabled.\n /// \n RequiresEnabled,\n\n /// \n /// The dependent setting requires the required setting to be disabled.\n /// \n RequiresDisabled\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Interfaces/IPowerPlanService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Core.Features.Optimize.Interfaces\n{\n /// \n /// Provides functionality for managing Windows power plans.\n /// \n public interface IPowerPlanService\n {\n /// \n /// Gets the GUID of the currently active power plan.\n /// \n /// The GUID of the active power plan.\n Task GetActivePowerPlanGuidAsync();\n\n /// \n /// Sets the active power plan.\n /// \n /// The GUID of the power plan to set as active.\n /// True if the operation succeeded; otherwise, false.\n Task SetPowerPlanAsync(string planGuid);\n\n /// \n /// Ensures that a power plan with the specified GUID exists.\n /// If it doesn't exist, creates it from the source plan if specified.\n /// \n /// The GUID of the power plan to ensure exists.\n /// The GUID of the source plan to create from, if needed.\n /// True if the plan exists or was created successfully; otherwise, false.\n Task EnsurePowerPlanExistsAsync(string planGuid, string sourcePlanGuid = null);\n\n /// \n /// Gets a list of all available power plans.\n /// \n /// A list of available power plans.\n Task> GetAvailablePowerPlansAsync();\n \n /// \n /// Executes a PowerCfg command.\n /// \n /// The PowerCfg command to execute.\n /// True if the operation succeeded; otherwise, false.\n Task ExecutePowerCfgCommandAsync(string command);\n \n /// \n /// Applies a power setting using PowerCfg.\n /// \n /// The subgroup GUID.\n /// The setting GUID.\n /// The value to set.\n /// True if this is an AC (plugged in) setting; false for DC (battery) setting.\n /// True if the operation succeeded; otherwise, false.\n Task ApplyPowerSettingAsync(string subgroupGuid, string settingGuid, string value, bool isAcSetting);\n \n /// \n /// Applies a collection of PowerCfg settings.\n /// \n /// The collection of PowerCfg settings to apply.\n /// True if all operations succeeded; otherwise, false.\n Task ApplyPowerCfgSettingsAsync(List settings);\n \n /// \n /// Checks if a PowerCfg setting is currently applied.\n /// \n /// The PowerCfg setting to check.\n /// True if the setting is applied; otherwise, false.\n Task IsPowerCfgSettingAppliedAsync(PowerCfgSetting setting);\n \n /// \n /// Checks if all PowerCfg settings in a collection are currently applied.\n /// \n /// The collection of PowerCfg settings to check.\n /// True if all settings are applied; otherwise, false.\n Task AreAllPowerCfgSettingsAppliedAsync(List settings);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/SearchBox.xaml.cs", "using System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// Interaction logic for SearchBox.xaml\n /// \n public partial class SearchBox : UserControl\n {\n /// \n /// Dependency property for the SearchText property.\n /// \n public static readonly DependencyProperty SearchTextProperty =\n DependencyProperty.Register(\n nameof(SearchText),\n typeof(string),\n typeof(SearchBox),\n new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSearchTextChanged));\n\n /// \n /// Dependency property for the Placeholder property.\n /// \n public static readonly DependencyProperty PlaceholderProperty =\n DependencyProperty.Register(\n nameof(Placeholder),\n typeof(string),\n typeof(SearchBox),\n new PropertyMetadata(\"Search...\"));\n\n /// \n /// Dependency property for the HasText property.\n /// \n public static readonly DependencyProperty HasTextProperty =\n DependencyProperty.Register(\n nameof(HasText),\n typeof(bool),\n typeof(SearchBox),\n new PropertyMetadata(false));\n\n /// \n /// Initializes a new instance of the class.\n /// \n public SearchBox()\n {\n InitializeComponent();\n }\n\n /// \n /// Gets or sets the search text.\n /// \n public string SearchText\n {\n get => (string)GetValue(SearchTextProperty);\n set => SetValue(SearchTextProperty, value);\n }\n\n /// \n /// Gets or sets the placeholder text.\n /// \n public string Placeholder\n {\n get => (string)GetValue(PlaceholderProperty);\n set => SetValue(PlaceholderProperty, value);\n }\n\n /// \n /// Gets a value indicating whether the search box has text.\n /// \n public bool HasText\n {\n get => (bool)GetValue(HasTextProperty);\n private set => SetValue(HasTextProperty, value);\n }\n\n /// \n /// Called when the search text changes.\n /// \n /// The dependency object.\n /// The event arguments.\n private static void OnSearchTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is SearchBox searchBox)\n {\n searchBox.HasText = !string.IsNullOrEmpty((string)e.NewValue);\n }\n }\n\n /// \n /// Handles the click event of the clear button.\n /// \n /// The sender.\n /// The event arguments.\n private void ClearButton_Click(object sender, RoutedEventArgs e)\n {\n SearchText = string.Empty;\n SearchTextBox.Focus();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ICommandService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for executing system commands related to optimizations.\n /// \n public interface ICommandService\n {\n /// \n /// Executes the specified command with elevated privileges if required.\n /// \n /// The command to execute.\n /// Whether the command requires elevation.\n /// The result of the command execution.\n Task<(bool Success, string Output, string Error)> ExecuteCommandAsync(string command, bool requiresElevation = true);\n \n /// \n /// Applies the command settings based on the enabled state.\n /// \n /// The command settings to apply.\n /// Whether the optimization is enabled.\n /// A result indicating success or failure with details.\n Task<(bool Success, string Message)> ApplyCommandSettingsAsync(IEnumerable settings, bool isEnabled);\n \n /// \n /// Gets the current state of a command setting.\n /// \n /// The command setting to check.\n /// True if the setting is in its enabled state, false otherwise.\n Task IsCommandSettingEnabledAsync(CommandSetting setting);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/ISpecialAppHandlerService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Provides functionality for handling special applications that require custom removal procedures.\n /// \n public interface ISpecialAppHandlerService\n {\n /// \n /// Gets all registered special app handlers.\n /// \n /// A collection of special app handlers.\n IEnumerable GetAllHandlers();\n\n /// \n /// Gets a special app handler by its type.\n /// \n /// The type of handler to retrieve.\n /// The requested special app handler, or null if not found.\n SpecialAppHandler? GetHandler(string handlerType);\n\n /// \n /// Removes Microsoft Edge.\n /// \n /// True if the operation succeeded; otherwise, false.\n Task RemoveEdgeAsync();\n\n /// \n /// Removes OneDrive.\n /// \n /// True if the operation succeeded; otherwise, false.\n Task RemoveOneDriveAsync();\n\n /// \n /// Removes OneNote.\n /// \n /// True if the operation succeeded; otherwise, false.\n Task RemoveOneNoteAsync();\n\n /// \n /// Removes a special application using its registered handler.\n /// \n /// The type of handler to use.\n /// True if the operation succeeded; otherwise, false.\n Task RemoveSpecialAppAsync(string handlerType);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ILogService.cs", "using System;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides logging functionality for the application.\n /// \n public interface ILogService\n {\n /// \n /// Starts logging to a file.\n /// \n void StartLog();\n\n /// \n /// Stops logging to a file.\n /// \n void StopLog();\n\n /// \n /// Logs an informational message.\n /// \n /// The message to log.\n void LogInformation(string message);\n\n /// \n /// Logs a warning message.\n /// \n /// The message to log.\n void LogWarning(string message);\n\n /// \n /// Logs an error message.\n /// \n /// The message to log.\n /// The exception associated with the error, if any.\n void LogError(string message, Exception? exception = null);\n\n /// \n /// Logs a success message.\n /// \n /// The message to log.\n void LogSuccess(string message);\n\n /// \n /// Gets the path to the current log file.\n /// \n /// The path to the log file.\n string GetLogPath();\n\n /// \n /// Logs a message with the specified level.\n /// \n /// The log level.\n /// The message to log.\n /// The exception associated with the message, if any.\n void Log(LogLevel level, string message, Exception? exception = null);\n\n /// \n /// Event raised when a log message is generated.\n /// \n event EventHandler? LogMessageGenerated;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Helpers/ValidationHelper.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Helpers\n{\n /// \n /// Helper class for common validation operations.\n /// \n public static class ValidationHelper\n {\n /// \n /// Validates that the specified object is not null.\n /// \n /// The object to validate.\n /// The name of the parameter being validated.\n /// Thrown if the value is null.\n public static void NotNull(object value, string paramName)\n {\n if (value == null)\n {\n throw new ArgumentNullException(paramName);\n }\n }\n\n /// \n /// Validates that the specified string is not null or empty.\n /// \n /// The string to validate.\n /// The name of the parameter being validated.\n /// Thrown if the value is null.\n /// Thrown if the value is empty.\n public static void NotNullOrEmpty(string value, string paramName)\n {\n if (value == null)\n {\n throw new ArgumentNullException(paramName);\n }\n\n if (string.IsNullOrEmpty(value))\n {\n throw new ArgumentException(\"Value cannot be empty.\", paramName);\n }\n }\n\n /// \n /// Validates that the specified string is not null, empty, or consists only of white-space characters.\n /// \n /// The string to validate.\n /// The name of the parameter being validated.\n /// Thrown if the value is null.\n /// Thrown if the value is empty or consists only of white-space characters.\n public static void NotNullOrWhiteSpace(string value, string paramName)\n {\n if (value == null)\n {\n throw new ArgumentNullException(paramName);\n }\n\n if (string.IsNullOrWhiteSpace(value))\n {\n throw new ArgumentException(\"Value cannot be empty or consist only of white-space characters.\", paramName);\n }\n }\n\n /// \n /// Validates that the specified value is greater than or equal to the minimum value.\n /// \n /// The value to validate.\n /// The minimum allowed value.\n /// The name of the parameter being validated.\n /// Thrown if the value is less than the minimum value.\n public static void GreaterThanOrEqualTo(int value, int minValue, string paramName)\n {\n if (value < minValue)\n {\n throw new ArgumentOutOfRangeException(paramName, value, $\"Value must be greater than or equal to {minValue}.\");\n }\n }\n\n /// \n /// Validates that the specified value is less than or equal to the maximum value.\n /// \n /// The value to validate.\n /// The maximum allowed value.\n /// The name of the parameter being validated.\n /// Thrown if the value is greater than the maximum value.\n public static void LessThanOrEqualTo(int value, int maxValue, string paramName)\n {\n if (value > maxValue)\n {\n throw new ArgumentOutOfRangeException(paramName, value, $\"Value must be less than or equal to {maxValue}.\");\n }\n }\n\n /// \n /// Validates that the specified value is in the specified range.\n /// \n /// The value to validate.\n /// The minimum allowed value.\n /// The maximum allowed value.\n /// The name of the parameter being validated.\n /// Thrown if the value is outside the specified range.\n public static void InRange(int value, int minValue, int maxValue, string paramName)\n {\n if (value < minValue || value > maxValue)\n {\n throw new ArgumentOutOfRangeException(paramName, value, $\"Value must be between {minValue} and {maxValue}.\");\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Resources/MaterialSymbols.cs", "using System.Collections.Generic;\n\nnamespace Winhance.WPF.Features.Common.Resources\n{\n /// \n /// Provides access to Material Symbols icon Unicode values.\n /// \n public static class MaterialSymbols\n {\n private static readonly Dictionary _iconMap = new Dictionary\n {\n // Navigation icons\n { \"RocketLaunch\", \"\\uEB9B\" },\n { \"Rocket\", \"\\uE837\" },\n { \"DeployedCode\", \"\\uE8A7\" },\n { \"DeployedCodeUpdate\", \"\\uE8A8\" },\n { \"CodeBraces\", \"\\uE86F\" },\n { \"Routine\", \"\\uEBB9\" },\n { \"ThemeLightDark\", \"\\uE51C\" },\n { \"Palette\", \"\\uE40A\" },\n { \"Information\", \"\\uE88E\" },\n { \"MicrosoftWindows\", \"\\uE950\" },\n\n // Other common icons\n { \"Apps\", \"\\uE5C3\" },\n { \"Settings\", \"\\uE8B8\" },\n { \"Close\", \"\\uE5CD\" },\n { \"Menu\", \"\\uE5D2\" },\n { \"Search\", \"\\uE8B6\" },\n { \"Add\", \"\\uE145\" },\n { \"Delete\", \"\\uE872\" },\n { \"Edit\", \"\\uE3C9\" },\n { \"Save\", \"\\uE161\" },\n { \"Download\", \"\\uE2C4\" },\n { \"Upload\", \"\\uE2C6\" },\n { \"Refresh\", \"\\uE5D5\" },\n { \"ArrowBack\", \"\\uE5C4\" },\n { \"ArrowForward\", \"\\uE5C8\" },\n { \"ChevronDown\", \"\\uE5CF\" },\n { \"ChevronUp\", \"\\uE5CE\" },\n { \"ChevronLeft\", \"\\uE5CB\" },\n { \"ChevronRight\", \"\\uE5CC\" },\n { \"ExpandMore\", \"\\uE5CF\" },\n { \"ExpandLess\", \"\\uE5CE\" },\n { \"MoreVert\", \"\\uE5D4\" },\n { \"MoreHoriz\", \"\\uE5D3\" },\n { \"Check\", \"\\uE5CA\" },\n { \"Clear\", \"\\uE14C\" },\n { \"Error\", \"\\uE000\" },\n { \"Warning\", \"\\uE002\" },\n { \"Info\", \"\\uE88E\" },\n { \"Help\", \"\\uE887\" },\n { \"HelpOutline\", \"\\uE8FD\" },\n { \"Sync\", \"\\uE627\" },\n { \"SyncDisabled\", \"\\uE628\" },\n { \"SyncProblem\", \"\\uE629\" },\n { \"Visibility\", \"\\uE8F4\" },\n { \"VisibilityOff\", \"\\uE8F5\" },\n { \"Lock\", \"\\uE897\" },\n { \"LockOpen\", \"\\uE898\" },\n { \"Star\", \"\\uE838\" },\n { \"StarBorder\", \"\\uE83A\" },\n { \"Favorite\", \"\\uE87D\" },\n { \"FavoriteBorder\", \"\\uE87E\" },\n { \"ThumbUp\", \"\\uE8DC\" },\n { \"ThumbDown\", \"\\uE8DB\" },\n { \"MicrosoftWindows\", \"\\uE9AA\" }\n };\n\n /// \n /// Gets the Unicode character for the specified icon name.\n /// \n /// The name of the icon.\n /// The Unicode character for the icon, or a question mark if not found.\n public static string GetIcon(string iconName)\n {\n if (_iconMap.TryGetValue(iconName, out string iconChar))\n {\n return iconChar;\n }\n\n return \"?\"; // Return a question mark if the icon is not found\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/EnumToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts an enum value to a Visibility value based on whether it matches the parameter.\n /// \n public class EnumToVisibilityConverter : IValueConverter\n {\n /// \n /// Converts an enum value to a Visibility value.\n /// \n /// The enum value to convert.\n /// The type of the binding target property.\n /// The parameter to compare against.\n /// The culture to use in the converter.\n /// \n /// Visibility.Visible if the value matches the parameter; otherwise, Visibility.Collapsed.\n /// \n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null || parameter == null)\n {\n return Visibility.Collapsed;\n }\n\n // Check if the value is equal to the parameter\n bool isEqual = value.Equals(parameter);\n return isEqual ? Visibility.Visible : Visibility.Collapsed;\n }\n\n /// \n /// Converts a Visibility value back to an enum value.\n /// \n /// The Visibility value to convert back.\n /// The type of the binding source property.\n /// The parameter to use in the converter.\n /// The culture to use in the converter.\n /// \n /// The parameter if the value is Visibility.Visible; otherwise, null.\n /// \n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is Visibility visibility && visibility == Visibility.Visible)\n {\n return parameter;\n }\n\n return Binding.DoNothing;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/InverseBooleanToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean value to a Visibility value, with the boolean value inverted.\n /// True becomes Collapsed, False becomes Visible.\n /// \n public class InverseBooleanToVisibilityConverter : IValueConverter\n {\n /// \n /// Converts a boolean value to a Visibility value, with the boolean value inverted.\n /// \n /// The boolean value to convert.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// Visibility.Collapsed if the value is true, Visibility.Visible if the value is false.\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return boolValue ? Visibility.Collapsed : Visibility.Visible;\n }\n \n return Visibility.Visible;\n }\n \n /// \n /// Converts a Visibility value back to a boolean value, with the boolean value inverted.\n /// \n /// The Visibility value to convert back.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// False if the value is Visibility.Visible, true otherwise.\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is Visibility visibility)\n {\n return visibility != Visibility.Visible;\n }\n \n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppVerificationService.cs", "using System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces;\n\n/// \n/// Interface for services that handle verification of application installations.\n/// \npublic interface IAppVerificationService\n{\n /// \n /// Verifies if an app is installed.\n /// \n /// The package name to verify.\n /// True if the app is installed; otherwise, false.\n Task VerifyAppInstallationAsync(string packageName);\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IScheduledTaskService.cs", "using System.Threading.Tasks;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for a service that manages scheduled tasks for script execution.\n /// \n public interface IScheduledTaskService\n {\n /// \n /// Registers a scheduled task to run the specified script.\n /// \n /// The script to register as a scheduled task.\n /// True if the task was registered successfully, false otherwise.\n Task RegisterScheduledTaskAsync(RemovalScript script);\n\n /// \n /// Unregisters a scheduled task with the specified name.\n /// \n /// The name of the task to unregister.\n /// True if the task was unregistered successfully, false otherwise.\n Task UnregisterScheduledTaskAsync(string taskName);\n\n /// \n /// Checks if a scheduled task with the specified name is registered.\n /// \n /// The name of the task to check.\n /// True if the task exists, false otherwise.\n Task IsTaskRegisteredAsync(string taskName);\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryExtensions.cs", "using System;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Extension methods for registry operations.\n /// \n public static class RegistryExtensions\n {\n /// \n /// Converts a RegistryHive enum to its string representation (HKCU, HKLM, etc.)\n /// \n /// The registry hive.\n /// The string representation of the registry hive.\n public static string GetRegistryHiveString(this RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => throw new ArgumentException($\"Unsupported registry hive: {hive}\")\n };\n }\n\n /// \n /// Gets the full registry path by combining the hive and subkey.\n /// \n /// The registry hive.\n /// The registry subkey.\n /// The full registry path.\n public static string GetFullRegistryPath(this RegistryHive hive, string subKey)\n {\n return $\"{hive.GetRegistryHiveString()}\\\\{subKey}\";\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/StatusToTextConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class StatusToTextConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is RegistrySettingStatus status)\n {\n return status switch\n {\n RegistrySettingStatus.Applied => \"Applied\",\n RegistrySettingStatus.NotApplied => \"Not Applied\",\n RegistrySettingStatus.Modified => \"Modified\",\n RegistrySettingStatus.Error => \"Error\",\n _ => \"Unknown\"\n };\n }\n\n return \"Unknown\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppDiscoveryService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for discovering and retrieving information about installed applications.\n /// \n public interface IAppDiscoveryService\n {\n /// \n /// Gets all standard (built-in) applications.\n /// \n /// A collection of standard applications.\n Task> GetStandardAppsAsync();\n\n /// \n /// Gets all installable third-party applications.\n /// \n /// A collection of installable applications.\n Task> GetInstallableAppsAsync();\n\n /// \n /// Gets all available Windows capabilities.\n /// \n /// A collection of Windows capabilities.\n Task> GetCapabilitiesAsync();\n\n /// \n /// Gets all available Windows optional features.\n /// \n /// A collection of Windows optional features.\n Task> GetOptionalFeaturesAsync();\n\n /// \n /// Checks if Microsoft Edge is installed.\n /// \n /// True if Edge is installed; otherwise, false.\n Task IsEdgeInstalledAsync();\n\n /// \n /// Checks if OneDrive is installed.\n /// \n /// True if OneDrive is installed; otherwise, false.\n Task IsOneDriveInstalledAsync();\n\n /// \n /// Checks if OneNote is installed.\n /// \n /// True if OneNote is installed; otherwise, false.\n Task IsOneNoteInstalledAsync();\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IConfigurationService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Defines methods for saving and loading application configuration files.\n /// \n public interface IConfigurationService\n {\n /// \n /// Saves a configuration file containing the selected items.\n /// \n /// The type of items to save.\n /// The collection of items to save.\n /// The type of configuration being saved.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task SaveConfigurationAsync(IEnumerable items, string configType);\n\n /// \n /// Loads a configuration file and returns the configuration file.\n /// \n /// The type of configuration being loaded.\n /// A task representing the asynchronous operation. Returns the configuration file if successful, null otherwise.\n Task LoadConfigurationAsync(string configType);\n\n /// \n /// Saves a unified configuration file containing settings for multiple parts of the application.\n /// \n /// The unified configuration to save.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile unifiedConfig);\n\n /// \n /// Loads a unified configuration file.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file if successful, null otherwise.\n Task LoadUnifiedConfigurationAsync();\n\n /// \n /// Creates a unified configuration file from individual configuration sections.\n /// \n /// Dictionary of section names and their corresponding configuration items.\n /// List of section names to include in the unified configuration.\n /// A unified configuration file.\n UnifiedConfigurationFile CreateUnifiedConfiguration(Dictionary> sections, IEnumerable includedSections);\n\n /// \n /// Extracts a specific section from a unified configuration file.\n /// \n /// The unified configuration file.\n /// The name of the section to extract.\n /// A configuration file containing only the specified section.\n ConfigurationFile ExtractSectionFromUnifiedConfiguration(UnifiedConfigurationFile unifiedConfig, string sectionName);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/MaterialSymbol.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\nusing Winhance.WPF.Features.Common.Resources;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// Interaction logic for MaterialSymbol.xaml\n /// \n public partial class MaterialSymbol : UserControl\n {\n public static readonly DependencyProperty IconProperty = DependencyProperty.Register(\n \"Icon\", typeof(string), typeof(MaterialSymbol), \n new PropertyMetadata(string.Empty, OnIconChanged));\n\n public static readonly DependencyProperty IconTextProperty = DependencyProperty.Register(\n \"IconText\", typeof(string), typeof(MaterialSymbol), \n new PropertyMetadata(string.Empty));\n\n public string Icon\n {\n get { return (string)GetValue(IconProperty); }\n set { SetValue(IconProperty, value); }\n }\n\n public string IconText\n {\n get { return (string)GetValue(IconTextProperty); }\n set { SetValue(IconTextProperty, value); }\n }\n\n public MaterialSymbol()\n {\n InitializeComponent();\n }\n\n private static void OnIconChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is MaterialSymbol control && e.NewValue is string iconName)\n {\n control.IconText = MaterialSymbols.GetIcon(iconName);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/RegistryHiveToFullNameConverter.cs", "using Microsoft.Win32;\nusing System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a RegistryHive enum to its full string representation (HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, etc.)\n /// \n public class RegistryHiveToFullNameConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKEY_CLASSES_ROOT\",\n RegistryHive.CurrentUser => \"HKEY_CURRENT_USER\",\n RegistryHive.LocalMachine => \"HKEY_LOCAL_MACHINE\",\n RegistryHive.Users => \"HKEY_USERS\",\n RegistryHive.CurrentConfig => \"HKEY_CURRENT_CONFIG\",\n _ => value.ToString()\n };\n }\n \n return value?.ToString() ?? string.Empty;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IVersionService.cs", "using System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n public interface IVersionService\n {\n /// \n /// Gets the current application version\n /// \n VersionInfo GetCurrentVersion();\n \n /// \n /// Checks if an update is available\n /// \n /// A task that resolves to true if an update is available, false otherwise\n Task CheckForUpdateAsync();\n \n /// \n /// Downloads and launches the installer for the latest version\n /// \n /// A task that completes when the download is initiated\n Task DownloadAndInstallUpdateAsync();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/CapabilityInfo.cs", "// This contains the model for Windows capability information\n\nusing System;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models\n{\n /// \n /// Represents information about a Windows capability.\n /// \n public class CapabilityInfo : IInstallableItem\n {\n public string PackageId => PackageName;\n public string DisplayName => Name;\n public InstallItemType ItemType => InstallItemType.Capability;\n public bool RequiresRestart { get; set; }\n\n /// \n /// Gets or sets the name of the capability.\n /// \n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description of the capability.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the package name of the capability.\n /// This is the identifier used by Windows to reference the capability.\n /// \n public string PackageName { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the category of the capability.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether the capability is installed.\n /// \n public bool IsInstalled { get; set; }\n\n /// \n /// Gets or sets the registry settings associated with this capability.\n /// \n public AppRegistrySetting[]? RegistrySettings { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the capability is protected by the system.\n /// \n public bool IsSystemProtected { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the capability can be reenabled after disabling.\n /// \n public bool CanBeReenabled { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether the capability is selected for installation or removal.\n /// \n public bool IsSelected { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/FeatureInfo.cs", "// This contains the model for Windows optional feature information\n\nusing System;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models\n{\n /// \n /// Represents information about a Windows optional feature.\n /// \n public class FeatureInfo : IInstallableItem\n {\n public string PackageId => PackageName;\n public string DisplayName => Name;\n public InstallItemType ItemType => InstallItemType.Feature;\n public bool RequiresRestart => RequiresReboot;\n\n /// \n /// Gets or sets the name of the feature.\n /// \n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description of the feature.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the package name of the feature.\n /// This is the identifier used by Windows to reference the feature.\n /// \n public string PackageName { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the category of the feature.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether the feature is installed.\n /// \n public bool IsInstalled { get; set; }\n\n /// \n /// Gets or sets the registry settings associated with this feature.\n /// \n public AppRegistrySetting[]? RegistrySettings { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the feature is protected by the system.\n /// \n public bool IsSystemProtected { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the feature requires a reboot after installation or removal.\n /// \n public bool RequiresReboot { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the feature can be reenabled after disabling.\n /// \n public bool CanBeReenabled { get; set; } = true;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/RefreshResult.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents the result of a refresh operation for installation statuses.\n /// \n public class RefreshResult\n {\n /// \n /// Gets or sets a value indicating whether the refresh operation was successful.\n /// \n public bool Success { get; set; }\n\n /// \n /// Gets or sets the error message if the refresh operation failed.\n /// \n public string? ErrorMessage { get; set; }\n\n /// \n /// Gets or sets the collection of app IDs that were successfully refreshed.\n /// \n public IEnumerable RefreshedAppIds { get; set; } = new List();\n\n /// \n /// Gets or sets the collection of app IDs that failed to refresh.\n /// \n public IEnumerable FailedAppIds { get; set; } = new List();\n\n /// \n /// Gets or sets the number of successfully refreshed apps.\n /// \n public int SuccessCount { get; set; }\n\n /// \n /// Gets or sets the number of failed refreshed apps.\n /// \n public int FailedCount { get; set; }\n\n /// \n /// Gets or sets the collection of errors.\n /// \n public Dictionary Errors { get; set; } = new Dictionary();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IConfigurationCoordinatorService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for coordinating configuration operations across multiple view models.\n /// \n public interface IConfigurationCoordinatorService\n {\n /// \n /// Creates a unified configuration file containing settings from all view models.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file.\n Task CreateUnifiedConfigurationAsync();\n\n /// \n /// Applies a unified configuration to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task ApplyUnifiedConfigurationAsync(UnifiedConfigurationFile config, IEnumerable selectedSections);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Customize/Interfaces/IThemeService.cs", "using System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.Customize.Interfaces\n{\n /// \n /// Interface for theme-related operations.\n /// \n public interface IThemeService\n {\n /// \n /// Checks if dark mode is enabled.\n /// \n /// True if dark mode is enabled; otherwise, false.\n bool IsDarkModeEnabled();\n\n /// \n /// Sets the theme mode.\n /// \n /// True to enable dark mode; false to enable light mode.\n /// True if the operation succeeded; otherwise, false.\n bool SetThemeMode(bool isDarkMode);\n\n /// \n /// Sets the theme mode and optionally changes the wallpaper.\n /// \n /// True to enable dark mode; false to enable light mode.\n /// True to change the wallpaper; otherwise, false.\n /// A task representing the asynchronous operation.\n Task ApplyThemeAsync(bool isDarkMode, bool changeWallpaper);\n\n /// \n /// Gets the name of the current theme.\n /// \n /// The name of the current theme (\"Light Mode\" or \"Dark Mode\").\n string GetCurrentThemeName();\n\n /// \n /// Refreshes the Windows GUI to apply theme changes.\n /// \n /// True to restart Explorer; otherwise, false.\n /// A task representing the asynchronous operation.\n Task RefreshGUIAsync(bool restartExplorer);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/TaskProgressDetail.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents detailed progress information for a task.\n /// \n public class TaskProgressDetail\n {\n /// \n /// Gets or sets the progress value (0-100), or null if not applicable.\n /// \n public double? Progress { get; set; }\n \n /// \n /// Gets or sets the status text.\n /// \n public string StatusText { get; set; }\n \n /// \n /// Gets or sets a detailed message about the current operation.\n /// \n public string DetailedMessage { get; set; }\n \n /// \n /// Gets or sets the log level for the detailed message.\n /// \n public LogLevel LogLevel { get; set; } = LogLevel.Info;\n \n /// \n /// Gets or sets whether the progress is indeterminate.\n /// \n public bool IsIndeterminate { get; set; }\n \n /// \n /// Gets or sets additional information about the progress as key-value pairs.\n /// This can be used to provide more detailed information for logging or debugging.\n /// \n public Dictionary AdditionalInfo { get; set; } = new Dictionary();\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/RegistryModels.cs", "using Microsoft.Win32;\nusing System;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models;\n\npublic record RegistrySetting\n{\n public required string Category { get; init; }\n public required RegistryHive Hive { get; init; }\n public required string SubKey { get; init; }\n public required string Name { get; init; }\n\n /// \n /// The value shown in the tooltip to indicate the recommended value.\n /// \n public required object RecommendedValue { get; init; }\n\n /// \n /// The value shown in the tooltip to indicate the default value. (or null to delete the registry key).\n /// \n public object? DefaultValue { get; init; }\n\n /// \n /// The value to set when the toggle is ON (enabled).\n /// \n public object? EnabledValue { get; init; }\n\n /// \n /// The value to set when the toggle is OFF (disabled), or null to delete the registry key.\n /// \n public object? DisabledValue { get; init; }\n\n public required RegistryValueKind ValueType { get; init; }\n /// \n /// Description of the registry setting. This is optional as the parent OptimizationSetting\n /// typically already has a Description property that serves the same purpose.\n /// \n public string Description { get; init; } = string.Empty;\n\n /// \n /// Specifies the intended action for this registry setting.\n /// Default is Set for backward compatibility.\n /// \n public RegistryActionType ActionType { get; init; } = RegistryActionType.Set;\n\n /// \n /// Specifies whether the absence of the registry key/value means the feature is enabled.\n /// Default is false, meaning absence = not applied.\n /// When true, absence of the key/value means the feature is enabled (Applied).\n /// \n public bool AbsenceMeansEnabled { get; init; } = false;\n\n /// \n /// Specifies whether this setting is a primary setting when used in linked settings.\n /// For settings with LinkedSettingsLogic.Primary, only the primary setting's status is used.\n /// \n public bool IsPrimary { get; init; } = false;\n\n /// \n /// Specifies whether this setting is a Group Policy registry key.\n /// When true, the entire key will be deleted when disabling the setting instead of just changing the value.\n /// This is necessary for Windows to recognize that the policy is no longer applied.\n /// \n public bool IsGroupPolicy { get; init; } = false;\n \n /// \n /// Dictionary to store custom properties for specific control types like ComboBox.\n /// This allows storing additional information that doesn't fit into the standard registry setting model.\n /// \n public Dictionary? CustomProperties { get; set; }\n}\n\npublic enum RegistryAction\n{\n Apply,\n Test,\n Rollback\n}\n\npublic record ValuePair\n{\n public required object Value { get; init; }\n public required RegistryValueKind Type { get; init; }\n\n public ValuePair(object value, RegistryValueKind type)\n {\n Value = value;\n Type = type;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IApplicationCloseService.cs", "using System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for handling application close functionality\n /// \n public interface IApplicationCloseService\n {\n /// \n /// Shows the support dialog if needed and handles the application close process\n /// \n /// A task representing the asynchronous operation\n Task CloseApplicationWithSupportDialogAsync();\n \n /// \n /// Saves the \"Don't show support dialog\" preference\n /// \n /// Whether to show the support dialog in the future\n /// A task representing the asynchronous operation\n Task SaveDontShowSupportPreferenceAsync(bool dontShow);\n \n /// \n /// Checks if the support dialog should be shown based on user preferences\n /// \n /// True if the dialog should be shown, false otherwise\n Task ShouldShowSupportDialogAsync();\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScriptGenerationServiceExtensions.cs", "using Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Extension methods for registering script generation services.\n /// \n public static class ScriptGenerationServiceExtensions\n {\n /// \n /// Adds script generation services to the service collection.\n /// \n /// The service collection.\n /// The service collection.\n public static IServiceCollection AddScriptGenerationServices(this IServiceCollection services)\n {\n // Register script template provider\n services.AddSingleton();\n \n // Register script builder service\n services.AddSingleton();\n \n // Register script factory\n services.AddSingleton();\n \n // Register script generation service\n services.AddSingleton();\n \n // Register script content modifier\n services.AddSingleton();\n \n // Register composite script content modifier\n services.AddSingleton();\n \n // Register specialized script modifiers\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n \n // Register scheduled task service\n services.AddSingleton();\n \n // Register script update service\n services.AddSingleton();\n \n return services;\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IFileSystemService.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Interfaces.Services\n{\n /// \n /// Provides access to the file system.\n /// \n public interface IFileSystemService\n {\n /// \n /// Determines whether the specified file exists.\n /// \n /// The file to check.\n /// True if the file exists; otherwise, false.\n bool FileExists(string path);\n\n /// \n /// Determines whether the specified directory exists.\n /// \n /// The directory to check.\n /// True if the directory exists; otherwise, false.\n bool DirectoryExists(string path);\n\n /// \n /// Creates a directory if it doesn't already exist.\n /// \n /// The directory to create.\n /// True if the directory was created or already exists; otherwise, false.\n bool CreateDirectory(string path);\n\n /// \n /// Deletes a file if it exists.\n /// \n /// The file to delete.\n /// True if the file was deleted or didn't exist; otherwise, false.\n bool DeleteFile(string path);\n\n /// \n /// Reads all text from a file.\n /// \n /// The file to read.\n /// The contents of the file.\n string ReadAllText(string path);\n\n /// \n /// Writes all text to a file.\n /// \n /// The file to write to.\n /// The text to write.\n /// True if the text was written successfully; otherwise, false.\n bool WriteAllText(string path, string contents);\n\n /// \n /// Gets all files in a directory that match the specified pattern.\n /// \n /// The directory to search.\n /// The search pattern.\n /// Whether to search subdirectories.\n /// A collection of file paths.\n IEnumerable GetFiles(string path, string pattern, bool recursive);\n\n /// \n /// Gets all directories in a directory that match the specified pattern.\n /// \n /// The directory to search.\n /// The search pattern.\n /// Whether to search subdirectories.\n /// A collection of directory paths.\n IEnumerable GetDirectories(string path, string pattern, bool recursive);\n\n /// \n /// Gets the path to a special folder, such as AppData, ProgramFiles, etc.\n /// \n /// The name of the special folder.\n /// The path to the special folder.\n string GetSpecialFolderPath(string specialFolder);\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceCompletion.cs", "using Microsoft.Win32;\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Security.AccessControl;\nusing System.Security.Principal;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing LogLevel = Winhance.Core.Features.Common.Enums.LogLevel;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n [SupportedOSPlatform(\"windows\")]\n public partial class RegistryService\n {\n private RegistryKey? GetRootKey(string rootKeyName)\n {\n // Normalize the input by converting to uppercase\n rootKeyName = rootKeyName.ToUpper();\n \n // Check for full names first\n if (rootKeyName == \"HKEY_LOCAL_MACHINE\" || rootKeyName == \"LOCALMACHINE\")\n return Microsoft.Win32.Registry.LocalMachine;\n if (rootKeyName == \"HKEY_CURRENT_USER\" || rootKeyName == \"CURRENTUSER\")\n return Microsoft.Win32.Registry.CurrentUser;\n if (rootKeyName == \"HKEY_CLASSES_ROOT\")\n return Microsoft.Win32.Registry.ClassesRoot;\n if (rootKeyName == \"HKEY_USERS\")\n return Microsoft.Win32.Registry.Users;\n if (rootKeyName == \"HKEY_CURRENT_CONFIG\")\n return Microsoft.Win32.Registry.CurrentConfig;\n \n // Then check for abbreviated names using the extension method's constants\n if (rootKeyName == RegistryExtensions.GetRegistryHiveString(RegistryHive.LocalMachine))\n return Microsoft.Win32.Registry.LocalMachine;\n if (rootKeyName == RegistryExtensions.GetRegistryHiveString(RegistryHive.CurrentUser))\n return Microsoft.Win32.Registry.CurrentUser;\n if (rootKeyName == RegistryExtensions.GetRegistryHiveString(RegistryHive.ClassesRoot))\n return Microsoft.Win32.Registry.ClassesRoot;\n if (rootKeyName == RegistryExtensions.GetRegistryHiveString(RegistryHive.Users))\n return Microsoft.Win32.Registry.Users;\n if (rootKeyName == RegistryExtensions.GetRegistryHiveString(RegistryHive.CurrentConfig))\n return Microsoft.Win32.Registry.CurrentConfig;\n \n // If no match is found, return null\n return null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/UI/Interfaces/INotificationService.cs", "using System;\n\nnamespace Winhance.Core.Features.UI.Interfaces\n{\n /// \n /// Interface for notification services that can display toast notifications and other alerts.\n /// \n public interface INotificationService\n {\n /// \n /// Shows a toast notification.\n /// \n /// The title of the notification.\n /// The message content of the notification.\n /// The type of notification.\n void ShowToast(string title, string message, ToastType type);\n }\n\n /// \n /// Defines the types of toast notifications.\n /// \n public enum ToastType\n {\n /// \n /// Information notification.\n /// \n Information,\n\n /// \n /// Success notification.\n /// \n Success,\n\n /// \n /// Warning notification.\n /// \n Warning,\n\n /// \n /// Error notification.\n /// \n Error\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/StringToMaximizeIconConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing MaterialDesignThemes.Wpf;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class StringToMaximizeIconConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is string iconName)\n {\n switch (iconName)\n {\n case \"WindowMaximize\":\n return PackIconKind.WindowMaximize;\n case \"WindowRestore\":\n return PackIconKind.WindowRestore;\n default:\n return PackIconKind.WindowMaximize;\n }\n }\n \n return PackIconKind.WindowMaximize;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is PackIconKind kind)\n {\n switch (kind)\n {\n case PackIconKind.WindowMaximize:\n return \"WindowMaximize\";\n case PackIconKind.WindowRestore:\n return \"WindowRestore\";\n default:\n return \"WindowMaximize\";\n }\n }\n \n return \"WindowMaximize\";\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Interfaces/IWallpaperService.cs", "using System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.Customize.Interfaces\n{\n /// \n /// Interface for wallpaper operations.\n /// \n public interface IWallpaperService\n {\n /// \n /// Sets the desktop wallpaper.\n /// \n /// The path to the wallpaper image.\n /// A task representing the asynchronous operation.\n Task SetWallpaperAsync(string wallpaperPath);\n\n /// \n /// Sets the default wallpaper based on Windows version and theme.\n /// \n /// Whether the system is Windows 11.\n /// Whether dark mode is enabled.\n /// A task representing the asynchronous operation.\n Task SetDefaultWallpaperAsync(bool isWindows11, bool isDarkMode);\n\n /// \n /// Gets the default wallpaper path based on Windows version and theme.\n /// \n /// Whether the system is Windows 11.\n /// Whether dark mode is enabled.\n /// The path to the default wallpaper.\n string GetDefaultWallpaperPath(bool isWindows11, bool isDarkMode);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IScriptDetectionService.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for detecting the presence of script files used by Winhance to remove applications.\n /// \n public interface IScriptDetectionService\n {\n /// \n /// Checks if any removal scripts are present.\n /// \n /// True if any removal scripts are present, false otherwise.\n bool AreRemovalScriptsPresent();\n \n /// \n /// Gets information about all active removal scripts.\n /// \n /// A collection of script information objects.\n IEnumerable GetActiveScripts();\n }\n \n /// \n /// Represents information about a script file.\n /// \n public class ScriptInfo\n {\n /// \n /// Gets or sets the name of the script file.\n /// \n public string Name { get; set; }\n \n /// \n /// Gets or sets the description of what the script does.\n /// \n public string Description { get; set; }\n \n /// \n /// Gets or sets the full path to the script file.\n /// \n public string FilePath { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IDependencyManager.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Defines methods for managing dependencies between settings.\n /// \n public interface IDependencyManager\n {\n /// \n /// Determines if a setting can be enabled based on its dependencies.\n /// \n /// The ID of the setting to check.\n /// All available settings that might be dependencies.\n /// True if the setting can be enabled; otherwise, false.\n bool CanEnableSetting(string settingId, IEnumerable allSettings);\n \n /// \n /// Handles the disabling of a setting by automatically disabling any dependent settings.\n /// \n /// The ID of the setting that was disabled.\n /// All available settings that might depend on the disabled setting.\n void HandleSettingDisabled(string settingId, IEnumerable allSettings);\n \n /// \n /// Handles the enabling of a setting by automatically enabling any required settings.\n /// \n /// The ID of the setting that is being enabled.\n /// All available settings that might be required by the enabled setting.\n /// True if all required settings were enabled successfully; otherwise, false.\n bool HandleSettingEnabled(string settingId, IEnumerable allSettings);\n\n /// \n /// Gets a list of unsatisfied dependencies for a setting.\n /// \n /// The ID of the setting to check.\n /// All available settings that might be dependencies.\n /// A list of settings that are required by the specified setting but are not enabled.\n List GetUnsatisfiedDependencies(string settingId, IEnumerable allSettings);\n\n /// \n /// Enables all dependencies in the provided list.\n /// \n /// The dependencies to enable.\n /// True if all dependencies were enabled successfully; otherwise, false.\n bool EnableDependencies(IEnumerable dependencies);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Messaging/Messages.cs", "using System;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Messaging\n{\n /// \n /// Base class for all messages that will be sent through the messenger\n /// \n public abstract class MessageBase\n {\n public DateTime Timestamp { get; } = DateTime.Now;\n }\n\n /// \n /// Message sent when a log entry is created\n /// \n public class LogMessage : MessageBase\n {\n public string Message { get; set; }\n public LogLevel Level { get; set; }\n public Exception Exception { get; set; }\n }\n\n /// \n /// Message sent when progress changes\n /// \n public class ProgressMessage : MessageBase\n {\n public double Progress { get; set; }\n public string StatusText { get; set; }\n public bool IsIndeterminate { get; set; }\n public bool IsTaskRunning { get; set; }\n }\n\n /// \n /// Message sent when detailed task progress changes\n /// \n public class TaskProgressMessage : MessageBase\n {\n public string TaskName { get; set; }\n public double Progress { get; set; }\n public string StatusText { get; set; }\n public bool IsIndeterminate { get; set; }\n public bool IsTaskRunning { get; set; }\n public bool CanCancel { get; set; }\n }\n\n /// \n /// Message sent when window state changes\n /// \n public class WindowStateMessage : MessageBase\n {\n public enum WindowStateAction\n {\n Minimize,\n Maximize,\n Restore,\n Close\n }\n\n public WindowStateAction Action { get; set; }\n }\n\n /// \n /// Message sent to update the UI theme\n /// \n public class ThemeChangedMessage : MessageBase\n {\n public bool IsDarkTheme { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IUacSettingsService.cs", "using System.Threading.Tasks;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Models.Enums;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for a service that manages UAC settings persistence.\n /// \n public interface IUacSettingsService\n {\n /// \n /// Saves custom UAC settings.\n /// \n /// The ConsentPromptBehaviorAdmin registry value.\n /// The PromptOnSecureDesktop registry value.\n /// A task representing the asynchronous operation.\n Task SaveCustomUacSettingsAsync(int consentPromptValue, int secureDesktopValue);\n\n /// \n /// Loads custom UAC settings.\n /// \n /// A CustomUacSettings object if settings exist, null otherwise.\n Task LoadCustomUacSettingsAsync();\n\n /// \n /// Checks if custom UAC settings exist.\n /// \n /// True if custom settings exist, false otherwise.\n Task HasCustomUacSettingsAsync();\n\n /// \n /// Gets custom UAC settings if they exist.\n /// \n /// The ConsentPromptBehaviorAdmin registry value.\n /// The PromptOnSecureDesktop registry value.\n /// True if custom settings were retrieved, false otherwise.\n bool TryGetCustomUacValues(out int consentPromptValue, out int secureDesktopValue);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Enums/InstallationErrorType.cs", "using System;\n\nnamespace Winhance.Core.Features.SoftwareApps.Enums\n{\n /// \n /// Defines the types of errors that can occur during installation operations.\n /// \n public enum InstallationErrorType\n {\n /// \n /// An unknown error occurred during installation.\n /// \n UnknownError,\n\n /// \n /// A network-related error occurred during installation.\n /// \n NetworkError,\n\n /// \n /// A permission-related error occurred during installation.\n /// \n PermissionError,\n\n /// \n /// The package was not found in the repositories.\n /// \n PackageNotFoundError,\n\n /// \n /// WinGet is not installed and could not be installed automatically.\n /// \n WinGetNotInstalledError,\n\n /// \n /// The package is already installed.\n /// \n AlreadyInstalledError,\n\n /// \n /// The installation was cancelled by the user.\n /// \n CancelledByUserError,\n\n /// \n /// The system is in a state that prevents installation.\n /// \n SystemStateError,\n\n /// \n /// The package is corrupted or invalid.\n /// \n PackageCorruptedError,\n\n /// \n /// The package dependencies could not be resolved.\n /// \n DependencyResolutionError\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/CustomUacSettings.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace Winhance.Core.Features.Optimize.Models\n{\n /// \n /// Represents custom User Account Control (UAC) settings that don't match standard Windows GUI options.\n /// \n [Serializable]\n public class CustomUacSettings\n {\n /// \n /// Gets or sets the ConsentPromptBehaviorAdmin registry value.\n /// \n [JsonProperty(\"ConsentPromptValue\")]\n public int ConsentPromptValue { get; set; }\n\n /// \n /// Gets or sets the PromptOnSecureDesktop registry value.\n /// \n [JsonProperty(\"SecureDesktopValue\")]\n public int SecureDesktopValue { get; set; }\n\n /// \n /// Gets or sets a timestamp when these settings were last detected or saved.\n /// \n [JsonProperty(\"LastUpdated\")]\n public DateTime LastUpdated { get; set; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n public CustomUacSettings()\n {\n // Default constructor for serialization\n }\n\n /// \n /// Initializes a new instance of the class with specific values.\n /// \n /// The ConsentPromptBehaviorAdmin registry value.\n /// The PromptOnSecureDesktop registry value.\n public CustomUacSettings(int consentPromptValue, int secureDesktopValue)\n {\n ConsentPromptValue = consentPromptValue;\n SecureDesktopValue = secureDesktopValue;\n LastUpdated = DateTime.Now;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ConfigurationServiceExtensions.cs", "using Microsoft.Extensions.DependencyInjection;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Extension methods for registering configuration services with the dependency injection container.\n /// \n public static class ConfigurationServiceExtensions\n {\n /// \n /// Adds all configuration services to the service collection.\n /// \n /// The service collection.\n /// The service collection for chaining.\n public static IServiceCollection AddConfigurationServices(this IServiceCollection services)\n {\n // Register the main configuration applier service\n services.AddTransient();\n \n // Register the property updater and view model refresher\n services.AddTransient();\n services.AddTransient();\n \n // Register all section-specific appliers\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n \n return services;\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BoolToArrowConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean value to an arrow character for UI display.\n /// True returns an up arrow, False returns a down arrow.\n /// \n public class BoolToArrowConverter : IValueConverter\n {\n public static BoolToArrowConverter Instance { get; } = new BoolToArrowConverter();\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isExpanded)\n {\n // Up arrow for expanded, down arrow for collapsed\n return isExpanded ? \"\\uE70E\" : \"\\uE70D\";\n }\n \n // Default to down arrow if value is not a boolean\n return \"\\uE70D\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // This converter doesn't support converting back\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IInstallationStatusService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n public interface IInstallationStatusService\n {\n Task GetInstallStatusAsync(string appId);\n Task RefreshStatusAsync(IEnumerable appIds);\n Task SetInstallStatusAsync(string appId, InstallStatus status);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Models/LinkedRegistrySettingWithValue.cs", "using System;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Models\n{\n /// \n /// Wrapper class for RegistrySetting that includes the current value.\n /// Used for displaying registry settings with their current values in tooltips.\n /// \n public class LinkedRegistrySettingWithValue\n {\n /// \n /// Gets the underlying registry setting.\n /// \n public RegistrySetting Setting { get; }\n\n /// \n /// Gets or sets the current value of the registry setting.\n /// \n public object? CurrentValue { get; set; }\n\n /// \n /// Creates a new instance of the LinkedRegistrySettingWithValue class.\n /// \n /// The registry setting.\n /// The current value of the registry setting.\n public LinkedRegistrySettingWithValue(RegistrySetting setting, object? currentValue)\n {\n Setting = setting ?? throw new ArgumentNullException(nameof(setting));\n CurrentValue = currentValue;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ISearchService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for services that handle search operations.\n /// \n public interface ISearchService\n {\n /// \n /// Filters a collection of items based on a search term.\n /// \n /// The type of items to filter.\n /// The collection of items to filter.\n /// The search term to filter by.\n /// A filtered collection of items that match the search term.\n IEnumerable FilterItems(IEnumerable items, string searchTerm) where T : ISearchable;\n\n /// \n /// Asynchronously filters a collection of items based on a search term.\n /// \n /// The type of items to filter.\n /// The collection of items to filter.\n /// The search term to filter by.\n /// A task that represents the asynchronous operation. The task result contains a filtered collection of items that match the search term.\n Task> FilterItemsAsync(IEnumerable items, string searchTerm) where T : ISearchable;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IMessengerService.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides functionality for messaging between components.\n /// \n public interface IMessengerService\n {\n /// \n /// Sends a message of the specified type.\n /// \n /// The type of the message to send.\n /// The message to send.\n void Send(TMessage message);\n\n /// \n /// Registers a recipient for messages of the specified type.\n /// \n /// The type of message to register for.\n /// The recipient object.\n /// The action to perform when a message is received.\n void Register(object recipient, Action action);\n\n /// \n /// Unregisters a recipient from receiving messages.\n /// \n /// The recipient to unregister.\n void Unregister(object recipient);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/IConfigurationApplierService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Interface for the service that applies configuration settings to different view models.\n /// \n public interface IConfigurationApplierService\n {\n /// \n /// Applies configuration settings to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A dictionary of section names and their application result.\n Task> ApplySectionsAsync(UnifiedConfigurationFile config, IEnumerable selectedSections);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/IconNameToSymbolConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing Winhance.WPF.Features.Common.Resources;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts an icon name to a Material Symbols Unicode character.\n /// \n public class IconNameToSymbolConverter : IValueConverter\n {\n public static IconNameToSymbolConverter Instance { get; } = new IconNameToSymbolConverter();\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is string iconName)\n {\n return MaterialSymbols.GetIcon(iconName);\n }\n \n return \"?\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToGridSpanConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Converters\n{\n /// \n /// Converts a boolean value to an integer grid span - true returns 4 (full width), false returns 1\n /// \n public class BooleanToGridSpanConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return boolValue ? 4 : 1; // Return 4 for true (header spans full width), 1 for false\n }\n return 1;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScriptModifierServiceExtensions.cs", "using Microsoft.Extensions.DependencyInjection;\nusing System;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Extension methods for registering script modifier services with the dependency injection container.\n /// \n public static class ScriptModifierServiceExtensions\n {\n /// \n /// Adds script modifier services to the specified .\n /// \n /// The to add the services to.\n /// The so that additional calls can be chained.\n public static IServiceCollection AddScriptModifierServices(this IServiceCollection services)\n {\n // Register the specialized modifiers\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n\n // Register the composite modifier as the implementation of IScriptContentModifier\n services.AddTransient();\n\n return services;\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Exceptions/AppLoadingException.cs", "using System;\n\nnamespace Winhance.Core.Models.Exceptions\n{\n public enum AppLoadingErrorCode\n {\n Unknown,\n CacheFailure,\n Timeout,\n PackageManagerError,\n InvalidConfiguration,\n NetworkError\n }\n\n public class AppLoadingException : Exception\n {\n public AppLoadingErrorCode ErrorCode { get; }\n public Exception? OriginalException { get; }\n\n public AppLoadingException(AppLoadingErrorCode errorCode, string message, \n Exception? originalException = null)\n : base(message, originalException)\n {\n ErrorCode = errorCode;\n OriginalException = originalException;\n }\n }\n\n public class PackageManagerException : Exception\n {\n public string PackageId { get; }\n public string Operation { get; }\n public Exception? OriginalException { get; }\n\n public PackageManagerException(string packageId, string operation, string message,\n Exception? originalException = null)\n : base($\"Package {operation} failed for {packageId}: {message}\", originalException)\n {\n PackageId = packageId;\n Operation = operation;\n OriginalException = originalException;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/AppModels.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\npublic enum AppInstallType\n{\n Store,\n WinGet,\n DirectDownload,\n Custom\n}\n\npublic enum TaskAction\n{\n Apply,\n Test,\n Rollback\n}\n\npublic record AppInstallConfig\n{\n public required string FriendlyName { get; init; }\n public required AppInstallType InstallType { get; init; }\n public string? PackageId { get; init; }\n public string? DownloadUrl { get; init; }\n public string? CustomInstallHandler { get; init; }\n public IDictionary? CustomProperties { get; init; }\n public bool IsInstalled { get; init; }\n}\n\npublic record InstallResult\n{\n public required bool Success { get; init; }\n public string? ErrorMessage { get; init; }\n public Exception? Exception { get; init; }\n}\n\npublic class RegistryTestResult\n{\n public string KeyPath { get; set; } = string.Empty;\n public string ValueName { get; set; } = string.Empty;\n public bool IsSuccess { get; set; }\n public object? ActualValue { get; set; }\n public object? ExpectedValue { get; set; }\n public string Message { get; set; } = string.Empty;\n public string Description { get; set; } = string.Empty;\n public string Category { get; set; } = string.Empty;\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/AppliedStatusToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class AppliedStatusToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // If the status is Applied, return Visible, otherwise return Collapsed\n if (value is RegistrySettingStatus status)\n {\n return status == RegistrySettingStatus.Applied ? Visibility.Visible : Visibility.Collapsed;\n }\n \n return Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// A simple boolean converter that returns the parameter when true, and null when false.\n /// Useful for conditional resource selection.\n /// \n public class BooleanConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return boolValue ? parameter : null;\n }\n \n return null;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return value != null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/InverseBooleanConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean value to its inverse (true to false, false to true)\n /// \n public class InverseBooleanConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return !boolValue;\n }\n \n return value;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return !boolValue;\n }\n \n return value;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/IConfigurationPropertyUpdater.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Interface for a service that updates properties of configuration items.\n /// \n public interface IConfigurationPropertyUpdater\n {\n /// \n /// Updates properties of items based on the configuration.\n /// \n /// The items to update.\n /// The configuration file containing the updates.\n /// The number of items that were updated.\n Task UpdateItemsAsync(IEnumerable items, ConfigurationFile configFile);\n\n /// \n /// Updates additional properties of an item based on the configuration.\n /// \n /// The item to update.\n /// The configuration item containing the updates.\n /// True if any properties were updated, false otherwise.\n bool UpdateAdditionalProperties(object item, ConfigurationItem configItem);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/RegistryTestResult.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents the result of a registry value test.\n /// \n public class RegistryTestResult\n {\n /// \n /// Gets or sets the registry key path.\n /// \n public string KeyPath { get; set; }\n\n /// \n /// Gets or sets the registry value name.\n /// \n public string ValueName { get; set; }\n\n /// \n /// Gets or sets the expected value.\n /// \n public object ExpectedValue { get; set; }\n\n /// \n /// Gets or sets the actual value.\n /// \n public object ActualValue { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the test was successful.\n /// \n public bool IsSuccess { get; set; }\n\n /// \n /// Gets or sets the test result message.\n /// \n public string Message { get; set; }\n\n /// \n /// Gets or sets the category of the registry setting.\n /// \n public string Category { get; set; }\n\n /// \n /// Gets or sets the description of the registry setting.\n /// \n public string Description { get; set; }\n\n /// \n /// Gets a formatted string representation of the test result.\n /// \n /// A formatted string representation of the test result.\n public override string ToString()\n {\n return $\"{(IsSuccess ? \"✓\" : \"✗\")} {KeyPath}\\\\{ValueName}: {Message}\";\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/UnifiedConfigurationFile.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents a unified configuration file that stores settings for multiple parts of the application.\n /// \n public class UnifiedConfigurationFile\n {\n /// \n /// Gets or sets the version of the configuration file format.\n /// \n public string Version { get; set; } = \"1.0\";\n\n /// \n /// Gets or sets the date and time when the configuration file was created.\n /// \n public DateTime CreatedAt { get; set; } = DateTime.UtcNow;\n\n /// \n /// Gets or sets the Windows Apps configuration section.\n /// \n public ConfigSection WindowsApps { get; set; } = new ConfigSection();\n\n /// \n /// Gets or sets the External Apps configuration section.\n /// \n public ConfigSection ExternalApps { get; set; } = new ConfigSection();\n\n /// \n /// Gets or sets the Customize configuration section.\n /// \n public ConfigSection Customize { get; set; } = new ConfigSection();\n\n /// \n /// Gets or sets the Optimize configuration section.\n /// \n public ConfigSection Optimize { get; set; } = new ConfigSection();\n }\n\n /// \n /// Represents a section in the unified configuration file.\n /// \n public class ConfigSection\n {\n /// \n /// Gets or sets a value indicating whether this section is included in the configuration.\n /// \n public bool IsIncluded { get; set; } = false;\n\n /// \n /// Gets or sets the collection of configuration items in this section.\n /// \n public List Items { get; set; } = new List();\n\n /// \n /// Gets or sets the description of this section.\n /// \n public string Description { get; set; }\n\n /// \n /// Gets or sets the icon for this section.\n /// \n public string Icon { get; set; }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/ApplicationAction.cs", "using CommunityToolkit.Mvvm.ComponentModel;\nusing System;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Base class for application actions that can be performed in both Optimization and Customization features.\n /// \n public partial class ApplicationAction : ObservableObject\n {\n [ObservableProperty]\n private string _id = string.Empty;\n \n [ObservableProperty]\n private string _name = string.Empty;\n \n [ObservableProperty]\n private string _description = string.Empty;\n \n [ObservableProperty]\n private string _groupName = string.Empty;\n \n [ObservableProperty]\n private string _confirmationMessage = string.Empty;\n \n [ObservableProperty]\n private string _actionType = string.Empty;\n \n [ObservableProperty]\n private string _command = string.Empty;\n \n [ObservableProperty]\n private string _commandAction = string.Empty;\n \n /// \n /// Gets or sets the registry setting or other action to perform.\n /// \n public RegistrySetting? RegistrySetting { get; set; }\n \n /// \n /// Gets or sets optional additional actions to perform.\n /// \n public Func>? CustomAction { get; set; }\n \n /// \n /// Gets or sets a value indicating whether this action supports backup.\n /// \n public bool SupportsBackup { get; set; }\n \n /// \n /// Gets or sets optional backup action to perform.\n /// \n public Func>? BackupAction { get; set; }\n \n /// \n /// Gets or sets the parameters for this action.\n /// \n public Dictionary Parameters { get; set; } = new Dictionary();\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/WindowStateToCommandConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Input;\n\nnamespace Winhance.WPF.Converters\n{\n public class WindowStateToCommandConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is WindowState windowState)\n {\n return windowState == WindowState.Maximized\n ? SystemCommands.RestoreWindowCommand\n : SystemCommands.MaximizeWindowCommand;\n }\n \n return SystemCommands.MaximizeWindowCommand;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/GreaterThanOneConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converter that returns true if the input value is greater than one.\n /// \n public class GreaterThanOneConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is int count)\n {\n return count > 1;\n }\n return false;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/ExternalAppsCategoryViewModel.cs", "using System.Collections.ObjectModel;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.WPF.Features.SoftwareApps.Models;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n public partial class ExternalAppsCategoryViewModel : ObservableObject\n {\n [ObservableProperty]\n private string _name;\n\n [ObservableProperty]\n private ObservableCollection _apps = new();\n\n [ObservableProperty]\n private bool _isExpanded = true;\n\n public ExternalAppsCategoryViewModel(string name, ObservableCollection apps)\n {\n _name = name;\n _apps = apps;\n }\n\n public int AppCount => Apps.Count;\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ISectionConfigurationApplier.cs", "using System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Interface for services that apply configuration to specific sections.\n /// \n public interface ISectionConfigurationApplier\n {\n /// \n /// Gets the section name that this applier handles.\n /// \n string SectionName { get; }\n\n /// \n /// Applies the configuration to the section.\n /// \n /// The configuration file to apply.\n /// True if any items were updated, false otherwise.\n Task ApplyConfigAsync(ConfigurationFile configFile);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IParameterSerializerService.cs", "namespace Winhance.Core.Interfaces.Services\n{\n /// \n /// Service for serializing and deserializing navigation parameters.\n /// \n public interface IParameterSerializerService\n {\n /// \n /// Serializes an object to a string.\n /// \n /// The object to serialize.\n /// The serialized string.\n string Serialize(object value);\n\n /// \n /// Deserializes a string to an object of the specified type.\n /// \n /// The type to deserialize to.\n /// The string to deserialize.\n /// The deserialized object.\n T Deserialize(string value);\n\n /// \n /// Deserializes a string to an object of the specified type.\n /// \n /// The type to deserialize to.\n /// The string to deserialize.\n /// The deserialized object.\n object Deserialize(System.Type type, string value);\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/IScriptContentModifier.cs", "using System;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\n/// \n/// Provides methods for modifying script content.\n/// \npublic interface IScriptContentModifier\n{\n /// \n /// Removes a capability from the script content.\n /// \n /// The script content.\n /// The name of the capability to remove.\n /// The updated script content.\n string RemoveCapabilityFromScript(string scriptContent, string capabilityName);\n\n /// \n /// Removes a package from the script content.\n /// \n /// The script content.\n /// The name of the package to remove.\n /// The updated script content.\n string RemovePackageFromScript(string scriptContent, string packageName);\n\n /// \n /// Removes an optional feature from the script content.\n /// \n /// The script content.\n /// The name of the optional feature to remove.\n /// The updated script content.\n string RemoveOptionalFeatureFromScript(string scriptContent, string featureName);\n\n /// \n /// Removes app-specific registry settings from the script content.\n /// \n /// The script content.\n /// The name of the app whose registry settings should be removed.\n /// The updated script content.\n string RemoveAppRegistrySettingsFromScript(string scriptContent, string appName);\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/IsPrimaryToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean IsPrimary value to a Visibility value.\n /// Returns Visible if the value is true, otherwise returns Collapsed.\n /// \n public class IsPrimaryToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isPrimary && isPrimary)\n {\n return Visibility.Visible;\n }\n \n return Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/RegistryScriptHelper.cs", "using System;\nusing Microsoft.Win32;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\n/// \n/// Provides helper methods for working with registry scripts.\n/// \npublic static class RegistryScriptHelper\n{\n /// \n /// Converts a RegistryValueKind to the corresponding reg.exe type string.\n /// \n /// The registry value kind.\n /// The reg.exe type string.\n public static string GetRegTypeString(RegistryValueKind valueKind)\n {\n return valueKind switch\n {\n RegistryValueKind.String => \"REG_SZ\",\n RegistryValueKind.ExpandString => \"REG_EXPAND_SZ\",\n RegistryValueKind.Binary => \"REG_BINARY\",\n RegistryValueKind.DWord => \"REG_DWORD\",\n RegistryValueKind.MultiString => \"REG_MULTI_SZ\",\n RegistryValueKind.QWord => \"REG_QWORD\",\n _ => \"REG_SZ\"\n };\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Interfaces/IViewModelLocator.cs", "using System.Windows;\n\nnamespace Winhance.WPF.Features.Common.Interfaces\n{\n /// \n /// Interface for locating view models in the application.\n /// \n public interface IViewModelLocator\n {\n /// \n /// Finds a view model of the specified type in the application.\n /// \n /// The type of view model to find.\n /// The view model if found, otherwise null.\n T? FindViewModel() where T : class;\n\n /// \n /// Finds a view model of the specified type in the specified window.\n /// \n /// The type of view model to find.\n /// The window to search in.\n /// The view model if found, otherwise null.\n T? FindViewModelInWindow(Window window) where T : class;\n\n /// \n /// Finds a view model of the specified type in the visual tree starting from the specified element.\n /// \n /// The type of view model to find.\n /// The starting element.\n /// The view model if found, otherwise null.\n T? FindViewModelInVisualTree(DependencyObject element) where T : class;\n\n /// \n /// Finds a view model by its name.\n /// \n /// The name of the view model to find.\n /// The view model if found, otherwise null.\n object? FindViewModelByName(string viewModelName);\n\n /// \n /// Gets a property from a view model.\n /// \n /// The type of the property to get.\n /// The view model to get the property from.\n /// The name of the property to get.\n /// The property value if found, otherwise null.\n T? GetPropertyFromViewModel(object viewModel, string propertyName) where T : class;\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/InverseCountToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts an integer count to a Visibility value, with the count inverted.\n /// Returns Visible if the count is 0, otherwise returns Collapsed.\n /// \n public class InverseCountToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is int count)\n {\n return count == 0 ? Visibility.Visible : Visibility.Collapsed;\n }\n \n return Visibility.Visible;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IScriptTemplateProvider.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides templates for PowerShell scripts used in the application.\n /// \n public interface IScriptTemplateProvider\n {\n /// \n /// Gets the template for removing a package.\n /// \n /// The template string for package removal.\n string GetPackageRemovalTemplate();\n\n /// \n /// Gets the template for removing a capability.\n /// \n /// The template string for capability removal.\n string GetCapabilityRemovalTemplate();\n\n /// \n /// Gets the template for removing an optional feature.\n /// \n /// The template string for optional feature removal.\n string GetFeatureRemovalTemplate();\n\n /// \n /// Gets the template for a registry setting operation.\n /// \n /// True if this is a delete operation; false if it's a set operation.\n /// The template string for registry operations.\n string GetRegistrySettingTemplate(bool isDelete);\n\n /// \n /// Gets the header for a script.\n /// \n /// The name of the script.\n /// The header string for the script.\n string GetScriptHeader(string scriptName);\n\n /// \n /// Gets the footer for a script.\n /// \n /// The footer string for the script.\n string GetScriptFooter();\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Models/ApplicationSettingGroup.cs", "using CommunityToolkit.Mvvm.ComponentModel;\nusing System.Collections.ObjectModel;\n\nnamespace Winhance.WPF.Features.Common.Models\n{\n /// \n /// Base class for application setting groups used in both Optimization and Customization features.\n /// \n public partial class ApplicationSettingGroup : ObservableObject\n {\n [ObservableProperty]\n private string _name = string.Empty;\n\n [ObservableProperty]\n private string _description = string.Empty;\n\n [ObservableProperty]\n private bool _isSelected;\n \n [ObservableProperty]\n private bool _isGroupHeader;\n \n [ObservableProperty]\n private string _groupName = string.Empty;\n \n [ObservableProperty]\n private bool _isVisible = true;\n \n /// \n /// Gets the collection of settings in this group.\n /// \n public ObservableCollection Settings { get; } = new();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ISettingsRegistry.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for a registry of settings.\n /// \n public interface ISettingsRegistry\n {\n /// \n /// Registers a setting in the registry.\n /// \n /// The setting to register.\n void RegisterSetting(ISettingItem setting);\n\n /// \n /// Gets a setting by its ID.\n /// \n /// The ID of the setting to get.\n /// The setting if found, otherwise null.\n ISettingItem? GetSettingById(string id);\n\n /// \n /// Gets all settings in the registry.\n /// \n /// A list of all settings.\n List GetAllSettings();\n\n /// \n /// Gets all settings of a specific type.\n /// \n /// The type of settings to get.\n /// A list of settings of the specified type.\n List GetSettingsByType() where T : ISettingItem;\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/CountToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts an integer count to a Visibility value.\n /// Returns Visible if the count is greater than 0, otherwise returns Collapsed.\n /// \n public class CountToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is int count)\n {\n return count > 0 ? Visibility.Visible : Visibility.Collapsed;\n }\n \n return Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/ConfigurationFile.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents a configuration file that stores application settings.\n /// \n public class ConfigurationFile\n {\n /// \n /// Gets or sets the type of configuration (e.g., \"ExternalApps\", \"WindowsApps\").\n /// \n public string ConfigType { get; set; }\n\n /// \n /// Gets or sets the version of the configuration file format.\n /// \n public string Version { get; set; } = \"1.0\";\n\n /// \n /// Gets or sets the date and time when the configuration file was created.\n /// \n public DateTime CreatedAt { get; set; } = DateTime.UtcNow;\n\n /// \n /// Gets or sets the collection of configuration items.\n /// \n public List Items { get; set; } = new List();\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/IRegistryScriptModifier.cs", "using System;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Provides methods for modifying registry-related script content.\n /// \n public interface IRegistryScriptModifier\n {\n /// \n /// Removes app-specific registry settings from the script content.\n /// \n /// The script content.\n /// The name of the app whose registry settings should be removed.\n /// The updated script content.\n string RemoveAppRegistrySettingsFromScript(string scriptContent, string appName);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ISearchable.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for objects that can be searched.\n /// \n public interface ISearchable\n {\n /// \n /// Determines if the object matches the given search term.\n /// \n /// The search term to match against.\n /// True if the object matches the search term, false otherwise.\n bool MatchesSearch(string searchTerm);\n \n /// \n /// Gets the searchable properties of the object.\n /// \n /// An array of property names that should be searched.\n string[] GetSearchableProperties();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/RemovalScript.cs", "using System;\nusing System.IO;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a script for removing applications and preventing their reinstallation.\n/// \npublic class RemovalScript\n{\n /// \n /// Gets or sets the name of the script.\n /// \n public string Name { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the content of the script.\n /// \n public string Content { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the name of the scheduled task to create for running the script.\n /// \n public string TargetScheduledTaskName { get; init; } = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether the script should run on system startup.\n /// \n public bool RunOnStartup { get; init; }\n\n /// \n /// Gets the path where the script will be saved.\n /// \n public string ScriptPath => Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n \"Winhance\",\n \"Scripts\",\n $\"{Name}.ps1\");\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BoolToChevronConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing MaterialDesignThemes.Wpf;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class BoolToChevronConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isExpanded)\n {\n return isExpanded ? PackIconKind.ChevronUp : PackIconKind.ChevronDown;\n }\n \n return PackIconKind.ChevronDown;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is PackIconKind kind)\n {\n return kind == PackIconKind.ChevronUp;\n }\n \n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/IViewModelRefresher.cs", "using System.Threading.Tasks;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Interface for a service that refreshes view models after configuration changes.\n /// \n public interface IViewModelRefresher\n {\n /// \n /// Refreshes a view model after configuration changes.\n /// \n /// The view model to refresh.\n /// A task representing the asynchronous operation.\n Task RefreshViewModelAsync(object viewModel);\n\n /// \n /// Refreshes a child view model after configuration changes.\n /// \n /// The child view model to refresh.\n /// A task representing the asynchronous operation.\n Task RefreshChildViewModelAsync(object childViewModel);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToReinstallableIconConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing MaterialDesignThemes.Wpf;\n\nnamespace Winhance.WPF.Converters\n{\n /// \n /// Converts a boolean value indicating whether an item can be reinstalled to the appropriate MaterialDesign icon.\n /// \n public class BooleanToReinstallableIconConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // Return the appropriate MaterialDesign PackIconKind\n return (bool)value ? PackIconKind.Sync : PackIconKind.SyncDisabled;\n }\n\n public object ConvertBack(\n object value,\n Type targetType,\n object parameter,\n CultureInfo culture\n )\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/RemoveActionToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class RemoveActionToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // If the action type is Remove, return Visible, otherwise return Collapsed\n if (value is RegistryActionType actionType)\n {\n return actionType == RegistryActionType.Remove ? Visibility.Visible : Visibility.Collapsed;\n }\n \n return Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Exceptions/InstallationStatusException.cs", "using System;\n\nnamespace Winhance.Core.Models.Exceptions\n{\n public class InstallationStatusException : Exception\n {\n public InstallationStatusException(string message) : base(message)\n {\n }\n\n public InstallationStatusException(string message, Exception innerException) \n : base(message, innerException)\n {\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/UacLevel.cs", "namespace Winhance.Core.Models.Enums\n{\n /// \n /// Represents User Account Control (UAC) levels in Windows.\n /// \n public enum UacLevel\n {\n /// \n /// Never notify the user when programs try to install software or make changes to the computer.\n /// \n NeverNotify = 0,\n\n /// \n /// Notify the user only when programs try to make changes to the computer, without dimming the desktop.\n /// \n NotifyNoDesktopDim = 1,\n\n /// \n /// Notify the user only when programs try to make changes to the computer (default).\n /// \n NotifyChangesOnly = 2,\n\n /// \n /// Always notify the user when programs try to install software or make changes to the computer\n /// or when the user makes changes to Windows settings.\n /// \n AlwaysNotify = 3,\n\n /// \n /// Custom UAC setting that doesn't match any of the standard Windows GUI options.\n /// This is used when the registry contains values that don't match the standard options.\n /// \n Custom = 99,\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IParameterSerializer.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for serializing and deserializing navigation parameters.\n /// \n public interface IParameterSerializer\n {\n /// \n /// Serializes an object to a string representation.\n /// \n /// The object to serialize.\n /// A string representation of the object.\n string Serialize(object parameter);\n\n /// \n /// Deserializes a string to an object of the specified type.\n /// \n /// The type to deserialize to.\n /// The string to deserialize.\n /// The deserialized object.\n object Deserialize(Type targetType, string value);\n\n /// \n /// Deserializes a string to an object of the specified type.\n /// \n /// The type to deserialize to.\n /// The string to deserialize.\n /// The deserialized object.\n T Deserialize(string serialized);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IViewModel.cs", "namespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Base interface for all view models.\n /// \n public interface IViewModel\n {\n /// \n /// Called when navigation to the view model has occurred.\n /// \n /// The navigation parameter.\n void OnNavigatedTo(object? parameter = null);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/InstalledStatusToColorConverter.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Converters;\n\npublic class InstalledStatusToColorConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (bool)value \n ? new SolidColorBrush(Color.FromRgb(0, 255, 60)) // Electric Green (#00FF3C) \n : new SolidColorBrush(Color.FromRgb(255, 40, 0)); // Ferrari Red (#FF2800)\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/CustomizationSetting.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Enums;\n\nnamespace Winhance.Core.Features.Customize.Models\n{\n /// \n /// Represents a setting that customizes the system by modifying registry values.\n /// \n public record CustomizationSetting : ApplicationSetting\n {\n /// \n /// Gets or sets the customization category for this setting.\n /// \n public required CustomizationCategory Category { get; init; }\n\n /// \n /// Gets or sets the linked settings for this setting.\n /// This allows grouping multiple settings together under a parent setting.\n /// \n public List LinkedSettings { get; init; } = new List();\n\n /// \n /// Gets or sets a value indicating whether this setting is only applicable to Windows 11.\n /// \n public bool IsWindows11Only { get; init; }\n\n /// \n /// Gets or sets a value indicating whether this setting is only applicable to Windows 10.\n /// \n public bool IsWindows10Only { get; init; }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Properties/Settings.Designer.cs", "namespace Winhance.WPF.Properties {\n \n [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator\", \"17.0.0.0\")]\n internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {\n \n private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));\n \n public static Settings Default {\n get {\n return defaultInstance;\n }\n }\n \n [global::System.Configuration.UserScopedSettingAttribute()]\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n [global::System.Configuration.DefaultSettingValueAttribute(\"True\")]\n public bool IsDarkTheme {\n get {\n return ((bool)(this[\"IsDarkTheme\"]));\n }\n set {\n this[\"IsDarkTheme\"] = value;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Models/LogMessageViewModel.cs", "using System;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Models\n{\n /// \n /// View model for log messages displayed in the UI.\n /// \n public class LogMessageViewModel\n {\n /// \n /// Gets or sets the message content.\n /// \n public string Message { get; set; }\n \n /// \n /// Gets or sets the log level.\n /// \n public LogLevel Level { get; set; }\n \n /// \n /// Gets or sets the timestamp when the message was created.\n /// \n public DateTime Timestamp { get; set; }\n \n /// \n /// Gets the formatted message with timestamp.\n /// \n public string FormattedMessage => $\"[{Timestamp:HH:mm:ss}] {Message}\";\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ICapabilityScriptModifier.cs", "using System;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Provides methods for modifying capability-related script content.\n /// \n public interface ICapabilityScriptModifier\n {\n /// \n /// Removes a capability from the script content.\n /// \n /// The script content.\n /// The name of the capability to remove.\n /// The updated script content.\n string RemoveCapabilityFromScript(string scriptContent, string capabilityName);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/CommandSetting.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents a command-based setting that can be executed to enable or disable an optimization.\n /// \n public class CommandSetting\n {\n /// \n /// Gets or sets the unique identifier for this command setting.\n /// \n public string Id { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the category this command belongs to.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description of what this command does.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the command to execute when the setting is enabled.\n /// \n public string EnabledCommand { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the command to execute when the setting is disabled.\n /// \n public string DisabledCommand { get; set; } = string.Empty;\n\n /// \n /// Gets or sets whether this command requires elevation.\n /// \n public bool RequiresElevation { get; set; } = true;\n\n /// \n /// Gets or sets whether this is the primary command in a group.\n /// \n public bool IsPrimary { get; set; } = true;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/OptimizationSetting.cs", "using Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models\n{\n /// \n /// Represents a setting that optimizes the system by modifying registry values.\n /// \n public record OptimizationSetting : ApplicationSetting\n {\n /// \n /// Gets or sets the optimization category for this setting.\n /// \n public required OptimizationCategory Category { get; init; }\n \n /// \n /// Gets or sets custom properties for this setting.\n /// This can be used to store additional data specific to certain optimization types,\n /// such as PowerCfg settings.\n /// \n public Dictionary CustomProperties { get; init; } = new Dictionary();\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/IFeatureScriptModifier.cs", "using System;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Provides methods for modifying feature-related script content.\n /// \n public interface IFeatureScriptModifier\n {\n /// \n /// Removes an optional feature from the script content.\n /// \n /// The script content.\n /// The name of the optional feature to remove.\n /// The updated script content.\n string RemoveOptionalFeatureFromScript(string scriptContent, string featureName);\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/IPackageScriptModifier.cs", "using System;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Provides methods for modifying package-related script content.\n /// \n public interface IPackageScriptModifier\n {\n /// \n /// Removes a package from the script content.\n /// \n /// The script content.\n /// The name of the package to remove.\n /// The updated script content.\n string RemovePackageFromScript(string scriptContent, string packageName);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/LinkedSettingsLogic.cs", "namespace Winhance.Core.Features.Common.Enums;\n\n/// \n/// Defines the logic to use when determining the status of linked registry settings.\n/// \npublic enum LinkedSettingsLogic\n{\n /// \n /// If any of the linked settings is applied, the entire setting is considered applied.\n /// \n Any,\n \n /// \n /// All linked settings must be applied for the entire setting to be considered applied.\n /// \n All,\n \n /// \n /// Only use the first (primary) setting to determine the status.\n /// \n Primary,\n \n /// \n /// Use a custom logic defined in the code.\n /// \n Custom\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Messages/ResetExpansionStateMessage.cs", "using System;\n\nnamespace Winhance.WPF.Features.Common.Messages\n{\n /// \n /// Message to notify the view to reset the expansion state of collapsible sections.\n /// \n public class ResetExpansionStateMessage\n {\n /// \n /// Gets the timestamp when the message was created.\n /// \n public DateTime Timestamp { get; } = DateTime.Now;\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToReinstallableTextConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Converters\n{\n /// \n /// Converts a boolean value indicating whether an item can be reinstalled to a descriptive text.\n /// \n public class BooleanToReinstallableTextConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (bool)value ? \"Is Installable\" : \"Is Not Installable\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/OptimizationEnums.cs", "namespace Winhance.Core.Features.Common.Enums;\n\npublic enum OptimizationCategory\n{\n Privacy,\n Gaming,\n Updates,\n Performance,\n GamingandPerformance,\n Personalization,\n Taskbar,\n StartMenu,\n Explorer,\n Notifications,\n Sound,\n Accessibility,\n Search,\n Services,\n Power\n}\n\npublic enum WindowsAppType\n{\n AppX,\n Capability,\n Special // For Edge, OneDrive, etc.\n}\n\npublic enum ServiceStartupType\n{\n Automatic = 2,\n Manual = 3,\n Disabled = 4\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/PowerShellProgressData.cs", "using Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents progress data from PowerShell operations.\n /// \n public class PowerShellProgressData\n {\n /// \n /// Gets or sets the percent complete value (0-100).\n /// \n public int? PercentComplete { get; set; }\n\n /// \n /// Gets or sets the activity description.\n /// \n public string Activity { get; set; }\n\n /// \n /// Gets or sets the status description.\n /// \n public string StatusDescription { get; set; }\n\n /// \n /// Gets or sets the current operation description.\n /// \n public string CurrentOperation { get; set; }\n\n /// \n /// Gets or sets the PowerShell stream type.\n /// \n public PowerShellStreamType StreamType { get; set; }\n\n /// \n /// Gets or sets the message content.\n /// \n public string Message { get; set; }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/IDesignTimeDataService.cs", "using System.Collections.Generic;\nusing Winhance.WPF.Features.SoftwareApps.Models;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Interface for providing design-time data for the application.\n /// This allows for proper visualization in the designer without running the application.\n /// \n public interface IDesignTimeDataService\n {\n /// \n /// Gets a collection of sample third-party applications for design-time.\n /// \n /// A collection of ThirdPartyApp instances.\n IEnumerable GetSampleThirdPartyApps();\n\n /// \n /// Gets a collection of sample Windows applications for design-time.\n /// \n /// A collection of WindowsApp instances.\n IEnumerable GetSampleWindowsApps();\n\n /// \n /// Gets a collection of sample Windows capabilities for design-time.\n /// \n /// A collection of WindowsApp instances configured as capabilities.\n IEnumerable GetSampleWindowsCapabilities();\n\n /// \n /// Gets a collection of sample Windows features for design-time.\n /// \n /// A collection of WindowsApp instances configured as features.\n IEnumerable GetSampleWindowsFeatures();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ISettingItem.cs", "using System.Collections.Generic;\nusing System.Windows.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Defines the common properties that all setting items should have.\n /// \n public interface ISettingItem\n {\n /// \n /// Gets or sets the unique identifier for the setting.\n /// \n string Id { get; set; }\n\n /// \n /// Gets or sets the name of the setting.\n /// \n string Name { get; set; }\n\n /// \n /// Gets or sets the description of the setting.\n /// \n string Description { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the setting is selected.\n /// \n bool IsSelected { get; set; }\n\n /// \n /// Gets or sets the group name that this setting belongs to.\n /// \n string GroupName { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the setting is visible in the UI.\n /// \n bool IsVisible { get; set; }\n\n /// \n /// Gets or sets the type of control used for this setting.\n /// \n ControlType ControlType { get; set; }\n\n /// \n /// Gets or sets the dependencies for this setting.\n /// \n List Dependencies { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the setting is being updated from code.\n /// \n bool IsUpdatingFromCode { get; set; }\n\n /// \n /// Gets the command to apply the setting.\n /// \n ICommand ApplySettingCommand { get; }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/NullToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Converters\n{\n public class NullToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // If the value is null, return Visible, otherwise return Collapsed\n return value == null ? Visibility.Visible : Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/InstalledStatusToTextConverter.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Converters;\n\npublic class InstalledStatusToTextConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (bool)value ? \"Installed\" : \"Not Installed\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/WindowsPackageModels.cs", "using Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\npublic record WindowsPackage\n{\n public required string Category { get; init; }\n public required string FriendlyName { get; init; }\n public required string PackageName { get; init; }\n public WindowsAppType AppType { get; init; }\n public IReadOnlyList? SubPackages { get; init; }\n public string? Description { get; init; }\n public IReadOnlyList? RegistrySettings { get; init; }\n public bool IsInstalled { get; init; }\n}\n\npublic record LegacyCapability\n{\n public required string FriendlyName { get; init; }\n public required string Name { get; init; }\n public bool IsInstalled { get; init; }\n}\n\npublic record WindowsService\n{\n public required string Name { get; init; }\n public required string DisplayName { get; init; }\n public required string Description { get; init; }\n public required ServiceStartupType RecommendedState { get; init; }\n public ServiceStartupType? CurrentState { get; init; }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/OptimizationConfig.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.Common.Models;\n\npublic class OptimizationConfig\n{\n public required IDictionary> RegistrySettings { get; init; }\n public required IReadOnlyList WindowsPackages { get; init; }\n public required IReadOnlyList LegacyCapabilities { get; init; }\n public required IReadOnlyList Services { get; init; }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/PowerShellStreamType.cs", "namespace Winhance.Core.Features.Common.Enums\n{\n /// \n /// Defines the types of PowerShell streams.\n /// \n public enum PowerShellStreamType\n {\n /// \n /// The output stream.\n /// \n Output,\n \n /// \n /// The error stream.\n /// \n Error,\n \n /// \n /// The warning stream.\n /// \n Warning,\n \n /// \n /// The verbose stream.\n /// \n Verbose,\n \n /// \n /// The debug stream.\n /// \n Debug,\n \n /// \n /// The information stream.\n /// \n Information,\n \n /// \n /// The progress stream.\n /// \n Progress\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/StartMenuLayouts.cs", "using System;\n\nnamespace Winhance.Core.Features.Customize.Models;\n\n/// \n/// Contains layout templates for Windows 10 and Windows 11 Start Menus.\n/// \npublic static class StartMenuLayouts\n{\n /// \n /// Gets the Windows 10 Start Menu layout XML template.\n /// \n public static string Windows10Layout => @\"\n\n \n \n \n \n \n \n\";\n\n /// \n /// Gets the Windows 11 Start Menu binary certificate template.\n /// This is a base64 encoded representation of the start2.bin file.\n /// \n public static string Windows11StartBinCertificate => @\"-----BEGIN CERTIFICATE-----\n4nrhSwH8TRucAIEL3m5RhU5aX0cAW7FJilySr5CE+V40mv9utV7aAZARAABc9u55\nLN8F4borYyXEGl8Q5+RZ+qERszeqUhhZXDvcjTF6rgdprauITLqPgMVMbSZbRsLN\n/O5uMjSLEr6nWYIwsMJkZMnZyZrhR3PugUhUKOYDqwySCY6/CPkL/Ooz/5j2R2hw\nWRGqc7ZsJxDFM1DWofjUiGjDUny+Y8UjowknQVaPYao0PC4bygKEbeZqCqRvSgPa\nlSc53OFqCh2FHydzl09fChaos385QvF40EDEgSO8U9/dntAeNULwuuZBi7BkWSIO\nmWN1l4e+TZbtSJXwn+EINAJhRHyCSNeku21dsw+cMoLorMKnRmhJMLvE+CCdgNKI\naPo/Krizva1+bMsI8bSkV/CxaCTLXodb/NuBYCsIHY1sTvbwSBRNMPvccw43RJCU\nKZRkBLkCVfW24ANbLfHXofHDMLxxFNUpBPSgzGHnueHknECcf6J4HCFBqzvSH1Tj\nQ3S6J8tq2yaQ+jFNkxGRMushdXNNiTNjDFYMJNvgRL2lu606PZeypEjvPg7SkGR2\n7a42GDSJ8n6HQJXFkOQPJ1mkU4qpA78U+ZAo9ccw8XQPPqE1eG7wzMGihTWfEMVs\nK1nsKyEZCLYFmKwYqdIF0somFBXaL/qmEHxwlPCjwRKpwLOue0Y8fgA06xk+DMti\nzWahOZNeZ54MN3N14S22D75riYEccVe3CtkDoL+4Oc2MhVdYEVtQcqtKqZ+DmmoI\n5BqkECeSHZ4OCguheFckK5Eq5Yf0CKRN+RY2OJ0ZCPUyxQnWdnOi9oBcZsz2NGzY\ng8ifO5s5UGscSDMQWUxPJQePDh8nPUittzJ+iplQqJYQ/9p5nKoDukzHHkSwfGms\n1GiSYMUZvaze7VSWOHrgZ6dp5qc1SQy0FSacBaEu4ziwx1H7w5NZj+zj2ZbxAZhr\n7Wfvt9K1xp58H66U4YT8Su7oq5JGDxuwOEbkltA7PzbFUtq65m4P4LvS4QUIBUqU\n0+JRyppVN5HPe11cCPaDdWhcr3LsibWXQ7f0mK8xTtPkOUb5pA2OUIkwNlzmwwS1\nNn69/13u7HmPSyofLck77zGjjqhSV22oHhBSGEr+KagMLZlvt9pnD/3I1R1BqItW\nKF3woyb/QizAqScEBsOKj7fmGA7f0KKQkpSpenF1Q/LNdyyOc77wbu2aywLGLN7H\nBCdwwjjMQ43FHSQPCA3+5mQDcfhmsFtORnRZWqVKwcKWuUJ7zLEIxlANZ7rDcC30\nFKmeUJuKk0Upvhsz7UXzDtNmqYmtg6vY/yPtG5Cc7XXGJxY2QJcbg1uqYI6gKtue\n00Mfpjw7XpUMQbIW9rXMA9PSWX6h2ln2TwlbrRikqdQXACZyhtuzSNLK7ifSqw4O\nJcZ8JrQ/xePmSd0z6O/MCTiUTFwG0E6WS1XBV1owOYi6jVif1zg75DTbXQGTNRvK\nKarodfnpYg3sgTe/8OAI1YSwProuGNNh4hxK+SmljqrYmEj8BNK3MNCyIskCcQ4u\ncyoJJHmsNaGFyiKp1543PktIgcs8kpF/SN86/SoB/oI7KECCCKtHNdFV8p9HO3t8\n5OsgGUYgvh7Z/Z+P7UGgN1iaYn7El9XopQ/XwK9zc9FBr73+xzE5Hh4aehNVIQdM\nMb+Rfm11R0Jc4WhqBLCC3/uBRzesyKUzPoRJ9IOxCwzeFwGQ202XVlPvklXQwgHx\nBfEAWZY1gaX6femNGDkRldzImxF87Sncnt9Y9uQty8u0IY3lLYNcAFoTobZmFkAQ\nvuNcXxObmHk3rZNAbRLFsXnWUKGjuK5oP2TyTNlm9fMmnf/E8deez3d8KOXW9YMZ\nDkA/iElnxcCKUFpwI+tWqHQ0FT96sgIP/EyhhCq6o/RnNtZvch9zW8sIGD7Lg0cq\nSzPYghZuNVYwr90qt7UDekEei4CHTzgWwlSWGGCrP6Oxjk1Fe+KvH4OYwEiDwyRc\nl7NRJseqpW1ODv8c3VLnTJJ4o3QPlAO6tOvon7vA1STKtXylbjWARNcWuxT41jtC\nCzrAroK2r9bCij4VbwHjmpQnhYbF/hCE1r71Z5eHdWXqpSgIWeS/1avQTStsehwD\n2+NGFRXI8mwLBLQN/qi8rqmKPi+fPVBjFoYDyDc35elpdzvqtN/mEp+xDrnAbwXU\nyfhkZvyo2+LXFMGFLdYtWTK/+T/4n03OJH1gr6j3zkoosewKTiZeClnK/qfc8YLw\nbCdwBm4uHsZ9I14OFCepfHzmXp9nN6a3u0sKi4GZpnAIjSreY4rMK8c+0FNNDLi5\nDKuck7+WuGkcRrB/1G9qSdpXqVe86uNojXk9P6TlpXyL/noudwmUhUNTZyOGcmhJ\nEBiaNbT2Awx5QNssAlZFuEfvPEAixBz476U8/UPb9ObHbsdcZjXNV89WhfYX04DM\n9qcMhCnGq25sJPc5VC6XnNHpFeWhvV/edYESdeEVwxEcExKEAwmEZlGJdxzoAH+K\nY+xAZdgWjPPL5FaYzpXc5erALUfyT+n0UTLcjaR4AKxLnpbRqlNzrWa6xqJN9NwA\n+xa38I6EXbQ5Q2kLcK6qbJAbkEL76WiFlkc5mXrGouukDvsjYdxG5Rx6OYxb41Ep\n1jEtinaNfXwt/JiDZxuXCMHdKHSH40aZCRlwdAI1C5fqoUkgiDdsxkEq+mGWxMVE\nZd0Ch9zgQLlA6gYlK3gt8+dr1+OSZ0dQdp3ABqb1+0oP8xpozFc2bK3OsJvucpYB\nOdmS+rfScY+N0PByGJoKbdNUHIeXv2xdhXnVjM5G3G6nxa3x8WFMJsJs2ma1xRT1\n8HKqjX9Ha072PD8Zviu/bWdf5c4RrphVqvzfr9wNRpfmnGOoOcbkRE4QrL5CqrPb\nVRujOBMPGAxNlvwq0w1XDOBDawZgK7660yd4MQFZk7iyZgUSXIo3ikleRSmBs+Mt\nr+3Og54Cg9QLPHbQQPmiMsu21IJUh0rTgxMVBxNUNbUaPJI1lmbkTcc7HeIk0Wtg\nRxwYc8aUn0f/V//c+2ZAlM6xmXmj6jIkOcfkSBd0B5z63N4trypD3m+w34bZkV1I\ncQ8h7SaUUqYO5RkjStZbvk2IDFSPUExvqhCstnJf7PZGilbsFPN8lYqcIvDZdaAU\nMunNh6f/RnhFwKHXoyWtNI6yK6dm1mhwy+DgPlA2nAevO+FC7Vv98Sl9zaVjaPPy\n3BRyQ6kISCL065AKVPEY0ULHqtIyfU5gMvBeUa5+xbU+tUx4ZeP/BdB48/LodyYV\nkkgqTafVxCvz4vgmPbnPjm/dlRbVGbyygN0Noq8vo2Ea8Z5zwO32coY2309AC7wv\nPp2wJZn6LKRmzoLWJMFm1A1Oa4RUIkEpA3AAL+5TauxfawpdtTjicoWGQ5gGNwum\n+evTnGEpDimE5kUU6uiJ0rotjNpB52I+8qmbgIPkY0Fwwal5Z5yvZJ8eepQjvdZ2\nUcdvlTS8oA5YayGi+ASmnJSbsr/v1OOcLmnpwPI+hRgPP+Hwu5rWkOT+SDomF1TO\nn/k7NkJ967X0kPx6XtxTPgcG1aKJwZBNQDKDP17/dlZ869W3o6JdgCEvt1nIOPty\nlGgvGERC0jCNRJpGml4/py7AtP0WOxrs+YS60sPKMATtiGzp34++dAmHyVEmelhK\napQBuxFl6LQN33+2NNn6L5twI4IQfnm6Cvly9r3VBO0Bi+rpjdftr60scRQM1qw+\n9dEz4xL9VEL6wrnyAERLY58wmS9Zp73xXQ1mdDB+yKkGOHeIiA7tCwnNZqClQ8Mf\nRnZIAeL1jcqrIsmkQNs4RTuE+ApcnE5DMcvJMgEd1fU3JDRJbaUv+w7kxj4/+G5b\nIU2bfh52jUQ5gOftGEFs1LOLj4Bny2XlCiP0L7XLJTKSf0t1zj2ohQWDT5BLo0EV\n5rye4hckB4QCiNyiZfavwB6ymStjwnuaS8qwjaRLw4JEeNDjSs/JC0G2ewulUyHt\nkEobZO/mQLlhso2lnEaRtK1LyoD1b4IEDbTYmjaWKLR7J64iHKUpiQYPSPxcWyei\no4kcyGw+QvgmxGaKsqSBVGogOV6YuEyoaM0jlfUmi2UmQkju2iY5tzCObNQ41nsL\ndKwraDrcjrn4CAKPMMfeUSvYWP559EFfDhDSK6Os6Sbo8R6Zoa7C2NdAicA1jPbt\n5ENSrVKf7TOrthvNH9vb1mZC1X2RBmriowa/iT+LEbmQnAkA6Y1tCbpzvrL+cX8K\npUTOAovaiPbab0xzFP7QXc1uK0XA+M1wQ9OF3XGp8PS5QRgSTwMpQXW2iMqihYPv\nHu6U1hhkyfzYZzoJCjVsY2xghJmjKiKEfX0w3RaxfrJkF8ePY9SexnVUNXJ1654/\nPQzDKsW58Au9QpIH9VSwKNpv003PksOpobM6G52ouCFOk6HFzSLfnlGZW0yyUQL3\nRRyEE2PP0LwQEuk2gxrW8eVy9elqn43S8CG2h2NUtmQULc/IeX63tmCOmOS0emW9\n66EljNdMk/e5dTo5XplTJRxRydXcQpgy9bQuntFwPPoo0fXfXlirKsav2rPSWayw\nKQK4NxinT+yQh//COeQDYkK01urc2G7SxZ6H0k6uo8xVp9tDCYqHk/lbvukoN0RF\ntUI4aLWuKet1O1s1uUAxjd50ELks5iwoqLJ/1bzSmTRMifehP07sbK/N1f4hLae+\njykYgzDWNfNvmPEiz0DwO/rCQTP6x69g+NJaFlmPFwGsKfxP8HqiNWQ6D3irZYcQ\nR5Mt2Iwzz2ZWA7B2WLYZWndRCosRVWyPdGhs7gkmLPZ+WWo/Yb7O1kIiWGfVuPNA\nMKmgPPjZy8DhZfq5kX20KF6uA0JOZOciXhc0PPAUEy/iQAtzSDYjmJ8HR7l4mYsT\nO3Mg3QibMK8MGGa4tEM8OPGktAV5B2J2QOe0f1r3vi3QmM+yukBaabwlJ+dUDQGm\n+Ll/1mO5TS+BlWMEAi13cB5bPRsxkzpabxq5kyQwh4vcMuLI0BOIfE2pDKny5jhW\n0C4zzv3avYaJh2ts6kvlvTKiSMeXcnK6onKHT89fWQ7Hzr/W8QbR/GnIWBbJMoTc\nWcgmW4fO3AC+YlnLVK4kBmnBmsLzLh6M2LOabhxKN8+0Oeoouww7g0HgHkDyt+MS\n97po6SETwrdqEFslylLo8+GifFI1bb68H79iEwjXojxQXcD5qqJPxdHsA32eWV0b\nqXAVojyAk7kQJfDIK+Y1q9T6KI4ew4t6iauJ8iVJyClnHt8z/4cXdMX37EvJ+2BS\nYKHv5OAfS7/9ZpKgILT8NxghgvguLB7G9sWNHntExPtuRLL4/asYFYSAJxUPm7U2\nxnp35Zx5jCXesd5OlKNdmhXq519cLl0RGZfH2ZIAEf1hNZqDuKesZ2enykjFlIec\nhZsLvEW/pJQnW0+LFz9N3x3vJwxbC7oDgd7A2u0I69Tkdzlc6FFJcfGabT5C3eF2\nEAC+toIobJY9hpxdkeukSuxVwin9zuBoUM4X9x/FvgfIE0dKLpzsFyMNlO4taCLc\nv1zbgUk2sR91JmbiCbqHglTzQaVMLhPwd8GU55AvYCGMOsSg3p952UkeoxRSeZRp\njQHr4bLN90cqNcrD3h5knmC61nDKf8e+vRZO8CVYR1eb3LsMz12vhTJGaQ4jd0Kz\nQyosjcB73wnE9b/rxfG1dRactg7zRU2BfBK/CHpIFJH+XztwMJxn27foSvCY6ktd\nuJorJvkGJOgwg0f+oHKDvOTWFO1GSqEZ5BwXKGH0t0udZyXQGgZWvF5s/ojZVcK3\nIXz4tKhwrI1ZKnZwL9R2zrpMJ4w6smQgipP0yzzi0ZvsOXRksQJNCn4UPLBhbu+C\neFBbpfe9wJFLD+8F9EY6GlY2W9AKD5/zNUCj6ws8lBn3aRfNPE+Cxy+IKC1NdKLw\neFdOGZr2y1K2IkdefmN9cLZQ/CVXkw8Qw2nOr/ntwuFV/tvJoPW2EOzRmF2XO8mQ\nDQv51k5/v4ZE2VL0dIIvj1M+KPw0nSs271QgJanYwK3CpFluK/1ilEi7JKDikT8X\nTSz1QZdkum5Y3uC7wc7paXh1rm11nwluCC7jiA==\n-----END CERTIFICATE-----\";\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/InstallStatus.cs", "namespace Winhance.Core.Features.Common.Models\n{\n public enum InstallStatus\n {\n Success,\n NotFound,\n Failed,\n Pending\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/PowerPlan.cs", "using System;\n\nnamespace Winhance.Core.Features.Optimize.Models\n{\n /// \n /// Represents a Windows power plan.\n /// \n public class PowerPlan\n {\n /// \n /// Gets or sets the name of the power plan.\n /// \n public string Name { get; set; }\n\n /// \n /// Gets or sets the GUID of the power plan.\n /// \n public string Guid { get; set; }\n\n /// \n /// Gets or sets the source GUID for plans that need to be created from another plan.\n /// \n public string SourceGuid { get; set; }\n\n /// \n /// Gets or sets the description of the power plan.\n /// \n public string Description { get; set; }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/RegistrySettingStatus.cs", "namespace Winhance.Core.Features.Common.Enums;\n\npublic enum RegistrySettingStatus\n{\n Unknown, // Status couldn't be determined\n NotApplied, // Registry key doesn't exist or has default value\n Applied, // Current value matches recommended value\n Modified, // Value exists but doesn't match recommended or default\n Error // Error occurred while checking status\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IVisibleSettingItem.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for setting items that can be shown or hidden in the UI.\n /// \n public interface IVisibleSettingItem\n {\n /// \n /// Gets or sets a value indicating whether this setting item is visible in the UI.\n /// \n bool IsVisible { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/CustomizationGroup.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Customize.Enums;\n\nnamespace Winhance.Core.Features.Customize.Models\n{\n /// \n /// Represents a group of customization settings.\n /// \n public record CustomizationGroup\n {\n /// \n /// Gets or sets the name of the customization group.\n /// \n public required string Name { get; init; }\n\n /// \n /// Gets or sets the category of the customization group.\n /// \n public required CustomizationCategory Category { get; init; }\n\n /// \n /// Gets or sets the settings in the customization group.\n /// \n public required IReadOnlyList Settings { get; init; }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Theme/MaterialSymbols.cs", "namespace Winhance.WPF.Theme\n{\n /// \n /// Contains constants for Material Symbols icon names.\n /// \n public static class MaterialSymbols\n {\n // Sync icons\n public const string Sync = \"sync\";\n public const string SyncProblem = \"sync_problem\";\n\n // Other commonly used icons\n public const string Check = \"check\";\n public const string Close = \"close\";\n public const string Info = \"info\";\n public const string Warning = \"warning\";\n public const string Error = \"error\";\n public const string Settings = \"settings\";\n public const string Add = \"add\";\n public const string Remove = \"remove\";\n public const string Edit = \"edit\";\n public const string Delete = \"delete\";\n public const string Search = \"search\";\n public const string Download = \"download\";\n public const string Upload = \"upload\";\n public const string Refresh = \"refresh\";\n public const string Save = \"save\";\n public const string Menu = \"menu\";\n public const string Home = \"home\";\n public const string Person = \"person\";\n public const string Help = \"help\";\n public const string ArrowBack = \"arrow_back\";\n public const string ArrowForward = \"arrow_forward\";\n public const string ArrowUpward = \"arrow_upward\";\n public const string ArrowDownward = \"arrow_downward\";\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/RegistryActionType.cs", "namespace Winhance.Core.Features.Common.Enums;\n\n/// \n/// Defines the intended action for a registry setting.\n/// \npublic enum RegistryActionType\n{\n /// \n /// The setting is intended to set a specific value.\n /// \n Set,\n \n /// \n /// The setting is intended to remove a key or value.\n /// \n Remove,\n \n /// \n /// The setting is intended to modify an existing value.\n /// \n Modify\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/IInstallableItem.cs", "namespace Winhance.Core.Features.Common.Models\n{\n public interface IInstallableItem\n {\n string PackageId { get; }\n string DisplayName { get; }\n InstallItemType ItemType { get; }\n bool IsInstalled { get; set; }\n bool RequiresRestart { get; }\n }\n\n public enum InstallItemType\n {\n WindowsApp,\n Capability,\n Feature,\n ThirdParty\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Enums/CustomizationCategory.cs", "namespace Winhance.Core.Features.Customize.Enums;\n\n/// \n/// Defines the categories for customization settings.\n/// \npublic enum CustomizationCategory\n{\n /// \n /// Theme-related customization settings.\n /// \n Theme,\n \n /// \n /// Taskbar-related customization settings.\n /// \n Taskbar,\n \n /// \n /// Start menu-related customization settings.\n /// \n StartMenu,\n \n /// \n /// Explorer-related customization settings.\n /// \n Explorer,\n \n /// \n /// Notification-related customization settings.\n /// \n Notifications,\n \n /// \n /// Sound-related customization settings.\n /// \n Sound,\n \n /// \n /// Accessibility-related customization settings.\n /// \n Accessibility\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Views/WindowsAppsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Views\n{\n /// \n /// Interaction logic for WindowsAppsView.xaml\n /// \n public partial class WindowsAppsView : UserControl\n {\n public WindowsAppsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/Views/StartMenuCustomizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Customize.Views\n{\n /// \n /// Interaction logic for StartMenuCustomizationsView.xaml\n /// \n public partial class StartMenuCustomizationsView : UserControl\n {\n public StartMenuCustomizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/ControlType.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Enums\n{\n /// \n /// Defines the type of control to use for a setting.\n /// \n public enum ControlType\n {\n /// \n /// A binary toggle (on/off) control.\n /// \n BinaryToggle,\n\n /// \n /// A three-state slider control.\n /// \n ThreeStateSlider,\n\n /// \n /// A combo box control for selecting from a list of options.\n /// \n ComboBox,\n\n /// \n /// A custom control.\n /// \n Custom,\n\n /// \n /// A slider control.\n /// \n Slider,\n\n /// \n /// A dropdown control.\n /// \n Dropdown,\n\n /// \n /// A color picker control.\n /// \n ColorPicker\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Converters;\n\npublic class BooleanToVisibilityConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (bool)value ? Visibility.Visible : Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (Visibility)value == Visibility.Visible;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/LogLevel.cs", "namespace Winhance.Core.Features.Common.Enums\n{\n public enum LogLevel\n {\n Info,\n Warning,\n Error,\n Success,\n Debug\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Customize/Views/TaskbarCustomizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Customize.Views\n{\n /// \n /// Interaction logic for TaskbarCustomizationsView.xaml\n /// \n public partial class TaskbarCustomizationsView : UserControl\n {\n public TaskbarCustomizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/UpdateOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for UpdateOptimizationsView.xaml\n /// \n public partial class UpdateOptimizationsView : UserControl\n {\n public UpdateOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/Views/ExplorerCustomizationsView.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Customize.Views\n{\n /// \n /// Interaction logic for ExplorerCustomizationsView.xaml\n /// \n public partial class ExplorerCustomizationsView : UserControl\n {\n public ExplorerCustomizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/Views/WindowsThemeCustomizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Customize.Views\n{\n /// \n /// Interaction logic for WindowsThemeCustomizationsView.xaml\n /// \n public partial class WindowsThemeCustomizationsView : UserControl\n {\n public WindowsThemeCustomizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/ExplorerOptimizationsView.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for ExplorerOptimizationsView.xaml\n /// \n public partial class ExplorerOptimizationsView : UserControl\n {\n public ExplorerOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/NotificationOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for NotificationOptimizationsView.xaml\n /// \n public partial class NotificationOptimizationsView : UserControl\n {\n public NotificationOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/SoundOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for SoundOptimizationsView.xaml\n /// \n public partial class SoundOptimizationsView : UserControl\n {\n public SoundOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/PowerOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for PowerOptimizationsView.xaml\n /// \n public partial class PowerOptimizationsView : UserControl\n {\n public PowerOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/PrivacyOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for PrivacyOptimizationsView.xaml\n /// \n public partial class PrivacyOptimizationsView : UserControl\n {\n public PrivacyOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/WindowsSecurityOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for WindowsSecurityOptimizationsView.xaml\n /// \n public partial class WindowsSecurityOptimizationsView : UserControl\n {\n public WindowsSecurityOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/GamingandPerformanceOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for GamingandPerformanceOptimizationsView.xaml\n /// \n public partial class GamingandPerformanceOptimizationsView : UserControl\n {\n public GamingandPerformanceOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Resources/Theme/IThemeManager.cs", "using System;\n\nnamespace Winhance.WPF.Features.Common.Resources.Theme\n{\n public interface IThemeManager : IDisposable\n {\n bool IsDarkTheme { get; set; }\n void ToggleTheme();\n void ApplyTheme();\n void LoadThemePreference();\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Customize/Enums/CustomizationSettingType.cs", "using System;\n\nnamespace Winhance.Core.Features.Customize.Enums\n{\n /// \n /// Defines the type of customization setting.\n /// \n public enum CustomizationSettingType\n {\n /// \n /// A standard setting.\n /// \n Standard,\n\n /// \n /// A slider setting.\n /// \n Slider,\n\n /// \n /// A dropdown setting.\n /// \n Dropdown,\n\n /// \n /// A color picker setting.\n /// \n ColorPicker\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 19:10:26", "created_task_model": "DeepSeek-R1", "function_skeleton": "private async Task StartConnectivityMonitoring (AppInfo appInfo, CancellationTokenSource cts) {}", "code_description": "This code segment functions to: Monitor network availability during critical operations and trigger status updates and cancellation procedures when connectivity is disrupted, while providing user notifications and maintaining event handler integrity through proper registration and cleanup routines."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n private async Task StartConnectivityMonitoring(AppInfo appInfo, CancellationTokenSource cts)\n {\n try\n {\n while (!cts.IsCancellationRequested)\n {\n if (!_connectivityService.IsConnected)\n {\n var errorMessage = $\"Lost internet connectivity during installation of {appInfo.Name}\";\n _logService.LogError(errorMessage);\n \n // Show notification if service is available\n _notificationService?.ShowErrorNotification(errorMessage);\n \n // Show dialog if service is available\n if (_dialogService != null)\n {\n await _dialogService.ShowMessageAsync(\n \"Connection Lost\",\n \"The installation has been paused due to internet connectivity issues. Please check your network connection.\",\n \"OK\");\n }\n \n cts.Cancel();\n return true;\n }\n \n await Task.Delay(TimeSpan.FromSeconds(5), cts.Token);\n }\n }\n catch (OperationCanceledException)\n {\n // Expected cancellation when monitoring is stopped\n }\n \n return false;\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-10-50"}, "editdistance_info": {"edit_distance": 26.1965, "calculate_time": "2025-08-20 19:10:50", "true_code_clean": "private async Task StartConnectivityMonitoring(AppInfo appInfo, CancellationTokenSource cts)\n {\n bool connectivityIssueDetected = false;\n EventHandler connectivityChangedHandler = null;\n connectivityChangedHandler = (sender, args) =>\n {\n if (cts.Token.IsCancellationRequested)\n {\n return; \n }\n if (args.IsUserCancelled)\n {\n var message = $\"Installation of {appInfo.Name} was cancelled by user\";\n RaiseStatusChanged(appInfo, message, false, false, true);\n }\n else if (!args.IsConnected)\n {\n connectivityIssueDetected = true;\n var message = $\"Error: Internet connection lost while installing {appInfo.Name}. Installation stopped.\";\n RaiseStatusChanged(appInfo, message, false, false, false, true);\n _notificationService?.ShowToast(\n \"Internet Connection Lost\",\n \"Internet connection has been lost during installation. Installation has been stopped.\",\n ToastType.Error\n );\n if (_dialogService != null)\n {\n _ = _dialogService.ShowInformationAsync(\n $\"The installation of {appInfo.Name} has been stopped because internet connection was lost. Please check your network connection and try again when your internet connection is stable.\",\n \"Internet Connection Lost\"\n );\n }\n cts.Cancel();\n }\n };\n try\n {\n _connectivityService.ConnectivityChanged += connectivityChangedHandler;\n await _connectivityService.StartMonitoringAsync(5, cts.Token);\n try\n {\n await Task.Delay(-1, cts.Token);\n }\n catch (OperationCanceledException)\n {\n }\n return connectivityIssueDetected;\n }\n finally\n {\n if (connectivityChangedHandler != null)\n {\n _connectivityService.ConnectivityChanged -= connectivityChangedHandler;\n }\n _connectivityService.StopMonitoring();\n }\n }", "predict_code_clean": "private async Task StartConnectivityMonitoring(AppInfo appInfo, CancellationTokenSource cts)\n {\n try\n {\n while (!cts.IsCancellationRequested)\n {\n if (!_connectivityService.IsConnected)\n {\n var errorMessage = $\"Lost internet connectivity during installation of {appInfo.Name}\";\n _logService.LogError(errorMessage);\n _notificationService?.ShowErrorNotification(errorMessage);\n if (_dialogService != null)\n {\n await _dialogService.ShowMessageAsync(\n \"Connection Lost\",\n \"The installation has been paused due to internet connectivity issues. Please check your network connection.\",\n \"OK\");\n }\n cts.Cancel();\n return true;\n }\n await Task.Delay(TimeSpan.FromSeconds(5), cts.Token);\n }\n }\n catch (OperationCanceledException)\n {\n }\n return false;\n }"}} {"repo_name": "Winhance", "file_name": "/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToThemeIconConverter.cs", "inference_info": {"prefix_code": "using System;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Media.Imaging;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean value (IsDarkTheme) to the appropriate themed icon path\n /// \n public class BooleanToThemeIconConverter : IValueConverter\n {\n ", "suffix_code": "\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // This converter doesn't support converting back\n throw new NotImplementedException();\n }\n }\n}\n", "middle_code": "public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n bool isDarkTheme = false;\n if (value is bool boolValue)\n {\n isDarkTheme = boolValue;\n Debug.WriteLine($\"BooleanToThemeIconConverter: isDarkTheme = {isDarkTheme} (from bool)\");\n }\n else if (value is string stringValue)\n {\n isDarkTheme = stringValue.Equals(\"Dark\", StringComparison.OrdinalIgnoreCase);\n Debug.WriteLine($\"BooleanToThemeIconConverter: isDarkTheme = {isDarkTheme} (from string '{stringValue}')\");\n }\n else\n {\n Debug.WriteLine($\"BooleanToThemeIconConverter: value is {(value == null ? \"null\" : value.GetType().Name)}\");\n }\n if (parameter is string paramString)\n {\n string[] iconPaths = paramString.Split('|');\n if (iconPaths.Length >= 2)\n {\n string darkIconPath = iconPaths[0];\n string lightIconPath = iconPaths[1];\n string selectedPath = isDarkTheme ? darkIconPath : lightIconPath;\n Debug.WriteLine($\"BooleanToThemeIconConverter: Selected path = {selectedPath}\");\n if (targetType == typeof(BitmapImage))\n {\n return new BitmapImage(new Uri(selectedPath, UriKind.Relative));\n }\n return selectedPath;\n }\n }\n Debug.WriteLine(\"BooleanToThemeIconConverter: Using fallback icon path\");\n return \"/Resources/AppIcons/winhance-rocket.ico\";\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/Winhance/src/Winhance.WPF/Features/Common/Views/LoadingWindow.xaml.cs", "using System;\nusing System.Diagnostics;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Media.Imaging;\nusing System.Runtime.InteropServices;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Interaction logic for LoadingWindow.xaml\n /// \n public partial class LoadingWindow : Window\n {\n private readonly IThemeManager? _themeManager;\n private LoadingWindowViewModel? _viewModel;\n\n /// \n /// Default constructor for design-time\n /// \n public LoadingWindow()\n {\n // Ignore this error, it works fine in the designer\n InitializeComponent();\n }\n\n /// \n /// Constructor with dependency injection\n /// \n /// The theme manager\n public LoadingWindow(IThemeManager themeManager)\n {\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n // Ignore this error, it works fine in the designer\n InitializeComponent();\n }\n\n /// \n /// Constructor with dependency injection and progress service\n /// \n /// The theme manager\n /// The progress service\n public LoadingWindow(IThemeManager themeManager, ITaskProgressService progressService)\n {\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n // Ignore this error, it works fine in the designer\n InitializeComponent();\n\n // Create and set the view model\n _viewModel = new LoadingWindowViewModel(progressService);\n DataContext = _viewModel;\n\n // Set the appropriate icon based on the theme\n UpdateThemeIcon();\n }\n\n /// \n /// Called when the window source is initialized\n /// \n /// Event arguments\n protected override void OnSourceInitialized(EventArgs e)\n {\n base.OnSourceInitialized(e);\n\n try\n {\n var helper = new WindowInteropHelper(this);\n if (helper.Handle != IntPtr.Zero)\n {\n EnableBlur();\n }\n }\n catch (Exception)\n {\n // Ignore blur errors - not critical for loading window\n }\n }\n\n /// \n /// Enables the blur effect on the window\n /// \n private void EnableBlur()\n {\n var windowHelper = new WindowInteropHelper(this);\n var accent = new AccentPolicy { AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND };\n var accentStructSize = Marshal.SizeOf(accent);\n\n var accentPtr = IntPtr.Zero;\n try\n {\n accentPtr = Marshal.AllocHGlobal(accentStructSize);\n Marshal.StructureToPtr(accent, accentPtr, false);\n\n var data = new WindowCompositionAttributeData\n {\n Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY,\n SizeOfData = accentStructSize,\n Data = accentPtr\n };\n\n SetWindowCompositionAttribute(windowHelper.Handle, ref data);\n }\n finally\n {\n if (accentPtr != IntPtr.Zero)\n {\n Marshal.FreeHGlobal(accentPtr);\n }\n }\n }\n\n /// \n /// P/Invoke for SetWindowCompositionAttribute\n /// \n [DllImport(\"user32.dll\")]\n internal static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data);\n\n /// \n /// Accent policy structure\n /// \n [StructLayout(LayoutKind.Sequential)]\n internal struct AccentPolicy\n {\n public AccentState AccentState;\n public int AccentFlags;\n public int GradientColor;\n public int AnimationId;\n }\n\n /// \n /// Window composition attribute data structure\n /// \n [StructLayout(LayoutKind.Sequential)]\n internal struct WindowCompositionAttributeData\n {\n public WindowCompositionAttribute Attribute;\n public IntPtr Data;\n public int SizeOfData;\n }\n\n /// \n /// Accent state enum\n /// \n internal enum AccentState\n {\n ACCENT_DISABLED = 0,\n ACCENT_ENABLE_GRADIENT = 1,\n ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,\n ACCENT_ENABLE_BLURBEHIND = 3,\n ACCENT_ENABLE_ACRYLICBLURBEHIND = 4,\n ACCENT_INVALID_STATE = 5\n }\n\n /// \n /// Window composition attribute enum\n /// \n internal enum WindowCompositionAttribute\n {\n WCA_ACCENT_POLICY = 19\n }\n\n /// \n /// Updates the window and image icons based on the current theme\n /// \n private void UpdateThemeIcon()\n {\n if (_themeManager == null)\n {\n Debug.WriteLine(\"Cannot update theme icon: ThemeManager is null\");\n return;\n }\n\n try\n {\n Debug.WriteLine($\"Updating theme icon. Current theme: {(_themeManager.IsDarkTheme ? \"Dark\" : \"Light\")}\");\n\n // Get the appropriate icon based on the theme\n string iconPath = _themeManager.IsDarkTheme\n ? \"pack://application:,,,/Resources/AppIcons/winhance-rocket-white-transparent-bg.ico\"\n : \"pack://application:,,,/Resources/AppIcons/winhance-rocket-black-transparent-bg.ico\";\n\n Debug.WriteLine($\"Selected icon path: {iconPath}\");\n\n // Create a BitmapImage from the icon path\n var iconImage = new BitmapImage(new Uri(iconPath, UriKind.Absolute));\n iconImage.Freeze(); // Freeze for better performance and thread safety\n\n // Set the window icon\n this.Icon = iconImage;\n Debug.WriteLine(\"Window icon updated\");\n\n // Set the image control source\n if (AppIconImage != null)\n {\n AppIconImage.Source = iconImage;\n Debug.WriteLine(\"AppIconImage source updated\");\n }\n else\n {\n Debug.WriteLine(\"AppIconImage is null, cannot update source\");\n }\n }\n catch (Exception ex)\n {\n // If there's an error, fall back to the default icon\n try\n {\n var defaultIcon = new BitmapImage(new Uri(\"pack://application:,,,/Resources/AppIcons/winhance-rocket.ico\", UriKind.Absolute));\n this.Icon = defaultIcon;\n if (AppIconImage != null)\n {\n AppIconImage.Source = defaultIcon;\n }\n }\n catch\n {\n // Ignore any errors with the fallback icon\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToThemeConverter.cs", "using System;\nusing System.Globalization;\nusing System.Linq;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean value to a theme string (\"Dark\" or \"Light\") or theme-specific colors\n /// \n public class BooleanToThemeConverter : IValueConverter, IMultiValueConverter\n {\n // Default track colors\n private static readonly Color DarkTrackColor = Color.FromRgb(68, 68, 68);\n private static readonly Color LightTrackColor = Color.FromRgb(204, 204, 204);\n \n // Checked track colors\n private static readonly Color DarkCheckedTrackColor = Color.FromRgb(85, 85, 85);\n private static readonly Color LightCheckedTrackColor = Color.FromRgb(66, 66, 66);\n \n // Knob colors\n private static readonly Color DefaultKnobColor = Color.FromRgb(255, 255, 255); // White for unchecked\n private static readonly Color DarkCheckedKnobColor = Color.FromRgb(255, 222, 0); // Yellow for dark theme checked\n private static readonly Color LightCheckedKnobColor = Color.FromRgb(66, 66, 66); // Gray for light theme checked\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n bool isDarkTheme = false;\n bool isChecked = false;\n \n // Handle different input types for theme\n if (value is bool boolValue)\n {\n isDarkTheme = boolValue;\n }\n else if (value is string stringValue)\n {\n isDarkTheme = stringValue.Equals(\"Dark\", StringComparison.OrdinalIgnoreCase);\n }\n \n // Extract checked state from parameter if provided\n if (parameter is string paramString)\n {\n string[] parts = paramString.Split(':');\n string elementType = parts[0];\n \n // Check if we have checked state information\n if (parts.Length > 1)\n {\n isChecked = parts[1].Equals(\"Checked\", StringComparison.OrdinalIgnoreCase);\n }\n \n if (targetType == typeof(Brush) || targetType == typeof(SolidColorBrush))\n {\n if (elementType.Equals(\"Track\", StringComparison.OrdinalIgnoreCase))\n {\n if (isChecked)\n {\n return new SolidColorBrush(isDarkTheme ? DarkCheckedTrackColor : LightCheckedTrackColor);\n }\n else\n {\n return new SolidColorBrush(isDarkTheme ? DarkTrackColor : LightTrackColor);\n }\n }\n else if (elementType.Equals(\"Knob\", StringComparison.OrdinalIgnoreCase))\n {\n if (isChecked)\n {\n // Use the hardcoded colors for better reliability\n return new SolidColorBrush(isDarkTheme ? DarkCheckedKnobColor : LightCheckedKnobColor);\n }\n else\n {\n // Use white for unchecked knobs in both themes\n return new SolidColorBrush(DefaultKnobColor);\n }\n }\n }\n }\n \n // Default behavior - return theme string\n return isDarkTheme ? \"Dark\" : \"Light\";\n }\n \n // Implementation for IMultiValueConverter\n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n if (values.Length < 2)\n return Binding.DoNothing;\n \n bool isDarkTheme = false;\n bool isChecked = false;\n \n // First value is the theme\n if (values[0] is bool themeBool)\n {\n isDarkTheme = themeBool;\n }\n else if (values[0] is string themeString)\n {\n isDarkTheme = themeString.Equals(\"Dark\", StringComparison.OrdinalIgnoreCase);\n }\n \n // Second value is the checked state\n if (values[1] is bool checkedBool)\n {\n isChecked = checkedBool;\n }\n \n // Determine which element we're styling based on parameter\n string elementType = parameter as string ?? \"Track\";\n \n if (targetType == typeof(Brush) || targetType == typeof(SolidColorBrush))\n {\n if (elementType.Equals(\"Track\", StringComparison.OrdinalIgnoreCase))\n {\n if (isChecked)\n {\n return new SolidColorBrush(isDarkTheme ? DarkCheckedTrackColor : LightCheckedTrackColor);\n }\n else\n {\n return new SolidColorBrush(isDarkTheme ? DarkTrackColor : LightTrackColor);\n }\n }\n else if (elementType.Equals(\"Knob\", StringComparison.OrdinalIgnoreCase))\n {\n if (isChecked)\n {\n // Use the hardcoded colors for better reliability\n return new SolidColorBrush(isDarkTheme ? DarkCheckedKnobColor : LightCheckedKnobColor);\n }\n else\n {\n // Use white for unchecked knobs in both themes\n return new SolidColorBrush(DefaultKnobColor);\n }\n }\n }\n \n return Binding.DoNothing;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is string themeString)\n {\n return themeString.Equals(\"Dark\", StringComparison.OrdinalIgnoreCase);\n }\n \n return false; // Default to Light theme (false) if value is not a string\n }\n \n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n // We don't need to implement this for our use case\n return targetTypes.Select(t => Binding.DoNothing).ToArray();\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Resources/Theme/ThemeManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Reflection;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Media;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Properties;\n\nnamespace Winhance.WPF.Features.Common.Resources.Theme\n{\n public partial class ThemeManager : ObservableObject, IThemeManager, IDisposable\n {\n private bool _isDarkTheme = true;\n\n public bool IsDarkTheme\n {\n get => _isDarkTheme;\n set\n {\n if (_isDarkTheme != value)\n {\n _isDarkTheme = value;\n OnPropertyChanged(nameof(IsDarkTheme));\n\n // Update the application resource\n Application.Current.Resources[\"IsDarkTheme\"] = _isDarkTheme;\n }\n }\n }\n\n private readonly INavigationService _navigationService;\n\n // Dictionary with default color values for each theme\n private static readonly Dictionary DarkThemeColors = new()\n {\n { \"PrimaryTextColor\", Color.FromRgb(255, 255, 255) },\n { \"SecondaryTextColor\", Color.FromRgb(170, 170, 170) },\n { \"TertiaryTextColor\", Color.FromRgb(128, 128, 128) },\n { \"HelpIconColor\", Color.FromRgb(255, 255, 255) },\n { \"TooltipBackgroundColor\", Color.FromRgb(43, 45, 48) },\n { \"TooltipForegroundColor\", Color.FromRgb(255, 255, 255) },\n { \"TooltipBorderColor\", Color.FromRgb(255, 222, 0) },\n { \"ControlForegroundColor\", Color.FromRgb(255, 255, 255) },\n { \"ControlFillColor\", Color.FromRgb(255, 255, 255) },\n { \"ControlBorderColor\", Color.FromRgb(255, 222, 0) },\n { \"ToggleKnobColor\", Color.FromRgb(255, 255, 255) },\n { \"ToggleKnobCheckedColor\", Color.FromRgb(255, 222, 0) },\n { \"ContentSectionBorderColor\", Color.FromRgb(31, 32, 34) },\n { \"MainContainerBorderColor\", Color.FromRgb(43, 45, 48) },\n { \"PrimaryButtonForegroundColor\", Color.FromRgb(255, 255, 255) },\n { \"AccentColor\", Color.FromRgb(255, 222, 0) },\n { \"ButtonHoverTextColor\", Color.FromRgb(32, 33, 36) },\n { \"ButtonDisabledForegroundColor\", Color.FromRgb(153, 163, 164) },\n { \"ButtonDisabledBorderColor\", Color.FromRgb(43, 45, 48) },\n { \"NavigationButtonBackgroundColor\", Color.FromRgb(31, 32, 34) },\n { \"NavigationButtonForegroundColor\", Color.FromRgb(255, 255, 255) },\n { \"SliderTrackColor\", Color.FromRgb(64, 64, 64) },\n { \"BackgroundColor\", Color.FromRgb(32, 32, 32) },\n { \"ContentSectionBackgroundColor\", Color.FromRgb(31, 32, 34) },\n { \"ScrollBarThumbColor\", Color.FromRgb(255, 222, 0) },\n { \"ScrollBarThumbHoverColor\", Color.FromRgb(255, 233, 76) },\n { \"ScrollBarThumbPressedColor\", Color.FromRgb(255, 240, 102) },\n };\n\n private static readonly Dictionary LightThemeColors = new()\n {\n { \"PrimaryTextColor\", Color.FromRgb(32, 33, 36) },\n { \"SecondaryTextColor\", Color.FromRgb(102, 102, 102) },\n { \"TertiaryTextColor\", Color.FromRgb(153, 153, 153) },\n { \"HelpIconColor\", Color.FromRgb(32, 33, 36) },\n { \"TooltipBackgroundColor\", Color.FromRgb(255, 255, 255) },\n { \"TooltipForegroundColor\", Color.FromRgb(32, 33, 36) },\n { \"TooltipBorderColor\", Color.FromRgb(66, 66, 66) },\n { \"ControlForegroundColor\", Color.FromRgb(32, 33, 36) },\n { \"ControlFillColor\", Color.FromRgb(66, 66, 66) },\n { \"ControlBorderColor\", Color.FromRgb(66, 66, 66) },\n { \"ToggleKnobColor\", Color.FromRgb(255, 255, 255) },\n { \"ToggleKnobCheckedColor\", Color.FromRgb(66, 66, 66) },\n { \"ContentSectionBorderColor\", Color.FromRgb(246, 248, 252) },\n { \"MainContainerBorderColor\", Color.FromRgb(255, 255, 255) },\n { \"PrimaryButtonForegroundColor\", Color.FromRgb(32, 33, 36) },\n { \"AccentColor\", Color.FromRgb(66, 66, 66) },\n { \"ButtonHoverTextColor\", Color.FromRgb(255, 255, 255) },\n { \"ButtonDisabledForegroundColor\", Color.FromRgb(204, 204, 204) },\n { \"ButtonDisabledBorderColor\", Color.FromRgb(238, 238, 238) },\n { \"NavigationButtonBackgroundColor\", Color.FromRgb(255, 255, 255) },\n { \"NavigationButtonForegroundColor\", Color.FromRgb(32, 33, 36) },\n { \"SliderTrackColor\", Color.FromRgb(204, 204, 204) },\n { \"BackgroundColor\", Color.FromRgb(246, 248, 252) },\n { \"ContentSectionBackgroundColor\", Color.FromRgb(240, 240, 240) },\n { \"ScrollBarThumbColor\", Color.FromRgb(66, 66, 66) },\n { \"ScrollBarThumbHoverColor\", Color.FromRgb(102, 102, 102) },\n { \"ScrollBarThumbPressedColor\", Color.FromRgb(34, 34, 34) },\n };\n\n public ThemeManager(INavigationService navigationService)\n {\n _navigationService = navigationService ?? throw new ArgumentNullException(nameof(navigationService));\n\n // Subscribe to navigation events to update toggle switches when navigating between views\n _navigationService.Navigated += NavigationService_Navigated;\n\n LoadThemePreference();\n ApplyTheme();\n }\n\n private void NavigationService_Navigated(object sender, NavigationEventArgs e)\n {\n // We no longer need to update toggle switches on navigation\n // as they will automatically pick up the correct theme from the application resources\n }\n\n public void ToggleTheme()\n {\n IsDarkTheme = !IsDarkTheme;\n ApplyTheme();\n\n // Ensure the window icons are updated when toggling the theme\n NotifyWindowsOfThemeChange();\n }\n\n public void ApplyTheme()\n {\n try\n {\n var themeColors = IsDarkTheme ? DarkThemeColors : LightThemeColors;\n\n // We no longer need to explicitly update toggle switches\n // as they will automatically pick up the theme from application resources\n\n // Create brushes for all UI elements\n var brushes = new List<(string key, SolidColorBrush brush)>\n {\n (\"WindowBackground\", new SolidColorBrush(themeColors[\"BackgroundColor\"])),\n (\"PrimaryTextColor\", new SolidColorBrush(themeColors[\"PrimaryTextColor\"])),\n (\"SecondaryTextColor\", new SolidColorBrush(themeColors[\"SecondaryTextColor\"])),\n (\"TertiaryTextColor\", new SolidColorBrush(themeColors[\"TertiaryTextColor\"])),\n (\"SubTextColor\", new SolidColorBrush(themeColors[\"SecondaryTextColor\"])),\n (\"HelpIconForeground\", new SolidColorBrush(themeColors[\"HelpIconColor\"])),\n (\n \"ContentSectionBackground\",\n new SolidColorBrush(themeColors[\"ContentSectionBackgroundColor\"])\n ),\n (\n \"ContentSectionBorderBrush\",\n new SolidColorBrush(themeColors[\"ContentSectionBorderColor\"])\n ),\n (\n \"MainContainerBorderBrush\",\n new SolidColorBrush(themeColors[\"MainContainerBorderColor\"])\n ),\n (\n \"NavigationButtonBackground\",\n new SolidColorBrush(themeColors[\"NavigationButtonBackgroundColor\"])\n ),\n (\n \"NavigationButtonForeground\",\n new SolidColorBrush(themeColors[\"NavigationButtonForegroundColor\"])\n ),\n (\"ButtonBorderBrush\", new SolidColorBrush(themeColors[\"AccentColor\"])),\n (\"ButtonHoverBackground\", new SolidColorBrush(themeColors[\"AccentColor\"])),\n (\n \"ButtonHoverTextColor\",\n new SolidColorBrush(themeColors[\"ButtonHoverTextColor\"])\n ),\n (\n \"PrimaryButtonForeground\",\n new SolidColorBrush(themeColors[\"PrimaryButtonForegroundColor\"])\n ),\n (\n \"ButtonDisabledForeground\",\n new SolidColorBrush(themeColors[\"ButtonDisabledForegroundColor\"])\n ),\n (\n \"ButtonDisabledBorderBrush\",\n new SolidColorBrush(themeColors[\"ButtonDisabledBorderColor\"])\n ),\n (\n \"ButtonDisabledHoverBackground\",\n new SolidColorBrush(themeColors[\"ButtonDisabledBorderColor\"])\n ),\n (\n \"ButtonDisabledHoverForeground\",\n new SolidColorBrush(themeColors[\"ButtonDisabledForegroundColor\"])\n ),\n (\n \"TooltipBackground\",\n new SolidColorBrush(themeColors[\"TooltipBackgroundColor\"])\n ),\n (\n \"TooltipForeground\",\n new SolidColorBrush(themeColors[\"TooltipForegroundColor\"])\n ),\n (\"TooltipBorderBrush\", new SolidColorBrush(themeColors[\"TooltipBorderColor\"])),\n (\n \"ControlForeground\",\n new SolidColorBrush(themeColors[\"ControlForegroundColor\"])\n ),\n (\"ControlFillColor\", new SolidColorBrush(themeColors[\"ControlFillColor\"])),\n (\n \"ControlBorderBrush\",\n new SolidColorBrush(themeColors[\"ControlBorderColor\"])\n ),\n (\n \"ToggleKnobBrush\",\n new SolidColorBrush(themeColors[\"ToggleKnobColor\"])\n ),\n (\n \"ToggleKnobCheckedBrush\",\n new SolidColorBrush(themeColors[\"ToggleKnobCheckedColor\"])\n ),\n (\"SliderTrackBackground\", new SolidColorBrush(themeColors[\"SliderTrackColor\"])),\n // Special handling for slider thumb in light mode to make them more visible\n (\n \"SliderAccentColor\",\n new SolidColorBrush(\n IsDarkTheme ? themeColors[\"AccentColor\"] : Color.FromRgb(240, 240, 240)\n )\n ),\n (\"TickBarForeground\", new SolidColorBrush(themeColors[\"PrimaryTextColor\"])),\n (\n \"ScrollBarThumbBrush\",\n new SolidColorBrush(themeColors[\"ScrollBarThumbColor\"])\n ),\n (\n \"ScrollBarThumbHoverBrush\",\n new SolidColorBrush(themeColors[\"ScrollBarThumbHoverColor\"])\n ),\n (\n \"ScrollBarThumbPressedBrush\",\n new SolidColorBrush(themeColors[\"ScrollBarThumbPressedColor\"])\n ),\n };\n\n var resources = Application.Current.Resources;\n\n // Update all brushes in the application resources\n foreach (var (key, brush) in brushes)\n {\n // Freeze for better performance\n brush.Freeze();\n\n // Update in main resources dictionary\n resources[key] = brush;\n }\n\n // Notify the ViewNameToBackgroundConverter that the theme has changed\n try\n {\n Winhance.WPF.Features.Common.Converters.ViewNameToBackgroundConverter.Instance.NotifyThemeChanged();\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error notifying ViewNameToBackgroundConverter: {ex.Message}\");\n }\n\n // Attempt to force a visual refresh of the main window\n var mainWindow = Application.Current.MainWindow;\n if (mainWindow != null)\n {\n // Force a layout update\n mainWindow.InvalidateVisual();\n\n // Directly update the navigation buttons and toggle switches\n Application.Current.Dispatcher.Invoke(() =>\n {\n try\n {\n // Find the navigation buttons by name\n var softwareAppsButton = FindChildByName(\n mainWindow,\n \"SoftwareAppsButton\"\n );\n var optimizeButton = FindChildByName(mainWindow, \"OptimizeButton\");\n var customizeButton = FindChildByName(mainWindow, \"CustomizeButton\");\n var aboutButton = FindChildByName(mainWindow, \"AboutButton\");\n\n // Get the current view name from the main view model\n string currentViewName = string.Empty;\n if (mainWindow.DataContext != null)\n {\n var mainViewModel = mainWindow.DataContext as dynamic;\n currentViewName = mainViewModel.CurrentViewName;\n }\n\n // Update each button's background if not null\n if (softwareAppsButton != null)\n UpdateButtonBackground(\n softwareAppsButton,\n \"SoftwareApps\",\n currentViewName\n );\n if (optimizeButton != null)\n UpdateButtonBackground(optimizeButton, \"Optimize\", currentViewName);\n if (customizeButton != null)\n UpdateButtonBackground(\n customizeButton,\n \"Customize\",\n currentViewName\n );\n if (aboutButton != null)\n UpdateButtonBackground(aboutButton, \"About\", currentViewName);\n\n // We no longer need to explicitly update toggle switches\n // as they will automatically pick up the theme from application resources\n\n // Force a more thorough refresh of the UI\n mainWindow.UpdateLayout();\n\n // Update theme-dependent icons\n NotifyWindowsOfThemeChange();\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error updating UI elements: {ex.Message}\");\n }\n });\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error applying theme: {ex.Message}\");\n Debug.WriteLine(ex.StackTrace);\n }\n\n // Save theme preference\n SaveThemePreference();\n }\n\n private void SaveThemePreference()\n {\n try\n {\n Settings.Default.IsDarkTheme = IsDarkTheme;\n Settings.Default.Save();\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Failed to save theme preference: {ex.Message}\");\n }\n }\n\n public void LoadThemePreference()\n {\n try\n {\n IsDarkTheme = Settings.Default.IsDarkTheme;\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Failed to load theme preference: {ex.Message}\");\n // Keep default value if loading fails\n }\n }\n\n // Clean up event subscriptions\n public void Dispose()\n {\n try\n {\n if (_navigationService != null)\n {\n _navigationService.Navigated -= NavigationService_Navigated;\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error cleaning up ThemeManager: {ex.Message}\");\n }\n }\n\n public void ResetThemePreference()\n {\n try\n {\n Settings.Default.Reset();\n LoadThemePreference();\n ApplyTheme();\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Failed to reset theme preference: {ex.Message}\");\n }\n }\n\n // Helper method to find a child element by name\n private static System.Windows.Controls.Button? FindChildByName(\n DependencyObject parent,\n string name\n )\n {\n if (parent == null)\n return null;\n\n // Check if the current element is the one we're looking for\n if (\n parent is FrameworkElement element\n && element.Name == name\n && element is System.Windows.Controls.Button button\n )\n {\n return button;\n }\n\n // Get the number of children\n int childCount = VisualTreeHelper.GetChildrenCount(parent);\n\n // Recursively search through all children\n for (int i = 0; i < childCount; i++)\n {\n var child = VisualTreeHelper.GetChild(parent, i);\n var result = FindChildByName(child, name);\n if (result != null)\n {\n return result;\n }\n }\n\n return null;\n }\n\n // Helper method to update a button's background based on whether it's selected\n private void UpdateButtonBackground(\n System.Windows.Controls.Button button,\n string buttonViewName,\n string currentViewName\n )\n {\n if (button == null)\n return;\n\n var themeColors = IsDarkTheme ? DarkThemeColors : LightThemeColors;\n\n // Determine if this button is for the currently selected view\n bool isSelected = string.Equals(\n buttonViewName,\n currentViewName,\n StringComparison.OrdinalIgnoreCase\n );\n\n // Set the appropriate background color\n if (isSelected)\n {\n button.Background = new SolidColorBrush(themeColors[\"MainContainerBorderColor\"]);\n }\n else\n {\n button.Background = new SolidColorBrush(\n themeColors[\"NavigationButtonBackgroundColor\"]\n );\n }\n\n // Update the foreground color for the button's content\n button.Foreground = new SolidColorBrush(themeColors[\"NavigationButtonForegroundColor\"]);\n }\n\n // Method to update all toggle switches in all open windows\n private void UpdateAllToggleSwitches()\n {\n try\n {\n // Update toggle switches in all open windows\n foreach (Window window in Application.Current.Windows)\n {\n UpdateToggleSwitches(window);\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error updating toggle switches: {ex.Message}\");\n Debug.WriteLine(ex.StackTrace);\n }\n }\n\n // Method to notify windows about theme changes\n private void NotifyWindowsOfThemeChange()\n {\n try\n {\n Debug.WriteLine($\"NotifyWindowsOfThemeChange called. Current theme: {(IsDarkTheme ? \"Dark\" : \"Light\")}\");\n\n // Notify all open windows about theme changes\n foreach (Window window in Application.Current.Windows)\n {\n Debug.WriteLine($\"Processing window: {window.GetType().Name}\");\n\n // Check if the window is a MainWindow or LoadingWindow\n if (window is MainWindow mainWindow)\n {\n // Call the UpdateThemeIcon method using reflection\n try\n {\n Debug.WriteLine(\"Attempting to update MainWindow icon\");\n var method = mainWindow.GetType().GetMethod(\"UpdateThemeIcon\", BindingFlags.Instance | BindingFlags.NonPublic);\n if (method != null)\n {\n // Use the dispatcher to ensure UI updates happen on the UI thread\n mainWindow.Dispatcher.Invoke(() =>\n {\n method.Invoke(mainWindow, null);\n });\n Debug.WriteLine(\"Updated theme icon in MainWindow\");\n }\n else\n {\n Debug.WriteLine(\"UpdateThemeIcon method not found in MainWindow\");\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error updating theme icon in MainWindow: {ex.Message}\");\n Debug.WriteLine(ex.StackTrace);\n }\n }\n else if (window is LoadingWindow loadingWindow)\n {\n // Call the UpdateThemeIcon method using reflection\n try\n {\n Debug.WriteLine(\"Attempting to update LoadingWindow icon\");\n var method = loadingWindow.GetType().GetMethod(\"UpdateThemeIcon\", BindingFlags.Instance | BindingFlags.NonPublic);\n if (method != null)\n {\n // Use the dispatcher to ensure UI updates happen on the UI thread\n loadingWindow.Dispatcher.Invoke(() =>\n {\n method.Invoke(loadingWindow, null);\n });\n Debug.WriteLine(\"Updated theme icon in LoadingWindow\");\n }\n else\n {\n Debug.WriteLine(\"UpdateThemeIcon method not found in LoadingWindow\");\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error updating theme icon in LoadingWindow: {ex.Message}\");\n Debug.WriteLine(ex.StackTrace);\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error notifying windows of theme change: {ex.Message}\");\n Debug.WriteLine(ex.StackTrace);\n }\n }\n\n // Helper method to update all toggle switches in the visual tree\n private void UpdateToggleSwitches(DependencyObject parent)\n {\n if (parent == null)\n return;\n\n // Check if the current element is a ToggleButton\n if (parent is ToggleButton toggleButton)\n {\n try\n {\n // Always set the Tag property for all toggle buttons\n toggleButton.Tag = IsDarkTheme ? \"Dark\" : \"Light\";\n\n // Force a visual refresh for all toggle buttons\n toggleButton.InvalidateVisual();\n\n // Force a more thorough refresh\n if (toggleButton.Parent is FrameworkElement parentElement)\n {\n parentElement.InvalidateVisual();\n parentElement.UpdateLayout();\n }\n\n // Ensure the toggle button is enabled and clickable if it should be\n if (!toggleButton.IsEnabled && toggleButton.IsEnabled != false)\n {\n toggleButton.IsEnabled = true;\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error updating toggle button: {ex.Message}\");\n }\n }\n\n // Get the number of children\n int childCount = VisualTreeHelper.GetChildrenCount(parent);\n\n // Recursively search through all children\n for (int i = 0; i < childCount; i++)\n {\n var child = VisualTreeHelper.GetChild(parent, i);\n UpdateToggleSwitches(child);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/MainWindow.xaml.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Interop;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.Common.Utilities;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n public partial class MainWindow : Window\n {\n private readonly Winhance.Core.Features.Common.Interfaces.INavigationService _navigationService =\n null!;\n private WindowSizeManager _windowSizeManager;\n private readonly UserPreferencesService _userPreferencesService;\n private readonly IApplicationCloseService _applicationCloseService;\n\n private void LogDebug(string message, Exception? ex = null)\n {\n string fullMessage = message + (ex != null ? $\" - Exception: {ex.Message}\" : \"\");\n\n // Use proper logging service for application logging\n _messengerService?.Send(\n new LogMessage\n {\n Message = fullMessage,\n Level = ex != null ? LogLevel.Error : LogLevel.Debug,\n Exception = ex,\n }\n );\n\n // Also log to diagnostic file for troubleshooting\n FileLogger.Log(\"MainWindow\", fullMessage);\n\n // If there's an exception, log the stack trace as well\n if (ex != null)\n {\n FileLogger.Log(\"MainWindow\", $\"Stack trace: {ex.StackTrace}\");\n }\n\n // Also log to WinhanceStartupLog.txt for debugging the white screen issue\n LogToStartupLog(fullMessage);\n if (ex != null)\n {\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n }\n }\n\n /// \n /// Logs a message directly to the WinhanceStartupLog.txt file\n /// \n private void LogToStartupLog(string message)\n {\n#if DEBUG\n try\n {\n string logsDir = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\"\n );\n string logFile = Path.Combine(logsDir, \"WinhanceStartupLog.txt\");\n\n // Ensure the logs directory exists\n if (!Directory.Exists(logsDir))\n {\n Directory.CreateDirectory(logsDir);\n }\n\n // Format the log message with timestamp\n string formattedMessage =\n $\"[{DateTime.Now:yyyy/MM/dd HH:mm:ss}] [MainWindow] {message}\";\n\n // Append to the log file\n using (StreamWriter writer = File.AppendText(logFile))\n {\n writer.WriteLine(formattedMessage);\n }\n }\n catch\n {\n // Ignore errors in logging to avoid cascading issues\n }\n#endif\n }\n\n public MainWindow()\n {\n LogDebug(\"Default constructor called - THIS SHOULD NOT HAPPEN\");\n try\n {\n // Don't worry about this error, it is initialized at runtime.\n InitializeComponent();\n LogDebug(\"Default constructor completed initialization\");\n\n // Direct event handlers for window control buttons\n this.MinimizeButton.Click += (s, e) => this.WindowState = WindowState.Minimized;\n this.MaximizeRestoreButton.Click += (s, e) =>\n {\n this.WindowState =\n (this.WindowState == WindowState.Maximized)\n ? WindowState.Normal\n : WindowState.Maximized;\n };\n this.CloseButton.Click += CloseButton_Click;\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in default constructor\", ex);\n throw;\n }\n }\n\n // No need to define InitializeComponent here, it's generated by the WPF build system\n\n public MainWindow(\n IThemeManager themeManager,\n IServiceProvider serviceProvider,\n IMessengerService messengerService,\n Winhance.Core.Features.Common.Interfaces.INavigationService navigationService,\n IVersionService versionService,\n UserPreferencesService userPreferencesService,\n IApplicationCloseService applicationCloseService\n )\n {\n try\n {\n // Use FileLogger directly to ensure we capture everything\n FileLogger.Log(\"MainWindow\", \"MainWindow constructor starting\");\n FileLogger.Log(\n \"MainWindow\",\n $\"Parameters: themeManager={themeManager != null}, serviceProvider={serviceProvider != null}, messengerService={messengerService != null}, navigationService={navigationService != null}, versionService={versionService != null}, userPreferencesService={userPreferencesService != null}\"\n );\n\n // Verify dependencies\n if (themeManager == null)\n throw new ArgumentNullException(nameof(themeManager));\n if (serviceProvider == null)\n throw new ArgumentNullException(nameof(serviceProvider));\n if (messengerService == null)\n throw new ArgumentNullException(nameof(messengerService));\n if (navigationService == null)\n throw new ArgumentNullException(nameof(navigationService));\n if (versionService == null)\n throw new ArgumentNullException(nameof(versionService));\n if (userPreferencesService == null)\n throw new ArgumentNullException(nameof(userPreferencesService));\n FileLogger.Log(\"MainWindow\", \"Dependencies verified\");\n\n // Let the build system initialize the component\n try\n {\n LogToStartupLog(\"Starting InitializeComponent\");\n\n // We'll use a try-catch block around each part of the InitializeComponent process\n try\n {\n LogToStartupLog(\"Calling InitializeComponent()\");\n InitializeComponent();\n LogToStartupLog(\"InitializeComponent() completed successfully\");\n }\n catch (Exception initEx)\n {\n LogToStartupLog($\"ERROR in InitializeComponent(): {initEx.Message}\");\n LogToStartupLog($\"Stack trace: {initEx.StackTrace}\");\n throw; // Re-throw to be caught by the outer try-catch\n }\n\n LogToStartupLog(\"InitializeComponent completed\");\n\n // Direct event handlers for window control buttons\n try\n {\n LogToStartupLog(\"Setting up window control button event handlers\");\n\n LogToStartupLog($\"MinimizeButton exists: {this.MinimizeButton != null}\");\n this.MinimizeButton.Click += (s, e) =>\n this.WindowState = WindowState.Minimized;\n\n LogToStartupLog(\n $\"MaximizeRestoreButton exists: {this.MaximizeRestoreButton != null}\"\n );\n this.MaximizeRestoreButton.Click += (s, e) =>\n {\n this.WindowState =\n (this.WindowState == WindowState.Maximized)\n ? WindowState.Normal\n : WindowState.Maximized;\n\n // Update button content when window state changes\n if (DataContext is MainViewModel viewModel)\n {\n viewModel.MaximizeButtonContent =\n (this.WindowState == WindowState.Maximized)\n ? \"WindowRestore\"\n : \"WindowMaximize\";\n }\n };\n\n LogToStartupLog($\"CloseButton exists: {this.CloseButton != null}\");\n this.CloseButton.Click += CloseButton_Click;\n\n LogToStartupLog($\"MoreButton exists: {this.MoreButton != null}\");\n LogToStartupLog($\"MoreMenuControl exists: {this.MoreMenuControl != null}\");\n this.MoreButton.Click += MoreButton_Click;\n\n LogToStartupLog(\n \"Successfully set up all window control button event handlers\"\n );\n }\n catch (Exception buttonEx)\n {\n LogToStartupLog(\n $\"ERROR setting up button event handlers: {buttonEx.Message}\"\n );\n LogToStartupLog($\"Stack trace: {buttonEx.StackTrace}\");\n }\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in InitializeComponent\", ex);\n // This is not ideal, but we'll continue since the constructor errors will be handled\n }\n\n LogDebug(\"Setting fields\");\n _themeManager = themeManager;\n _serviceProvider = serviceProvider;\n _messengerService = messengerService;\n _navigationService = navigationService;\n _versionService =\n versionService ?? throw new ArgumentNullException(nameof(versionService));\n\n // Create the window size manager\n try\n {\n var logService =\n _serviceProvider.GetService(typeof(ILogService)) as ILogService;\n\n if (userPreferencesService != null && logService != null)\n {\n _windowSizeManager = new WindowSizeManager(\n this,\n userPreferencesService,\n logService\n );\n LogDebug(\"WindowSizeManager created successfully\");\n }\n else\n {\n LogDebug(\"Could not create WindowSizeManager: services not available\");\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error creating WindowSizeManager: {ex.Message}\", ex);\n }\n _userPreferencesService =\n userPreferencesService\n ?? throw new ArgumentNullException(nameof(userPreferencesService));\n _applicationCloseService =\n applicationCloseService\n ?? throw new ArgumentNullException(nameof(applicationCloseService));\n LogDebug(\"Fields set\");\n\n // Hook up events for ContentPresenter-based navigation\n if (\n _navigationService\n is Winhance.Core.Features.Common.Interfaces.INavigationService navService\n )\n {\n LogDebug(\"Setting up navigation service for ContentPresenter-based navigation\");\n\n // Add PreviewMouseWheel event handler for better scrolling\n this.PreviewMouseWheel += MainWindow_PreviewMouseWheel;\n\n // We'll navigate once the window is fully loaded\n this.Loaded += (sender, e) =>\n {\n LogDebug(\"Window loaded, navigating to default view\");\n\n // Apply the theme to ensure all toggle switches are properly initialized\n try\n {\n LogDebug(\"Applying theme to initialize toggle switches\");\n if (_themeManager != null)\n {\n // Apply the theme which will update all toggle switches\n _themeManager.ApplyTheme();\n LogDebug(\"Successfully initialized toggle switches\");\n\n // Update the app icon based on the theme\n UpdateThemeIcon();\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error initializing toggle switches: {ex.Message}\", ex);\n }\n\n if (DataContext is MainViewModel mainViewModel)\n {\n try\n {\n // Navigate to SoftwareApps view by default\n LogDebug(\"Navigating to SoftwareApps view\");\n _navigationService.NavigateTo(\"SoftwareApps\");\n\n // Verify that navigation succeeded\n if (mainViewModel.CurrentViewModel == null)\n {\n LogDebug(\n \"WARNING: Navigation succeeded but CurrentViewModel is null\"\n );\n }\n else\n {\n LogDebug(\n $\"Navigation succeeded, CurrentViewModel is {mainViewModel.CurrentViewModel.GetType().Name}\"\n );\n }\n }\n catch (Exception ex)\n {\n LogDebug(\n $\"Error navigating to SoftwareApps view: {ex.Message}\",\n ex\n );\n\n // Try to recover by navigating to another view\n try\n {\n LogDebug(\"Attempting to navigate to About view as fallback\");\n _navigationService.NavigateTo(\"About\");\n }\n catch (Exception fallbackEx)\n {\n LogDebug(\n $\"Error navigating to fallback view: {fallbackEx.Message}\",\n fallbackEx\n );\n }\n }\n }\n else\n {\n LogDebug(\n $\"DataContext is not MainViewModel, it is {DataContext?.GetType().Name ?? \"null\"}\"\n );\n }\n };\n\n // Add StateChanged event to update Maximize/Restore button content only\n this.StateChanged += (sender, e) =>\n {\n if (DataContext is MainViewModel viewModel)\n {\n viewModel.MaximizeButtonContent =\n (this.WindowState == WindowState.Maximized)\n ? \"WindowRestore\"\n : \"WindowMaximize\";\n }\n };\n\n // We no longer save window position/size to preferences\n }\n else\n {\n LogDebug(\n $\"_navigationService is not INavigationService, it is {_navigationService?.GetType().Name ?? \"null\"}\"\n );\n }\n\n // Register for window state messages\n LogDebug(\"Registering for window state messages\");\n _messengerService.Register(this, HandleWindowStateMessage);\n LogDebug(\"Registered for window state messages\");\n\n // Add Closing event handler to log the closing process\n this.Closing += MainWindow_Closing;\n\n // Clean up when window is closed\n this.Closed += (sender, e) =>\n {\n LogDebug(\"Window closed, unregistering from messenger service\");\n _messengerService.Unregister(this);\n };\n\n LogDebug($\"DataContext is {(DataContext == null ? \"null\" : \"not null\")}\");\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in parameterized constructor\", ex);\n throw;\n }\n }\n\n private async void CloseButton_Click(object sender, RoutedEventArgs e)\n {\n try\n {\n LogDebug(\"CloseButton_Click called, delegating to ApplicationCloseService\");\n await _applicationCloseService.CloseApplicationWithSupportDialogAsync();\n }\n catch (Exception ex)\n {\n LogDebug($\"Error in CloseButton_Click: {ex.Message}\", ex);\n\n // Fallback to direct close if there's an error\n try\n {\n this.Close();\n }\n catch\n {\n // Last resort\n Application.Current.Shutdown();\n }\n }\n }\n\n private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)\n {\n try\n {\n // Check if the DataContext is MainViewModel\n if (DataContext is MainViewModel viewModel)\n {\n LogDebug(\"DataContext is MainViewModel\");\n\n // Log any relevant properties or state from the ViewModel\n LogDebug($\"CurrentViewName: {viewModel.CurrentViewName}\");\n LogDebug(\n $\"CurrentViewModel type: {viewModel.CurrentViewModel?.GetType().FullName ?? \"null\"}\"\n );\n }\n else\n {\n LogDebug(\n $\"DataContext is not MainViewModel, it is {DataContext?.GetType().Name ?? \"null\"}\"\n );\n }\n\n // Log active windows\n LogDebug(\"Active windows:\");\n foreach (Window window in Application.Current.Windows)\n {\n LogDebug(\n $\"Window: {window.GetType().FullName}, IsVisible: {window.IsVisible}, WindowState: {window.WindowState}\"\n );\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error in MainWindow_Closing: {ex.Message}\", ex);\n }\n }\n\n private readonly IMessengerService _messengerService = null!;\n private readonly IVersionService _versionService = null!;\n\n #region More Button Event Handlers\n\n /// \n /// Event handler for the More button click\n /// Shows the context menu when the More button is clicked\n /// \n private void MoreButton_Click(object sender, RoutedEventArgs e)\n {\n // Log to the startup log file\n LogToStartupLog(\"More button clicked\");\n\n try\n {\n // Show the context menu using the MoreMenu control\n LogToStartupLog($\"MoreMenuControl exists: {MoreMenuControl != null}\");\n LogToStartupLog($\"MoreButton exists: {MoreButton != null}\");\n\n if (MoreMenuControl != null)\n {\n LogToStartupLog(\"About to call MoreMenuControl.ShowMenu()\");\n\n try\n {\n // Show the menu with the More button as the placement target\n MoreMenuControl.ShowMenu(MoreButton);\n LogToStartupLog(\"MoreMenuControl.ShowMenu() called successfully\");\n }\n catch (Exception menuEx)\n {\n LogToStartupLog($\"ERROR in MoreMenuControl.ShowMenu(): {menuEx.Message}\");\n LogToStartupLog($\"Stack trace: {menuEx.StackTrace}\");\n }\n }\n else\n {\n LogToStartupLog(\"MoreMenuControl is null, cannot show menu\");\n }\n }\n catch (Exception ex)\n {\n LogToStartupLog($\"Error in MoreButton_Click: {ex.Message}\");\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n }\n }\n\n // Context menu event handlers have been moved to MoreMenuViewModel\n\n #endregion\n\n private void HandleWindowStateMessage(WindowStateMessage message)\n {\n LogDebug($\"Received window state message: {message.Action}\");\n\n try\n {\n switch (message.Action)\n {\n case WindowStateMessage.WindowStateAction.Minimize:\n LogDebug(\"Processing minimize action\");\n WindowState = WindowState.Minimized;\n break;\n\n case WindowStateMessage.WindowStateAction.Maximize:\n LogDebug(\"Processing maximize action\");\n WindowState = WindowState.Maximized;\n break;\n\n case WindowStateMessage.WindowStateAction.Restore:\n LogDebug(\"Processing restore action\");\n WindowState = WindowState.Normal;\n break;\n\n case WindowStateMessage.WindowStateAction.Close:\n LogDebug(\"Processing close action\");\n Close();\n break;\n\n default:\n LogDebug($\"Unknown window state action: {message.Action}\");\n break;\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error handling window state message: {ex.Message}\", ex);\n }\n }\n\n private readonly IServiceProvider _serviceProvider = null!;\n private readonly IThemeManager _themeManager = null!;\n\n protected override void OnSourceInitialized(EventArgs e)\n {\n LogDebug(\"OnSourceInitialized starting\");\n try\n {\n base.OnSourceInitialized(e);\n LogDebug(\"Base OnSourceInitialized called\");\n\n var helper = new WindowInteropHelper(this);\n if (helper.Handle == IntPtr.Zero)\n {\n throw new InvalidOperationException(\"Window handle not available\");\n }\n LogDebug(\"Window handle verified\");\n\n // Initialize the window size manager to set size and center the window\n if (_windowSizeManager != null)\n {\n _windowSizeManager.Initialize();\n LogDebug(\"WindowSizeManager initialized\");\n }\n else\n {\n // Fallback if window size manager is not available\n SetDynamicWindowSize();\n LogDebug(\"Used fallback dynamic window sizing\");\n }\n\n EnableBlur();\n LogDebug(\"Blur enabled successfully\");\n }\n catch (Exception ex)\n {\n LogDebug(\"Error in OnSourceInitialized\", ex);\n // Don't throw - blur is not critical\n }\n }\n\n /// \n /// Sets the window size dynamically based on the screen resolution\n /// \n private void SetDynamicWindowSize()\n {\n try\n {\n LogDebug(\"Setting dynamic window size\");\n\n // Get the current screen's working area (excludes taskbar)\n var workArea = GetCurrentScreenWorkArea();\n\n // Get DPI scaling factor for the current screen\n double dpiScaleX = 1.0;\n double dpiScaleY = 1.0;\n\n try\n {\n var presentationSource = PresentationSource.FromVisual(this);\n if (presentationSource?.CompositionTarget != null)\n {\n dpiScaleX = presentationSource.CompositionTarget.TransformToDevice.M11;\n dpiScaleY = presentationSource.CompositionTarget.TransformToDevice.M22;\n LogDebug($\"DPI scale factors: X={dpiScaleX}, Y={dpiScaleY}\");\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting DPI scale: {ex.Message}\", ex);\n }\n\n // Calculate available screen space\n double screenWidth = workArea.Width / dpiScaleX;\n double screenHeight = workArea.Height / dpiScaleY;\n double screenLeft = workArea.X / dpiScaleX;\n double screenTop = workArea.Y / dpiScaleY;\n\n // Calculate window size (75% of screen size with minimum/maximum constraints)\n double windowWidth = Math.Min(1600, screenWidth * 0.75);\n double windowHeight = Math.Min(900, screenHeight * 0.75);\n\n // Ensure minimum size for usability\n windowWidth = Math.Max(windowWidth, 1024);\n windowHeight = Math.Max(windowHeight, 700);\n\n // Set the window size\n this.Width = windowWidth;\n this.Height = windowHeight;\n\n // Center the window on screen\n this.Left = screenLeft + (screenWidth - windowWidth) / 2;\n this.Top = screenTop + (screenHeight - windowHeight) / 2;\n\n LogDebug(\n $\"Screen resolution: {screenWidth}x{screenHeight}, Window size set to: {windowWidth}x{windowHeight}\"\n );\n LogDebug($\"Window centered at: Left={this.Left}, Top={this.Top}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error setting dynamic window size: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Gets the working area of the screen that contains the window\n /// \n private Rect GetCurrentScreenWorkArea()\n {\n try\n {\n // Get the window handle\n var windowHandle = new WindowInteropHelper(this).Handle;\n if (windowHandle != IntPtr.Zero)\n {\n // Get the monitor info for the monitor containing the window\n var monitorInfo = new MONITORINFO();\n monitorInfo.cbSize = Marshal.SizeOf(typeof(MONITORINFO));\n\n if (\n GetMonitorInfo(\n MonitorFromWindow(windowHandle, MONITOR_DEFAULTTONEAREST),\n ref monitorInfo\n )\n )\n {\n // Convert the working area to a WPF Rect\n return new Rect(\n monitorInfo.rcWork.left,\n monitorInfo.rcWork.top,\n monitorInfo.rcWork.right - monitorInfo.rcWork.left,\n monitorInfo.rcWork.bottom - monitorInfo.rcWork.top\n );\n }\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting current screen: {ex.Message}\", ex);\n }\n\n // Fallback to primary screen working area\n return SystemParameters.WorkArea;\n }\n\n [DllImport(\"user32.dll\")]\n private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);\n\n [DllImport(\"user32.dll\")]\n private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);\n\n private const uint MONITOR_DEFAULTTONEAREST = 2;\n\n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int left;\n public int top;\n public int right;\n public int bottom;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct MONITORINFO\n {\n public int cbSize;\n public RECT rcMonitor;\n public RECT rcWork;\n public uint dwFlags;\n }\n\n private void EnableBlur()\n {\n LogDebug(\"EnableBlur starting\");\n var windowHelper = new WindowInteropHelper(this);\n var accent = new AccentPolicy { AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND };\n var accentStructSize = Marshal.SizeOf(accent);\n\n var accentPtr = IntPtr.Zero;\n try\n {\n accentPtr = Marshal.AllocHGlobal(accentStructSize);\n Marshal.StructureToPtr(accent, accentPtr, false);\n\n var data = new WindowCompositionAttributeData\n {\n Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY,\n SizeOfData = accentStructSize,\n Data = accentPtr,\n };\n\n int result = SetWindowCompositionAttribute(windowHelper.Handle, ref data);\n if (result == 0)\n {\n throw new InvalidOperationException(\"SetWindowCompositionAttribute failed\");\n }\n LogDebug(\"Blur effect applied successfully\");\n }\n catch (Exception ex)\n {\n LogDebug(\"Error enabling blur\", ex);\n throw;\n }\n finally\n {\n if (accentPtr != IntPtr.Zero)\n {\n Marshal.FreeHGlobal(accentPtr);\n }\n }\n }\n\n [DllImport(\"user32.dll\")]\n internal static extern int SetWindowCompositionAttribute(\n IntPtr hwnd,\n ref WindowCompositionAttributeData data\n );\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct AccentPolicy\n {\n public AccentState AccentState;\n public int AccentFlags;\n public int GradientColor;\n public int AnimationId;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct WindowCompositionAttributeData\n {\n public WindowCompositionAttribute Attribute;\n public IntPtr Data;\n public int SizeOfData;\n }\n\n internal enum AccentState\n {\n ACCENT_DISABLED = 0,\n ACCENT_ENABLE_GRADIENT = 1,\n ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,\n ACCENT_ENABLE_BLURBEHIND = 3,\n ACCENT_ENABLE_ACRYLICBLURBEHIND = 4,\n ACCENT_INVALID_STATE = 5,\n }\n\n internal enum WindowCompositionAttribute\n {\n WCA_ACCENT_POLICY = 19,\n }\n\n // Window control is now handled through ViewModel commands and messaging\n\n /// \n /// Updates the window and image icons based on the current theme\n /// \n private void UpdateThemeIcon()\n {\n if (_themeManager == null)\n {\n LogDebug(\"Cannot update theme icon: ThemeManager is null\");\n return;\n }\n\n try\n {\n LogDebug(\n $\"Updating theme icon. Current theme: {(_themeManager.IsDarkTheme ? \"Dark\" : \"Light\")}\"\n );\n\n // Get the appropriate icon based on the theme\n string iconPath = _themeManager.IsDarkTheme\n ? \"pack://application:,,,/Resources/AppIcons/winhance-rocket-white-transparent-bg.ico\"\n : \"pack://application:,,,/Resources/AppIcons/winhance-rocket-black-transparent-bg.ico\";\n\n LogDebug($\"Selected icon path: {iconPath}\");\n\n // Create a BitmapImage from the icon path\n var iconImage = new BitmapImage(new Uri(iconPath, UriKind.Absolute));\n iconImage.Freeze(); // Freeze for better performance and thread safety\n\n // Set the window icon\n this.Icon = iconImage;\n LogDebug(\"Window icon updated\");\n\n // Set the image control source\n if (AppIconImage != null)\n {\n AppIconImage.Source = iconImage;\n LogDebug(\"AppIconImage source updated\");\n }\n else\n {\n LogDebug(\"AppIconImage is null, cannot update source\");\n }\n }\n catch (Exception ex)\n {\n LogDebug(\"Error updating theme icon\", ex);\n\n // If there's an error, fall back to the default icon\n try\n {\n var defaultIcon = new BitmapImage(\n new Uri(\n \"pack://application:,,,/Resources/AppIcons/winhance-rocket.ico\",\n UriKind.Absolute\n )\n );\n this.Icon = defaultIcon;\n if (AppIconImage != null)\n {\n AppIconImage.Source = defaultIcon;\n }\n }\n catch (Exception fallbackEx)\n {\n LogDebug(\"Error setting fallback icon\", fallbackEx);\n }\n }\n }\n\n /// \n /// Handles mouse wheel events at the window level and redirects them to the ScrollViewer\n /// \n private void MainWindow_PreviewMouseWheel(object sender, MouseWheelEventArgs e)\n {\n // Find the ScrollViewer in the visual tree\n var scrollViewer = FindVisualChild(this);\n if (scrollViewer != null)\n {\n // Redirect the mouse wheel event to the ScrollViewer\n if (e.Delta < 0)\n {\n scrollViewer.LineDown();\n }\n else\n {\n scrollViewer.LineUp();\n }\n\n // Mark the event as handled to prevent it from bubbling up\n e.Handled = true;\n }\n }\n\n /// \n /// Finds a visual child of the specified type in the visual tree\n /// \n private static T FindVisualChild(DependencyObject obj)\n where T : DependencyObject\n {\n for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)\n {\n DependencyObject child = VisualTreeHelper.GetChild(obj, i);\n\n if (child != null && child is T)\n {\n return (T)child;\n }\n\n T childOfChild = FindVisualChild(child);\n if (childOfChild != null)\n {\n return childOfChild;\n }\n }\n\n return null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/UpdateDialog.xaml.cs", "using System;\nusing System.Diagnostics;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media.Imaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Resources.Theme;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Update dialog that shows when a new version is available\n /// \n public partial class UpdateDialog : Window, System.ComponentModel.INotifyPropertyChanged\n {\n private readonly VersionInfo _currentVersion;\n private readonly VersionInfo _latestVersion;\n private readonly Func _downloadAndInstallAction;\n \n // Add a property for theme binding that defaults to dark theme\n private bool _isThemeDark = true;\n public bool IsThemeDark\n {\n get => _isThemeDark;\n set\n {\n if (_isThemeDark != value)\n {\n _isThemeDark = value;\n OnPropertyChanged(nameof(IsThemeDark));\n }\n }\n }\n \n public bool IsDownloading { get; private set; }\n\n // Implement INotifyPropertyChanged\n public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\n \n protected virtual void OnPropertyChanged(string propertyName)\n {\n PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\n }\n \n private UpdateDialog(string title, string message, VersionInfo currentVersion, VersionInfo latestVersion, Func downloadAndInstallAction)\n {\n InitializeComponent();\n DataContext = this;\n \n _currentVersion = currentVersion;\n _latestVersion = latestVersion;\n _downloadAndInstallAction = downloadAndInstallAction;\n \n // Try to determine the Winhance theme\n try\n {\n // First check if the theme is stored in Application.Current.Resources\n if (Application.Current.Resources.Contains(\"IsDarkTheme\"))\n {\n IsThemeDark = (bool)Application.Current.Resources[\"IsDarkTheme\"];\n }\n else\n {\n // Fall back to system theme if Winhance theme is not available\n bool systemUsesLightTheme = false;\n \n try\n {\n // Try to read the Windows registry to determine the system theme\n using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@\"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\"))\n {\n if (key != null)\n {\n var value = key.GetValue(\"AppsUseLightTheme\");\n if (value != null)\n {\n systemUsesLightTheme = Convert.ToInt32(value) == 1;\n }\n }\n }\n }\n catch (Exception)\n {\n // Ignore errors reading the registry\n }\n \n // Set the IsThemeDark property based on the system theme\n IsThemeDark = !systemUsesLightTheme;\n }\n }\n catch (Exception)\n {\n // Default to dark theme if we can't determine the theme\n IsThemeDark = true;\n }\n \n // Set up a handler to listen for theme changes\n this.Loaded += (sender, e) =>\n {\n // Listen for resource dictionary changes that might affect the theme\n if (Application.Current.Resources is System.Windows.ResourceDictionary resourceDictionary)\n {\n // Use reflection to get the event\n var eventInfo = resourceDictionary.GetType().GetEvent(\"ResourceDictionaryChanged\");\n if (eventInfo != null)\n {\n // Create a handler for the event\n EventHandler resourceChangedHandler = (s, args) =>\n {\n if (Application.Current.Resources.Contains(\"IsDarkTheme\"))\n {\n bool newIsDarkTheme = (bool)Application.Current.Resources[\"IsDarkTheme\"];\n if (IsThemeDark != newIsDarkTheme)\n {\n IsThemeDark = newIsDarkTheme;\n }\n }\n };\n \n // Add the handler to the event\n eventInfo.AddEventHandler(resourceDictionary, resourceChangedHandler);\n }\n }\n };\n \n Title = title;\n HeaderText.Text = title;\n MessageText.Text = message;\n \n // Ensure version text is properly displayed\n CurrentVersionText.Text = currentVersion.Version;\n LatestVersionText.Text = latestVersion.Version;\n \n // Make sure the footer text is visible\n FooterText.Visibility = Visibility.Visible;\n }\n \n private async void PrimaryButton_Click(object sender, RoutedEventArgs e)\n {\n try\n {\n // Disable buttons during download\n PrimaryButton.IsEnabled = false;\n SecondaryButton.IsEnabled = false;\n \n // Show progress indicator\n IsDownloading = true;\n OnPropertyChanged(nameof(IsDownloading));\n DownloadProgress.Visibility = Visibility.Visible;\n StatusText.Text = \"Downloading update...\";\n \n // Hide the footer text during download\n FooterText.Visibility = Visibility.Collapsed;\n \n // Execute the download and install action\n await _downloadAndInstallAction();\n \n // Set dialog result and close\n DialogResult = true;\n Close();\n }\n catch (Exception ex)\n {\n // Re-enable buttons\n PrimaryButton.IsEnabled = true;\n SecondaryButton.IsEnabled = true;\n \n // Hide progress indicator\n IsDownloading = false;\n OnPropertyChanged(nameof(IsDownloading));\n DownloadProgress.Visibility = Visibility.Collapsed;\n \n // Show error message\n StatusText.Text = $\"Error downloading update: {ex.Message}\";\n \n // Show the footer text again\n FooterText.Visibility = Visibility.Visible;\n }\n }\n\n private void SecondaryButton_Click(object sender, RoutedEventArgs e)\n {\n // User chose to be reminded later\n DialogResult = false;\n Close();\n }\n \n /// \n /// Shows an update dialog with the specified parameters\n /// \n /// The title of the dialog\n /// The message to display\n /// The current version information\n /// The latest version information\n /// The action to execute when the user clicks Download & Install\n /// True if the user chose to download and install, false otherwise\n public static async Task ShowAsync(\n string title, \n string message, \n VersionInfo currentVersion, \n VersionInfo latestVersion, \n Func downloadAndInstallAction)\n {\n try\n {\n var dialog = new UpdateDialog(title, message, currentVersion, latestVersion, downloadAndInstallAction)\n {\n WindowStartupLocation = WindowStartupLocation.CenterScreen,\n ShowInTaskbar = false,\n Topmost = true\n };\n \n // Set the owner to the main window to ensure it appears on top\n if (Application.Current.MainWindow != null && Application.Current.MainWindow != dialog)\n {\n dialog.Owner = Application.Current.MainWindow;\n }\n else\n {\n // Try to find the main window another way\n foreach (Window window in Application.Current.Windows)\n {\n if (window != dialog && window.IsVisible)\n {\n dialog.Owner = window;\n break;\n }\n }\n }\n \n // Show the dialog and wait for the result\n return await Task.Run(() =>\n {\n return Application.Current.Dispatcher.Invoke(() =>\n {\n try\n {\n return dialog.ShowDialog() ?? false;\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error showing dialog: {ex.Message}\");\n return false;\n }\n });\n });\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error in ShowAsync: {ex.Message}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Customize/Services/ThemeService.cs", "using System;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.Customize.Models;\n\nnamespace Winhance.Infrastructure.Features.Customize.Services\n{\n /// \n /// Service for theme-related operations.\n /// \n public class ThemeService : IThemeService\n {\n private readonly IRegistryService _registryService;\n private readonly ILogService _logService;\n private readonly IWallpaperService _wallpaperService;\n private readonly ISystemServices _systemServices;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The registry service.\n /// The log service.\n /// The wallpaper service.\n /// The system services.\n public ThemeService(\n IRegistryService registryService,\n ILogService logService,\n IWallpaperService wallpaperService,\n ISystemServices systemServices)\n {\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _wallpaperService = wallpaperService ?? throw new ArgumentNullException(nameof(wallpaperService));\n _systemServices = systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n }\n\n /// \n public bool IsDarkModeEnabled()\n {\n try\n {\n string keyPath = $\"HKCU\\\\{WindowsThemeSettings.Registry.ThemesPersonalizeSubKey}\";\n var value = _registryService.GetValue(keyPath, WindowsThemeSettings.Registry.AppsUseLightThemeName);\n bool isDarkMode = value != null && (int)value == 0;\n\n _logService.Log(LogLevel.Info, $\"Dark mode check completed. Is Dark Mode: {isDarkMode}\");\n return isDarkMode;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking dark mode status: {ex.Message}\");\n return false;\n }\n }\n\n /// \n public string GetCurrentThemeName()\n {\n return IsDarkModeEnabled() ? \"Dark Mode\" : \"Light Mode\";\n }\n\n /// \n public bool SetThemeMode(bool isDarkMode)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Setting theme mode to {(isDarkMode ? \"dark\" : \"light\")}\");\n\n string keyPath = $\"HKCU\\\\{WindowsThemeSettings.Registry.ThemesPersonalizeSubKey}\";\n int valueToSet = isDarkMode ? 0 : 1;\n\n // Set both registry values\n bool appsSuccess = _registryService.SetValue(\n keyPath,\n WindowsThemeSettings.Registry.AppsUseLightThemeName,\n valueToSet,\n Microsoft.Win32.RegistryValueKind.DWord);\n\n bool systemSuccess = _registryService.SetValue(\n keyPath,\n WindowsThemeSettings.Registry.SystemUsesLightThemeName,\n valueToSet,\n Microsoft.Win32.RegistryValueKind.DWord);\n\n bool success = appsSuccess && systemSuccess;\n if (success)\n {\n _logService.Log(LogLevel.Success, $\"Theme mode set to {(isDarkMode ? \"dark\" : \"light\")}\");\n }\n else\n {\n _logService.Log(LogLevel.Error, \"Failed to set theme mode\");\n }\n\n return success;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting theme mode: {ex.Message}\");\n return false;\n }\n }\n\n /// \n public async Task ApplyThemeAsync(bool isDarkMode, bool changeWallpaper)\n {\n try\n {\n // Apply theme in registry\n bool themeSuccess = SetThemeMode(isDarkMode);\n if (!themeSuccess)\n {\n return false;\n }\n\n // Change wallpaper if requested\n if (changeWallpaper)\n {\n _logService.Log(LogLevel.Info, $\"Changing wallpaper for {(isDarkMode ? \"dark\" : \"light\")} mode\");\n // Check Windows version directly instead of using ISystemServices\n bool isWindows11 = Environment.OSVersion.Version.Build >= 22000;\n await _wallpaperService.SetDefaultWallpaperAsync(isWindows11, isDarkMode);\n }\n\n // Use the improved RefreshWindowsGUI method to refresh the UI\n bool refreshResult = await _systemServices.RefreshWindowsGUI(true);\n if (!refreshResult)\n {\n _logService.Log(LogLevel.Warning, \"Failed to refresh Windows GUI after applying theme\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Theme applied successfully: {(isDarkMode ? \"Dark\" : \"Light\")} Mode\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying theme: {ex.Message}\");\n return false;\n }\n }\n\n /// \n public async Task RefreshGUIAsync(bool restartExplorer)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Refreshing GUI with WindowsSystemService (restartExplorer: {restartExplorer})\");\n \n // Use the improved implementation from WindowsSystemService\n bool result = await _systemServices.RefreshWindowsGUI(restartExplorer);\n \n if (result)\n {\n _logService.Log(LogLevel.Info, \"Windows GUI refresh completed successfully\");\n }\n else\n {\n _logService.Log(LogLevel.Error, \"Failed to refresh Windows GUI\");\n }\n \n return result;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error refreshing GUI: {ex.Message}\");\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Customize/ViewModels/WindowsThemeCustomizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.Customize.Models;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Customize.ViewModels\n{\n /// \n /// ViewModel for Windows Theme customizations.\n /// \n public partial class WindowsThemeCustomizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDialogService _dialogService;\n private readonly IThemeService _themeService;\n private readonly WindowsThemeSettings _themeSettings;\n private readonly IRegistryService _registryService;\n\n // Flags to prevent triggering dark mode action during property change\n private bool _isHandlingDarkModeChange = false;\n private bool _isShowingDialog = false;\n \n // Store the original state before any changes\n private bool _originalDarkModeState;\n private string _originalTheme = string.Empty;\n \n // Store the requested state for the dialog\n private bool _requestedDarkModeState;\n private string _requestedTheme = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether dark mode is enabled.\n /// \n [ObservableProperty]\n private bool _isDarkModeEnabled;\n \n /// \n /// Gets or sets a value indicating whether to change the wallpaper when changing the theme.\n /// \n [ObservableProperty]\n private bool _changeWallpaper;\n\n /// \n /// Gets a value indicating whether theme options are available.\n /// \n public bool HasThemeOptions => true;\n\n /// \n /// Gets the available theme options.\n /// \n public List ThemeOptions => new List { \"Light Mode\", \"Dark Mode\" };\n\n /// \n /// Gets or sets the selected theme.\n /// \n public string SelectedTheme\n {\n get => IsDarkModeEnabled ? \"Dark Mode\" : \"Light Mode\";\n set\n {\n if (value == \"Dark Mode\" && !IsDarkModeEnabled)\n {\n IsDarkModeEnabled = true;\n }\n else if (value == \"Light Mode\" && IsDarkModeEnabled)\n {\n IsDarkModeEnabled = false;\n }\n OnPropertyChanged();\n }\n }\n\n /// \n /// Gets the category name.\n /// \n public string CategoryName => \"Windows Theme\";\n\n /// \n /// Gets the command to apply the theme.\n /// \n public ICommand ApplyThemeCommand { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dialog service.\n /// The theme service.\n public WindowsThemeCustomizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDialogService dialogService,\n IThemeService themeService)\n : base(progressService, registryService, logService)\n {\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _themeService = themeService ?? throw new ArgumentNullException(nameof(themeService));\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n \n // Initialize the theme settings model\n _themeSettings = new WindowsThemeSettings(themeService);\n \n // Load the current theme state\n LoadDarkModeState();\n \n // Initialize commands\n ApplyThemeCommand = new AsyncRelayCommand(ApplyThemeWithConfirmationAsync);\n\n // Subscribe to property changes to handle dark mode toggle and theme selection\n this.PropertyChanged += (s, e) =>\n {\n // Skip if we're already handling a change or showing a dialog\n if (_isHandlingDarkModeChange || _isShowingDialog)\n return;\n \n if (e.PropertyName == nameof(IsDarkModeEnabled))\n {\n HandleDarkModePropertyChange();\n }\n else if (e.PropertyName == nameof(SelectedTheme))\n {\n HandleThemeSelectionChange();\n }\n };\n }\n\n /// \n /// Handles changes to the IsDarkModeEnabled property.\n /// \n private void HandleDarkModePropertyChange()\n {\n // Store the original state before any changes\n _originalDarkModeState = _themeService.IsDarkModeEnabled();\n _originalTheme = _originalDarkModeState ? \"Dark Mode\" : \"Light Mode\";\n \n // Store the requested state\n _requestedDarkModeState = IsDarkModeEnabled;\n _requestedTheme = IsDarkModeEnabled ? \"Dark Mode\" : \"Light Mode\";\n \n // Log the state change\n _logService.Log(LogLevel.Info, $\"Dark mode check completed. Is Dark Mode: {_originalDarkModeState}\");\n \n // Update the selected theme to match the dark mode state\n _isHandlingDarkModeChange = true;\n try\n {\n SelectedTheme = IsDarkModeEnabled ? \"Dark Mode\" : \"Light Mode\";\n \n // Update the theme settings model\n _themeSettings.IsDarkMode = IsDarkModeEnabled;\n \n // Update the theme selector setting if it exists\n UpdateThemeSelectorSetting();\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n \n // Prompt for confirmation\n PromptForThemeChange();\n }\n\n /// \n /// Handles changes to the SelectedTheme property.\n /// \n private void HandleThemeSelectionChange()\n {\n // Store the original state before any changes\n _originalDarkModeState = _themeService.IsDarkModeEnabled();\n _originalTheme = _originalDarkModeState ? \"Dark Mode\" : \"Light Mode\";\n \n // Store the requested state\n _requestedTheme = SelectedTheme;\n _requestedDarkModeState = SelectedTheme == \"Dark Mode\";\n \n // Log the state change\n _logService.Log(LogLevel.Info, $\"Theme mode changed to {SelectedTheme}\");\n \n // Update the dark mode state based on the selected theme\n _isHandlingDarkModeChange = true;\n try\n {\n IsDarkModeEnabled = SelectedTheme == \"Dark Mode\";\n \n // Update the theme settings model\n _themeSettings.IsDarkMode = IsDarkModeEnabled;\n \n // Update the theme selector setting if it exists\n UpdateThemeSelectorSetting();\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n \n // Prompt for confirmation\n PromptForThemeChange();\n }\n\n /// \n /// Loads the dark mode state.\n /// \n private void LoadDarkModeState()\n {\n try\n {\n // Load the current theme settings\n _themeSettings.LoadCurrentSettings();\n \n // Update the view model properties\n _isHandlingDarkModeChange = true;\n try\n {\n IsDarkModeEnabled = _themeSettings.IsDarkMode;\n SelectedTheme = _themeSettings.ThemeName;\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n\n // Store the original state\n _originalDarkModeState = IsDarkModeEnabled;\n _originalTheme = SelectedTheme;\n\n _logService.Log(LogLevel.Info, $\"Loaded theme settings: {SelectedTheme}\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading dark mode state: {ex.Message}\");\n IsDarkModeEnabled = true; // Default to dark mode if there's an error\n SelectedTheme = \"Dark Mode\"; // Set selected theme to match\n \n // Store the original state\n _originalDarkModeState = IsDarkModeEnabled;\n _originalTheme = SelectedTheme;\n }\n }\n\n /// \n /// Prompts the user for theme change confirmation.\n /// \n private async void PromptForThemeChange()\n {\n // Prevent multiple dialogs from being shown at once\n if (_isShowingDialog)\n {\n _logService.Log(LogLevel.Info, \"Dialog already showing, ignoring request\");\n return;\n }\n \n _isShowingDialog = true;\n \n try\n {\n // Store the current UI state before showing the dialog\n bool currentDarkModeState = IsDarkModeEnabled;\n string currentTheme = SelectedTheme;\n \n // Revert to the original state before showing the dialog\n // This ensures that if the user cancels, we're already in the original state\n _isHandlingDarkModeChange = true;\n try\n {\n IsDarkModeEnabled = _originalDarkModeState;\n SelectedTheme = _originalTheme;\n _themeSettings.IsDarkMode = _originalDarkModeState;\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n \n // Prompt user about wallpaper change\n _logService.Log(LogLevel.Info, \"Showing dialog for theme change confirmation\");\n \n // Use the DialogService to show the confirmation dialog\n var result = await _dialogService.ShowYesNoCancelAsync(\n $\"Would you also like to change to the default {(currentDarkModeState ? \"dark\" : \"light\")} theme wallpaper?\",\n \"Windows Theme Change\"\n );\n\n switch (result)\n {\n case true: // Yes - Change theme AND apply wallpaper\n _logService.Log(LogLevel.Info, \"User selected to apply theme with wallpaper\");\n _isHandlingDarkModeChange = true;\n try\n {\n // Apply the requested theme\n IsDarkModeEnabled = _requestedDarkModeState;\n SelectedTheme = _requestedTheme;\n ChangeWallpaper = true; // Store the user's preference\n \n // Update the theme settings model\n _themeSettings.IsDarkMode = _requestedDarkModeState;\n _themeSettings.ChangeWallpaper = true;\n \n // Apply the theme\n await ApplyThemeAsync(true);\n _logService.Log(LogLevel.Info, $\"Theme changed to {(IsDarkModeEnabled ? \"dark\" : \"light\")} mode with wallpaper\");\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n break;\n\n case false: // No - Change theme but DON'T change wallpaper\n _logService.Log(LogLevel.Info, \"User selected to apply theme without wallpaper\");\n _isHandlingDarkModeChange = true;\n try\n {\n // Apply the requested theme\n IsDarkModeEnabled = _requestedDarkModeState;\n SelectedTheme = _requestedTheme;\n ChangeWallpaper = false; // Store the user's preference\n \n // Update the theme settings model\n _themeSettings.IsDarkMode = _requestedDarkModeState;\n _themeSettings.ChangeWallpaper = false;\n \n // Apply the theme\n await ApplyThemeAsync(false);\n _logService.Log(LogLevel.Info, $\"Theme changed to {(IsDarkModeEnabled ? \"dark\" : \"light\")} mode without wallpaper\");\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n break;\n\n case null: // Cancel - Do NOTHING, just close dialog\n _logService.Log(LogLevel.Info, \"User canceled theme change - keeping original state\");\n break;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error toggling dark mode: {ex.Message}\");\n await _dialogService.ShowErrorAsync(\"Theme Error\", $\"Failed to switch themes: {ex.Message}\");\n\n // Revert the toggle and selected theme on error\n _isHandlingDarkModeChange = true;\n try\n {\n // Revert to the original state\n IsDarkModeEnabled = _originalDarkModeState;\n SelectedTheme = _originalTheme;\n _themeSettings.IsDarkMode = _originalDarkModeState;\n \n _logService.Log(LogLevel.Info, \"Reverted to original state after error\");\n }\n finally\n {\n _isHandlingDarkModeChange = false;\n }\n }\n finally\n {\n // Always reset the dialog flag\n _isShowingDialog = false;\n _logService.Log(LogLevel.Info, \"Dialog handling completed\");\n }\n }\n\n /// \n /// Applies the theme with confirmation dialog.\n /// \n /// Whether to change the wallpaper.\n /// A task representing the asynchronous operation.\n private async Task ApplyThemeWithConfirmationAsync(bool changeWallpaper)\n {\n // Store the current state\n bool currentDarkMode = IsDarkModeEnabled;\n \n // Prompt for confirmation\n var result = await _dialogService.ShowConfirmationAsync(\n \"Apply Theme\",\n $\"Are you sure you want to apply the {(currentDarkMode ? \"dark\" : \"light\")} theme?\"\n );\n \n if (result)\n {\n await ApplyThemeAsync(changeWallpaper);\n }\n }\n\n /// \n /// Applies the dark mode setting.\n /// \n /// Whether to change the wallpaper.\n /// A task representing the asynchronous operation.\n public async Task ApplyThemeAsync(bool changeWallpaper)\n {\n try\n {\n // Update the theme settings model\n _themeSettings.IsDarkMode = IsDarkModeEnabled;\n _themeSettings.ChangeWallpaper = changeWallpaper;\n \n // Apply the theme\n bool success = await _themeSettings.ApplyThemeAsync();\n \n if (success)\n {\n _logService.Log(LogLevel.Info, $\"Windows Dark Mode {(IsDarkModeEnabled ? \"enabled\" : \"disabled\")}\");\n }\n else\n {\n _logService.Log(LogLevel.Error, \"Failed to apply theme\");\n }\n \n return success;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying dark mode: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Loads the settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, \"Loading Windows theme settings\");\n\n // Load dark mode state\n LoadDarkModeState();\n \n // Clear existing settings\n Settings.Clear();\n \n // Add a searchable item for the Theme Selector\n var themeItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = \"ThemeSelector\",\n Name = \"Windows Theme\",\n Description = \"Select between light and dark theme for Windows\",\n GroupName = \"Windows Theme\",\n IsVisible = true,\n IsSelected = true, // Always mark as selected so it appears in the config list\n ControlType = ControlType.ComboBox,\n SelectedValue = SelectedTheme, // Store the selected theme directly\n // Create a registry setting for the theme selector\n RegistrySetting = new RegistrySetting\n {\n Category = \"WindowsTheme\",\n Hive = Microsoft.Win32.RegistryHive.CurrentUser,\n SubKey = WindowsThemeSettings.Registry.ThemesPersonalizeSubKey,\n Name = WindowsThemeSettings.Registry.AppsUseLightThemeName,\n RecommendedValue = SelectedTheme == \"Dark Mode\" ? 0 : 1,\n DefaultValue = 1,\n EnabledValue = SelectedTheme == \"Dark Mode\" ? 0 : 1,\n DisabledValue = SelectedTheme == \"Dark Mode\" ? 1 : 0,\n ValueType = Microsoft.Win32.RegistryValueKind.DWord,\n Description = \"Windows Theme Mode\",\n // Store the selected theme and wallpaper preference\n CustomProperties = new Dictionary\n {\n { \"SelectedTheme\", SelectedTheme },\n { \"ChangeWallpaper\", ChangeWallpaper },\n { \"ThemeOptions\", ThemeOptions } // Store available options\n }\n }\n };\n Settings.Add(themeItem);\n \n _logService.Log(LogLevel.Info, $\"Added {Settings.Count} searchable items for Windows Theme settings\");\n\n // Check the status of all settings\n await CheckSettingStatusesAsync();\n\n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading Windows theme settings: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, \"Checking status for Windows theme settings\");\n\n // Refresh dark mode state\n LoadDarkModeState();\n\n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Windows theme settings status: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n // Get status\n var status = setting.Status;\n string message = status switch\n {\n RegistrySettingStatus.Applied => \"Setting is applied with recommended value\",\n RegistrySettingStatus.NotApplied => \"Setting is not applied or using default value\",\n RegistrySettingStatus.Modified => \"Setting has a custom value different from recommended\",\n RegistrySettingStatus.Error => \"Error checking setting status\",\n _ => \"Unknown status\"\n };\n\n return message;\n }\n\n // ApplySelectedSettingsAsync and RestoreDefaultsAsync methods removed as part of the refactoring\n \n /// \n /// Updates the theme selector setting to match the current selected theme.\n /// \n private void UpdateThemeSelectorSetting()\n {\n // Find the theme selector setting\n var themeSelector = Settings.FirstOrDefault(s => s.Id == \"ThemeSelector\");\n if (themeSelector != null)\n {\n themeSelector.IsUpdatingFromCode = true;\n try\n {\n // Update the SelectedValue directly with the current theme\n themeSelector.SelectedValue = SelectedTheme;\n _logService.Log(LogLevel.Info, $\"Updated theme selector setting to {SelectedTheme}\");\n \n // Store the wallpaper preference and selected theme in the setting's additional properties\n // This will be used when saving/loading configurations\n // Create a new RegistrySetting object with updated values\n var customProperties = new Dictionary();\n customProperties[\"ChangeWallpaper\"] = ChangeWallpaper;\n customProperties[\"SelectedTheme\"] = SelectedTheme;\n customProperties[\"ThemeOptions\"] = ThemeOptions; // Store available options\n \n // Create a new RegistrySetting with the updated values\n var newRegistrySetting = new RegistrySetting\n {\n Category = \"WindowsTheme\",\n Hive = Microsoft.Win32.RegistryHive.CurrentUser,\n SubKey = WindowsThemeSettings.Registry.ThemesPersonalizeSubKey,\n Name = WindowsThemeSettings.Registry.AppsUseLightThemeName,\n RecommendedValue = SelectedTheme == \"Dark Mode\" ? 0 : 1,\n DefaultValue = 1,\n EnabledValue = SelectedTheme == \"Dark Mode\" ? 0 : 1,\n DisabledValue = SelectedTheme == \"Dark Mode\" ? 1 : 0,\n ValueType = Microsoft.Win32.RegistryValueKind.DWord,\n Description = \"Windows Theme Mode\",\n CustomProperties = customProperties\n };\n \n // Assign the new RegistrySetting to the theme selector\n themeSelector.RegistrySetting = newRegistrySetting;\n \n _logService.Log(LogLevel.Info, $\"Stored theme preferences: SelectedTheme={SelectedTheme}, ChangeWallpaper={ChangeWallpaper}\");\n }\n finally\n {\n themeSelector.IsUpdatingFromCode = false;\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ConfigurationPropertyUpdater.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for updating properties of configuration items.\n /// \n public class ConfigurationPropertyUpdater : IConfigurationPropertyUpdater\n {\n private readonly ILogService _logService;\n private readonly IRegistryService _registryService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The registry service.\n public ConfigurationPropertyUpdater(\n ILogService logService,\n IRegistryService registryService\n )\n {\n _logService = logService;\n _registryService = registryService;\n }\n\n /// \n /// Updates properties of items based on the configuration.\n /// \n /// The items to update.\n /// The configuration file containing the updates.\n /// The number of items that were updated.\n public async Task UpdateItemsAsync(\n IEnumerable items,\n ConfigurationFile configFile\n )\n {\n int updatedCount = 0;\n\n // Create dictionaries of config items by name and ID for faster lookup\n var configItemsByName = new Dictionary(\n StringComparer.OrdinalIgnoreCase\n );\n var configItemsById = new Dictionary(\n StringComparer.OrdinalIgnoreCase\n );\n\n if (configFile.Items != null)\n {\n foreach (var item in configFile.Items)\n {\n if (\n !string.IsNullOrEmpty(item.Name)\n && !configItemsByName.ContainsKey(item.Name)\n )\n {\n configItemsByName.Add(item.Name, item);\n }\n\n if (\n item.CustomProperties.TryGetValue(\"Id\", out var id)\n && id != null\n && !string.IsNullOrEmpty(id.ToString())\n && !configItemsById.ContainsKey(id.ToString())\n )\n {\n configItemsById.Add(id.ToString(), item);\n }\n }\n }\n\n // Update the items\n foreach (var item in items)\n {\n try\n {\n var nameProperty = item.GetType().GetProperty(\"Name\");\n var idProperty = item.GetType().GetProperty(\"Id\");\n var isSelectedProperty = item.GetType().GetProperty(\"IsSelected\");\n\n if (nameProperty != null && isSelectedProperty != null)\n {\n var name = nameProperty.GetValue(item)?.ToString();\n var id = idProperty?.GetValue(item)?.ToString();\n\n ConfigurationItem configItem = null;\n\n // Try to match by ID first\n if (\n !string.IsNullOrEmpty(id)\n && configItemsById.TryGetValue(id, out var itemById)\n )\n {\n configItem = itemById;\n }\n // Then try to match by name\n else if (\n !string.IsNullOrEmpty(name)\n && configItemsByName.TryGetValue(name, out var itemByName)\n )\n {\n configItem = itemByName;\n }\n\n if (configItem != null)\n {\n bool anyPropertyUpdated = false;\n\n // Update IsSelected - Always apply regardless of current state\n bool currentIsSelected = (bool)(\n isSelectedProperty.GetValue(item) ?? false\n );\n\n // Always set the value and apply registry settings, even if it hasn't changed\n isSelectedProperty.SetValue(item, configItem.IsSelected);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Info,\n $\"Updated IsSelected for item {name} (ID: {id}) to {configItem.IsSelected}\"\n );\n\n // Always apply registry settings for this item during import\n await ApplyRegistrySettingsAsync(item, configItem.IsSelected);\n\n // Update additional properties\n if (UpdateAdditionalProperties(item, configItem))\n {\n anyPropertyUpdated = true;\n }\n\n if (anyPropertyUpdated)\n {\n updatedCount++;\n TriggerPropertyChangedIfPossible(item);\n }\n }\n }\n }\n catch (Exception ex)\n {\n // Log the error but continue processing other items\n _logService.Log(\n LogLevel.Debug,\n $\"Error applying configuration to item: {ex.Message}\"\n );\n }\n }\n\n return updatedCount;\n }\n\n /// \n /// Updates additional properties of an item based on the configuration.\n /// \n /// The item to update.\n /// The configuration item containing the updates.\n /// True if any properties were updated, false otherwise.\n public bool UpdateAdditionalProperties(object item, ConfigurationItem configItem)\n {\n bool anyPropertyUpdated = false;\n\n try\n {\n // Get the item type to access its properties\n var itemType = item.GetType();\n var itemName =\n itemType.GetProperty(\"Name\")?.GetValue(item)?.ToString() ?? \"Unknown\";\n var itemId = itemType.GetProperty(\"Id\")?.GetValue(item)?.ToString() ?? \"\";\n\n // Check if this is a special item that needs special handling\n bool isUacSlider =\n itemName.Contains(\"User Account Control\") || itemId == \"UACSlider\";\n bool isPowerPlan = itemName.Contains(\"Power Plan\") || itemId == \"PowerPlanComboBox\";\n bool isThemeSelector =\n itemName.Contains(\"Windows Theme\")\n || itemName.Contains(\"Theme Selector\")\n || itemName.Contains(\"Choose Your Mode\");\n\n // Special handling for Windows Theme Selector\n if (isThemeSelector)\n {\n // For Windows Theme Selector, prioritize using SelectedValue or SelectedTheme\n var selectedValueProperty = itemType.GetProperty(\"SelectedValue\");\n if (selectedValueProperty != null)\n {\n try\n {\n string currentSelectedValue = selectedValueProperty\n .GetValue(item)\n ?.ToString();\n string newSelectedValue = null;\n\n // First try to get the value from CustomProperties.SelectedTheme (preferred method)\n if (\n configItem.CustomProperties.TryGetValue(\n \"SelectedTheme\",\n out var selectedTheme\n )\n && selectedTheme != null\n )\n {\n newSelectedValue = selectedTheme.ToString();\n _logService.Log(\n LogLevel.Info,\n $\"Found SelectedTheme in CustomProperties: {newSelectedValue} for item {itemName}\"\n );\n }\n // Then try to get the value directly from configItem.SelectedValue\n else if (!string.IsNullOrEmpty(configItem.SelectedValue))\n {\n newSelectedValue = configItem.SelectedValue;\n _logService.Log(\n LogLevel.Info,\n $\"Found SelectedValue in config: {newSelectedValue} for item {itemName}\"\n );\n }\n // As a last resort, try to derive it from SliderValue (for backward compatibility)\n else if (\n configItem.CustomProperties.TryGetValue(\n \"SliderValue\",\n out var sliderValue\n )\n )\n {\n int sliderValueInt = Convert.ToInt32(sliderValue);\n newSelectedValue = sliderValueInt == 1 ? \"Dark Mode\" : \"Light Mode\";\n _logService.Log(\n LogLevel.Info,\n $\"Derived SelectedValue from SliderValue {sliderValueInt}: {newSelectedValue} for item {itemName}\"\n );\n }\n\n if (\n !string.IsNullOrEmpty(newSelectedValue)\n && currentSelectedValue != newSelectedValue\n )\n {\n selectedValueProperty.SetValue(item, newSelectedValue);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Info,\n $\"Updated SelectedValue for item {itemName} from {currentSelectedValue} to {newSelectedValue}\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating SelectedValue for item {itemName}: {ex.Message}\"\n );\n }\n }\n\n // Also update SelectedTheme property if it exists\n var selectedThemeProperty = itemType.GetProperty(\"SelectedTheme\");\n if (selectedThemeProperty != null)\n {\n try\n {\n string currentSelectedTheme = selectedThemeProperty\n .GetValue(item)\n ?.ToString();\n string newSelectedTheme = null;\n\n // Try to get SelectedTheme from CustomProperties first (preferred method)\n if (\n configItem.CustomProperties.TryGetValue(\n \"SelectedTheme\",\n out var selectedTheme\n )\n && selectedTheme != null\n )\n {\n newSelectedTheme = selectedTheme.ToString();\n }\n // Then try to use SelectedValue directly\n else if (!string.IsNullOrEmpty(configItem.SelectedValue))\n {\n newSelectedTheme = configItem.SelectedValue;\n }\n // As a last resort, try to derive it from SliderValue (for backward compatibility)\n else if (\n configItem.CustomProperties.TryGetValue(\n \"SliderValue\",\n out var themeSliderValue\n )\n )\n {\n int sliderValueInt = Convert.ToInt32(themeSliderValue);\n newSelectedTheme = sliderValueInt == 1 ? \"Dark Mode\" : \"Light Mode\";\n }\n\n if (\n !string.IsNullOrEmpty(newSelectedTheme)\n && currentSelectedTheme != newSelectedTheme\n )\n {\n selectedThemeProperty.SetValue(item, newSelectedTheme);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Debug,\n $\"Updated SelectedTheme for item {itemName} to {newSelectedTheme}\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating SelectedTheme for item {itemName}: {ex.Message}\"\n );\n }\n }\n }\n // For non-theme items, handle SliderValue for ThreeStateSlider or ComboBox\n else if (\n configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue)\n )\n {\n var sliderValueProperty = itemType.GetProperty(\"SliderValue\");\n if (sliderValueProperty != null)\n {\n try\n {\n int newSliderValue = Convert.ToInt32(sliderValue);\n int currentSliderValue = (int)(sliderValueProperty.GetValue(item) ?? 0);\n\n if (currentSliderValue != newSliderValue)\n {\n _logService.Log(\n LogLevel.Info,\n $\"About to update SliderValue for item {itemName} from {currentSliderValue} to {newSliderValue}\"\n );\n sliderValueProperty.SetValue(item, newSliderValue);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Info,\n $\"Updated SliderValue for item {itemName} to {newSliderValue}\"\n );\n\n // Get the control type\n var controlTypeProperty = itemType.GetProperty(\"ControlType\");\n if (controlTypeProperty != null)\n {\n var controlType = controlTypeProperty.GetValue(item);\n _logService.Log(\n LogLevel.Info,\n $\"Item {itemName} has ControlType: {controlType}\"\n );\n\n // If this is a ComboBox, also update the SelectedValue property if available\n if (controlType?.ToString() == \"ComboBox\")\n {\n _logService.Log(\n LogLevel.Info,\n $\"Item {itemName} is a ComboBox, checking for SelectedValue property\"\n );\n var comboBoxSelectedValueProperty = itemType.GetProperty(\n \"SelectedValue\"\n );\n if (comboBoxSelectedValueProperty != null)\n {\n // First try to get the value directly from configItem.SelectedValue\n if (!string.IsNullOrEmpty(configItem.SelectedValue))\n {\n _logService.Log(\n LogLevel.Info,\n $\"Setting SelectedValue to {configItem.SelectedValue} from config for ComboBox {itemName}\"\n );\n comboBoxSelectedValueProperty.SetValue(\n item,\n configItem.SelectedValue\n );\n anyPropertyUpdated = true;\n }\n // Then try to get the value from CustomProperties.SelectedTheme\n else if (\n configItem.CustomProperties.TryGetValue(\n \"SelectedTheme\",\n out var selectedTheme\n )\n && selectedTheme != null\n )\n {\n _logService.Log(\n LogLevel.Info,\n $\"Setting SelectedValue to {selectedTheme} from CustomProperties.SelectedTheme for ComboBox {itemName}\"\n );\n comboBoxSelectedValueProperty.SetValue(\n item,\n selectedTheme.ToString()\n );\n anyPropertyUpdated = true;\n }\n // Finally try to map from SliderValue using SliderLabels\n else\n {\n // Try to get the SliderLabels collection to map the index to a value\n var sliderLabelsProperty = itemType.GetProperty(\n \"SliderLabels\"\n );\n if (sliderLabelsProperty != null)\n {\n var sliderLabels =\n sliderLabelsProperty.GetValue(item)\n as System.Collections.IList;\n if (\n sliderLabels != null\n && newSliderValue < sliderLabels.Count\n )\n {\n var selectedValue = sliderLabels[\n newSliderValue\n ]\n ?.ToString();\n if (!string.IsNullOrEmpty(selectedValue))\n {\n _logService.Log(\n LogLevel.Info,\n $\"Setting SelectedValue to {selectedValue} from SliderLabels for ComboBox {itemName}\"\n );\n comboBoxSelectedValueProperty.SetValue(\n item,\n selectedValue\n );\n anyPropertyUpdated = true;\n }\n }\n }\n }\n }\n }\n }\n\n // Also update specific properties based on the item identification\n if (isPowerPlan)\n {\n // Update PowerPlanValue property\n var powerPlanValueProperty = itemType.GetProperty(\n \"PowerPlanValue\"\n );\n if (powerPlanValueProperty != null)\n {\n int currentPowerPlanValue = (int)(\n powerPlanValueProperty.GetValue(item) ?? 0\n );\n if (currentPowerPlanValue != newSliderValue)\n {\n powerPlanValueProperty.SetValue(item, newSliderValue);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Info,\n $\"Updated PowerPlanValue for item {itemName} from {currentPowerPlanValue} to {newSliderValue}\"\n );\n\n // Try to call OnPowerPlanValueChanged method to apply the power plan\n try\n {\n var onPowerPlanValueChangedMethod =\n itemType.GetMethod(\n \"OnPowerPlanValueChanged\",\n System.Reflection.BindingFlags.NonPublic\n | System\n .Reflection\n .BindingFlags\n .Instance\n );\n\n if (onPowerPlanValueChangedMethod != null)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Calling OnPowerPlanValueChanged method with value {newSliderValue}\"\n );\n onPowerPlanValueChangedMethod.Invoke(\n item,\n new object[] { newSliderValue }\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Debug,\n \"OnPowerPlanValueChanged method not found\"\n );\n\n // Try to find ApplyPowerPlanCommand\n var applyPowerPlanCommandProperty =\n itemType.GetProperty(\n \"ApplyPowerPlanCommand\"\n );\n if (applyPowerPlanCommandProperty != null)\n {\n var command =\n applyPowerPlanCommandProperty.GetValue(\n item\n ) as System.Windows.Input.ICommand;\n if (\n command != null\n && command.CanExecute(newSliderValue)\n )\n {\n _logService.Log(\n LogLevel.Info,\n $\"Executing ApplyPowerPlanCommand with value {newSliderValue}\"\n );\n command.Execute(newSliderValue);\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Error calling power plan methods: {ex.Message}\"\n );\n }\n }\n }\n\n // Also update any ComboBox in the Settings collection\n try\n {\n var settingsProperty = itemType.GetProperty(\"Settings\");\n if (settingsProperty != null)\n {\n var settings =\n settingsProperty.GetValue(item)\n as System.Collections.IEnumerable;\n if (settings != null)\n {\n foreach (var setting in settings)\n {\n var settingType = setting.GetType();\n var settingIdProperty = settingType.GetProperty(\n \"Id\"\n );\n var settingNameProperty =\n settingType.GetProperty(\"Name\");\n\n string settingId = settingIdProperty\n ?.GetValue(setting)\n ?.ToString();\n string settingName = settingNameProperty\n ?.GetValue(setting)\n ?.ToString();\n\n bool isPowerPlanSetting =\n settingId == \"PowerPlanComboBox\"\n || (\n settingName != null\n && settingName.Contains(\"Power Plan\")\n );\n\n if (isPowerPlanSetting)\n {\n var settingSliderValueProperty =\n settingType.GetProperty(\"SliderValue\");\n if (settingSliderValueProperty != null)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Updating SliderValue for Power Plan setting to {newSliderValue}\"\n );\n settingSliderValueProperty.SetValue(\n setting,\n newSliderValue\n );\n }\n\n var selectedValueProperty =\n settingType.GetProperty(\n \"SelectedValue\"\n );\n if (selectedValueProperty != null)\n {\n // First try to get the value from PowerPlanOptions in the configItem\n if (\n configItem.CustomProperties.TryGetValue(\n \"PowerPlanOptions\",\n out var powerPlanOptions\n )\n )\n {\n // Handle different types of PowerPlanOptions\n if (\n powerPlanOptions\n is List options\n && newSliderValue >= 0\n && newSliderValue\n < options.Count\n )\n {\n string powerPlanLabel = options[\n newSliderValue\n ];\n _logService.Log(\n LogLevel.Info,\n $\"Updating SelectedValue for Power Plan setting to {powerPlanLabel} from configItem.PowerPlanOptions\"\n );\n selectedValueProperty.SetValue(\n setting,\n powerPlanLabel\n );\n }\n else if (\n powerPlanOptions\n is Newtonsoft.Json.Linq.JArray jArray\n && newSliderValue >= 0\n && newSliderValue < jArray.Count\n )\n {\n string powerPlanLabel = jArray[\n newSliderValue\n ]\n ?.ToString();\n _logService.Log(\n LogLevel.Info,\n $\"Updating SelectedValue for Power Plan setting to {powerPlanLabel} from configItem.PowerPlanOptions (JArray)\"\n );\n selectedValueProperty.SetValue(\n setting,\n powerPlanLabel\n );\n }\n else\n {\n // Fall back to SliderLabels\n TryUpdateFromSliderLabels(\n settingType,\n setting,\n selectedValueProperty,\n newSliderValue\n );\n }\n }\n // Then try to get it from the setting's SliderLabels\n else\n {\n TryUpdateFromSliderLabels(\n settingType,\n setting,\n selectedValueProperty,\n newSliderValue\n );\n }\n }\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating Power Plan settings: {ex.Message}\"\n );\n }\n }\n else if (isUacSlider)\n {\n var uacLevelProperty = itemType.GetProperty(\"SelectedUacLevel\");\n if (uacLevelProperty != null)\n {\n uacLevelProperty.SetValue(item, newSliderValue);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Debug,\n $\"Updated SelectedUacLevel for item {itemName} to {newSliderValue}\"\n );\n\n // Force the correct ControlType\n if (controlTypeProperty != null)\n {\n controlTypeProperty.SetValue(\n item,\n ControlType.ThreeStateSlider\n );\n _logService.Log(\n LogLevel.Debug,\n $\"Forced ControlType to ThreeStateSlider for item {itemName}\"\n );\n }\n }\n\n // Also try to update the parent view model's UacLevel property\n try\n {\n // Try to get the parent view model\n var viewModelProperty = itemType.GetProperty(\"ViewModel\");\n if (viewModelProperty != null)\n {\n var viewModel = viewModelProperty.GetValue(item);\n if (viewModel != null)\n {\n var viewModelType = viewModel.GetType();\n var viewModelUacLevelProperty =\n viewModelType.GetProperty(\"SelectedUacLevel\");\n if (viewModelUacLevelProperty != null)\n {\n viewModelUacLevelProperty.SetValue(\n viewModel,\n newSliderValue\n );\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Debug,\n $\"Updated SelectedUacLevel on parent view model to {newSliderValue}\"\n );\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating parent view model UacLevel: {ex.Message}\"\n );\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating SliderValue for item {itemName}: {ex.Message}\"\n );\n }\n }\n }\n\n // For non-theme items, also check for SelectedValue property\n if (!isThemeSelector)\n {\n var selectedValueProperty = itemType.GetProperty(\"SelectedValue\");\n if (selectedValueProperty != null)\n {\n try\n {\n string currentSelectedValue = selectedValueProperty\n .GetValue(item)\n ?.ToString();\n string newSelectedValue = null;\n\n // First try to get the value directly from configItem.SelectedValue\n if (!string.IsNullOrEmpty(configItem.SelectedValue))\n {\n newSelectedValue = configItem.SelectedValue;\n _logService.Log(\n LogLevel.Info,\n $\"Found SelectedValue in config: {newSelectedValue} for item {itemName}\"\n );\n }\n // Then try to get the value from CustomProperties.SelectedTheme\n else if (\n configItem.CustomProperties.TryGetValue(\n \"SelectedTheme\",\n out var selectedTheme\n )\n && selectedTheme != null\n )\n {\n newSelectedValue = selectedTheme.ToString();\n _logService.Log(\n LogLevel.Info,\n $\"Found SelectedTheme in CustomProperties: {newSelectedValue} for item {itemName}\"\n );\n }\n // Finally try to map from SliderValue using SliderLabels\n else if (\n configItem.CustomProperties.TryGetValue(\n \"SliderValue\",\n out var configSliderValueForMapping\n )\n )\n {\n var sliderLabelsProperty = itemType.GetProperty(\"SliderLabels\");\n if (sliderLabelsProperty != null)\n {\n var sliderLabels =\n sliderLabelsProperty.GetValue(item)\n as System.Collections.IList;\n int sliderValueInt = Convert.ToInt32(\n configSliderValueForMapping\n );\n if (sliderLabels != null && sliderValueInt < sliderLabels.Count)\n {\n newSelectedValue = sliderLabels[sliderValueInt]?.ToString();\n _logService.Log(\n LogLevel.Info,\n $\"Mapped SliderValue {sliderValueInt} to SelectedValue {newSelectedValue} for item {itemName}\"\n );\n }\n }\n }\n\n if (\n !string.IsNullOrEmpty(newSelectedValue)\n && currentSelectedValue != newSelectedValue\n )\n {\n selectedValueProperty.SetValue(item, newSelectedValue);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Info,\n $\"Updated SelectedValue for item {itemName} from {currentSelectedValue} to {newSelectedValue}\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating SelectedValue for item {itemName}: {ex.Message}\"\n );\n }\n }\n }\n\n // For toggle switches, ensure IsChecked is synchronized with IsSelected\n var isCheckedProperty = itemType.GetProperty(\"IsChecked\");\n if (isCheckedProperty != null)\n {\n try\n {\n bool currentIsChecked = (bool)(isCheckedProperty.GetValue(item) ?? false);\n\n if (currentIsChecked != configItem.IsSelected)\n {\n isCheckedProperty.SetValue(item, configItem.IsSelected);\n anyPropertyUpdated = true;\n _logService.Log(\n LogLevel.Debug,\n $\"Updated IsChecked for item {itemName} to {configItem.IsSelected}\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error updating IsChecked for item {itemName}: {ex.Message}\"\n );\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error in UpdateAdditionalProperties: {ex.Message}\"\n );\n }\n\n return anyPropertyUpdated;\n }\n\n /// \n /// Helper method to try updating SelectedValue from SliderLabels.\n /// \n /// The type of the setting.\n /// The setting object.\n /// The SelectedValue property.\n /// The new slider value.\n private void TryUpdateFromSliderLabels(\n Type settingType,\n object setting,\n System.Reflection.PropertyInfo selectedValueProperty,\n int newSliderValue\n )\n {\n // Try to get the power plan label from SliderLabels\n var sliderLabelsProperty = settingType.GetProperty(\"SliderLabels\");\n if (sliderLabelsProperty != null)\n {\n var sliderLabels =\n sliderLabelsProperty.GetValue(setting) as System.Collections.IList;\n if (\n sliderLabels != null\n && newSliderValue >= 0\n && newSliderValue < sliderLabels.Count\n )\n {\n string powerPlanLabel = sliderLabels[newSliderValue]?.ToString();\n if (!string.IsNullOrEmpty(powerPlanLabel))\n {\n _logService.Log(\n LogLevel.Info,\n $\"Updating SelectedValue for Power Plan setting to {powerPlanLabel} from SliderLabels\"\n );\n selectedValueProperty.SetValue(setting, powerPlanLabel);\n }\n }\n else\n {\n // Fall back to default values\n string[] defaultLabels =\n {\n \"Balanced\",\n \"High Performance\",\n \"Ultimate Performance\",\n };\n if (newSliderValue >= 0 && newSliderValue < defaultLabels.Length)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Updating SelectedValue for Power Plan setting to {defaultLabels[newSliderValue]} from default labels\"\n );\n selectedValueProperty.SetValue(setting, defaultLabels[newSliderValue]);\n }\n }\n }\n }\n\n private void TriggerPropertyChangedIfPossible(object item)\n {\n try\n {\n // Check if the item implements INotifyPropertyChanged\n if (item is System.ComponentModel.INotifyPropertyChanged)\n {\n try\n {\n // Use a safer approach to find property changed methods\n var methods = item.GetType()\n .GetMethods(\n System.Reflection.BindingFlags.Public\n | System.Reflection.BindingFlags.NonPublic\n | System.Reflection.BindingFlags.Instance\n )\n .Where(m =>\n (m.Name == \"RaisePropertyChanged\" || m.Name == \"OnPropertyChanged\")\n && m.GetParameters().Length == 1\n && m.GetParameters()[0].ParameterType == typeof(string)\n )\n .ToList();\n\n if (methods.Any())\n {\n var method = methods.First();\n // Invoke the method with null string to refresh all properties\n method.Invoke(item, new object[] { null });\n return;\n }\n\n // If no method with string parameter is found, try to find a method that takes PropertyChangedEventArgs\n var eventArgsMethods = item.GetType()\n .GetMethods(\n System.Reflection.BindingFlags.Public\n | System.Reflection.BindingFlags.NonPublic\n | System.Reflection.BindingFlags.Instance\n )\n .Where(m =>\n (m.Name == \"OnPropertyChanged\")\n && m.GetParameters().Length == 1\n && m.GetParameters()[0].ParameterType.Name\n == \"PropertyChangedEventArgs\"\n )\n .ToList();\n\n if (eventArgsMethods.Any())\n {\n // Create PropertyChangedEventArgs with null property name to refresh all properties\n var eventArgsType = eventArgsMethods\n .First()\n .GetParameters()[0]\n .ParameterType;\n var eventArgs = Activator.CreateInstance(\n eventArgsType,\n new object[] { null }\n );\n eventArgsMethods.First().Invoke(item, new[] { eventArgs });\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Error finding property changed method: {ex.Message}\"\n );\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error triggering property changed: {ex.Message}\");\n }\n }\n\n /// \n /// Applies registry settings for an item based on its IsSelected state.\n /// \n /// The item to apply registry settings for.\n /// Whether the setting is selected (enabled) or not.\n /// A task representing the asynchronous operation.\n private async Task ApplyRegistrySettingsAsync(object item, bool isSelected)\n {\n try\n {\n // Check if this is an ApplicationSettingItem\n if (item is ApplicationSettingItem settingItem)\n {\n _logService.Log(\n LogLevel.Debug,\n $\"Applying registry settings for {settingItem.Name}, IsSelected={isSelected}\"\n );\n\n // Apply registry setting if present\n if (settingItem.RegistrySetting != null)\n {\n string hiveString = GetRegistryHiveString(settingItem.RegistrySetting.Hive);\n object valueToApply = isSelected\n ? settingItem.RegistrySetting.EnabledValue\n ?? settingItem.RegistrySetting.RecommendedValue\n : settingItem.RegistrySetting.DisabledValue\n ?? settingItem.RegistrySetting.DefaultValue;\n\n // Ensure the key exists and set the value\n string keyPath = $\"{hiveString}\\\\{settingItem.RegistrySetting.SubKey}\";\n\n // First ensure the key exists\n bool keyExists = _registryService.KeyExists(keyPath);\n if (!keyExists)\n {\n _logService.Log(LogLevel.Info, $\"Creating registry key: {keyPath}\");\n bool keyCreated = _registryService.CreateKeyIfNotExists(keyPath);\n if (!keyCreated)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to create registry key: {keyPath}, trying direct registry access\"\n );\n\n // Try direct registry access to create the key\n try\n {\n RegistryKey rootKey = GetRegistryRootKey(\n settingItem.RegistrySetting.Hive\n );\n if (rootKey != null)\n {\n rootKey.CreateSubKey(\n settingItem.RegistrySetting.SubKey,\n true\n );\n _logService.Log(\n LogLevel.Success,\n $\"Successfully created registry key using direct access: {keyPath}\"\n );\n keyCreated = true;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to create registry key using direct access: {keyPath}, Error: {ex.Message}\"\n );\n }\n\n // If direct access failed, try using PowerShell\n if (!keyCreated)\n {\n try\n {\n string psCommand =\n $\"$ErrorActionPreference = 'Stop'; try {{ if (-not (Test-Path -Path '{keyPath.Replace(\"HKLM\", \"HKLM:\")}')) {{ New-Item -Path '{keyPath.Replace(\"HKLM\", \"HKLM:\")}' -Force | Out-Null; Write-Output 'Key created successfully' }} }} catch {{ Write-Error $_.Exception.Message; exit 1 }}\";\n\n _logService.Log(\n LogLevel.Info,\n $\"Attempting to create registry key using PowerShell: {keyPath}\"\n );\n\n // Execute PowerShell command\n var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-Command \\\"{psCommand}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n },\n };\n\n process.Start();\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n process.WaitForExit();\n\n if (process.ExitCode == 0)\n {\n _logService.Log(\n LogLevel.Success,\n $\"Successfully created registry key using PowerShell: {keyPath}\"\n );\n keyCreated = true;\n }\n else\n {\n _logService.Log(\n LogLevel.Error,\n $\"Failed to create registry key using PowerShell: {keyPath}, Error: {error}\"\n );\n }\n }\n catch (Exception psEx)\n {\n _logService.Log(\n LogLevel.Error,\n $\"PowerShell execution failed: {psEx.Message}\"\n );\n }\n }\n }\n }\n\n // Now set the value - always attempt to set the value even if key creation failed\n // This is important for configuration import to ensure values are applied\n bool success = false;\n\n // First try using the registry service\n success = _registryService.SetValue(\n keyPath,\n settingItem.RegistrySetting.Name,\n valueToApply,\n settingItem.RegistrySetting.ValueType\n );\n\n if (success)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Applied registry setting for {settingItem.Name}: {(isSelected ? \"Enabled\" : \"Disabled\")}\"\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to apply registry setting for {settingItem.Name}, trying direct registry access\"\n );\n\n // Try direct registry access as a fallback\n try\n {\n RegistryKey rootKey = GetRegistryRootKey(\n settingItem.RegistrySetting.Hive\n );\n if (rootKey != null)\n {\n using (\n RegistryKey regKey = rootKey.CreateSubKey(\n settingItem.RegistrySetting.SubKey,\n true\n )\n )\n {\n if (regKey != null)\n {\n regKey.SetValue(\n settingItem.RegistrySetting.Name,\n valueToApply,\n (RegistryValueKind)\n settingItem.RegistrySetting.ValueType\n );\n _logService.Log(\n LogLevel.Success,\n $\"Successfully applied registry setting using direct access: {keyPath}\\\\{settingItem.RegistrySetting.Name}\"\n );\n success = true;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Error,\n $\"Failed to apply registry setting using direct access: {ex.Message}\"\n );\n }\n\n // If direct access failed, try using PowerShell\n if (!success)\n {\n try\n {\n string psCommand =\n $\"$ErrorActionPreference = 'Stop'; try {{ if (-not (Test-Path -Path '{keyPath.Replace(\"HKLM\", \"HKLM:\")}')) {{ New-Item -Path '{keyPath.Replace(\"HKLM\", \"HKLM:\")}' -Force | Out-Null; }} Set-ItemProperty -Path '{keyPath.Replace(\"HKLM\", \"HKLM:\")}' -Name '{settingItem.RegistrySetting.Name}' -Value {valueToApply} -Type {settingItem.RegistrySetting.ValueType} -Force; }} catch {{ Write-Error $_.Exception.Message; exit 1 }}\";\n\n _logService.Log(\n LogLevel.Info,\n $\"Attempting to set registry value using PowerShell: {keyPath}\\\\{settingItem.RegistrySetting.Name}\"\n );\n\n // Execute PowerShell command\n var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-Command \\\"{psCommand}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n },\n };\n\n process.Start();\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n process.WaitForExit();\n\n if (process.ExitCode == 0)\n {\n _logService.Log(\n LogLevel.Success,\n $\"Successfully set registry value using PowerShell: {keyPath}\\\\{settingItem.RegistrySetting.Name}\"\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Error,\n $\"Failed to set registry value using PowerShell: {keyPath}\\\\{settingItem.RegistrySetting.Name}, Error: {error}\"\n );\n }\n }\n catch (Exception psEx)\n {\n _logService.Log(\n LogLevel.Error,\n $\"PowerShell execution failed: {psEx.Message}\"\n );\n }\n }\n }\n }\n // Apply linked registry settings if present\n else if (\n settingItem.LinkedRegistrySettings != null\n && settingItem.LinkedRegistrySettings.Settings.Count > 0\n )\n {\n _logService.Log(\n LogLevel.Info,\n $\"Applying linked registry settings for {settingItem.Name}, IsSelected={isSelected}\"\n );\n\n // Use the registry service to apply linked settings\n bool success = await _registryService.ApplyLinkedSettingsAsync(\n settingItem.LinkedRegistrySettings,\n isSelected\n );\n\n if (success)\n {\n _logService.Log(\n LogLevel.Success,\n $\"Successfully applied all linked registry settings for {settingItem.Name}\"\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Some linked registry settings for {settingItem.Name} failed to apply\"\n );\n }\n }\n\n // Refresh the status of the setting after applying changes\n await settingItem.RefreshStatus();\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying registry settings: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n }\n\n /// \n /// Gets the registry root key for a given hive.\n /// \n /// The registry hive.\n /// The registry root key.\n private RegistryKey GetRegistryRootKey(RegistryHive hive)\n {\n switch (hive)\n {\n case RegistryHive.ClassesRoot:\n return Registry.ClassesRoot;\n case RegistryHive.CurrentUser:\n return Registry.CurrentUser;\n case RegistryHive.LocalMachine:\n return Registry.LocalMachine;\n case RegistryHive.Users:\n return Registry.Users;\n case RegistryHive.CurrentConfig:\n return Registry.CurrentConfig;\n default:\n return null;\n }\n }\n\n /// \n /// Gets the registry hive string.\n /// \n /// The registry hive.\n /// The registry hive string.\n private string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => throw new ArgumentOutOfRangeException(nameof(hive), hive, null),\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/WindowsSystemService.cs", "using System;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Services;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.Customize.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Models.Enums;\n\n// We're now using the UacLevel from Models.Enums directly\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Contains detailed information about the Windows version\n /// \n public class WindowsVersionInfo\n {\n /// \n /// The full OS version\n /// \n public Version Version { get; set; }\n\n /// \n /// The major version number\n /// \n public int MajorVersion { get; set; }\n\n /// \n /// The minor version number\n /// \n public int MinorVersion { get; set; }\n\n /// \n /// The build number\n /// \n public int BuildNumber { get; set; }\n\n /// \n /// The product name from registry\n /// \n public string ProductName { get; set; }\n\n /// \n /// Whether this is Windows 11 based on build number\n /// \n public bool IsWindows11ByBuild { get; set; }\n\n /// \n /// Whether this is Windows 11 based on product name\n /// \n public bool IsWindows11ByProductName { get; set; }\n\n /// \n /// Whether this is Windows 11 (combined determination)\n /// \n public bool IsWindows11 { get; set; }\n\n /// \n /// Whether this is Windows 10\n /// \n public bool IsWindows10 { get; set; }\n }\n\n public class WindowsSystemService : ISystemServices\n {\n // Dependencies\n private readonly IRegistryService _registryService;\n private readonly ILogService _logService;\n private readonly IThemeService _themeService;\n private readonly IUacSettingsService _uacSettingsService;\n private readonly IInternetConnectivityService _connectivityService;\n\n public WindowsSystemService(\n IRegistryService registryService,\n ILogService logService,\n IInternetConnectivityService connectivityService,\n IThemeService themeService = null,\n IUacSettingsService uacSettingsService = null\n ) // Optional to maintain backward compatibility\n {\n _registryService =\n registryService ?? throw new ArgumentNullException(nameof(registryService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _connectivityService =\n connectivityService ?? throw new ArgumentNullException(nameof(connectivityService));\n _themeService = themeService; // May be null if not provided\n _uacSettingsService = uacSettingsService; // May be null if not provided\n }\n\n /// \n /// Gets the registry service.\n /// \n public IRegistryService RegistryService => _registryService;\n\n public bool IsAdministrator()\n {\n try\n {\n#if WINDOWS\n WindowsIdentity identity = WindowsIdentity.GetCurrent();\n WindowsPrincipal principal = new WindowsPrincipal(identity);\n bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);\n\n _logService.LogInformation(\n $\"Administrator check completed. Is Administrator: {isAdmin}\"\n );\n return isAdmin;\n#else\n _logService.LogWarning(\"Administrator check is not supported on this platform.\");\n return false;\n#endif\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking administrator status\", ex);\n return false;\n }\n }\n\n /// \n /// Gets detailed Windows version information including build number and product name\n /// \n /// A WindowsVersionInfo object containing detailed version information\n private WindowsVersionInfo GetWindowsVersionInfo()\n {\n var result = new WindowsVersionInfo();\n\n try\n {\n var osVersion = Environment.OSVersion;\n result.Version = osVersion.Version;\n result.MajorVersion = osVersion.Version.Major;\n result.MinorVersion = osVersion.Version.Minor;\n result.BuildNumber = osVersion.Version.Build;\n\n // Check if Windows 11 using build number\n result.IsWindows11ByBuild =\n result.MajorVersion == 10 && result.BuildNumber >= 22000;\n\n // Check registry ProductName for more reliable detection\n try\n {\n using (\n var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(\n @\"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\"\n )\n )\n {\n if (key != null)\n {\n result.ProductName = key.GetValue(\"ProductName\") as string;\n result.IsWindows11ByProductName =\n result.ProductName != null\n && result.ProductName.Contains(\"Windows 11\");\n\n // Log the actual product name for debugging\n _logService.LogInformation(\n $\"Windows registry ProductName: {result.ProductName}\"\n );\n }\n }\n }\n catch (Exception regEx)\n {\n _logService.LogWarning($\"Error reading registry ProductName: {regEx.Message}\");\n }\n\n // Log detailed version information\n _logService.LogInformation(\n $\"Windows build number: {result.BuildNumber}, IsWin11ByBuild: {result.IsWindows11ByBuild}, IsWin11ByProductName: {result.IsWindows11ByProductName}\"\n );\n\n // Determine if this is Windows 11 using both methods, with ProductName taking precedence if available\n result.IsWindows11 =\n result.IsWindows11ByProductName\n || (result.IsWindows11ByBuild && !result.IsWindows11ByProductName == false);\n result.IsWindows10 = result.MajorVersion == 10 && !result.IsWindows11;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error getting Windows version info\", ex);\n }\n\n return result;\n }\n\n public string GetWindowsVersion()\n {\n try\n {\n var versionInfo = GetWindowsVersionInfo();\n string versionString;\n\n if (versionInfo.MajorVersion == 10)\n {\n versionString = versionInfo.IsWindows11 ? \"Windows 11\" : \"Windows 10\";\n }\n else\n {\n versionString = $\"Windows {versionInfo.Version}\";\n }\n\n _logService.LogInformation($\"Detected Windows version: {versionString}\");\n return versionString;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error detecting Windows version\", ex);\n return \"Unknown Windows Version\";\n }\n }\n\n public void RestartExplorer()\n {\n try\n {\n _logService.LogInformation(\"Attempting to restart Explorer\");\n\n // Kill all explorer processes\n var explorerProcesses = Process.GetProcessesByName(\"explorer\");\n foreach (var process in explorerProcesses)\n {\n _logService.LogInformation($\"Killing Explorer process (PID: {process.Id})\");\n process.Kill();\n }\n\n // Wait a moment - using Thread.Sleep since we can't use await anymore\n Thread.Sleep(1000);\n\n // Restart explorer\n Process.Start(\"explorer.exe\");\n\n _logService.LogSuccess(\"Explorer restarted successfully\");\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to restart Explorer\", ex);\n }\n }\n\n public void RefreshDesktop()\n {\n try\n {\n [DllImport(\"user32.dll\", SetLastError = true)]\n static extern bool SystemParametersInfo(\n uint uiAction,\n uint uiParam,\n IntPtr pvParam,\n uint fWinIni\n );\n\n const uint SPI_SETDESKWALLPAPER = 0x0014;\n const uint SPIF_UPDATEINIFILE = 0x01;\n const uint SPIF_SENDCHANGE = 0x02;\n\n _logService.LogInformation(\"Attempting to refresh desktop\");\n SystemParametersInfo(\n SPI_SETDESKWALLPAPER,\n 0,\n IntPtr.Zero,\n SPIF_UPDATEINIFILE | SPIF_SENDCHANGE\n );\n\n _logService.LogSuccess(\"Desktop refreshed successfully\");\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to refresh desktop\", ex);\n }\n }\n\n public bool IsProcessRunning(string processName)\n {\n try\n {\n bool isRunning = Process.GetProcessesByName(processName).Length > 0;\n _logService.LogInformation($\"Process check for {processName}: {isRunning}\");\n return isRunning;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking if process {processName} is running\", ex);\n return false;\n }\n }\n\n public void KillProcess(string processName)\n {\n try\n {\n _logService.LogInformation($\"Attempting to kill process: {processName}\");\n\n var processes = Process.GetProcessesByName(processName);\n foreach (var process in processes)\n {\n _logService.LogInformation(\n $\"Killing process {processName} (PID: {process.Id})\"\n );\n process.Kill();\n }\n\n _logService.LogSuccess($\"Killed all instances of {processName}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to kill process {processName}\", ex);\n }\n }\n\n // IsInternetConnected method has been moved to InternetConnectivityService\n\n // IsInternetConnectedAsync method has been moved to InternetConnectivityService\n\n public bool IsWindows11()\n {\n try\n {\n // Use our centralized version detection method\n var versionInfo = GetWindowsVersionInfo();\n\n _logService.LogInformation(\n $\"Windows 11 check completed. Is Windows 11: {versionInfo.IsWindows11} (By build: {versionInfo.IsWindows11ByBuild}, By ProductName: {versionInfo.IsWindows11ByProductName})\"\n );\n return versionInfo.IsWindows11;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking Windows 11 version\", ex);\n return false;\n }\n }\n\n public bool RequireAdministrator()\n {\n try\n {\n if (!IsAdministrator())\n {\n _logService.LogWarning(\n \"Application requires administrator privileges. Attempting to elevate.\"\n );\n\n ProcessStartInfo startInfo = new ProcessStartInfo\n {\n UseShellExecute = true,\n WorkingDirectory = Environment.CurrentDirectory,\n FileName =\n Process.GetCurrentProcess().MainModule?.FileName\n ?? throw new InvalidOperationException(\"MainModule is null\"),\n Verb = \"runas\",\n };\n\n try\n {\n // Start the elevated process and capture the Process object\n Process elevatedProcess = Process.Start(startInfo);\n\n // If elevatedProcess is null, it means the UAC prompt was canceled or denied\n if (elevatedProcess == null)\n {\n _logService.LogWarning(\n \"User denied UAC elevation. Application will exit.\"\n );\n Environment.Exit(1); // Exit with error code to indicate denial\n return false;\n }\n\n _logService.LogInformation(\n \"Elevation request accepted. Exiting current process.\"\n );\n Environment.Exit(0);\n }\n catch (System.ComponentModel.Win32Exception w32Ex)\n when (w32Ex.NativeErrorCode == 1223)\n {\n // Error code 1223 specifically means \"The operation was canceled by the user\"\n // This happens when the user clicks \"No\" on the UAC prompt\n _logService.LogWarning(\"User denied UAC elevation. Application will exit.\");\n Environment.Exit(1); // Exit with error code to indicate denial\n return false;\n }\n catch (Exception elevationEx)\n {\n _logService.LogError(\"Failed to elevate privileges\", elevationEx);\n Environment.Exit(1); // Exit with error code to indicate failure\n return false;\n }\n }\n\n _logService.LogInformation(\"Application is running with administrator privileges\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Unexpected error during privilege elevation\", ex);\n return false;\n }\n }\n\n public bool IsDarkModeEnabled()\n {\n // Delegate to ThemeService if available, otherwise use legacy implementation\n if (_themeService != null)\n {\n try\n {\n return _themeService.IsDarkModeEnabled();\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Error using ThemeService.IsDarkModeEnabled: {ex.Message}. Falling back to legacy implementation.\"\n );\n // Fall through to legacy implementation\n }\n }\n\n // Legacy implementation\n try\n {\n using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(\n WindowsThemeSettings.Registry.ThemesPersonalizeSubKey\n );\n\n if (key == null)\n {\n _logService.LogWarning(\"Could not open registry key for dark mode check\");\n return false;\n }\n\n var value = key.GetValue(WindowsThemeSettings.Registry.AppsUseLightThemeName);\n bool isDarkMode = value != null && (int)value == 0;\n\n _logService.LogInformation(\n $\"Dark mode check completed. Is Dark Mode: {isDarkMode}\"\n );\n return isDarkMode;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking dark mode status\", ex);\n return false;\n }\n }\n\n public void SetDarkMode(bool enabled)\n {\n // Delegate to ThemeService if available, otherwise use legacy implementation\n if (_themeService != null)\n {\n try\n {\n _themeService.SetThemeMode(enabled);\n return;\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Error using ThemeService.SetThemeMode: {ex.Message}. Falling back to legacy implementation.\"\n );\n // Fall through to legacy implementation\n }\n }\n\n // Legacy implementation\n try\n {\n _logService.LogInformation(\n $\"Attempting to {(enabled ? \"enable\" : \"disable\")} dark mode\"\n );\n\n string[] keys = new[] { WindowsThemeSettings.Registry.ThemesPersonalizeSubKey };\n\n string[] values = new[]\n {\n WindowsThemeSettings.Registry.AppsUseLightThemeName,\n WindowsThemeSettings.Registry.SystemUsesLightThemeName,\n };\n\n foreach (var key in keys)\n {\n using var registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(\n key,\n true\n );\n if (registryKey == null)\n {\n _logService.LogWarning($\"Could not open registry key: {key}\");\n continue;\n }\n\n foreach (var value in values)\n {\n registryKey.SetValue(\n value,\n enabled ? 0 : 1,\n Microsoft.Win32.RegistryValueKind.DWord\n );\n _logService.LogInformation($\"Set {value} to {(enabled ? 0 : 1)}\");\n }\n }\n\n _logService.LogSuccess(\n $\"Dark mode {(enabled ? \"enabled\" : \"disabled\")} successfully\"\n );\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to {(enabled ? \"enable\" : \"disable\")} dark mode\", ex);\n }\n }\n\n public void SetUacLevel(Winhance.Core.Models.Enums.UacLevel level)\n {\n try\n {\n // No need to convert as we're already using the Core UacLevel\n Winhance.Core.Models.Enums.UacLevel coreLevel = level;\n\n // Special handling for Custom UAC level\n if (coreLevel == Winhance.Core.Models.Enums.UacLevel.Custom)\n {\n // For Custom level, try to get the saved custom settings and apply them\n if (_uacSettingsService != null && _uacSettingsService.TryGetCustomUacValues(\n out int customConsentPromptValue, \n out int customSecureDesktopValue))\n {\n _logService.Log(\n LogLevel.Info,\n $\"Applying saved custom UAC settings: ConsentPrompt={customConsentPromptValue}, SecureDesktop={customSecureDesktopValue}\"\n );\n \n string registryPath = $\"HKLM\\\\{UacOptimizations.RegistryPath}\";\n \n // Set the ConsentPromptBehaviorAdmin value\n _registryService.SetValue(\n registryPath,\n UacOptimizations.ConsentPromptName,\n customConsentPromptValue,\n UacOptimizations.ValueKind\n );\n \n // Set the PromptOnSecureDesktop value\n _registryService.SetValue(\n registryPath,\n UacOptimizations.SecureDesktopName,\n customSecureDesktopValue,\n UacOptimizations.ValueKind\n );\n \n return;\n }\n else\n {\n // No saved custom settings found\n _logService.Log(\n LogLevel.Warning,\n \"Custom UAC level selected but no saved settings found - preserving current registry settings\"\n );\n return;\n }\n }\n\n // Get both registry values for the selected UAC level\n if (\n !UacOptimizations.UacLevelToConsentPromptValue.TryGetValue(\n coreLevel,\n out int consentPromptValue\n )\n || !UacOptimizations.UacLevelToSecureDesktopValue.TryGetValue(\n coreLevel,\n out int secureDesktopValue\n )\n )\n {\n throw new ArgumentException($\"Invalid UAC level: {level}\");\n }\n\n string fullPath = $\"HKLM\\\\{UacOptimizations.RegistryPath}\";\n\n bool keyExists = _registryService.KeyExists(fullPath);\n if (!keyExists)\n {\n _logService.Log(\n LogLevel.Info,\n $\"UAC registry key doesn't exist, creating: {fullPath}\"\n );\n _registryService.CreateKey(fullPath);\n }\n\n // Set the ConsentPromptBehaviorAdmin value\n _registryService.SetValue(\n fullPath,\n UacOptimizations.ConsentPromptName,\n consentPromptValue,\n UacOptimizations.ValueKind\n );\n\n // Set the PromptOnSecureDesktop value\n _registryService.SetValue(\n fullPath,\n UacOptimizations.SecureDesktopName,\n secureDesktopValue,\n UacOptimizations.ValueKind\n );\n\n string levelName = UacOptimizations.UacLevelNames.TryGetValue(\n coreLevel,\n out string name\n )\n ? name\n : coreLevel.ToString();\n _logService.Log(\n LogLevel.Info,\n $\"UAC level set to {levelName} (ConsentPrompt: {consentPromptValue}, SecureDesktop: {secureDesktopValue})\"\n );\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting UAC level: {ex.Message}\");\n throw;\n }\n }\n\n public Winhance.Core.Models.Enums.UacLevel GetUacLevel()\n {\n try\n {\n string fullPath = $\"HKLM\\\\{UacOptimizations.RegistryPath}\";\n\n // Get both registry values needed to determine the UAC level\n var consentPromptValue = _registryService.GetValue(\n fullPath,\n UacOptimizations.ConsentPromptName\n );\n var secureDesktopValue = _registryService.GetValue(\n fullPath,\n UacOptimizations.SecureDesktopName\n );\n\n // Convert to integers with appropriate defaults if values are null\n var consentPromptInt = Convert.ToInt32(consentPromptValue ?? 5); // Default to 5 (Notify)\n var secureDesktopInt = Convert.ToInt32(secureDesktopValue ?? 1); // Default to 1 (Enabled)\n\n _logService.Log(\n LogLevel.Info,\n $\"UAC registry values retrieved: ConsentPrompt={consentPromptInt}, SecureDesktop={secureDesktopInt}\"\n );\n\n // Determine the UacLevel from both registry values\n Winhance.Core.Models.Enums.UacLevel coreLevel =\n UacOptimizations.GetUacLevelFromRegistryValues(\n consentPromptInt,\n secureDesktopInt,\n _uacSettingsService\n );\n string levelName = UacOptimizations.UacLevelNames.TryGetValue(\n coreLevel,\n out string name\n )\n ? name\n : coreLevel.ToString();\n\n _logService.Log(LogLevel.Info, $\"UAC level mapped to: {levelName}\");\n\n // Return the Core UacLevel directly\n return coreLevel;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting UAC level: {ex.Message}\");\n return Winhance.Core.Models.Enums.UacLevel.NotifyChangesOnly; // Default value\n }\n }\n\n public async Task RefreshWindowsGUI(bool killExplorer)\n {\n try\n {\n _logService.Log(\n LogLevel.Info,\n $\"Refreshing Windows GUI (killExplorer: {killExplorer})\"\n );\n\n // Define Windows message constants\n const int HWND_BROADCAST = 0xffff;\n const uint WM_SYSCOLORCHANGE = 0x0015;\n const uint WM_SETTINGCHANGE = 0x001A;\n const uint WM_THEMECHANGE = 0x031A;\n\n // Import Windows API functions\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\n static extern IntPtr SendMessage(\n IntPtr hWnd,\n uint Msg,\n IntPtr wParam,\n IntPtr lParam\n );\n\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n static extern IntPtr SendMessageTimeout(\n IntPtr hWnd,\n uint Msg,\n IntPtr wParam,\n IntPtr lParam,\n uint fuFlags,\n uint uTimeout,\n out IntPtr lpdwResult\n );\n\n SendMessage((IntPtr)HWND_BROADCAST, WM_SYSCOLORCHANGE, IntPtr.Zero, IntPtr.Zero);\n SendMessage((IntPtr)HWND_BROADCAST, WM_THEMECHANGE, IntPtr.Zero, IntPtr.Zero);\n\n if (killExplorer)\n {\n _logService.Log(\n LogLevel.Info,\n \"Refreshing Windows GUI by terminating Explorer process\"\n );\n\n await Task.Delay(500);\n\n bool explorerWasRunning = Process.GetProcessesByName(\"explorer\").Length > 0;\n\n if (explorerWasRunning)\n {\n _logService.Log(\n LogLevel.Info,\n \"Terminating Explorer processes - Windows will restart it automatically\"\n );\n\n foreach (var process in Process.GetProcessesByName(\"explorer\"))\n {\n try\n {\n process.Kill();\n _logService.Log(\n LogLevel.Info,\n $\"Killed Explorer process (PID: {process.Id})\"\n );\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to kill Explorer process: {ex.Message}\"\n );\n }\n }\n\n _logService.Log(\n LogLevel.Info,\n \"Waiting for Windows to automatically restart Explorer\"\n );\n\n // Wait for Explorer to be terminated completely\n await Task.Delay(1000);\n\n // Check if Explorer has restarted automatically\n int retryCount = 0;\n const int maxRetries = 5;\n bool explorerRestarted = false;\n\n while (retryCount < maxRetries && !explorerRestarted)\n {\n if (Process.GetProcessesByName(\"explorer\").Length > 0)\n {\n explorerRestarted = true;\n _logService.Log(\n LogLevel.Info,\n \"Explorer process restarted automatically\"\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Explorer not restarted yet, waiting... (Attempt {retryCount + 1}/{maxRetries})\"\n );\n retryCount++;\n await Task.Delay(1000);\n }\n }\n\n // If Explorer didn't restart automatically, start it manually\n if (!explorerRestarted)\n {\n _logService.Log(\n LogLevel.Warning,\n \"Explorer did not restart automatically, starting it manually\"\n );\n try\n {\n Process.Start(\"explorer.exe\");\n _logService.Log(LogLevel.Info, \"Explorer process started manually\");\n\n // Wait for Explorer to initialize\n await Task.Delay(2000);\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Error,\n $\"Failed to start Explorer manually: {ex.Message}\"\n );\n return false;\n }\n }\n }\n }\n else\n {\n _logService.Log(\n LogLevel.Info,\n \"Refreshing Windows GUI without killing Explorer\"\n );\n }\n\n string themeChanged = \"ImmersiveColorSet\";\n IntPtr themeChangedPtr = Marshal.StringToHGlobalUni(themeChanged);\n\n try\n {\n IntPtr result;\n SendMessageTimeout(\n (IntPtr)HWND_BROADCAST,\n WM_SETTINGCHANGE,\n IntPtr.Zero,\n themeChangedPtr,\n 0x0000,\n 1000,\n out result\n );\n\n SendMessage((IntPtr)HWND_BROADCAST, WM_SETTINGCHANGE, IntPtr.Zero, IntPtr.Zero);\n }\n finally\n {\n Marshal.FreeHGlobal(themeChangedPtr);\n }\n\n _logService.Log(LogLevel.Info, \"Windows GUI refresh completed successfully\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error refreshing Windows GUI: {ex.Message}\");\n return false;\n }\n }\n\n public Task RefreshWindowsGUI()\n {\n return RefreshWindowsGUI(true);\n }\n\n /// \n /// Checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// True if internet is connected, false otherwise.\n public bool IsInternetConnected(bool forceCheck = false)\n {\n return _connectivityService.IsInternetConnected(forceCheck);\n }\n\n /// \n /// Asynchronously checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// Cancellation token for the operation.\n /// True if internet is connected, false otherwise.\n public async Task IsInternetConnectedAsync(\n bool forceCheck = false,\n CancellationToken cancellationToken = default,\n bool userInitiatedCancellation = false\n )\n {\n return await _connectivityService.IsInternetConnectedAsync(\n forceCheck,\n cancellationToken,\n userInitiatedCancellation\n );\n }\n\n private async Task RunCommand(string command, string arguments)\n {\n try\n {\n using var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = command,\n Arguments = arguments,\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n },\n };\n\n process.Start();\n await process.WaitForExitAsync();\n\n if (process.ExitCode != 0)\n {\n _logService.Log(LogLevel.Warning, $\"Command failed: {command} {arguments}\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error running command: {ex.Message}\");\n throw;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/CategoryToIconConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing MaterialDesignThemes.Wpf;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a category name to an appropriate Material Design icon.\n /// \n public class CategoryToIconConverter : IValueConverter\n {\n public static CategoryToIconConverter Instance { get; } = new CategoryToIconConverter();\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is string categoryName)\n {\n // Convert category name to lowercase for case-insensitive comparison\n string category = categoryName.ToLowerInvariant();\n\n // Map category names to appropriate Material Design icons\n return category switch\n {\n // Browser related categories\n var c when c.Contains(\"browser\") => PackIconKind.Web,\n \n // Compression related categories\n var c when c.Contains(\"compression\") => PackIconKind.ZipBox,\n var c when c.Contains(\"zip\") => PackIconKind.ZipBox,\n var c when c.Contains(\"archive\") => PackIconKind.Archive,\n \n // Customization related categories\n var c when c.Contains(\"customization\") => PackIconKind.Palette,\n var c when c.Contains(\"utilities\") => PackIconKind.Tools,\n var c when c.Contains(\"shell\") => PackIconKind.Console,\n \n // Development related categories\n var c when c.Contains(\"development\") => PackIconKind.CodeBraces,\n var c when c.Contains(\"programming\") => PackIconKind.CodeBraces,\n var c when c.Contains(\"code\") => PackIconKind.CodeBraces,\n \n // Document related categories\n var c when c.Contains(\"document\") => PackIconKind.FileDocument,\n var c when c.Contains(\"pdf\") => PackIconKind.File,\n var c when c.Contains(\"office\") => PackIconKind.FileDocument,\n var c when c.Contains(\"viewer\") => PackIconKind.FileDocument,\n \n // Media related categories\n var c when c.Contains(\"media\") => PackIconKind.Play,\n var c when c.Contains(\"video\") => PackIconKind.Video,\n var c when c.Contains(\"audio\") => PackIconKind.Music,\n var c when c.Contains(\"player\") => PackIconKind.Play,\n var c when c.Contains(\"multimedia\") => PackIconKind.Play,\n \n // Communication related categories\n var c when c.Contains(\"communication\") => PackIconKind.Message,\n var c when c.Contains(\"chat\") => PackIconKind.Chat,\n var c when c.Contains(\"email\") => PackIconKind.Email,\n var c when c.Contains(\"messaging\") => PackIconKind.Message,\n var c when c.Contains(\"calendar\") => PackIconKind.Calendar,\n \n // Security related categories\n var c when c.Contains(\"security\") => PackIconKind.Shield,\n var c when c.Contains(\"antivirus\") => PackIconKind.ShieldOutline,\n var c when c.Contains(\"firewall\") => PackIconKind.Fire,\n var c when c.Contains(\"privacy\") => PackIconKind.Lock,\n \n // File & Disk Management\n var c when c.Contains(\"file\") => PackIconKind.Folder,\n var c when c.Contains(\"disk\") => PackIconKind.Database,\n \n // Gaming\n var c when c.Contains(\"gaming\") => PackIconKind.GamepadVariant,\n var c when c.Contains(\"game\") => PackIconKind.GamepadVariant,\n \n // Imaging\n var c when c.Contains(\"imaging\") => PackIconKind.Image,\n var c when c.Contains(\"image\") => PackIconKind.Image,\n \n // Online Storage\n var c when c.Contains(\"storage\") => PackIconKind.Cloud,\n var c when c.Contains(\"cloud\") => PackIconKind.Cloud,\n \n // Remote Access\n var c when c.Contains(\"remote\") => PackIconKind.Remote,\n var c when c.Contains(\"access\") => PackIconKind.Remote,\n \n // Optical Disc Utilities\n var c when c.Contains(\"optical\") => PackIconKind.Album,\n var c when c.Contains(\"disc\") => PackIconKind.Album,\n var c when c.Contains(\"dvd\") => PackIconKind.Album,\n var c when c.Contains(\"cd\") => PackIconKind.Album,\n \n // Default icon for unknown categories\n _ => PackIconKind.Apps\n };\n }\n \n // Default to Apps icon if value is not a string\n return PackIconKind.Apps;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // This converter doesn't support converting back\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/WindowsThemeSettings.cs", "using Microsoft.Win32;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Enums;\nusing Winhance.Core.Features.Customize.Interfaces;\n\nnamespace Winhance.Core.Features.Customize.Models\n{\n /// \n /// Model for Windows theme settings.\n /// \n public class WindowsThemeSettings\n {\n // Registry paths and keys\n public static class Registry\n {\n public const string ThemesPersonalizeSubKey = @\"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\";\n public const string AppsUseLightThemeName = \"AppsUseLightTheme\";\n public const string SystemUsesLightThemeName = \"SystemUsesLightTheme\";\n }\n\n // Wallpaper paths\n public static class Wallpaper\n {\n // Windows 11 wallpaper paths\n public const string Windows11BasePath = @\"C:\\Windows\\Web\\Wallpaper\\Windows\";\n public const string Windows11LightWallpaper = \"img0.jpg\";\n public const string Windows11DarkWallpaper = \"img19.jpg\";\n\n // Windows 10 wallpaper path\n public const string Windows10Wallpaper = @\"C:\\Windows\\Web\\4K\\Wallpaper\\Windows\\img0_3840x2160.jpg\";\n\n public static string GetDefaultWallpaperPath(bool isWindows11, bool isDarkMode)\n {\n if (isWindows11)\n {\n return System.IO.Path.Combine(\n Windows11BasePath, \n isDarkMode ? Windows11DarkWallpaper : Windows11LightWallpaper);\n }\n \n return Windows10Wallpaper;\n }\n }\n\n private readonly IThemeService _themeService;\n private bool _isDarkMode;\n private bool _changeWallpaper;\n\n /// \n /// Gets or sets a value indicating whether dark mode is enabled.\n /// \n public bool IsDarkMode\n {\n get => _isDarkMode;\n set => _isDarkMode = value;\n }\n\n /// \n /// Gets or sets a value indicating whether to change the wallpaper when changing the theme.\n /// \n public bool ChangeWallpaper\n {\n get => _changeWallpaper;\n set => _changeWallpaper = value;\n }\n\n /// \n /// Gets the current theme name.\n /// \n public string ThemeName => IsDarkMode ? \"Dark Mode\" : \"Light Mode\";\n\n /// \n /// Gets the available theme options.\n /// \n public List ThemeOptions { get; } = new List { \"Light Mode\", \"Dark Mode\" };\n\n /// \n /// Initializes a new instance of the class.\n /// \n public WindowsThemeSettings()\n {\n // Default constructor for serialization\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The theme service.\n public WindowsThemeSettings(IThemeService themeService)\n {\n _themeService = themeService;\n _isDarkMode = themeService?.IsDarkModeEnabled() ?? false;\n }\n\n /// \n /// Loads the current theme settings from the system.\n /// \n public void LoadCurrentSettings()\n {\n if (_themeService != null)\n {\n _isDarkMode = _themeService.IsDarkModeEnabled();\n }\n }\n\n /// \n /// Applies the current theme settings to the system.\n /// \n /// True if the operation succeeded; otherwise, false.\n public bool ApplyTheme()\n {\n return _themeService?.SetThemeMode(_isDarkMode) ?? false;\n }\n\n /// \n /// Applies the current theme settings to the system asynchronously.\n /// \n /// A task representing the asynchronous operation.\n public async Task ApplyThemeAsync()\n {\n if (_themeService == null)\n return false;\n\n return await _themeService.ApplyThemeAsync(_isDarkMode, _changeWallpaper);\n }\n\n /// \n /// Creates registry settings for Windows theme.\n /// \n /// A list of registry settings.\n public static List CreateRegistrySettings()\n {\n return new List\n {\n new RegistrySetting\n {\n Category = \"WindowsTheme\",\n Hive = RegistryHive.CurrentUser,\n SubKey = Registry.ThemesPersonalizeSubKey,\n Name = Registry.AppsUseLightThemeName,\n EnabledValue = 0, // Dark mode\n DisabledValue = 1, // Light mode\n ValueType = RegistryValueKind.DWord,\n Description = \"Windows Apps Theme Mode\",\n // For backward compatibility\n RecommendedValue = 0,\n DefaultValue = 1\n },\n new RegistrySetting\n {\n Category = \"WindowsTheme\",\n Hive = RegistryHive.CurrentUser,\n SubKey = Registry.ThemesPersonalizeSubKey,\n Name = Registry.SystemUsesLightThemeName,\n EnabledValue = 0, // Dark mode\n DisabledValue = 1, // Light mode\n ValueType = RegistryValueKind.DWord,\n Description = \"Windows System Theme Mode\",\n // For backward compatibility\n RecommendedValue = 0,\n DefaultValue = 1\n }\n };\n }\n\n /// \n /// Creates a customization setting for Windows theme.\n /// \n /// A customization setting.\n public static CustomizationSetting CreateCustomizationSetting()\n {\n var setting = new CustomizationSetting\n {\n Id = \"WindowsTheme\",\n Name = \"Windows Theme\",\n Description = \"Toggle between light and dark theme for Windows\",\n GroupName = \"Windows Theme\",\n Category = CustomizationCategory.Theme,\n ControlType = ControlType.ComboBox,\n RegistrySettings = CreateRegistrySettings()\n };\n\n return setting;\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Customize/Views/CustomizeView.xaml.cs", "using System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing MaterialDesignThemes.Wpf;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Messages;\nusing Winhance.WPF.Features.Customize.ViewModels;\n\nnamespace Winhance.WPF.Features.Customize.Views\n{\n /// \n /// Interaction logic for CustomizeView.xaml\n /// \n public partial class CustomizeView : UserControl\n {\n private IMessengerService? _messengerService; // Changed from readonly to allow assignment\n \n public CustomizeView()\n {\n InitializeComponent();\n Loaded += CustomizeView_Loaded;\n \n // Get messenger service from DataContext when it's set\n DataContextChanged += (s, e) => \n {\n if (e.NewValue is CustomizeViewModel viewModel && \n viewModel.MessengerService is IMessengerService messengerService)\n {\n _messengerService = messengerService;\n SubscribeToMessages();\n }\n };\n }\n \n private void SubscribeToMessages()\n {\n if (_messengerService == null)\n return;\n \n // Subscribe to the message that signals resetting expansion states\n _messengerService.Register(this, OnResetExpansionState);\n }\n \n private void OnResetExpansionState(ResetExpansionStateMessage message)\n {\n // Reset all sections to be expanded\n ResetAllExpansionStates();\n }\n \n /// \n /// Resets all section expansion states to expanded\n /// \n private void ResetAllExpansionStates()\n {\n // Ensure all content is visible\n TaskbarContent.Visibility = Visibility.Visible;\n StartMenuContent.Visibility = Visibility.Visible;\n ExplorerContent.Visibility = Visibility.Visible;\n WindowsThemeContent.Visibility = Visibility.Visible;\n \n // Set all arrow icons to up (expanded state)\n TaskbarHeaderIcon.Kind = PackIconKind.ChevronUp;\n StartMenuHeaderIcon.Kind = PackIconKind.ChevronUp;\n ExplorerHeaderIcon.Kind = PackIconKind.ChevronUp;\n WindowsThemeHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n\n private void CustomizeView_Loaded(object sender, RoutedEventArgs e)\n {\n // Initialize sections to be expanded by default\n TaskbarContent.Visibility = Visibility.Visible;\n StartMenuContent.Visibility = Visibility.Visible;\n ExplorerContent.Visibility = Visibility.Visible;\n WindowsThemeContent.Visibility = Visibility.Visible;\n\n // Set arrow icons to up arrow\n TaskbarHeaderIcon.Kind = PackIconKind.ChevronUp; // Up arrow\n StartMenuHeaderIcon.Kind = PackIconKind.ChevronUp; // Up arrow\n ExplorerHeaderIcon.Kind = PackIconKind.ChevronUp; // Up arrow\n WindowsThemeHeaderIcon.Kind = PackIconKind.ChevronUp; // Up arrow\n\n // Remove all existing event handlers from all border elements\n foreach (var element in this.FindVisualChildren(this))\n {\n if (element?.Tag != null && element.Tag is string tag)\n {\n // Remove any existing MouseLeftButtonDown handlers\n element.MouseLeftButtonDown -= HeaderBorder_MouseLeftButtonDown;\n\n // Add our new handler\n element.PreviewMouseDown += Element_PreviewMouseDown;\n }\n }\n }\n\n private void Element_PreviewMouseDown(object sender, MouseButtonEventArgs e)\n {\n // If we clicked on a Button, don't handle it here\n if (e.OriginalSource is Button)\n {\n return;\n }\n\n if (sender is Border border && border.Tag is string tag)\n {\n try\n {\n // Toggle visibility and selection based on tag\n switch (tag)\n {\n case \"0\":\n ToggleSectionVisibility(TaskbarContent, TaskbarHeaderIcon);\n TaskbarToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n break;\n case \"1\":\n ToggleSectionVisibility(StartMenuContent, StartMenuHeaderIcon);\n StartMenuToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n break;\n case \"2\":\n ToggleSectionVisibility(ExplorerContent, ExplorerHeaderIcon);\n ExplorerToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n break;\n case \"3\":\n ToggleSectionVisibility(WindowsThemeContent, WindowsThemeHeaderIcon);\n WindowsThemeToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n break;\n }\n\n // Mark event as handled so it won't bubble up\n e.Handled = true;\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Error handling header click: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n }\n }\n }\n\n // This method is no longer needed since we're not checking for checkboxes anymore\n\n private void ToggleSectionVisibility(UIElement content, PackIcon icon)\n {\n if (content.Visibility == Visibility.Collapsed)\n {\n content.Visibility = Visibility.Visible;\n icon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n }\n else\n {\n content.Visibility = Visibility.Collapsed;\n icon.Kind = PackIconKind.ChevronDown; // Downward arrow for collapsed state\n }\n }\n\n // This is defined in the XAML, so we need to keep it to avoid errors\n private void HeaderBorder_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n // This no longer does anything because we're using PreviewMouseDown now\n // We'll just mark it as handled to prevent unexpected behavior\n e.Handled = true;\n }\n\n // Helper method to find visual children of a specific type\n private System.Collections.Generic.IEnumerable FindVisualChildren(DependencyObject parent) where T : DependencyObject\n {\n int childrenCount = VisualTreeHelper.GetChildrenCount(parent);\n for (int i = 0; i < childrenCount; i++)\n {\n DependencyObject child = VisualTreeHelper.GetChild(parent, i);\n\n if (child is T childOfType)\n yield return childOfType;\n\n foreach (T childOfChild in FindVisualChildren(child))\n yield return childOfChild;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/ViewNameToBackgroundConverter.cs", "using System;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing System.Windows.Threading;\nusing Winhance.WPF.Features.Common.Resources.Theme;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class ViewNameToBackgroundConverter : IValueConverter, INotifyPropertyChanged\n {\n private static ViewNameToBackgroundConverter? _instance;\n \n public static ViewNameToBackgroundConverter Instance \n {\n get \n {\n if (_instance == null)\n {\n _instance = new ViewNameToBackgroundConverter();\n }\n return _instance;\n }\n }\n \n public event PropertyChangedEventHandler? PropertyChanged;\n \n // This method will be called when the theme changes\n public void NotifyThemeChanged()\n {\n // Force a refresh of all bindings that use this converter\n Application.Current.Dispatcher.Invoke(() =>\n {\n // Notify all properties to force binding refresh\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(string.Empty));\n \n // Also notify specific properties to ensure all binding scenarios are covered\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(\"ThemeChanged\"));\n \n // Force WPF to update all bindings\n if (Application.Current.MainWindow != null)\n {\n Application.Current.MainWindow.UpdateLayout();\n }\n }, DispatcherPriority.Render);\n }\n \n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n try\n {\n var currentViewName = value as string;\n var buttonViewName = parameter as string;\n \n if (string.Equals(currentViewName, buttonViewName, StringComparison.OrdinalIgnoreCase))\n {\n // Return the main content background color for selected buttons\n var brush = Application.Current.Resources[\"MainContainerBorderBrush\"] as SolidColorBrush;\n return brush?.Color ?? Colors.Transparent;\n }\n \n // Return the default navigation button background color\n var defaultBrush = Application.Current.Resources[\"NavigationButtonBackground\"] as SolidColorBrush;\n return defaultBrush?.Color ?? Colors.Transparent;\n }\n catch\n {\n var defaultBrush = Application.Current.Resources[\"NavigationButtonBackground\"] as SolidColorBrush;\n return defaultBrush?.Color ?? Colors.Transparent;\n }\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/ViewModels/CustomizeViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Optimize.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.Common.Messages;\n\nnamespace Winhance.WPF.Features.Customize.ViewModels\n{\n /// \n /// ViewModel for the Customize view.\n /// \n public partial class CustomizeViewModel : SearchableViewModel\n {\n // Store a backup of all items for state recovery\n private List _allItemsBackup = new List();\n private bool _isInitialSearchDone = false;\n\n // Tracks if search has any results\n [ObservableProperty]\n private bool _hasSearchResults = true;\n private readonly ISystemServices _windowsService;\n private readonly IDialogService _dialogService;\n private readonly IThemeManager _themeManager;\n private readonly IConfigurationService _configurationService;\n private readonly IMessengerService _messengerService;\n private readonly ILogService _logService;\n\n /// \n /// Gets the messenger service.\n /// \n public IMessengerService MessengerService => _messengerService;\n\n // Flag to prevent cascading checkbox updates\n private bool _updatingCheckboxes = false;\n /// \n /// Gets or sets a value indicating whether dark mode is enabled.\n /// \n [ObservableProperty]\n private bool _isDarkModeEnabled;\n\n /// \n /// Gets or sets a value indicating whether all settings are selected.\n /// \n [ObservableProperty]\n private bool _isSelectAllSelected;\n\n /// \n /// Gets or sets a value indicating whether settings are being loaded.\n /// \n [ObservableProperty]\n private bool _isLoading;\n\n /// \n /// Gets or sets the status text.\n /// \n [ObservableProperty]\n private string _statusText = \"Customize Your Windows Appearance and Behaviour\";\n \n // Override the SearchText property to add explicit notification and direct control over the search flow\n private string _searchTextOverride = string.Empty;\n public override string SearchText\n {\n get => _searchTextOverride;\n set\n {\n if (_searchTextOverride != value)\n {\n _searchTextOverride = value;\n OnPropertyChanged(nameof(SearchText));\n LogInfo($\"CustomizeViewModel: SearchText changed to: '{value}'\");\n \n // Explicitly update IsSearchActive and call ApplySearch\n IsSearchActive = !string.IsNullOrWhiteSpace(value);\n ApplySearch();\n \n // Update status text based on search results\n if (IsSearchActive)\n {\n StatusText = $\"Found {Items.Count} settings matching '{value}'\";\n }\n else\n {\n StatusText = \"Customize Your Windows Appearance and Behaviour\";\n }\n }\n }\n }\n \n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n\n /// \n /// Gets the collection of customization items.\n /// \n public ObservableCollection CustomizationItems { get; } = new();\n\n /// \n /// Gets or sets the taskbar settings view model.\n /// \n [ObservableProperty]\n private TaskbarCustomizationsViewModel _taskbarSettings;\n\n /// \n /// Gets or sets the start menu settings view model.\n /// \n [ObservableProperty]\n private StartMenuCustomizationsViewModel _startMenuSettings;\n\n /// \n /// Gets or sets the explorer customizations view model.\n /// \n [ObservableProperty]\n private ExplorerCustomizationsViewModel _explorerSettings;\n\n /// \n /// Gets or sets the Windows theme customizations view model.\n /// \n [ObservableProperty]\n private WindowsThemeCustomizationsViewModel _windowsThemeSettings;\n\n /// \n /// Gets a value indicating whether the view model is initialized.\n /// \n public bool IsInitialized { get; private set; }\n\n /// \n /// Gets the initialize command.\n /// \n public AsyncRelayCommand InitializeCommand { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The Windows service.\n /// The log service.\n /// The dialog service.\n /// The theme manager.\n /// The search service.\n /// The configuration service.\n /// The taskbar customizations view model.\n /// The start menu customizations view model.\n /// The explorer settings view model.\n /// The Windows theme customizations view model.\n /// The messenger service.\n public CustomizeViewModel(\n ITaskProgressService progressService,\n ISystemServices windowsService,\n ILogService logService,\n IDialogService dialogService,\n IThemeManager themeManager,\n ISearchService searchService,\n IConfigurationService configurationService,\n TaskbarCustomizationsViewModel taskbarSettings,\n StartMenuCustomizationsViewModel startMenuSettings,\n ExplorerCustomizationsViewModel explorerSettings,\n WindowsThemeCustomizationsViewModel windowsThemeSettings,\n IMessengerService messengerService)\n : base(progressService, searchService, null)\n {\n _windowsService = windowsService ?? throw new ArgumentNullException(nameof(windowsService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));\n _messengerService = messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n\n TaskbarSettings = taskbarSettings ?? throw new ArgumentNullException(nameof(taskbarSettings));\n StartMenuSettings = startMenuSettings ?? throw new ArgumentNullException(nameof(startMenuSettings));\n ExplorerSettings = explorerSettings ?? throw new ArgumentNullException(nameof(explorerSettings));\n WindowsThemeSettings = windowsThemeSettings ?? throw new ArgumentNullException(nameof(windowsThemeSettings));\n\n InitializeCustomizationItems();\n \n // Sync with WindowsThemeSettings\n IsDarkModeEnabled = WindowsThemeSettings.IsDarkModeEnabled;\n \n // Subscribe to WindowsThemeSettings property changes\n WindowsThemeSettings.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(WindowsThemeSettings.IsDarkModeEnabled))\n {\n // Sync dark mode state with WindowsThemeSettings\n IsDarkModeEnabled = WindowsThemeSettings.IsDarkModeEnabled;\n }\n };\n\n // Create initialize command\n InitializeCommand = new AsyncRelayCommand(InitializeAsync);\n \n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n }\n\n /// \n /// Initializes a new instance of the class for design-time use.\n /// \n public CustomizeViewModel()\n : base(\n new Winhance.Infrastructure.Features.Common.Services.TaskProgressService(new Core.Features.Common.Services.LogService()),\n new Winhance.Infrastructure.Features.Common.Services.SearchService())\n {\n // Default constructor for design-time use\n CustomizationItems = new ObservableCollection();\n InitializeCustomizationItems();\n IsDarkModeEnabled = true; // Default to dark mode for design-time\n }\n\n /// \n /// Called when the view model is navigated to.\n /// \n /// The navigation parameter.\n public override void OnNavigatedTo(object parameter)\n {\n LogInfo(\"CustomizeViewModel.OnNavigatedTo called\");\n \n // Ensure the status text is set to the default value\n StatusText = \"Customize Your Windows Appearance and Behaviour\";\n\n // If not already initialized, initialize now\n if (!IsInitialized)\n {\n InitializeCommand.Execute(null);\n }\n }\n\n /// \n /// Initializes the view model asynchronously.\n /// \n /// The cancellation token.\n /// A task representing the asynchronous operation.\n private async Task InitializeAsync(CancellationToken cancellationToken)\n {\n if (IsInitialized)\n return;\n\n try\n {\n IsLoading = true;\n LogInfo(\"Initializing CustomizeViewModel\");\n\n // Report progress\n ProgressService.UpdateProgress(0, \"Loading customization settings...\");\n\n // Load settings for each category\n LogInfo(\"CustomizeViewModel.InitializeAsync: Loading Taskbar settings\");\n ProgressService.UpdateProgress(10, \"Loading taskbar settings...\");\n await TaskbarSettings.LoadSettingsAsync();\n await TaskbarSettings.CheckSettingStatusesAsync();\n\n LogInfo(\"CustomizeViewModel.InitializeAsync: Loading Start Menu settings\");\n ProgressService.UpdateProgress(30, \"Loading Start Menu settings...\");\n await StartMenuSettings.LoadSettingsAsync();\n await StartMenuSettings.CheckSettingStatusesAsync();\n\n LogInfo(\"CustomizeViewModel.InitializeAsync: Loading Explorer settings\");\n ProgressService.UpdateProgress(50, \"Loading Explorer settings...\");\n await ExplorerSettings.LoadSettingsAsync();\n await ExplorerSettings.CheckSettingStatusesAsync();\n\n // Load Windows Theme settings if available\n if (WindowsThemeSettings != null)\n {\n LogInfo(\"CustomizeViewModel.InitializeAsync: Loading Windows Theme settings\");\n ProgressService.UpdateProgress(70, \"Loading Windows Theme settings...\");\n await WindowsThemeSettings.LoadSettingsAsync();\n await WindowsThemeSettings.CheckSettingStatusesAsync();\n }\n\n // Progress is now complete\n ProgressService.UpdateProgress(90, \"Finalizing...\");\n\n LogInfo(\"CustomizeViewModel.InitializeAsync: All settings loaded\");\n ProgressService.UpdateProgress(100, \"Initialization complete\");\n\n // Set up property change handlers\n SetupPropertyChangeHandlers();\n\n // Update selection states\n UpdateSelectAllState();\n\n // Load all settings for search functionality\n await LoadItemsAsync();\n \n // Ensure Windows Theme settings are properly loaded for search\n if (WindowsThemeSettings != null && WindowsThemeSettings.Settings.Count == 0)\n {\n LogInfo(\"CustomizeViewModel: Reloading Windows Theme settings for search\");\n await WindowsThemeSettings.LoadSettingsAsync();\n }\n \n // Mark as initialized\n IsInitialized = true;\n\n LogInfo(\"CustomizeViewModel initialized successfully\");\n }\n catch (Exception ex)\n {\n LogError($\"Error initializing customization settings: {ex.Message}\");\n throw; // Rethrow to ensure the caller knows initialization failed\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Initializes the customization items.\n /// \n private void InitializeCustomizationItems()\n {\n CustomizationItems.Clear();\n\n // Taskbar customization\n var taskbarItem = new ApplicationSettingGroup\n {\n Name = \"Taskbar\",\n Description = \"Customize taskbar appearance and behavior\",\n IsSelected = false\n };\n CustomizationItems.Add(taskbarItem);\n\n // Start Menu customization\n var startMenuItem = new ApplicationSettingGroup\n {\n Name = \"Start Menu\",\n Description = \"Modify Start Menu layout and settings\",\n IsSelected = false\n };\n CustomizationItems.Add(startMenuItem);\n\n // Explorer customization\n var explorerItem = new ApplicationSettingGroup\n {\n Name = \"Explorer\",\n Description = \"Adjust File Explorer settings and appearance\",\n IsSelected = false\n };\n CustomizationItems.Add(explorerItem);\n\n // Windows Theme customization\n var windowsThemeItem = new ApplicationSettingGroup\n {\n Name = \"Windows Theme\",\n Description = \"Customize Windows appearance themes\",\n IsSelected = false\n };\n CustomizationItems.Add(windowsThemeItem);\n }\n\n /// \n /// Sets up property change handlers.\n /// \n private void SetupPropertyChangeHandlers()\n {\n // Set up property change handlers for all settings\n foreach (var item in CustomizationItems)\n {\n // Add property changed handler for the category itself\n item.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingGroup.IsSelected) && !_updatingCheckboxes)\n {\n _updatingCheckboxes = true;\n try\n {\n // Update all settings in this category\n UpdateCategorySettings(item);\n\n // Update the global state\n UpdateSelectAllState();\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n };\n }\n }\n\n /// \n /// Updates the settings for a category.\n /// \n /// The category.\n private void UpdateCategorySettings(ApplicationSettingGroup category)\n {\n if (category == null) return;\n\n // Get the IsSelected property from ISettingItem interface\n PropertyInfo isSelectedProp = typeof(ISettingItem).GetProperty(\"IsSelected\");\n if (isSelectedProp == null) return;\n\n switch (category.Name)\n {\n case \"Taskbar\":\n foreach (var setting in TaskbarSettings.Settings)\n {\n isSelectedProp.SetValue(setting, category.IsSelected);\n }\n break;\n case \"Start Menu\":\n foreach (var setting in StartMenuSettings.Settings)\n {\n isSelectedProp.SetValue(setting, category.IsSelected);\n }\n break;\n case \"Explorer\":\n foreach (var setting in ExplorerSettings.Settings)\n {\n isSelectedProp.SetValue(setting, category.IsSelected);\n }\n break;\n case \"Windows Theme\":\n if (WindowsThemeSettings != null && WindowsThemeSettings.Settings.Count > 0)\n {\n foreach (var setting in WindowsThemeSettings.Settings)\n {\n isSelectedProp.SetValue(setting, category.IsSelected);\n }\n }\n break;\n }\n }\n\n /// \n /// Updates the category selection state.\n /// \n /// The category name.\n private void UpdateCategorySelectionState(string categoryName)\n {\n // Skip if we're already in an update operation\n if (_updatingCheckboxes)\n return;\n\n _updatingCheckboxes = true;\n\n try\n {\n var category = CustomizationItems.FirstOrDefault(c => c.Name == categoryName);\n if (category == null) return;\n\n bool allSelected = false;\n\n // Get the IsSelected property from ISettingItem interface\n PropertyInfo isSelectedProp = typeof(ISettingItem).GetProperty(\"IsSelected\");\n if (isSelectedProp == null) return;\n\n switch (categoryName)\n {\n case \"Taskbar\":\n allSelected = TaskbarSettings.Settings.Count > 0 &&\n TaskbarSettings.Settings.All(s => (bool)isSelectedProp.GetValue(s));\n break;\n case \"Start Menu\":\n allSelected = StartMenuSettings.Settings.Count > 0 &&\n StartMenuSettings.Settings.All(s => (bool)isSelectedProp.GetValue(s));\n break;\n case \"Explorer\":\n allSelected = ExplorerSettings.Settings.Count > 0 &&\n ExplorerSettings.Settings.All(s => (bool)isSelectedProp.GetValue(s));\n break;\n case \"Windows Theme\":\n allSelected = WindowsThemeSettings != null && \n WindowsThemeSettings.Settings.Count > 0 &&\n WindowsThemeSettings.Settings.All(s => (bool)isSelectedProp.GetValue(s));\n break;\n // Removed Notifications and Sound cases\n }\n\n category.IsSelected = allSelected;\n\n // Update global state\n UpdateSelectAllState();\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Updates the select all state.\n /// \n private void UpdateSelectAllState()\n {\n // Skip if we're already in an update operation\n if (_updatingCheckboxes)\n return;\n\n _updatingCheckboxes = true;\n\n try\n {\n // Skip if no customization items\n if (CustomizationItems.Count == 0)\n return;\n\n // Update global \"Select All\" checkbox based on all categories\n IsSelectAllSelected = CustomizationItems.All(c => c.IsSelected);\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n\n /// \n /// Refreshes the Windows GUI.\n /// \n /// A task representing the asynchronous operation.\n private async Task RefreshWindowsGUI()\n {\n try\n {\n // Use the Windows service to refresh the GUI without restarting explorer\n await _windowsService.RefreshWindowsGUI(false);\n\n LogInfo(\"Windows GUI refresh completed\");\n }\n catch (Exception ex)\n {\n LogError($\"Error refreshing Windows GUI: {ex.Message}\");\n }\n }\n\n /// \n /// Toggles the select all state.\n /// \n [RelayCommand]\n private void ToggleSelectAll()\n {\n bool newState = !IsSelectAllSelected;\n IsSelectAllSelected = newState;\n\n _updatingCheckboxes = true;\n\n try\n {\n foreach (var item in CustomizationItems)\n {\n item.IsSelected = newState;\n UpdateCategorySettings(item);\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n // Note: ApplyCustomizationsCommand has been removed as settings are now applied immediately when toggled\n // Note: RestoreDefaultsCommand has been removed as settings are now applied immediately when toggled\n\n /// \n /// Executes a customization action.\n /// \n /// The action to execute.\n [RelayCommand]\n private async Task ExecuteAction(ApplicationAction? action)\n {\n if (action == null) return;\n\n try\n {\n IsLoading = true;\n StatusText = $\"Executing action: {action.Name}...\";\n\n // Execute the action through the appropriate view model\n if (action.GroupName == \"Taskbar\" && TaskbarSettings != null)\n {\n await TaskbarSettings.ExecuteActionAsync(action);\n }\n else if (action.GroupName == \"Start Menu\" && StartMenuSettings != null)\n {\n await StartMenuSettings.ExecuteActionAsync(action);\n }\n else if (action.GroupName == \"Explorer\" && ExplorerSettings != null)\n {\n await ExplorerSettings.ExecuteActionAsync(action);\n }\n else if (action.GroupName == \"Windows Theme\" && WindowsThemeSettings != null)\n {\n await WindowsThemeSettings.ExecuteActionAsync(action);\n }\n\n StatusText = $\"Action '{action.Name}' executed successfully\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Error executing action: {ex.Message}\";\n LogError($\"Error executing action '{action?.Name}': {ex.Message}\");\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Toggles a category.\n /// \n /// The category to toggle.\n [RelayCommand]\n private void ToggleCategory(ApplicationSettingGroup? category)\n {\n if (category == null) return;\n\n // Skip if we're already in an update operation\n if (_updatingCheckboxes)\n return;\n\n _updatingCheckboxes = true;\n\n try\n {\n switch (category.Name)\n {\n case \"Taskbar\":\n foreach (var setting in TaskbarSettings.Settings)\n {\n setting.IsSelected = category.IsSelected;\n }\n break;\n case \"Start Menu\":\n foreach (var setting in StartMenuSettings.Settings)\n {\n setting.IsSelected = category.IsSelected;\n }\n break;\n case \"Explorer\":\n foreach (var setting in ExplorerSettings.Settings)\n {\n setting.IsSelected = category.IsSelected;\n }\n break;\n case \"Windows Theme\":\n if (WindowsThemeSettings != null && WindowsThemeSettings.Settings.Count > 0)\n {\n foreach (var setting in WindowsThemeSettings.Settings)\n {\n setting.IsSelected = category.IsSelected;\n }\n }\n break;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n \n /// \n /// Loads items asynchronously.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadItemsAsync()\n {\n try\n {\n IsLoading = true;\n StatusText = \"Loading customization settings...\";\n\n // Clear the items collection\n Items.Clear();\n\n // Collect all settings from the various view models\n var allSettings = new List();\n\n // Add settings from each category\n if (TaskbarSettings != null && TaskbarSettings.Settings != null)\n {\n foreach (var setting in TaskbarSettings.Settings)\n {\n if (setting is ApplicationSettingItem applicationSetting)\n {\n allSettings.Add(applicationSetting);\n }\n }\n }\n\n if (StartMenuSettings != null && StartMenuSettings.Settings != null)\n {\n foreach (var setting in StartMenuSettings.Settings)\n {\n if (setting is ApplicationSettingItem applicationSetting)\n {\n allSettings.Add(applicationSetting);\n }\n }\n }\n\n if (ExplorerSettings != null && ExplorerSettings.Settings != null)\n {\n foreach (var setting in ExplorerSettings.Settings)\n {\n if (setting is ApplicationSettingItem applicationSetting)\n {\n allSettings.Add(applicationSetting);\n }\n }\n }\n\n if (WindowsThemeSettings != null && WindowsThemeSettings.Settings != null)\n {\n foreach (var setting in WindowsThemeSettings.Settings)\n {\n if (setting is ApplicationSettingItem applicationSetting)\n {\n allSettings.Add(applicationSetting);\n }\n }\n }\n\n // Add all settings to the Items collection\n foreach (var setting in allSettings)\n {\n Items.Add(setting);\n }\n\n // Create a backup of all items for state recovery\n _allItemsBackup = new List(Items);\n\n // Only update StatusText if it's currently showing a loading message\n if (StatusText.Contains(\"Loading\"))\n {\n StatusText = \"Customize Your Windows Appearance and Behaviour\";\n }\n }\n catch (Exception ex)\n {\n StatusText = $\"Error loading customization settings: {ex.Message}\";\n LogError($\"Error loading customization settings: {ex.Message}\", ex);\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the installation status of items asynchronously.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckInstallationStatusAsync()\n {\n // This method is not applicable for customization settings\n // but we need to implement it to satisfy the interface\n await Task.CompletedTask;\n }\n\n /// \n /// Restores all items visibility to their original state.\n /// \n private void RestoreAllItemsVisibility()\n {\n // Make all settings visible in each category\n if (TaskbarSettings?.Settings != null)\n {\n foreach (var setting in TaskbarSettings.Settings)\n {\n setting.IsVisible = true;\n }\n TaskbarSettings.HasVisibleSettings = TaskbarSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Restored visibility for {TaskbarSettings.Settings.Count} Taskbar settings\");\n }\n \n if (StartMenuSettings?.Settings != null)\n {\n foreach (var setting in StartMenuSettings.Settings)\n {\n setting.IsVisible = true;\n }\n StartMenuSettings.HasVisibleSettings = StartMenuSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Restored visibility for {StartMenuSettings.Settings.Count} Start Menu settings\");\n }\n \n if (ExplorerSettings?.Settings != null)\n {\n foreach (var setting in ExplorerSettings.Settings)\n {\n setting.IsVisible = true;\n }\n ExplorerSettings.HasVisibleSettings = ExplorerSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Restored visibility for {ExplorerSettings.Settings.Count} Explorer settings\");\n }\n \n if (WindowsThemeSettings?.Settings != null)\n {\n foreach (var setting in WindowsThemeSettings.Settings)\n {\n setting.IsVisible = true;\n }\n WindowsThemeSettings.HasVisibleSettings = WindowsThemeSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Restored visibility for {WindowsThemeSettings.Settings.Count} Windows Theme settings, HasVisibleSettings={WindowsThemeSettings.HasVisibleSettings}\");\n }\n \n // Make all customization items visible\n foreach (var item in CustomizationItems)\n {\n item.IsVisible = true;\n LogInfo($\"CustomizeViewModel: Restored visibility for CustomizationItem '{item.Name}'\");\n }\n \n // Always ensure HasSearchResults is true when restoring visibility\n HasSearchResults = true;\n \n // Send a message to notify the view to reset section expansion states\n _messengerService.Send(new ResetExpansionStateMessage());\n \n LogInfo(\"CustomizeViewModel: RestoreAllItemsVisibility has reset all UI elements to visible state\");\n }\n \n /// \n /// Applies the current search text to filter items.\n /// \n protected override void ApplySearch()\n {\n LogInfo($\"CustomizeViewModel: ApplySearch called with SearchText: '{SearchText}'\");\n \n // If we have no items yet, there's nothing to filter\n if (Items == null)\n return;\n \n // If this is our first time running a search and the backup isn't created yet, create it\n if (!_isInitialSearchDone && Items.Count > 0)\n {\n _allItemsBackup = new List(Items);\n _isInitialSearchDone = true;\n LogInfo($\"CustomizeViewModel: Created backup of all items ({_allItemsBackup.Count} items)\");\n }\n\n // If search is empty, restore all items visibility and the original items collection\n if (string.IsNullOrWhiteSpace(SearchText))\n {\n LogInfo(\"CustomizeViewModel: Empty search, restoring all items visibility\");\n \n // Restore visibility of UI elements first\n RestoreAllItemsVisibility();\n \n // Use the backup to restore all items\n if (_allItemsBackup.Count > 0)\n {\n LogInfo($\"CustomizeViewModel: Restoring {_allItemsBackup.Count} items from backup\");\n Items.Clear();\n foreach (var item in _allItemsBackup)\n {\n Items.Add(item);\n }\n }\n else if (Items.Count == 0)\n {\n // If we don't have a backup and Items is empty (which could happen after a no-results search),\n // try to reload items\n LogInfo(\"CustomizeViewModel: No backup available and Items is empty, attempting to reload\");\n _ = LoadItemsAsync();\n }\n \n // Always set HasSearchResults to true when search is cleared - critical to fix the bug\n HasSearchResults = true;\n \n // Make sure all CustomizationItems are visible\n foreach (var item in CustomizationItems)\n {\n item.IsVisible = true;\n LogInfo($\"CustomizeViewModel: Setting CustomizationItem '{item.Name}' visibility to true\");\n }\n \n // Ensure all sub-view models have HasVisibleSettings set to true\n if (TaskbarSettings != null)\n {\n TaskbarSettings.HasVisibleSettings = TaskbarSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Setting TaskbarSettings.HasVisibleSettings to {TaskbarSettings.HasVisibleSettings}\");\n }\n \n if (StartMenuSettings != null)\n {\n StartMenuSettings.HasVisibleSettings = StartMenuSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Setting StartMenuSettings.HasVisibleSettings to {StartMenuSettings.HasVisibleSettings}\");\n }\n \n if (ExplorerSettings != null)\n {\n ExplorerSettings.HasVisibleSettings = ExplorerSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Setting ExplorerSettings.HasVisibleSettings to {ExplorerSettings.HasVisibleSettings}\");\n }\n \n if (WindowsThemeSettings != null)\n {\n WindowsThemeSettings.HasVisibleSettings = WindowsThemeSettings.Settings.Count > 0;\n LogInfo($\"CustomizeViewModel: Setting WindowsThemeSettings.HasVisibleSettings to {WindowsThemeSettings.HasVisibleSettings}\");\n }\n \n // Update status text\n StatusText = \"Customize Your Windows Appearance and Behaviour\";\n LogInfo($\"CustomizeViewModel: Restored items, count={Items.Count}\");\n return;\n }\n\n // We're doing an active search, use the backup for filtering if available\n var itemsToFilter = _allItemsBackup.Count > 0 \n ? new ObservableCollection(_allItemsBackup) \n : Items;\n \n // Normalize and clean the search text\n string normalizedSearchText = SearchText.Trim().ToLowerInvariant();\n LogInfo($\"CustomizeViewModel: Normalized search text: '{normalizedSearchText}'\");\n \n // Handle edge case: if search is all whitespace after trimming, treat it as empty\n if (string.IsNullOrEmpty(normalizedSearchText))\n {\n // Same handling as empty search\n RestoreAllItemsVisibility();\n if (_allItemsBackup.Count > 0)\n {\n Items.Clear();\n foreach (var item in _allItemsBackup)\n {\n Items.Add(item);\n }\n }\n HasSearchResults = true;\n StatusText = \"Customize Your Windows Appearance and Behaviour\";\n return;\n }\n \n // Filter items based on search text - ensure we pass normalized text\n var filteredItems = FilterItems(itemsToFilter)\n .Where(item => \n item.Name?.IndexOf(normalizedSearchText, StringComparison.OrdinalIgnoreCase) >= 0 || \n item.Description?.IndexOf(normalizedSearchText, StringComparison.OrdinalIgnoreCase) >= 0)\n .ToList();\n \n // Log the number of filtered items\n int filteredCount = filteredItems.Count;\n LogInfo($\"CustomizeViewModel: Found {filteredCount} matching items\");\n \n // Update HasSearchResults based on filtered count\n HasSearchResults = filteredCount > 0;\n LogInfo($\"CustomizeViewModel: Setting HasSearchResults to {HasSearchResults} based on filtered count {filteredCount}\");\n \n // Create a HashSet of filtered item IDs for efficient lookup\n var filteredItemIds = new HashSet(filteredItems.Select(item => item.Id));\n\n // Update each sub-view model's Settings collection\n UpdateSubViewSettings(TaskbarSettings, filteredItemIds);\n UpdateSubViewSettings(StartMenuSettings, filteredItemIds);\n UpdateSubViewSettings(ExplorerSettings, filteredItemIds);\n UpdateSubViewSettings(WindowsThemeSettings, filteredItemIds);\n\n // Count the actual visible items after filtering\n int visibleItemsCount = 0;\n \n // Count visible items in each category\n if (TaskbarSettings?.Settings != null)\n visibleItemsCount += TaskbarSettings.Settings.Count(s => s is ApplicationSettingItem csItem && csItem.IsVisible);\n \n if (StartMenuSettings?.Settings != null)\n visibleItemsCount += StartMenuSettings.Settings.Count(s => s is ApplicationSettingItem csItem && csItem.IsVisible);\n \n if (ExplorerSettings?.Settings != null)\n visibleItemsCount += ExplorerSettings.Settings.Count(s => s is ApplicationSettingItem csItem && csItem.IsVisible);\n \n if (WindowsThemeSettings?.Settings != null)\n visibleItemsCount += WindowsThemeSettings.Settings.Count(s => s is ApplicationSettingItem csItem && csItem.IsVisible);\n\n // Update the Items collection to match visible items\n Items.Clear();\n foreach (var setting in filteredItems)\n {\n if (setting.IsVisible)\n {\n Items.Add(setting);\n }\n }\n\n // Update status text with correct count\n if (IsSearchActive)\n {\n StatusText = $\"Found {visibleItemsCount} settings matching '{SearchText}'\";\n LogInfo($\"CustomizeViewModel: StatusText updated to: '{StatusText}' with {visibleItemsCount} visible items\");\n }\n else\n {\n StatusText = $\"Showing all {Items.Count} customization settings\";\n LogInfo($\"CustomizeViewModel: StatusText updated to: '{StatusText}'\");\n }\n }\n\n /// \n /// Updates a sub-view model's Settings collection based on filtered items.\n /// \n /// The sub-view model to update.\n /// HashSet of IDs of items that match the search criteria.\n private void UpdateSubViewSettings(BaseSettingsViewModel viewModel, HashSet filteredItemIds)\n {\n if (viewModel == null || viewModel.Settings == null)\n return;\n\n // If not searching, show all settings\n if (!IsSearchActive)\n {\n foreach (var setting in viewModel.Settings)\n {\n setting.IsVisible = true;\n }\n \n // Update the view model's visibility\n viewModel.HasVisibleSettings = viewModel.Settings.Count > 0;\n \n // Update the corresponding CustomizationItem\n var item = CustomizationItems.FirstOrDefault(i => i.Name == viewModel.CategoryName);\n if (item != null)\n {\n item.IsVisible = true;\n }\n \n LogInfo($\"CustomizeViewModel: Set all settings visible in {viewModel.CategoryName}\");\n return;\n }\n\n // When searching, only show settings that match the search criteria\n bool hasVisibleSettings = false;\n int visibleCount = 0;\n \n foreach (var setting in viewModel.Settings)\n {\n // Check if this setting is in the filtered items\n setting.IsVisible = filteredItemIds.Contains(setting.Id);\n \n if (setting.IsVisible)\n {\n hasVisibleSettings = true;\n visibleCount++;\n }\n }\n \n // Update the view model's visibility\n viewModel.HasVisibleSettings = hasVisibleSettings;\n \n // Update the corresponding CustomizationItem - this is critical for proper UI behavior\n var categoryItem = CustomizationItems.FirstOrDefault(i => i.Name == viewModel.CategoryName);\n if (categoryItem != null)\n {\n categoryItem.IsVisible = hasVisibleSettings;\n LogInfo($\"CustomizeViewModel: Setting CustomizationItem '{categoryItem.Name}' visibility to {hasVisibleSettings}\");\n }\n \n LogInfo($\"CustomizeViewModel: {viewModel.CategoryName} has {visibleCount} visible settings, HasVisibleSettings={hasVisibleSettings}\");\n }\n\n // SaveConfig and ImportConfig methods removed as part of unified configuration cleanup\n\n /// \n /// Logs an informational message.\n /// \n /// The message to log.\n private void LogInfo(string message)\n {\n StatusText = message;\n _logService?.Log(LogLevel.Info, message);\n }\n\n /// \n /// Logs an error message.\n /// \n /// The message to log.\n private void LogError(string message)\n {\n StatusText = message;\n _logService?.Log(LogLevel.Error, message);\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/ConfigurationCoordinatorService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows.Input;\nusing Microsoft.Extensions.DependencyInjection;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Customize.ViewModels;\nusing Winhance.WPF.Features.Optimize.ViewModels;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\nusing Winhance.WPF.Features.SoftwareApps.Models;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for coordinating configuration operations across multiple view models.\n /// \n public class ConfigurationCoordinatorService : IConfigurationCoordinatorService\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly IConfigurationService _configurationService;\n private readonly ILogService _logService;\n private readonly IDialogService _dialogService;\n private readonly IRegistryService _registryService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The configuration service.\n /// The log service.\n /// The dialog service.\n public ConfigurationCoordinatorService(\n IServiceProvider serviceProvider,\n IConfigurationService configurationService,\n ILogService logService,\n IDialogService dialogService,\n IRegistryService registryService)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n }\n\n /// \n /// Creates a unified configuration file containing settings from all view models.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file.\n public async Task CreateUnifiedConfigurationAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Creating unified configuration from all view models\");\n \n // Create a dictionary to hold settings from all sections\n var sectionSettings = new Dictionary>();\n\n // Get all view models from the service provider\n var windowsAppsViewModel = _serviceProvider.GetService();\n var externalAppsViewModel = _serviceProvider.GetService();\n var customizeViewModel = _serviceProvider.GetService();\n var optimizeViewModel = _serviceProvider.GetService();\n\n // Add settings from each view model to the dictionary\n if (windowsAppsViewModel != null)\n {\n _logService.Log(LogLevel.Debug, \"Processing WindowsAppsViewModel\");\n \n // Ensure the view model is initialized\n if (!windowsAppsViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"WindowsAppsViewModel not initialized, loading items\");\n await windowsAppsViewModel.LoadItemsAsync();\n }\n \n // Log the number of items in the view model\n var itemsProperty = windowsAppsViewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(windowsAppsViewModel) as System.Collections.ICollection;\n if (items != null)\n {\n _logService.Log(LogLevel.Debug, $\"WindowsAppsViewModel has {items.Count} items\");\n \n // Log the type of the first item\n if (items.Count > 0)\n {\n var enumerator = items.GetEnumerator();\n enumerator.MoveNext();\n var firstItem = enumerator.Current;\n if (firstItem != null)\n {\n _logService.Log(LogLevel.Debug, $\"First item type: {firstItem.GetType().FullName}\");\n }\n }\n }\n }\n \n // For WindowsAppsViewModel, we need to use SaveConfig to get the settings\n // This is because the Items property is not of type ISettingItem\n // We'll use reflection to call the SaveConfig method\n var saveConfigMethod = windowsAppsViewModel.GetType().GetMethod(\"SaveConfig\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);\n \n // Instead of trying to call SaveConfig, directly access the Items collection\n // and convert them to WindowsAppSettingItems\n var windowsAppsItemsProperty = windowsAppsViewModel.GetType().GetProperty(\"Items\");\n if (windowsAppsItemsProperty != null)\n {\n var items = windowsAppsItemsProperty.GetValue(windowsAppsViewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n _logService.Log(LogLevel.Info, \"Directly accessing Items collection from WindowsAppsViewModel\");\n \n // Convert each WindowsApp to WindowsAppSettingItem\n var windowsAppSettingItems = new List();\n \n foreach (var item in items)\n {\n if (item is Winhance.WPF.Features.SoftwareApps.Models.WindowsApp windowsApp)\n {\n windowsAppSettingItems.Add(new WindowsAppSettingItem(windowsApp));\n _logService.Log(LogLevel.Debug, $\"Added WindowsAppSettingItem for {windowsApp.Name}\");\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Created {windowsAppSettingItems.Count} WindowsAppSettingItems\");\n \n // Always add WindowsApps to sectionSettings, even if empty\n sectionSettings[\"WindowsApps\"] = windowsAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added WindowsApps section with {windowsAppSettingItems.Count} items\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Items collection is null\");\n \n // Create some default WindowsApps\n var defaultApps = new[]\n {\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Microsoft Edge\",\n PackageName = \"Microsoft.MicrosoftEdge\",\n IsSelected = true,\n Description = \"Microsoft Edge browser\"\n },\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Calculator\",\n PackageName = \"Microsoft.WindowsCalculator\",\n IsSelected = true,\n Description = \"Windows Calculator app\"\n },\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Photos\",\n PackageName = \"Microsoft.Windows.Photos\",\n IsSelected = true,\n Description = \"Windows Photos app\"\n }\n };\n \n var defaultWindowsAppSettingItems = new List();\n foreach (var app in defaultApps)\n {\n defaultWindowsAppSettingItems.Add(new WindowsAppSettingItem(app));\n }\n \n // Always add WindowsApps to sectionSettings, even if using defaults\n sectionSettings[\"WindowsApps\"] = defaultWindowsAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added WindowsApps section with {defaultWindowsAppSettingItems.Count} default items\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Error, \"Could not find Items property in WindowsAppsViewModel\");\n \n // Create some default WindowsApps\n var defaultApps = new[]\n {\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Microsoft Edge\",\n PackageName = \"Microsoft.MicrosoftEdge\",\n IsSelected = true,\n Description = \"Microsoft Edge browser\"\n },\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Calculator\",\n PackageName = \"Microsoft.WindowsCalculator\",\n IsSelected = true,\n Description = \"Windows Calculator app\"\n },\n new Winhance.WPF.Features.SoftwareApps.Models.WindowsApp\n {\n Name = \"Photos\",\n PackageName = \"Microsoft.Windows.Photos\",\n IsSelected = true,\n Description = \"Windows Photos app\"\n }\n };\n \n var defaultWindowsAppSettingItems = new List();\n foreach (var app in defaultApps)\n {\n defaultWindowsAppSettingItems.Add(new WindowsAppSettingItem(app));\n }\n \n // Always add WindowsApps to sectionSettings, even if using defaults\n sectionSettings[\"WindowsApps\"] = defaultWindowsAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added WindowsApps section with {defaultWindowsAppSettingItems.Count} default items\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"WindowsAppsViewModel is null\");\n }\n\n if (externalAppsViewModel != null)\n {\n // Ensure the view model is initialized\n if (!externalAppsViewModel.IsInitialized)\n {\n await externalAppsViewModel.LoadItemsAsync();\n }\n \n // For ExternalAppsViewModel, we need to get the settings directly\n // This is because the Items property is not of type ISettingItem\n var externalAppsItems = new List();\n \n // Get the Items property\n var itemsProperty = externalAppsViewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(externalAppsViewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n foreach (var item in items)\n {\n if (item is Winhance.WPF.Features.SoftwareApps.Models.ExternalApp externalApp)\n {\n externalAppsItems.Add(new ExternalAppSettingItem(externalApp));\n }\n }\n }\n }\n \n // Add the settings to the dictionary\n sectionSettings[\"ExternalApps\"] = externalAppsItems;\n _logService.Log(LogLevel.Info, $\"Added ExternalApps section with {externalAppsItems.Count} items\");\n }\n\n if (customizeViewModel != null)\n {\n // Ensure the view model is initialized\n if (!customizeViewModel.IsInitialized)\n {\n await customizeViewModel.LoadItemsAsync();\n }\n \n // For CustomizeViewModel, we need to get the settings directly\n var customizeItems = new List();\n \n // Get the Items property\n var itemsProperty = customizeViewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(customizeViewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n foreach (var item in items)\n {\n if (item is ISettingItem settingItem)\n {\n customizeItems.Add(settingItem);\n }\n }\n }\n }\n \n // Add the settings to the dictionary\n sectionSettings[\"Customize\"] = customizeItems;\n _logService.Log(LogLevel.Info, $\"Added Customize section with {customizeItems.Count} items\");\n }\n\n if (optimizeViewModel != null)\n {\n _logService.Log(LogLevel.Debug, \"Processing OptimizeViewModel\");\n \n // Ensure the view model is initialized\n if (!optimizeViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"OptimizeViewModel not initialized, initializing now\");\n await optimizeViewModel.InitializeCommand.ExecuteAsync(null);\n \n // After initialization, ensure items are loaded\n await optimizeViewModel.LoadItemsAsync();\n _logService.Log(LogLevel.Debug, $\"OptimizeViewModel initialized and loaded with {optimizeViewModel.Items?.Count ?? 0} items\");\n }\n else\n {\n _logService.Log(LogLevel.Debug, \"OptimizeViewModel already initialized\");\n \n // Even if initialized, make sure items are loaded\n if (optimizeViewModel.Items == null || optimizeViewModel.Items.Count == 0)\n {\n _logService.Log(LogLevel.Debug, \"OptimizeViewModel items not loaded, loading now\");\n await optimizeViewModel.LoadItemsAsync();\n _logService.Log(LogLevel.Debug, $\"OptimizeViewModel items loaded, count: {optimizeViewModel.Items?.Count ?? 0}\");\n }\n }\n \n // For OptimizeViewModel, we need to get the settings directly\n var optimizeItems = new List();\n \n // Get the Items property\n var itemsProperty = optimizeViewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(optimizeViewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n _logService.Log(LogLevel.Debug, $\"OptimizeViewModel has items collection, enumerating\");\n \n // Log the type of the first item\n var enumerator = items.GetEnumerator();\n if (enumerator.MoveNext() && enumerator.Current != null)\n {\n _logService.Log(LogLevel.Debug, $\"First item type: {enumerator.Current.GetType().FullName}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"OptimizeViewModel items collection is empty or first item is null\");\n }\n \n // Reset the enumerator\n items = itemsProperty.GetValue(optimizeViewModel) as System.Collections.IEnumerable;\n \n foreach (var item in items)\n {\n if (item is Winhance.WPF.Features.Common.Models.ApplicationSettingItem applicationItem)\n {\n optimizeItems.Add(applicationItem);\n _logService.Log(LogLevel.Debug, $\"Added ApplicationSettingItem for {applicationItem.Name}\");\n }\n else if (item is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added generic ISettingItem for {settingItem.Name}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Item of type {item?.GetType().FullName ?? \"null\"} is not an ISettingItem\");\n }\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"OptimizeViewModel items collection is null\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Error, \"Could not find Items property in OptimizeViewModel\");\n }\n \n // If we still don't have any items, collect them directly from the child view models\n // This avoids showing the Optimizations Custom Dialog before the Save Dialog\n if (optimizeItems.Count == 0)\n {\n _logService.Log(LogLevel.Warning, \"No items found in OptimizeViewModel, collecting from child view models\");\n \n // Get all the child view models using reflection\n var childViewModels = new List();\n var properties = optimizeViewModel.GetType().GetProperties();\n \n foreach (var property in properties)\n {\n if (property.Name.EndsWith(\"ViewModel\") &&\n property.Name != \"OptimizeViewModel\" &&\n property.PropertyType.Name.Contains(\"Optimizations\"))\n {\n var childViewModel = property.GetValue(optimizeViewModel);\n if (childViewModel != null)\n {\n childViewModels.Add(childViewModel);\n _logService.Log(LogLevel.Debug, $\"Found child view model: {property.Name}\");\n }\n }\n }\n \n // Collect settings from each child view model\n foreach (var childViewModel in childViewModels)\n {\n var settingsProperty = childViewModel.GetType().GetProperty(\"Settings\");\n if (settingsProperty != null)\n {\n var settings = settingsProperty.GetValue(childViewModel) as System.Collections.IEnumerable;\n if (settings != null)\n {\n foreach (var setting in settings)\n {\n // Use dynamic to avoid type issues\n dynamic settingViewModel = setting;\n try\n {\n // Convert setting to ApplicationSettingItem using dynamic\n var item = new Winhance.WPF.Features.Common.Models.ApplicationSettingItem(_registryService, _dialogService, _logService);\n \n // Copy properties using reflection to avoid type issues\n try { item.Id = settingViewModel.Id; } catch { }\n try { item.Name = settingViewModel.Name; } catch { }\n try { item.Description = settingViewModel.Description; } catch { }\n try { item.IsSelected = settingViewModel.IsSelected; } catch { }\n try { item.GroupName = settingViewModel.GroupName; } catch { }\n try { item.IsVisible = settingViewModel.IsVisible; } catch { }\n try { item.ControlType = settingViewModel.ControlType; } catch { }\n try { item.SliderValue = settingViewModel.SliderValue; } catch { }\n try { item.SliderSteps = settingViewModel.SliderSteps; } catch { }\n try { item.Status = settingViewModel.Status; } catch { }\n try { item.StatusMessage = settingViewModel.StatusMessage; } catch { }\n try { item.RegistrySetting = settingViewModel.RegistrySetting; } catch { }\n \n // Skip LinkedRegistrySettings for now as it's causing issues\n \n optimizeItems.Add(item);\n _logService.Log(LogLevel.Debug, $\"Added setting from {childViewModel.GetType().Name}: {item.Name}\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error converting setting: {ex.Message}\");\n \n // Try to add as generic ISettingItem if possible\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added generic setting from {childViewModel.GetType().Name}: {settingItem.Name}\");\n }\n }\n }\n }\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Collected {optimizeItems.Count} items from child view models\");\n \n // If we still don't have any items, add a placeholder as a last resort\n if (optimizeItems.Count == 0)\n {\n _logService.Log(LogLevel.Warning, \"No items found in child view models, adding placeholder\");\n \n var placeholderItem = new Winhance.WPF.Features.Common.Models.ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = \"OptimizePlaceholder\",\n Name = \"Optimization Settings\",\n Description = \"Default optimization settings\",\n IsSelected = true,\n GroupName = \"Optimizations\"\n };\n \n optimizeItems.Add(placeholderItem);\n _logService.Log(LogLevel.Info, \"Added placeholder item to Optimize section\");\n }\n }\n \n // Add the settings to the dictionary\n sectionSettings[\"Optimize\"] = optimizeItems;\n _logService.Log(LogLevel.Info, $\"Added Optimize section with {optimizeItems.Count} items\");\n }\n\n // Create a list of all available sections - include all sections by default\n var availableSections = new List { \"WindowsApps\", \"ExternalApps\", \"Customize\", \"Optimize\" };\n\n // Create and return the unified configuration\n var unifiedConfig = _configurationService.CreateUnifiedConfiguration(sectionSettings, availableSections);\n \n _logService.Log(LogLevel.Info, \"Successfully created unified configuration from all view models\");\n \n return unifiedConfig;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating unified configuration: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Applies a unified configuration to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n public async Task ApplyUnifiedConfigurationAsync(UnifiedConfigurationFile config, IEnumerable selectedSections)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Applying unified configuration to selected sections: {string.Join(\", \", selectedSections)}\");\n \n // Log the contents of the unified configuration\n _logService.Log(LogLevel.Debug, $\"Unified configuration contains: \" +\n $\"WindowsApps: {config.WindowsApps?.Items?.Count ?? 0} items, \" +\n $\"ExternalApps: {config.ExternalApps?.Items?.Count ?? 0} items, \" +\n $\"Customize: {config.Customize?.Items?.Count ?? 0} items, \" +\n $\"Optimize: {config.Optimize?.Items?.Count ?? 0} items\");\n \n // Validate the configuration\n if (config == null)\n {\n _logService.Log(LogLevel.Error, \"Unified configuration is null\");\n return false;\n }\n \n // Validate the selected sections\n if (selectedSections == null || !selectedSections.Any())\n {\n _logService.Log(LogLevel.Error, \"No sections selected for import\");\n return false;\n }\n \n bool result = true;\n var sectionResults = new Dictionary();\n\n foreach (var section in selectedSections)\n {\n _logService.Log(LogLevel.Info, $\"Processing section: {section}\");\n \n // Extract the section from the unified configuration\n var configFile = _configurationService.ExtractSectionFromUnifiedConfiguration(config, section);\n \n if (configFile == null)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to extract section {section} from unified configuration\");\n sectionResults[section] = false;\n result = false;\n continue;\n }\n \n if (configFile.Items == null || !configFile.Items.Any())\n {\n _logService.Log(LogLevel.Warning, $\"Section {section} is empty or not included in the unified configuration\");\n sectionResults[section] = false;\n continue;\n }\n\n _logService.Log(LogLevel.Info, $\"Extracted section {section} with {configFile.Items.Count} items\");\n \n // Log all items for debugging\n foreach (var item in configFile.Items)\n {\n _logService.Log(LogLevel.Debug, $\"Item in {section}: {item.Name}, IsSelected: {item.IsSelected}, ControlType: {item.ControlType}\");\n }\n\n // Apply the configuration to the appropriate view model\n bool sectionResult = false;\n \n switch (section)\n {\n case \"WindowsApps\":\n _logService.Log(LogLevel.Info, $\"Getting WindowsAppsViewModel from service provider\");\n var windowsAppsViewModel = _serviceProvider.GetService();\n if (windowsAppsViewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"WindowsAppsViewModel found, importing configuration\");\n \n // Ensure the view model is initialized\n if (!windowsAppsViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, $\"WindowsAppsViewModel not initialized, initializing now\");\n await windowsAppsViewModel.LoadItemsAsync();\n }\n \n // Use the view model's own import method\n sectionResult = await ImportWindowsAppsConfig(windowsAppsViewModel, configFile);\n _logService.Log(LogLevel.Info, $\"WindowsApps import result: {sectionResult}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"WindowsAppsViewModel not available\");\n sectionResult = false;\n }\n break;\n\n case \"ExternalApps\":\n _logService.Log(LogLevel.Info, $\"Getting ExternalAppsViewModel from service provider\");\n var externalAppsViewModel = _serviceProvider.GetService();\n if (externalAppsViewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"ExternalAppsViewModel found, importing configuration\");\n \n // Ensure the view model is initialized\n if (!externalAppsViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, $\"ExternalAppsViewModel not initialized, initializing now\");\n await externalAppsViewModel.LoadItemsAsync();\n }\n \n // Use the view model's own import method\n sectionResult = await ImportExternalAppsConfig(externalAppsViewModel, configFile);\n _logService.Log(LogLevel.Info, $\"ExternalApps import result: {sectionResult}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"ExternalAppsViewModel not available\");\n sectionResult = false;\n }\n break;\n\n case \"Customize\":\n _logService.Log(LogLevel.Info, $\"Getting CustomizeViewModel from service provider\");\n var customizeViewModel = _serviceProvider.GetService();\n if (customizeViewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"CustomizeViewModel found, importing configuration\");\n \n // Ensure the view model is initialized\n if (!customizeViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, $\"CustomizeViewModel not initialized, initializing now\");\n await customizeViewModel.InitializeCommand.ExecuteAsync(null);\n }\n \n // Use the view model's own import method\n sectionResult = await ImportCustomizeConfig(customizeViewModel, configFile);\n _logService.Log(LogLevel.Info, $\"Customize import result: {sectionResult}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"CustomizeViewModel not available\");\n sectionResult = false;\n }\n break;\n\n case \"Optimize\":\n _logService.Log(LogLevel.Info, $\"Getting OptimizeViewModel from service provider\");\n var optimizeViewModel = _serviceProvider.GetService();\n if (optimizeViewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"OptimizeViewModel found, importing configuration\");\n \n // Ensure the view model is initialized\n if (!optimizeViewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, $\"OptimizeViewModel not initialized, initializing now\");\n await optimizeViewModel.InitializeCommand.ExecuteAsync(null);\n }\n \n // Use the view model's own import method\n sectionResult = await ImportOptimizeConfig(optimizeViewModel, configFile);\n _logService.Log(LogLevel.Info, $\"Optimize import result: {sectionResult}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"OptimizeViewModel not available\");\n sectionResult = false;\n }\n break;\n\n default:\n _logService.Log(LogLevel.Warning, $\"Unknown section: {section}\");\n sectionResult = false;\n break;\n }\n \n sectionResults[section] = sectionResult;\n if (!sectionResult)\n {\n result = false;\n }\n }\n\n // Log the results for each section\n _logService.Log(LogLevel.Info, \"Import results by section:\");\n foreach (var sectionResult in sectionResults)\n {\n _logService.Log(LogLevel.Info, $\" {sectionResult.Key}: {(sectionResult.Value ? \"Success\" : \"Failed\")}\");\n }\n\n _logService.Log(LogLevel.Info, $\"Finished applying unified configuration to selected sections. Overall result: {(result ? \"Success\" : \"Partial failure\")}\");\n return result;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying unified configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false; // Return false instead of throwing to prevent crashing the application\n }\n }\n\n /// \n /// Imports a configuration to a view model using reflection to call its ImportConfig method.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n private async Task ImportConfigToViewModel(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n string viewModelTypeName = viewModel.GetType().Name;\n _logService.Log(LogLevel.Info, $\"Starting to import configuration to {viewModelTypeName}\");\n _logService.Log(LogLevel.Debug, $\"Configuration file has {configFile.Items?.Count ?? 0} items\");\n \n // Log the first few items for debugging\n if (configFile.Items != null && configFile.Items.Any())\n {\n foreach (var item in configFile.Items.Take(5))\n {\n _logService.Log(LogLevel.Debug, $\"Item: {item.Name}, IsSelected: {item.IsSelected}, ControlType: {item.ControlType}\");\n }\n }\n\n // Store the original configuration file\n var originalConfigFile = configFile;\n\n // Create a wrapper for the configuration service\n var configServiceWrapper = new ConfigurationServiceWrapper(_configurationService, originalConfigFile);\n _logService.Log(LogLevel.Debug, \"Created configuration service wrapper\");\n\n // Replace the configuration service in the view model\n var configServiceField = viewModel.GetType().GetField(\"_configurationService\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n\n if (configServiceField != null)\n {\n _logService.Log(LogLevel.Debug, \"Found _configurationService field in view model\");\n \n // Store the original service\n var originalService = configServiceField.GetValue(viewModel);\n _logService.Log(LogLevel.Debug, $\"Original service type: {originalService?.GetType().Name ?? \"null\"}\");\n\n try\n {\n // Replace with our wrapper\n configServiceField.SetValue(viewModel, configServiceWrapper);\n _logService.Log(LogLevel.Debug, \"Replaced configuration service with wrapper\");\n\n // Special handling for different view model types\n bool importResult = false;\n \n if (viewModelTypeName.Contains(\"WindowsApps\"))\n {\n importResult = await ImportWindowsAppsConfig(viewModel, configFile);\n }\n else if (viewModelTypeName.Contains(\"ExternalApps\"))\n {\n importResult = await ImportExternalAppsConfig(viewModel, configFile);\n }\n else if (viewModelTypeName.Contains(\"Customize\"))\n {\n importResult = await ImportCustomizeConfig(viewModel, configFile);\n }\n else if (viewModelTypeName.Contains(\"Optimize\"))\n {\n importResult = await ImportOptimizeConfig(viewModel, configFile);\n }\n else\n {\n // Generic import for other view model types\n importResult = await ImportGenericConfig(viewModel, configFile);\n }\n \n if (importResult)\n {\n _logService.Log(LogLevel.Info, $\"Successfully imported configuration to {viewModelTypeName}\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Failed to import configuration to {viewModelTypeName}\");\n return false;\n }\n }\n finally\n {\n // Restore the original service\n configServiceField.SetValue(viewModel, originalService);\n _logService.Log(LogLevel.Debug, \"Restored original configuration service\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Could not find _configurationService field in {viewModelTypeName}\");\n \n // Try direct application as a fallback\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, $\"Successfully applied configuration directly to {viewModelTypeName}\");\n return true;\n }\n \n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing configuration to {viewModel.GetType().Name}: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Imports configuration to WindowsAppsViewModel.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// True if successful, false otherwise.\n private async Task ImportWindowsAppsConfig(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Importing configuration to WindowsAppsViewModel\");\n \n // First try using the ImportConfigCommand\n var importCommand = viewModel.GetType().GetProperty(\"ImportConfigCommand\")?.GetValue(viewModel) as IAsyncRelayCommand;\n if (importCommand != null)\n {\n _logService.Log(LogLevel.Debug, \"Found ImportConfigCommand, executing...\");\n await importCommand.ExecuteAsync(null);\n \n // Verify that the configuration was applied\n bool configApplied = await VerifyConfigurationApplied(viewModel, configFile);\n \n if (configApplied)\n {\n _logService.Log(LogLevel.Info, \"Successfully imported configuration using ImportConfigCommand\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Configuration may not have been properly applied using ImportConfigCommand\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"ImportConfigCommand not found\");\n }\n \n // If we get here, try direct application\n _logService.Log(LogLevel.Info, \"Falling back to direct application\");\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n \n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, \"Successfully applied configuration directly\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Failed to apply configuration directly\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing WindowsApps configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Imports configuration to ExternalAppsViewModel.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// True if successful, false otherwise.\n private async Task ImportExternalAppsConfig(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Importing configuration to ExternalAppsViewModel\");\n \n // First try using the ImportConfigCommand\n var importCommand = viewModel.GetType().GetProperty(\"ImportConfigCommand\")?.GetValue(viewModel) as IAsyncRelayCommand;\n if (importCommand != null)\n {\n _logService.Log(LogLevel.Debug, \"Found ImportConfigCommand, executing...\");\n await importCommand.ExecuteAsync(null);\n \n // Verify that the configuration was applied\n bool configApplied = await VerifyConfigurationApplied(viewModel, configFile);\n \n if (configApplied)\n {\n _logService.Log(LogLevel.Info, \"Successfully imported configuration using ImportConfigCommand\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Configuration may not have been properly applied using ImportConfigCommand\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"ImportConfigCommand not found\");\n }\n \n // If we get here, try direct application\n _logService.Log(LogLevel.Info, \"Falling back to direct application\");\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n \n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, \"Successfully applied configuration directly\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Failed to apply configuration directly\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing ExternalApps configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Imports configuration to CustomizeViewModel.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// True if successful, false otherwise.\n private async Task ImportCustomizeConfig(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Importing configuration to CustomizeViewModel\");\n \n // First try using the ImportConfigCommand\n var importCommand = viewModel.GetType().GetProperty(\"ImportConfigCommand\")?.GetValue(viewModel) as IAsyncRelayCommand;\n if (importCommand != null)\n {\n _logService.Log(LogLevel.Debug, \"Found ImportConfigCommand, executing...\");\n await importCommand.ExecuteAsync(null);\n \n // Verify that the configuration was applied\n bool configApplied = await VerifyConfigurationApplied(viewModel, configFile);\n \n if (configApplied)\n {\n _logService.Log(LogLevel.Info, \"Successfully imported configuration using ImportConfigCommand\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Configuration may not have been properly applied using ImportConfigCommand\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"ImportConfigCommand not found\");\n }\n \n // If we get here, try direct application\n _logService.Log(LogLevel.Info, \"Falling back to direct application\");\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n \n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, \"Successfully applied configuration directly\");\n \n // For CustomizeViewModel, try to call ApplyCustomizations if available\n var applyCustomizationsMethod = viewModel.GetType().GetMethod(\"ApplyCustomizations\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (applyCustomizationsMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling ApplyCustomizations method\");\n \n // Check if the method takes parameters\n var parameters = applyCustomizationsMethod.GetParameters();\n if (parameters.Length == 0)\n {\n applyCustomizationsMethod.Invoke(viewModel, null);\n }\n else if (parameters.Length == 1 && parameters[0].ParameterType == typeof(bool))\n {\n // If it takes a boolean parameter, pass true to force application\n applyCustomizationsMethod.Invoke(viewModel, new object[] { true });\n }\n }\n \n // Additionally, iterate through all items and ensure their registry settings are applied\n var itemsProperty = viewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(viewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n _logService.Log(LogLevel.Debug, \"Iterating through items to ensure registry settings are applied\");\n foreach (var item in items)\n {\n var applySettingCommand = item.GetType().GetProperty(\"ApplySettingCommand\")?.GetValue(item) as ICommand;\n if (applySettingCommand != null && applySettingCommand.CanExecute(null))\n {\n var nameProperty = item.GetType().GetProperty(\"Name\");\n var name = nameProperty?.GetValue(item)?.ToString() ?? \"unknown\";\n _logService.Log(LogLevel.Debug, $\"Executing ApplySettingCommand for {name}\");\n applySettingCommand.Execute(null);\n }\n }\n }\n }\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Failed to apply configuration directly\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing Customize configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Imports configuration to OptimizeViewModel.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// True if successful, false otherwise.\n private async Task ImportOptimizeConfig(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Importing configuration to OptimizeViewModel\");\n \n // First try using the ImportConfigCommand\n var importCommand = viewModel.GetType().GetProperty(\"ImportConfigCommand\")?.GetValue(viewModel) as IAsyncRelayCommand;\n if (importCommand != null)\n {\n _logService.Log(LogLevel.Debug, \"Found ImportConfigCommand, executing...\");\n await importCommand.ExecuteAsync(null);\n \n // Verify that the configuration was applied\n bool configApplied = await VerifyConfigurationApplied(viewModel, configFile);\n \n if (configApplied)\n {\n _logService.Log(LogLevel.Info, \"Successfully imported configuration using ImportConfigCommand\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Configuration may not have been properly applied using ImportConfigCommand\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"ImportConfigCommand not found\");\n }\n \n // If we get here, try direct application\n _logService.Log(LogLevel.Info, \"Falling back to direct application\");\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n \n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, \"Successfully applied configuration directly\");\n \n // For OptimizeViewModel, try to call ApplyOptimizations if available\n var applyOptimizationsMethod = viewModel.GetType().GetMethod(\"ApplyOptimizations\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (applyOptimizationsMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling ApplyOptimizations method\");\n \n // Check if the method takes parameters\n var parameters = applyOptimizationsMethod.GetParameters();\n if (parameters.Length == 0)\n {\n applyOptimizationsMethod.Invoke(viewModel, null);\n }\n else if (parameters.Length == 1 && parameters[0].ParameterType == typeof(bool))\n {\n // If it takes a boolean parameter, pass true to force application\n applyOptimizationsMethod.Invoke(viewModel, new object[] { true });\n }\n }\n \n // Additionally, iterate through all items and ensure their registry settings are applied\n var itemsProperty = viewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(viewModel) as System.Collections.IEnumerable;\n if (items != null)\n {\n _logService.Log(LogLevel.Debug, \"Iterating through items to ensure registry settings are applied\");\n foreach (var item in items)\n {\n var applySettingCommand = item.GetType().GetProperty(\"ApplySettingCommand\")?.GetValue(item) as ICommand;\n if (applySettingCommand != null && applySettingCommand.CanExecute(null))\n {\n var nameProperty = item.GetType().GetProperty(\"Name\");\n var name = nameProperty?.GetValue(item)?.ToString() ?? \"unknown\";\n _logService.Log(LogLevel.Debug, $\"Executing ApplySettingCommand for {name}\");\n applySettingCommand.Execute(null);\n }\n }\n }\n }\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Failed to apply configuration directly\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing Optimize configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Imports configuration to a generic view model.\n /// \n /// The view model to import to.\n /// The configuration file to import.\n /// True if successful, false otherwise.\n private async Task ImportGenericConfig(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Importing configuration to generic view model\");\n \n // First try using the ImportConfigCommand\n var importCommand = viewModel.GetType().GetProperty(\"ImportConfigCommand\")?.GetValue(viewModel) as IAsyncRelayCommand;\n if (importCommand != null)\n {\n _logService.Log(LogLevel.Debug, \"Found ImportConfigCommand, executing...\");\n await importCommand.ExecuteAsync(null);\n \n // Verify that the configuration was applied\n bool configApplied = await VerifyConfigurationApplied(viewModel, configFile);\n \n if (configApplied)\n {\n _logService.Log(LogLevel.Info, \"Successfully imported configuration using ImportConfigCommand\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Configuration may not have been properly applied using ImportConfigCommand\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"ImportConfigCommand not found\");\n }\n \n // If we get here, try direct application\n _logService.Log(LogLevel.Info, \"Falling back to direct application\");\n bool directApplyResult = await DirectlyApplyConfiguration(viewModel, configFile);\n \n if (directApplyResult)\n {\n _logService.Log(LogLevel.Info, \"Successfully applied configuration directly\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Failed to apply configuration directly\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing generic configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Verifies that the configuration was properly applied to the view model.\n /// \n /// The view model to verify.\n /// The configuration file that was applied.\n /// True if the configuration was applied, false otherwise.\n private async Task VerifyConfigurationApplied(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Debug, $\"Verifying configuration was applied to {viewModel.GetType().Name}\");\n \n // Get the Items property from the view model\n var itemsProperty = viewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty == null)\n {\n _logService.Log(LogLevel.Warning, $\"Could not find Items property in {viewModel.GetType().Name}\");\n return false;\n }\n \n var items = itemsProperty.GetValue(viewModel) as System.Collections.IEnumerable;\n if (items == null)\n {\n _logService.Log(LogLevel.Warning, $\"Items collection is null in {viewModel.GetType().Name}\");\n return false;\n }\n \n // Check if at least some items have the expected IsSelected state\n int matchCount = 0;\n int totalChecked = 0;\n \n // Create dictionaries of config items by name and ID for faster lookup\n var configItemsByName = new Dictionary(StringComparer.OrdinalIgnoreCase);\n var configItemsById = new Dictionary(StringComparer.OrdinalIgnoreCase);\n \n if (configFile.Items != null)\n {\n foreach (var item in configFile.Items)\n {\n if (!string.IsNullOrEmpty(item.Name) && !configItemsByName.ContainsKey(item.Name))\n {\n configItemsByName.Add(item.Name, item);\n }\n \n if (item.CustomProperties.TryGetValue(\"Id\", out var id) && id != null &&\n !string.IsNullOrEmpty(id.ToString()) && !configItemsById.ContainsKey(id.ToString()))\n {\n configItemsById.Add(id.ToString(), item);\n }\n }\n }\n \n // Get the view model type to determine special handling\n string viewModelTypeName = viewModel.GetType().Name;\n _logService.Log(LogLevel.Debug, $\"Verifying view model of type: {viewModelTypeName}\");\n \n // Check up to 15 items\n foreach (var item in items)\n {\n if (totalChecked >= 15) break;\n \n var nameProperty = item.GetType().GetProperty(\"Name\");\n var idProperty = item.GetType().GetProperty(\"Id\");\n var isSelectedProperty = item.GetType().GetProperty(\"IsSelected\");\n \n if (nameProperty != null && isSelectedProperty != null)\n {\n var name = nameProperty.GetValue(item)?.ToString();\n var id = idProperty?.GetValue(item)?.ToString();\n \n _logService.Log(LogLevel.Debug, $\"Processing item: {name}, Id: {id}\");\n \n ConfigurationItem configItem = null;\n \n // Try to match by ID first\n if (!string.IsNullOrEmpty(id) && configItemsById.TryGetValue(id, out var itemById))\n {\n configItem = itemById;\n }\n // Then try to match by name\n else if (!string.IsNullOrEmpty(name) && configItemsByName.TryGetValue(name, out var itemByName))\n {\n configItem = itemByName;\n }\n \n if (configItem != null)\n {\n totalChecked++;\n bool itemMatches = true;\n \n // Check IsSelected property\n if (isSelectedProperty.GetValue(item) is bool isSelected && isSelected != configItem.IsSelected)\n {\n _logService.Log(LogLevel.Debug, $\"Item {name} has IsSelected={isSelected}, expected {configItem.IsSelected}\");\n itemMatches = false;\n }\n \n // For controls with additional properties, check those too\n if (configItem.ControlType == ControlType.ThreeStateSlider || configItem.ControlType == ControlType.ComboBox)\n {\n var sliderValueProperty = item.GetType().GetProperty(\"SliderValue\");\n if (sliderValueProperty != null && configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int expectedValue = Convert.ToInt32(sliderValue);\n int actualValue = (int)(sliderValueProperty.GetValue(item) ?? 0);\n \n if (actualValue != expectedValue)\n {\n _logService.Log(LogLevel.Debug, $\"Item {name} has SliderValue={actualValue}, expected {expectedValue}\");\n itemMatches = false;\n }\n }\n }\n \n // For ComboBox, check SelectedValue\n if (configItem.ControlType == ControlType.ComboBox)\n {\n var selectedValueProperty = item.GetType().GetProperty(\"SelectedValue\");\n if (selectedValueProperty != null && !string.IsNullOrEmpty(configItem.SelectedValue))\n {\n string expectedValue = configItem.SelectedValue;\n string actualValue = selectedValueProperty.GetValue(item)?.ToString();\n \n if (actualValue != expectedValue)\n {\n _logService.Log(LogLevel.Debug, $\"Item {name} has SelectedValue={actualValue}, expected {expectedValue}\");\n itemMatches = false;\n }\n }\n }\n \n if (itemMatches)\n {\n matchCount++;\n }\n }\n }\n }\n \n _logService.Log(LogLevel.Debug, $\"Verification result: {matchCount} matches out of {totalChecked} checked items\");\n \n // If we checked at least 3 items and at least 50% match, consider it successful\n if (totalChecked >= 3 && (double)matchCount / totalChecked >= 0.5)\n {\n _logService.Log(LogLevel.Info, $\"Configuration verification passed: {matchCount}/{totalChecked} items match\");\n return true;\n }\n else if (totalChecked > 0)\n {\n _logService.Log(LogLevel.Warning, $\"Configuration verification failed: only {matchCount}/{totalChecked} items match\");\n \n // Even if verification fails, we'll try to directly apply the configuration\n _logService.Log(LogLevel.Info, \"Will attempt direct application as fallback\");\n return false;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"No items could be checked for verification\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error verifying configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Directly applies the configuration to the view model without using the ImportConfigCommand.\n /// \n /// The view model to apply the configuration to.\n /// The configuration file to apply.\n /// True if successful, false otherwise.\n private async Task DirectlyApplyConfiguration(object viewModel, ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Attempting to directly apply configuration to {viewModel.GetType().Name}\");\n \n // Get the Items property from the view model\n var itemsProperty = viewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty == null)\n {\n _logService.Log(LogLevel.Warning, $\"Could not find Items property in {viewModel.GetType().Name}\");\n return false;\n }\n \n var items = itemsProperty.GetValue(viewModel) as System.Collections.IEnumerable;\n if (items == null)\n {\n _logService.Log(LogLevel.Warning, $\"Items collection is null in {viewModel.GetType().Name}\");\n return false;\n }\n \n // Create dictionaries of config items by name and ID for faster lookup\n var configItemsByName = new Dictionary(StringComparer.OrdinalIgnoreCase);\n var configItemsById = new Dictionary(StringComparer.OrdinalIgnoreCase);\n \n if (configFile.Items != null)\n {\n foreach (var item in configFile.Items)\n {\n if (!string.IsNullOrEmpty(item.Name) && !configItemsByName.ContainsKey(item.Name))\n {\n configItemsByName.Add(item.Name, item);\n }\n \n if (item.CustomProperties.TryGetValue(\"Id\", out var id) && id != null &&\n !string.IsNullOrEmpty(id.ToString()) && !configItemsById.ContainsKey(id.ToString()))\n {\n configItemsById.Add(id.ToString(), item);\n }\n }\n }\n \n // Update the items in the view model\n int updatedCount = 0;\n \n // Determine if we're dealing with a collection that implements INotifyCollectionChanged\n bool isObservableCollection = false;\n var itemsType = items.GetType();\n if (typeof(System.Collections.Specialized.INotifyCollectionChanged).IsAssignableFrom(itemsType))\n {\n isObservableCollection = true;\n _logService.Log(LogLevel.Debug, $\"Items collection is an observable collection\");\n }\n \n // Get the view model type to determine special handling\n string viewModelTypeName = viewModel.GetType().Name;\n _logService.Log(LogLevel.Debug, $\"Processing view model of type: {viewModelTypeName}\");\n \n foreach (var item in items)\n {\n var nameProperty = item.GetType().GetProperty(\"Name\");\n var idProperty = item.GetType().GetProperty(\"Id\");\n var isSelectedProperty = item.GetType().GetProperty(\"IsSelected\");\n var isUpdatingFromCodeProperty = item.GetType().GetProperty(\"IsUpdatingFromCode\");\n \n if (nameProperty != null && isSelectedProperty != null)\n {\n var name = nameProperty.GetValue(item)?.ToString();\n var id = idProperty?.GetValue(item)?.ToString();\n \n _logService.Log(LogLevel.Debug, $\"Processing item: {name}, Id: {id}\");\n \n ConfigurationItem configItem = null;\n \n // Try to match by ID first\n if (!string.IsNullOrEmpty(id) && configItemsById.TryGetValue(id, out var itemById))\n {\n configItem = itemById;\n }\n // Then try to match by name\n else if (!string.IsNullOrEmpty(name) && configItemsByName.TryGetValue(name, out var itemByName))\n {\n configItem = itemByName;\n }\n \n if (configItem != null)\n {\n // Get the current IsSelected value before changing it\n bool currentIsSelected = (bool)(isSelectedProperty.GetValue(item) ?? false);\n \n // Set IsUpdatingFromCode to true before making changes\n if (isUpdatingFromCodeProperty != null)\n {\n isUpdatingFromCodeProperty.SetValue(item, true);\n }\n \n // Update IsSelected\n if (currentIsSelected != configItem.IsSelected)\n {\n _logService.Log(LogLevel.Debug, $\"Updating IsSelected for {name} from {currentIsSelected} to {configItem.IsSelected}\");\n isSelectedProperty.SetValue(item, configItem.IsSelected);\n }\n \n // Update other properties if available\n bool propertiesUpdated = UpdateAdditionalProperties(item, configItem);\n \n // If any property was updated, count it\n if (currentIsSelected != configItem.IsSelected || propertiesUpdated)\n {\n updatedCount++;\n }\n \n // Set IsUpdatingFromCode back to false to allow property change events to trigger\n if (isUpdatingFromCodeProperty != null)\n {\n isUpdatingFromCodeProperty.SetValue(item, false);\n }\n \n // Ensure UI state is properly updated\n TriggerPropertyChangedIfPossible(item);\n \n // Always explicitly call ApplySetting method to ensure registry changes are applied\n // regardless of view model type or IsSelected state\n var applySettingCommand = item.GetType().GetProperty(\"ApplySettingCommand\")?.GetValue(item) as ICommand;\n if (applySettingCommand != null && applySettingCommand.CanExecute(null))\n {\n _logService.Log(LogLevel.Debug, $\"Explicitly executing ApplySettingCommand for {name}\");\n applySettingCommand.Execute(null);\n }\n }\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Directly updated {updatedCount} items in {viewModel.GetType().Name}\");\n \n // Force UI refresh\n await RefreshUIIfNeeded(viewModel);\n \n return updatedCount > 0;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error directly applying configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Attempts to trigger property changed notifications on an item if it implements INotifyPropertyChanged.\n /// \n /// The item to trigger property changed on.\n private void TriggerPropertyChangedIfPossible(object item)\n {\n try\n {\n // Check if the item implements INotifyPropertyChanged\n if (item is System.ComponentModel.INotifyPropertyChanged notifyPropertyChanged)\n {\n try\n {\n // Try to find the OnPropertyChanged method with a string parameter\n var onPropertyChangedMethod = item.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(string) },\n null);\n \n if (onPropertyChangedMethod != null)\n {\n // Invoke the method with null string to refresh all properties\n onPropertyChangedMethod.Invoke(item, new object[] { null });\n _logService.Log(LogLevel.Debug, $\"Triggered OnPropertyChanged(string) for {item.GetType().Name}\");\n }\n else\n {\n // Try to find the OnPropertyChanged method with no parameters\n var onPropertyChangedNoParamsMethod = item.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n Type.EmptyTypes,\n null);\n \n if (onPropertyChangedNoParamsMethod != null)\n {\n // Invoke the method with no parameters\n onPropertyChangedNoParamsMethod.Invoke(item, null);\n _logService.Log(LogLevel.Debug, $\"Triggered OnPropertyChanged() for {item.GetType().Name}\");\n }\n else\n {\n // Try to find the RaisePropertyChanged method as an alternative\n var raisePropertyChangedMethod = item.GetType().GetMethod(\"RaisePropertyChanged\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (raisePropertyChangedMethod != null)\n {\n // Invoke with null to refresh all properties\n raisePropertyChangedMethod.Invoke(item, new object[] { null });\n _logService.Log(LogLevel.Debug, $\"Triggered RaisePropertyChanged for {item.GetType().Name}\");\n }\n }\n }\n }\n catch (System.Reflection.AmbiguousMatchException)\n {\n _logService.Log(LogLevel.Debug, $\"Ambiguous match for OnPropertyChanged in {item.GetType().Name}, trying alternative approach\");\n \n // Try to get all methods named OnPropertyChanged\n var methods = item.GetType().GetMethods(System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance)\n .Where(m => m.Name == \"OnPropertyChanged\").ToList();\n \n if (methods.Any())\n {\n // Try to find one that takes a string parameter\n var stringParamMethod = methods.FirstOrDefault(m =>\n {\n var parameters = m.GetParameters();\n return parameters.Length == 1 && parameters[0].ParameterType == typeof(string);\n });\n \n if (stringParamMethod != null)\n {\n stringParamMethod.Invoke(item, new object[] { null });\n _logService.Log(LogLevel.Debug, $\"Triggered OnPropertyChanged using specific method for {item.GetType().Name}\");\n }\n }\n }\n \n // Try to find a method that might trigger property changed\n var refreshMethod = item.GetType().GetMethod(\"Refresh\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);\n \n if (refreshMethod != null)\n {\n refreshMethod.Invoke(item, null);\n _logService.Log(LogLevel.Debug, $\"Called Refresh method for {item.GetType().Name}\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error triggering property changed: {ex.Message}\");\n }\n }\n \n /// \n /// Updates additional properties of an item based on the configuration item.\n /// \n /// The item to update.\n /// The configuration item containing the values to apply.\n /// True if any property was updated, false otherwise.\n private bool UpdateAdditionalProperties(object item, ConfigurationItem configItem)\n {\n try\n {\n bool anyPropertyUpdated = false;\n \n // Get the item type to access its properties\n var itemType = item.GetType();\n \n // Log the control type for debugging\n _logService.Log(LogLevel.Debug, $\"Updating additional properties for {configItem.Name}, ControlType: {configItem.ControlType}\");\n \n // Update SliderValue for ThreeStateSlider or ComboBox\n if (configItem.ControlType == ControlType.ThreeStateSlider || configItem.ControlType == ControlType.ComboBox)\n {\n var sliderValueProperty = itemType.GetProperty(\"SliderValue\");\n if (sliderValueProperty != null && configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int newSliderValue = Convert.ToInt32(sliderValue);\n int currentSliderValue = (int)(sliderValueProperty.GetValue(item) ?? 0);\n \n if (currentSliderValue != newSliderValue)\n {\n _logService.Log(LogLevel.Debug, $\"Updating SliderValue for {configItem.Name} from {currentSliderValue} to {newSliderValue}\");\n sliderValueProperty.SetValue(item, newSliderValue);\n anyPropertyUpdated = true;\n }\n }\n }\n \n // Update SelectedValue for ComboBox\n if (configItem.ControlType == ControlType.ComboBox)\n {\n var selectedValueProperty = itemType.GetProperty(\"SelectedValue\");\n if (selectedValueProperty != null && !string.IsNullOrEmpty(configItem.SelectedValue))\n {\n string currentSelectedValue = selectedValueProperty.GetValue(item)?.ToString();\n \n if (currentSelectedValue != configItem.SelectedValue)\n {\n _logService.Log(LogLevel.Debug, $\"Updating SelectedValue for {configItem.Name} from '{currentSelectedValue}' to '{configItem.SelectedValue}'\");\n selectedValueProperty.SetValue(item, configItem.SelectedValue);\n anyPropertyUpdated = true;\n }\n }\n }\n \n // Update SelectedTheme for theme selector\n if (configItem.Name.Contains(\"Theme\") && configItem.CustomProperties.TryGetValue(\"SelectedTheme\", out var selectedTheme))\n {\n var selectedThemeProperty = itemType.GetProperty(\"SelectedTheme\");\n if (selectedThemeProperty != null && selectedTheme != null)\n {\n string currentSelectedTheme = selectedThemeProperty.GetValue(item)?.ToString();\n string newSelectedTheme = selectedTheme.ToString();\n \n if (currentSelectedTheme != newSelectedTheme)\n {\n _logService.Log(LogLevel.Debug, $\"Updating SelectedTheme for {configItem.Name} from '{currentSelectedTheme}' to '{newSelectedTheme}'\");\n selectedThemeProperty.SetValue(item, newSelectedTheme);\n anyPropertyUpdated = true;\n }\n }\n }\n \n // Update Status for items that have a status property\n var statusProperty = itemType.GetProperty(\"Status\");\n if (statusProperty != null && configItem.CustomProperties.TryGetValue(\"Status\", out var status))\n {\n statusProperty.SetValue(item, status);\n anyPropertyUpdated = true;\n }\n \n // Update StatusMessage for items that have a status message property\n var statusMessageProperty = itemType.GetProperty(\"StatusMessage\");\n if (statusMessageProperty != null && configItem.CustomProperties.TryGetValue(\"StatusMessage\", out var statusMessage))\n {\n statusMessageProperty.SetValue(item, statusMessage?.ToString());\n anyPropertyUpdated = true;\n }\n \n // For toggle switches, ensure IsChecked is synchronized with IsSelected\n var isCheckedProperty = itemType.GetProperty(\"IsChecked\");\n if (isCheckedProperty != null)\n {\n bool currentIsChecked = (bool)(isCheckedProperty.GetValue(item) ?? false);\n \n if (currentIsChecked != configItem.IsSelected)\n {\n _logService.Log(LogLevel.Debug, $\"Updating IsChecked for {configItem.Name} from {currentIsChecked} to {configItem.IsSelected}\");\n isCheckedProperty.SetValue(item, configItem.IsSelected);\n anyPropertyUpdated = true;\n }\n }\n \n // Update CurrentValue property if it exists\n var currentValueProperty = itemType.GetProperty(\"CurrentValue\");\n if (currentValueProperty != null)\n {\n // For toggle buttons, set the current value based on IsSelected\n if (configItem.ControlType == ControlType.BinaryToggle)\n {\n object valueToSet = configItem.IsSelected ? 1 : 0;\n currentValueProperty.SetValue(item, valueToSet);\n _logService.Log(LogLevel.Debug, $\"Setting CurrentValue for {configItem.Name} to {valueToSet}\");\n anyPropertyUpdated = true;\n }\n // For other control types, use the appropriate value\n else if (configItem.ControlType == ControlType.ThreeStateSlider || configItem.ControlType == ControlType.ComboBox)\n {\n if (configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n currentValueProperty.SetValue(item, sliderValue);\n _logService.Log(LogLevel.Debug, $\"Setting CurrentValue for {configItem.Name} to {sliderValue}\");\n anyPropertyUpdated = true;\n }\n }\n }\n \n // Update RegistrySetting property if it exists\n var registrySettingProperty = itemType.GetProperty(\"RegistrySetting\");\n if (registrySettingProperty != null && configItem.CustomProperties.TryGetValue(\"RegistrySetting\", out var registrySetting))\n {\n registrySettingProperty.SetValue(item, registrySetting);\n _logService.Log(LogLevel.Debug, $\"Updated RegistrySetting for {configItem.Name}\");\n anyPropertyUpdated = true;\n }\n \n // Update LinkedRegistrySettings property if it exists\n var linkedRegistrySettingsProperty = itemType.GetProperty(\"LinkedRegistrySettings\");\n if (linkedRegistrySettingsProperty != null && configItem.CustomProperties.TryGetValue(\"LinkedRegistrySettings\", out var linkedRegistrySettings))\n {\n linkedRegistrySettingsProperty.SetValue(item, linkedRegistrySettings);\n _logService.Log(LogLevel.Debug, $\"Updated LinkedRegistrySettings for {configItem.Name}\");\n anyPropertyUpdated = true;\n }\n \n return anyPropertyUpdated;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating additional properties: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n \n /// \n /// Forces a UI refresh if needed for the view model.\n /// \n /// The view model to refresh.\n private async Task RefreshUIIfNeeded(object viewModel)\n {\n try\n {\n _logService.Log(LogLevel.Debug, $\"Refreshing UI for {viewModel.GetType().Name}\");\n bool refreshed = false;\n \n // Get the view model type to determine special handling\n string viewModelTypeName = viewModel.GetType().Name;\n \n // Try multiple refresh methods in order of preference\n \n // 1. First try RefreshCommand if available\n var refreshCommandProperty = viewModel.GetType().GetProperty(\"RefreshCommand\");\n if (refreshCommandProperty != null)\n {\n var refreshCommand = refreshCommandProperty.GetValue(viewModel) as IAsyncRelayCommand;\n if (refreshCommand != null && refreshCommand.CanExecute(null))\n {\n _logService.Log(LogLevel.Debug, \"Executing RefreshCommand\");\n await refreshCommand.ExecuteAsync(null);\n refreshed = true;\n }\n }\n \n // 2. Try RaisePropertyChanged for the Items property if the view model implements INotifyPropertyChanged\n if (!refreshed && viewModel is System.ComponentModel.INotifyPropertyChanged)\n {\n try\n {\n // Try to find the OnPropertyChanged method with a string parameter\n var onPropertyChangedMethod = viewModel.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(string) },\n null);\n \n if (onPropertyChangedMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling OnPropertyChanged(string) for Items property\");\n onPropertyChangedMethod.Invoke(viewModel, new object[] { \"Items\" });\n refreshed = true;\n }\n else\n {\n // Try to find the RaisePropertyChanged method as an alternative\n var raisePropertyChangedMethod = viewModel.GetType().GetMethod(\"RaisePropertyChanged\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (raisePropertyChangedMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling RaisePropertyChanged for Items property\");\n raisePropertyChangedMethod.Invoke(viewModel, new object[] { \"Items\" });\n refreshed = true;\n }\n else\n {\n // Try to find the NotifyPropertyChanged method as another alternative\n var notifyPropertyChangedMethod = viewModel.GetType().GetMethod(\"NotifyPropertyChanged\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (notifyPropertyChangedMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling NotifyPropertyChanged for Items property\");\n notifyPropertyChangedMethod.Invoke(viewModel, new object[] { \"Items\" });\n refreshed = true;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Warning, $\"Error calling property changed method: {ex.Message}\");\n // Continue with other refresh methods\n }\n }\n \n // 3. Try LoadItemsAsync method\n if (!refreshed)\n {\n var loadItemsMethod = viewModel.GetType().GetMethod(\"LoadItemsAsync\");\n if (loadItemsMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling LoadItemsAsync method\");\n await (Task)loadItemsMethod.Invoke(viewModel, null);\n refreshed = true;\n }\n }\n \n // 4. Try ApplySearch method\n if (!refreshed)\n {\n var applySearchMethod = viewModel.GetType().GetMethod(\"ApplySearch\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (applySearchMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling ApplySearch method\");\n applySearchMethod.Invoke(viewModel, null);\n refreshed = true;\n }\n }\n \n // 5. For specific view model types, try additional refresh methods\n if (!refreshed)\n {\n if (viewModelTypeName.Contains(\"Customize\"))\n {\n // Try to refresh the CustomizeViewModel specifically\n var refreshCustomizationsMethod = viewModel.GetType().GetMethod(\"RefreshCustomizations\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (refreshCustomizationsMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling RefreshCustomizations method\");\n refreshCustomizationsMethod.Invoke(viewModel, null);\n refreshed = true;\n }\n }\n else if (viewModelTypeName.Contains(\"Optimize\"))\n {\n // Try to refresh the OptimizeViewModel specifically\n var refreshOptimizationsMethod = viewModel.GetType().GetMethod(\"RefreshOptimizations\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (refreshOptimizationsMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling RefreshOptimizations method\");\n refreshOptimizationsMethod.Invoke(viewModel, null);\n refreshed = true;\n }\n }\n }\n \n // 6. If we still haven't refreshed, try to force a collection refresh\n if (!refreshed)\n {\n // Get the Items property\n var itemsProperty = viewModel.GetType().GetProperty(\"Items\");\n if (itemsProperty != null)\n {\n var items = itemsProperty.GetValue(viewModel);\n \n // Check if it's an ObservableCollection\n if (items != null && items.GetType().Name.Contains(\"ObservableCollection\"))\n {\n // Try to call a refresh method on the collection\n var refreshMethod = items.GetType().GetMethod(\"Refresh\");\n if (refreshMethod != null)\n {\n _logService.Log(LogLevel.Debug, \"Calling Refresh on ObservableCollection\");\n refreshMethod.Invoke(items, null);\n refreshed = true;\n }\n }\n }\n }\n \n if (!refreshed)\n {\n _logService.Log(LogLevel.Warning, \"Could not find a suitable method to refresh the UI\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error refreshing UI: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n }\n\n /// \n /// A wrapper for the configuration service that returns a specific configuration file.\n /// \n private class ConfigurationServiceWrapper : IConfigurationService\n {\n private readonly IConfigurationService _innerService;\n private readonly ConfigurationFile _configFile;\n private readonly ILogService _logService;\n\n public ConfigurationServiceWrapper(IConfigurationService innerService, ConfigurationFile configFile)\n {\n _innerService = innerService;\n _configFile = configFile;\n \n // Try to get the log service from the inner service using reflection\n try\n {\n var logServiceField = _innerService.GetType().GetField(\"_logService\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (logServiceField != null)\n {\n _logService = logServiceField.GetValue(_innerService) as ILogService;\n }\n }\n catch\n {\n // Ignore any errors, we'll just operate without logging\n }\n }\n\n public Task LoadConfigurationAsync(string configType)\n {\n // Log the operation if possible\n _logService?.Log(LogLevel.Debug, $\"ConfigurationServiceWrapper.LoadConfigurationAsync called with configType: {configType}\");\n _logService?.Log(LogLevel.Debug, $\"Returning config file with {_configFile.Items?.Count ?? 0} items\");\n \n // Always return our config file, but ensure it has the correct configType\n var configFileCopy = new ConfigurationFile\n {\n ConfigType = configType,\n CreatedAt = _configFile.CreatedAt,\n Items = _configFile.Items\n };\n \n return Task.FromResult(configFileCopy);\n }\n\n public Task SaveConfigurationAsync(IEnumerable items, string configType)\n {\n // Log the operation if possible\n _logService?.Log(LogLevel.Debug, $\"ConfigurationServiceWrapper.SaveConfigurationAsync called with configType: {configType}\");\n \n // Delegate to the inner service\n return _innerService.SaveConfigurationAsync(items, configType);\n }\n\n public Task LoadUnifiedConfigurationAsync()\n {\n // Log the operation if possible\n _logService?.Log(LogLevel.Debug, \"ConfigurationServiceWrapper.LoadUnifiedConfigurationAsync called\");\n \n // Delegate to the inner service\n return _innerService.LoadUnifiedConfigurationAsync();\n }\n\n public Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile unifiedConfig)\n {\n return Task.FromResult(true);\n }\n\n public UnifiedConfigurationFile CreateUnifiedConfiguration(Dictionary> sections, IEnumerable includedSections)\n {\n // Log the operation if possible\n _logService?.Log(LogLevel.Debug, \"ConfigurationServiceWrapper.CreateUnifiedConfiguration called\");\n \n // Delegate to the inner service\n return _innerService.CreateUnifiedConfiguration(sections, includedSections);\n }\n\n public ConfigurationFile ExtractSectionFromUnifiedConfiguration(UnifiedConfigurationFile unifiedConfig, string sectionName)\n {\n // Log the operation if possible\n _logService?.Log(LogLevel.Debug, $\"ConfigurationServiceWrapper.ExtractSectionFromUnifiedConfiguration called with sectionName: {sectionName}\");\n \n // Delegate to the inner service\n return _innerService.ExtractSectionFromUnifiedConfiguration(unifiedConfig, sectionName);\n }\n }\n\n /// \n /// A mock configuration service that captures the settings passed to SaveConfigurationAsync.\n /// \n private class MockConfigurationService : IConfigurationService\n {\n // Flag to indicate this is being used for unified configuration\n public bool IsUnifiedConfigurationMode { get; set; } = true;\n \n // Flag to suppress dialogs\n public bool SuppressDialogs { get; set; } = true;\n \n // Captured settings\n public List CapturedSettings { get; } = new List();\n \n // Dialog service for showing messages\n private readonly IDialogService _dialogService;\n \n public MockConfigurationService(IDialogService dialogService = null)\n {\n _dialogService = dialogService;\n }\n\n public Task LoadConfigurationAsync(string configType)\n {\n // Return an empty configuration file\n return Task.FromResult(new ConfigurationFile\n {\n ConfigType = configType,\n CreatedAt = DateTime.UtcNow,\n Items = new List()\n });\n }\n\n public Task SaveConfigurationAsync(IEnumerable items, string configType)\n {\n System.Diagnostics.Debug.WriteLine($\"MockConfigurationService.SaveConfigurationAsync called with configType: {configType}\");\n System.Diagnostics.Debug.WriteLine($\"Generic type T: {typeof(T).FullName}\");\n System.Diagnostics.Debug.WriteLine($\"SuppressDialogs: {SuppressDialogs}, IsUnifiedConfigurationMode: {IsUnifiedConfigurationMode}\");\n \n // Check if items is null or empty\n if (items == null)\n {\n System.Diagnostics.Debug.WriteLine(\"Items collection is null\");\n return Task.FromResult(true);\n }\n \n if (!items.Any())\n {\n System.Diagnostics.Debug.WriteLine(\"Items collection is empty\");\n return Task.FromResult(true);\n }\n \n // Log the count of items\n System.Diagnostics.Debug.WriteLine($\"Items count: {items.Count()}\");\n \n try\n {\n // We no longer need special handling for WindowsApps since we're directly accessing the Items collection\n // Special handling for ExternalApps\n if (configType == \"ExternalApps\")\n {\n System.Diagnostics.Debug.WriteLine(\"Processing ExternalApps configuration\");\n \n // Convert each ExternalApp to ExternalAppSettingItem\n var externalApps = new List();\n \n foreach (var item in items)\n {\n if (item is Winhance.WPF.Features.SoftwareApps.Models.ExternalApp externalApp)\n {\n externalApps.Add(new ExternalAppSettingItem(externalApp));\n System.Diagnostics.Debug.WriteLine($\"Added ExternalAppSettingItem for {externalApp.Name}\");\n }\n }\n \n System.Diagnostics.Debug.WriteLine($\"Created {externalApps.Count} ExternalAppSettingItems\");\n CapturedSettings.AddRange(externalApps);\n System.Diagnostics.Debug.WriteLine($\"Added {externalApps.Count} ExternalAppSettingItems to CapturedSettings\");\n }\n else\n {\n // For other types, try to cast directly to ISettingItem\n try\n {\n var settingItems = items.Cast().ToList();\n System.Diagnostics.Debug.WriteLine($\"Successfully cast to ISettingItem, count: {settingItems.Count}\");\n \n CapturedSettings.AddRange(settingItems);\n System.Diagnostics.Debug.WriteLine($\"Added {settingItems.Count} ISettingItems to CapturedSettings\");\n }\n catch (InvalidCastException ex)\n {\n // Log the error but don't throw it to avoid breaking the configuration process\n System.Diagnostics.Debug.WriteLine($\"Error casting items to ISettingItem: {ex.Message}\");\n \n // Try to convert each item individually\n int convertedCount = 0;\n foreach (var item in items)\n {\n try\n {\n if (item is Winhance.WPF.Features.SoftwareApps.Models.WindowsApp windowsApp)\n {\n CapturedSettings.Add(new WindowsAppSettingItem(windowsApp));\n System.Diagnostics.Debug.WriteLine($\"Added WindowsAppSettingItem for {windowsApp.Name}\");\n convertedCount++;\n }\n else if (item is Winhance.WPF.Features.SoftwareApps.Models.ExternalApp externalApp)\n {\n CapturedSettings.Add(new ExternalAppSettingItem(externalApp));\n System.Diagnostics.Debug.WriteLine($\"Added ExternalAppSettingItem for {externalApp.Name}\");\n convertedCount++;\n }\n else\n {\n System.Diagnostics.Debug.WriteLine($\"Unknown item type: {item?.GetType().FullName ?? \"null\"}\");\n }\n }\n catch (Exception itemEx)\n {\n System.Diagnostics.Debug.WriteLine($\"Error processing individual item: {itemEx.Message}\");\n }\n }\n System.Diagnostics.Debug.WriteLine($\"Converted {convertedCount} items individually\");\n }\n }\n }\n catch (Exception ex)\n {\n System.Diagnostics.Debug.WriteLine($\"Unexpected error in SaveConfigurationAsync: {ex.Message}\");\n }\n \n System.Diagnostics.Debug.WriteLine($\"CapturedSettings count after SaveConfigurationAsync: {CapturedSettings.Count}\");\n \n // Return true without showing any dialogs when in unified configuration mode\n if (SuppressDialogs || IsUnifiedConfigurationMode)\n {\n System.Diagnostics.Debug.WriteLine(\"Suppressing dialogs in unified configuration mode\");\n return Task.FromResult(true);\n }\n \n // Show a success dialog if not in unified configuration mode\n if (_dialogService != null)\n {\n _dialogService.ShowMessage($\"Configuration saved successfully.\", \"Configuration Saved\");\n }\n \n return Task.FromResult(true);\n }\n\n public Task LoadUnifiedConfigurationAsync()\n {\n // Return an empty unified configuration file\n return Task.FromResult(new UnifiedConfigurationFile\n {\n CreatedAt = DateTime.UtcNow,\n WindowsApps = new ConfigSection(),\n ExternalApps = new ConfigSection(),\n Customize = new ConfigSection(),\n Optimize = new ConfigSection()\n });\n }\n\n public Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile unifiedConfig)\n {\n return Task.FromResult(true);\n }\n\n public UnifiedConfigurationFile CreateUnifiedConfiguration(Dictionary> sections, IEnumerable includedSections)\n {\n // Create a unified configuration file with all sections included\n var unifiedConfig = new UnifiedConfigurationFile\n {\n CreatedAt = DateTime.UtcNow,\n WindowsApps = new ConfigSection(),\n ExternalApps = new ConfigSection(),\n Customize = new ConfigSection(),\n Optimize = new ConfigSection()\n };\n\n // Set the IsIncluded flag for each section based on whether it's in the includedSections list\n // and whether it has any items\n if (sections.TryGetValue(\"WindowsApps\", out var windowsApps) && windowsApps.Any())\n {\n unifiedConfig.WindowsApps.IsIncluded = true;\n unifiedConfig.WindowsApps.Items = ConvertToConfigurationItems(windowsApps);\n }\n\n if (sections.TryGetValue(\"ExternalApps\", out var externalApps) && externalApps.Any())\n {\n unifiedConfig.ExternalApps.IsIncluded = true;\n unifiedConfig.ExternalApps.Items = ConvertToConfigurationItems(externalApps);\n }\n\n if (sections.TryGetValue(\"Customize\", out var customize) && customize.Any())\n {\n unifiedConfig.Customize.IsIncluded = true;\n unifiedConfig.Customize.Items = ConvertToConfigurationItems(customize);\n }\n\n if (sections.TryGetValue(\"Optimize\", out var optimize) && optimize.Any())\n {\n unifiedConfig.Optimize.IsIncluded = true;\n unifiedConfig.Optimize.Items = ConvertToConfigurationItems(optimize);\n }\n\n return unifiedConfig;\n }\n\n // Helper method to convert ISettingItem objects to ConfigurationItem objects\n private List ConvertToConfigurationItems(IEnumerable items)\n {\n var result = new List();\n \n foreach (var item in items)\n {\n var configItem = new ConfigurationItem\n {\n Name = item.Name,\n IsSelected = item.IsSelected,\n ControlType = item.ControlType\n };\n \n // Add Id to custom properties\n if (!string.IsNullOrEmpty(item.Id))\n {\n configItem.CustomProperties[\"Id\"] = item.Id;\n }\n \n // Add GroupName to custom properties\n if (!string.IsNullOrEmpty(item.GroupName))\n {\n configItem.CustomProperties[\"GroupName\"] = item.GroupName;\n }\n \n // Add Description to custom properties\n if (!string.IsNullOrEmpty(item.Description))\n {\n configItem.CustomProperties[\"Description\"] = item.Description;\n }\n \n // Ensure SelectedValue is set for ComboBox controls\n configItem.EnsureSelectedValueIsSet();\n \n result.Add(configItem);\n }\n \n return result;\n }\n\n public ConfigurationFile ExtractSectionFromUnifiedConfiguration(UnifiedConfigurationFile unifiedConfig, string sectionName)\n {\n // Return an empty configuration file\n return new ConfigurationFile\n {\n ConfigType = sectionName,\n CreatedAt = DateTime.UtcNow,\n Items = new List()\n };\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/CustomizeConfigurationApplier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.Customize.Models;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.Customize.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for applying configuration to the Customize section.\n /// \n public class CustomizeConfigurationApplier : ISectionConfigurationApplier\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n private readonly IViewModelRefresher _viewModelRefresher;\n private readonly IConfigurationPropertyUpdater _propertyUpdater;\n private readonly IThemeService _themeService;\n private readonly IDialogService _dialogService;\n\n /// \n /// Gets the section name that this applier handles.\n /// \n public string SectionName => \"Customize\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n /// The view model refresher.\n /// The property updater.\n /// The theme service.\n /// The dialog service.\n public CustomizeConfigurationApplier(\n IServiceProvider serviceProvider,\n ILogService logService,\n IViewModelRefresher viewModelRefresher,\n IConfigurationPropertyUpdater propertyUpdater,\n IThemeService themeService,\n IDialogService dialogService)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _viewModelRefresher = viewModelRefresher ?? throw new ArgumentNullException(nameof(viewModelRefresher));\n _propertyUpdater = propertyUpdater ?? throw new ArgumentNullException(nameof(propertyUpdater));\n _themeService = themeService ?? throw new ArgumentNullException(nameof(themeService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n }\n\n /// \n /// Applies the configuration to the Customize section.\n /// \n /// The configuration file to apply.\n /// True if any items were updated, false otherwise.\n public async Task ApplyConfigAsync(ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Applying configuration to CustomizeViewModel\");\n \n var viewModel = _serviceProvider.GetService();\n if (viewModel == null)\n {\n _logService.Log(LogLevel.Warning, \"CustomizeViewModel not available\");\n return false;\n }\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, \"CustomizeViewModel not initialized, initializing now\");\n await viewModel.InitializeCommand.ExecuteAsync(null);\n }\n \n int totalUpdatedCount = 0;\n \n // Handle Windows Theme customizations\n totalUpdatedCount += await ApplyWindowsThemeCustomizations(viewModel, configFile);\n \n // Apply the configuration directly to the view model's items\n int itemsUpdatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Items, configFile);\n totalUpdatedCount += itemsUpdatedCount;\n \n _logService.Log(LogLevel.Info, $\"Updated {totalUpdatedCount} items in CustomizeViewModel\");\n \n // Refresh the UI\n await _viewModelRefresher.RefreshViewModelAsync(viewModel);\n \n // After applying all configuration settings, prompt for cleaning taskbar and Start Menu\n await PromptForCleaningTaskbarAndStartMenu(viewModel);\n \n return totalUpdatedCount > 0;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying Customize configuration: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Prompts the user to clean the taskbar and Start Menu after configuration import.\n /// \n /// The customize view model.\n /// A task representing the asynchronous operation.\n private async Task PromptForCleaningTaskbarAndStartMenu(CustomizeViewModel viewModel)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Prompting for cleaning taskbar and Start Menu\");\n \n // Prompt for cleaning taskbar\n if (viewModel.TaskbarSettings != null)\n {\n // Use Application.Current.Dispatcher to ensure we're on the UI thread\n bool? cleanTaskbarResult = await Application.Current.Dispatcher.InvokeAsync(() => {\n return CustomDialog.ShowConfirmation(\n \"Clean Taskbar\",\n \"Do you want to clean the taskbar?\",\n new List { \"Cleaning the taskbar will remove pinned items and reset it to default settings.\" }, // Put message in the middle section\n \"\" // Empty footer\n );\n });\n \n bool cleanTaskbar = cleanTaskbarResult == true;\n \n if (cleanTaskbar)\n {\n _logService.Log(LogLevel.Info, \"User chose to clean the taskbar\");\n \n // Execute the clean taskbar command\n if (viewModel.TaskbarSettings.CleanTaskbarCommand != null && \n viewModel.TaskbarSettings.CleanTaskbarCommand.CanExecute(null))\n {\n await viewModel.TaskbarSettings.CleanTaskbarCommand.ExecuteAsync(null);\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"CleanTaskbarCommand not available\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Info, \"User chose not to clean the taskbar\");\n }\n }\n \n // Prompt for cleaning Start Menu\n if (viewModel.StartMenuSettings != null)\n {\n // Use Application.Current.Dispatcher to ensure we're on the UI thread\n bool? cleanStartMenuResult = await Application.Current.Dispatcher.InvokeAsync(() => {\n return CustomDialog.ShowConfirmation(\n \"Clean Start Menu\",\n \"Do you want to clean the Start Menu?\",\n new List { \"Cleaning the Start Menu will remove pinned items and reset it to default settings.\" }, // Put message in the middle section\n \"\" // Empty footer\n );\n });\n \n bool cleanStartMenu = cleanStartMenuResult == true;\n \n if (cleanStartMenu)\n {\n _logService.Log(LogLevel.Info, \"User chose to clean the Start Menu\");\n \n // Execute the clean Start Menu command\n if (viewModel.StartMenuSettings.CleanStartMenuCommand != null && \n viewModel.StartMenuSettings.CleanStartMenuCommand.CanExecute(null))\n {\n await viewModel.StartMenuSettings.CleanStartMenuCommand.ExecuteAsync(null);\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"CleanStartMenuCommand not available\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Info, \"User chose not to clean the Start Menu\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error prompting for cleaning taskbar and Start Menu: {ex.Message}\");\n }\n }\n\n private async Task ApplyWindowsThemeCustomizations(CustomizeViewModel viewModel, ConfigurationFile configFile)\n {\n int updatedCount = 0;\n \n try\n {\n // Get the WindowsThemeSettings property from the view model\n var windowsThemeViewModel = viewModel.WindowsThemeSettings;\n if (windowsThemeViewModel == null)\n {\n _logService.Log(LogLevel.Warning, \"WindowsThemeSettings not found in CustomizeViewModel\");\n return 0;\n }\n \n _logService.Log(LogLevel.Info, \"Found WindowsThemeSettings, checking for Theme Selector item\");\n \n // Check if there's a Theme Selector item in the config file\n var themeItem = configFile.Items?.FirstOrDefault(item =>\n (item.Name?.Contains(\"Windows Theme\") == true ||\n item.Name?.Contains(\"Theme Selector\") == true ||\n item.Name?.Contains(\"Choose Your Mode\") == true ||\n (item.CustomProperties.TryGetValue(\"Id\", out var id) && id?.ToString() == \"ThemeSelector\")));\n \n if (themeItem != null)\n {\n _logService.Log(LogLevel.Info, $\"Found Theme Selector item: {themeItem.Name}\");\n \n string newSelectedTheme = null;\n \n // Try to get SelectedTheme from CustomProperties first (preferred method)\n if (themeItem.CustomProperties.TryGetValue(\"SelectedTheme\", out var selectedTheme) && selectedTheme != null)\n {\n newSelectedTheme = selectedTheme.ToString();\n _logService.Log(LogLevel.Info, $\"Found SelectedTheme in CustomProperties: {newSelectedTheme}\");\n }\n // If not available, try to use SelectedValue directly\n else if (!string.IsNullOrEmpty(themeItem.SelectedValue))\n {\n newSelectedTheme = themeItem.SelectedValue;\n _logService.Log(LogLevel.Info, $\"Using SelectedValue directly: {newSelectedTheme}\");\n }\n // As a last resort, try to derive it from SliderValue (for backward compatibility)\n else if (themeItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int sliderValueInt = Convert.ToInt32(sliderValue);\n newSelectedTheme = sliderValueInt == 1 ? \"Dark Mode\" : \"Light Mode\";\n _logService.Log(LogLevel.Info, $\"Derived SelectedTheme from SliderValue {sliderValueInt}: {newSelectedTheme}\");\n }\n \n if (!string.IsNullOrEmpty(newSelectedTheme))\n {\n _logService.Log(LogLevel.Info, $\"Updating theme settings in view model to: {newSelectedTheme}\");\n \n // Store the current state of the view model\n bool currentIsDarkMode = windowsThemeViewModel.IsDarkModeEnabled;\n string currentTheme = windowsThemeViewModel.SelectedTheme;\n \n // Update the view model properties to trigger the property change handlers\n // This will show the wallpaper dialog through the normal UI flow\n try\n {\n // Update the IsDarkModeEnabled property first\n bool isDarkMode = newSelectedTheme == \"Dark Mode\";\n \n _logService.Log(LogLevel.Info, $\"Setting IsDarkModeEnabled to {isDarkMode}\");\n windowsThemeViewModel.IsDarkModeEnabled = isDarkMode;\n \n // Then update the SelectedTheme property\n _logService.Log(LogLevel.Info, $\"Setting SelectedTheme to {newSelectedTheme}\");\n windowsThemeViewModel.SelectedTheme = newSelectedTheme;\n \n // The property change handlers in WindowsThemeCustomizationsViewModel will\n // show the wallpaper dialog and apply the theme\n \n _logService.Log(LogLevel.Success, $\"Successfully triggered theme change UI flow for: {newSelectedTheme}\");\n updatedCount++;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating theme settings in view model: {ex.Message}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not determine SelectedTheme from config item\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Theme Selector item not found in config file\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying Windows theme customizations: {ex.Message}\");\n }\n \n return updatedCount;\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/IconNameToSymbolConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing Winhance.WPF.Features.Common.Resources;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts an icon name to a Material Symbols Unicode character.\n /// \n public class IconNameToSymbolConverter : IValueConverter\n {\n public static IconNameToSymbolConverter Instance { get; } = new IconNameToSymbolConverter();\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is string iconName)\n {\n return MaterialSymbols.GetIcon(iconName);\n }\n \n return \"?\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/ConfigurationCollectorService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Customize.ViewModels;\nusing Winhance.WPF.Features.Optimize.ViewModels;\nusing Winhance.WPF.Features.SoftwareApps.Models;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for collecting configuration settings from different view models.\n /// \n public class ConfigurationCollectorService\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n\n /// \n /// A wrapper class that implements ISettingItem for Power Plan settings\n /// \n private class PowerPlanSettingItem : ISettingItem\n {\n private readonly ConfigurationItem _configItem;\n private readonly object _originalItem;\n private string _id;\n private string _name;\n private string _description;\n private bool _isSelected;\n private string _groupName;\n private bool _isVisible;\n private ControlType _controlType;\n private int _sliderValue;\n\n public PowerPlanSettingItem(ConfigurationItem configItem, object originalItem)\n {\n _configItem = configItem;\n _originalItem = originalItem;\n \n // Initialize properties from the ConfigurationItem\n _id = _configItem.CustomProperties.TryGetValue(\"Id\", out var id) ? id?.ToString() : \"PowerPlanComboBox\";\n _name = _configItem.Name;\n _description = _configItem.CustomProperties.TryGetValue(\"Description\", out var desc) ? desc?.ToString() : \"Power Plan setting\";\n _isSelected = _configItem.IsSelected;\n _groupName = _configItem.CustomProperties.TryGetValue(\"GroupName\", out var group) ? group?.ToString() : \"Power Management\";\n _isVisible = true;\n _controlType = ControlType.ComboBox;\n _sliderValue = _configItem.CustomProperties.TryGetValue(\"SliderValue\", out var value) ? Convert.ToInt32(value) : 0;\n \n // Ensure the ConfigurationItem has the correct format\n // Make sure SelectedValue is set properly\n if (_configItem.SelectedValue == null)\n {\n // Try to get it from PowerPlanOptions if available\n if (_configItem.CustomProperties.TryGetValue(\"PowerPlanOptions\", out var options) &&\n options is List powerPlanOptions &&\n powerPlanOptions.Count > 0 &&\n _configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int index = Convert.ToInt32(sliderValue);\n if (index >= 0 && index < powerPlanOptions.Count)\n {\n _configItem.SelectedValue = powerPlanOptions[index];\n }\n }\n }\n \n // Always ensure SelectedValue is set based on SliderValue if it's still null\n if (_configItem.SelectedValue == null && _configItem.CustomProperties.TryGetValue(\"SliderValue\", out var sv))\n {\n int index = Convert.ToInt32(sv);\n if (_configItem.CustomProperties.TryGetValue(\"PowerPlanOptions\", out var opt) &&\n opt is List planOptions &&\n planOptions.Count > index && index >= 0)\n {\n _configItem.SelectedValue = planOptions[index];\n }\n else\n {\n // Fallback to default power plan names if PowerPlanOptions is not available\n string[] defaultOptions = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n if (index >= 0 && index < defaultOptions.Length)\n {\n _configItem.SelectedValue = defaultOptions[index];\n }\n }\n }\n \n // Initialize other required properties\n Dependencies = new List();\n IsUpdatingFromCode = false;\n ApplySettingCommand = null;\n }\n\n // Properties with getters and setters\n public string Id { get => _id; set => _id = value; }\n public string Name { get => _name; set => _name = value; }\n public string Description { get => _description; set => _description = value; }\n public bool IsSelected { get => _isSelected; set => _isSelected = value; }\n public string GroupName { get => _groupName; set => _groupName = value; }\n public bool IsVisible { get => _isVisible; set => _isVisible = value; }\n public ControlType ControlType { get => _controlType; set => _controlType = value; }\n public int SliderValue { get => _sliderValue; set => _sliderValue = value; }\n \n // Additional required properties\n public List Dependencies { get; set; }\n public bool IsUpdatingFromCode { get; set; }\n public System.Windows.Input.ICommand ApplySettingCommand { get; set; }\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n public ConfigurationCollectorService(\n IServiceProvider serviceProvider,\n ILogService logService)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Collects settings from all view models.\n /// \n /// A dictionary of section names and their settings.\n public async Task>> CollectAllSettingsAsync()\n {\n var sectionSettings = new Dictionary>();\n\n // Get all view models from the service provider\n var windowsAppsViewModel = _serviceProvider.GetService();\n var externalAppsViewModel = _serviceProvider.GetService();\n var customizeViewModel = _serviceProvider.GetService();\n var optimizeViewModel = _serviceProvider.GetService();\n\n // Add settings from WindowsAppsViewModel\n if (windowsAppsViewModel != null)\n {\n await CollectWindowsAppsSettings(windowsAppsViewModel, sectionSettings);\n }\n\n // Add settings from ExternalAppsViewModel\n if (externalAppsViewModel != null)\n {\n await CollectExternalAppsSettings(externalAppsViewModel, sectionSettings);\n }\n\n // Add settings from CustomizeViewModel\n if (customizeViewModel != null)\n {\n await CollectCustomizeSettings(customizeViewModel, sectionSettings);\n }\n\n // Add settings from OptimizeViewModel\n if (optimizeViewModel != null)\n {\n await CollectOptimizeSettings(optimizeViewModel, sectionSettings);\n }\n\n return sectionSettings;\n }\n\n private async Task CollectWindowsAppsSettings(WindowsAppsViewModel viewModel, Dictionary> sectionSettings)\n {\n try\n {\n _logService.Log(LogLevel.Debug, \"Collecting settings from WindowsAppsViewModel\");\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"WindowsAppsViewModel not initialized, loading items\");\n await viewModel.LoadItemsAsync();\n }\n \n // Convert each WindowsApp to WindowsAppSettingItem\n var windowsAppSettingItems = new List();\n \n foreach (var item in viewModel.Items)\n {\n if (item is WindowsApp windowsApp)\n {\n windowsAppSettingItems.Add(new WindowsAppSettingItem(windowsApp));\n _logService.Log(LogLevel.Debug, $\"Added WindowsAppSettingItem for {windowsApp.Name}\");\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Created {windowsAppSettingItems.Count} WindowsAppSettingItems\");\n \n // Always add WindowsApps to sectionSettings, even if empty\n sectionSettings[\"WindowsApps\"] = windowsAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added WindowsApps section with {windowsAppSettingItems.Count} items\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error collecting WindowsApps settings: {ex.Message}\");\n \n // Create some default WindowsApps as fallback\n var defaultApps = new[]\n {\n new WindowsApp\n {\n Name = \"Microsoft Edge\",\n PackageName = \"Microsoft.MicrosoftEdge\",\n IsSelected = true,\n Description = \"Microsoft Edge browser\"\n },\n new WindowsApp\n {\n Name = \"Calculator\",\n PackageName = \"Microsoft.WindowsCalculator\",\n IsSelected = true,\n Description = \"Windows Calculator app\"\n },\n new WindowsApp\n {\n Name = \"Photos\",\n PackageName = \"Microsoft.Windows.Photos\",\n IsSelected = true,\n Description = \"Windows Photos app\"\n }\n };\n \n var defaultWindowsAppSettingItems = new List();\n foreach (var app in defaultApps)\n {\n defaultWindowsAppSettingItems.Add(new WindowsAppSettingItem(app));\n }\n \n // Always add WindowsApps to sectionSettings, even if using defaults\n sectionSettings[\"WindowsApps\"] = defaultWindowsAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added WindowsApps section with {defaultWindowsAppSettingItems.Count} default items\");\n }\n }\n\n private async Task CollectExternalAppsSettings(ExternalAppsViewModel viewModel, Dictionary> sectionSettings)\n {\n try\n {\n _logService.Log(LogLevel.Debug, \"Collecting settings from ExternalAppsViewModel\");\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"ExternalAppsViewModel not initialized, loading items\");\n await viewModel.LoadItemsAsync();\n }\n \n // Convert each ExternalApp to ExternalAppSettingItem\n var externalAppSettingItems = new List();\n \n foreach (var item in viewModel.Items)\n {\n if (item is ExternalApp externalApp)\n {\n externalAppSettingItems.Add(new ExternalAppSettingItem(externalApp));\n _logService.Log(LogLevel.Debug, $\"Added ExternalAppSettingItem for {externalApp.Name}\");\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Created {externalAppSettingItems.Count} ExternalAppSettingItems\");\n \n // Add the settings to the dictionary\n sectionSettings[\"ExternalApps\"] = externalAppSettingItems;\n _logService.Log(LogLevel.Info, $\"Added ExternalApps section with {externalAppSettingItems.Count} items\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error collecting ExternalApps settings: {ex.Message}\");\n \n // Add an empty list as fallback\n sectionSettings[\"ExternalApps\"] = new List();\n _logService.Log(LogLevel.Info, \"Added empty ExternalApps section due to error\");\n }\n }\n\n private async Task CollectCustomizeSettings(CustomizeViewModel viewModel, Dictionary> sectionSettings)\n {\n try\n {\n _logService.Log(LogLevel.Debug, \"Collecting settings from CustomizeViewModel\");\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"CustomizeViewModel not initialized, loading items\");\n await viewModel.LoadItemsAsync();\n }\n \n // Collect settings directly\n var customizeItems = new List();\n \n foreach (var item in viewModel.Items)\n {\n if (item is ISettingItem settingItem)\n {\n // Skip the DarkModeToggle item to avoid conflicts with ThemeSelector\n if (settingItem.Id == \"DarkModeToggle\")\n {\n _logService.Log(LogLevel.Debug, $\"Skipping DarkModeToggle item to avoid conflicts with ThemeSelector\");\n continue;\n }\n \n // Special handling for Windows Theme / Choose Your Mode\n if (settingItem.Id == \"ThemeSelector\" ||\n settingItem.Name.Contains(\"Windows Theme\") ||\n settingItem.Name.Contains(\"Theme Selector\") ||\n settingItem.Name.Contains(\"Choose Your Mode\"))\n {\n // Ensure it has the correct ControlType and properties for ComboBox\n if (settingItem is ApplicationSettingItem applicationSetting)\n {\n applicationSetting.ControlType = ControlType.ComboBox;\n \n // Get the SelectedTheme from the RegistrySetting if available\n if (applicationSetting.RegistrySetting?.CustomProperties != null &&\n applicationSetting.RegistrySetting.CustomProperties.ContainsKey(\"SelectedTheme\"))\n {\n var selectedTheme = applicationSetting.RegistrySetting.CustomProperties[\"SelectedTheme\"]?.ToString();\n _logService.Log(LogLevel.Debug, $\"Found SelectedTheme in RegistrySetting: {selectedTheme}\");\n }\n \n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ComboBox for Theme Selector\");\n }\n else if (settingItem is ApplicationSettingViewModel applicationViewModel)\n {\n applicationViewModel.ControlType = ControlType.ComboBox;\n \n // Ensure SelectedValue is set based on SelectedTheme if available\n var selectedThemeProperty = applicationViewModel.GetType().GetProperty(\"SelectedTheme\");\n var selectedValueProperty = applicationViewModel.GetType().GetProperty(\"SelectedValue\");\n \n if (selectedThemeProperty != null && selectedValueProperty != null)\n {\n var selectedTheme = selectedThemeProperty.GetValue(applicationViewModel)?.ToString();\n if (!string.IsNullOrEmpty(selectedTheme))\n {\n selectedValueProperty.SetValue(applicationViewModel, selectedTheme);\n }\n }\n \n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ComboBox for Theme Selector (ViewModel) and ensured SelectedValue is set\");\n }\n else if (settingItem is ApplicationSettingItem customizationSetting)\n {\n customizationSetting.ControlType = ControlType.ComboBox;\n \n // Get the SelectedTheme from the RegistrySetting if available\n if (customizationSetting.RegistrySetting?.CustomProperties != null &&\n customizationSetting.RegistrySetting.CustomProperties.ContainsKey(\"SelectedTheme\"))\n {\n var selectedTheme = customizationSetting.RegistrySetting.CustomProperties[\"SelectedTheme\"]?.ToString();\n _logService.Log(LogLevel.Debug, $\"Found SelectedTheme in RegistrySetting: {selectedTheme}\");\n }\n \n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ComboBox for Theme Selector (CustomizationSetting)\");\n }\n }\n \n customizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item for {settingItem.Name}\");\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Collected {customizeItems.Count} customize items\");\n \n // Add the settings to the dictionary\n sectionSettings[\"Customize\"] = customizeItems;\n _logService.Log(LogLevel.Info, $\"Added Customize section with {customizeItems.Count} items\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error collecting Customize settings: {ex.Message}\");\n \n // Add an empty list as fallback\n sectionSettings[\"Customize\"] = new List();\n _logService.Log(LogLevel.Info, \"Added empty Customize section due to error\");\n }\n }\n\n private async Task CollectOptimizeSettings(OptimizeViewModel viewModel, Dictionary> sectionSettings)\n {\n try\n {\n _logService.Log(LogLevel.Debug, \"Collecting settings from OptimizeViewModel\");\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Debug, \"OptimizeViewModel not initialized, initializing now\");\n await viewModel.InitializeCommand.ExecuteAsync(null);\n _logService.Log(LogLevel.Debug, \"OptimizeViewModel initialized\");\n }\n \n // Force load items even if already initialized to ensure we have the latest data\n _logService.Log(LogLevel.Debug, \"Loading OptimizeViewModel items\");\n await viewModel.LoadItemsAsync();\n _logService.Log(LogLevel.Debug, $\"OptimizeViewModel items loaded, count: {viewModel.Items?.Count ?? 0}\");\n \n // Collect settings directly\n var optimizeItems = new List();\n \n // First check if Items collection has any settings\n if (viewModel.Items != null && viewModel.Items.Count > 0)\n {\n foreach (var item in viewModel.Items)\n {\n if (item is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Items collection: {settingItem.Name}\");\n }\n }\n }\n \n // If we didn't get any items from the Items collection, try to collect from child view models directly\n if (optimizeItems.Count == 0)\n {\n _logService.Log(LogLevel.Debug, \"No items found in Items collection, collecting from child view models\");\n \n // Collect from GamingandPerformanceOptimizationsViewModel\n if (viewModel.GamingandPerformanceOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.GamingandPerformanceOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Gaming: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from PrivacyOptimizationsViewModel\n if (viewModel.PrivacyOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.PrivacyOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Privacy: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from UpdateOptimizationsViewModel\n if (viewModel.UpdateOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.UpdateOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Updates: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from PowerSettingsViewModel\n if (viewModel.PowerSettingsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.PowerSettingsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n // Special handling for Power Plan\n if (settingItem.Id == \"PowerPlanComboBox\" || settingItem.Name.Contains(\"Power Plan\"))\n {\n // Ensure it has the correct ControlType\n if (settingItem is ApplicationSettingItem applicationSetting)\n {\n applicationSetting.ControlType = ControlType.ComboBox;\n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ComboBox for Power Plan\");\n \n // Get the current power plan value from the view model\n if (viewModel.PowerSettingsViewModel != null)\n {\n // Set the SliderValue to the current power plan index\n int powerPlanIndex = viewModel.PowerSettingsViewModel.PowerPlanValue;\n applicationSetting.SliderValue = powerPlanIndex;\n _logService.Log(LogLevel.Debug, $\"Set SliderValue to {powerPlanIndex} for Power Plan\");\n \n // Instead of replacing the item, update its properties\n applicationSetting.ControlType = ControlType.ComboBox;\n applicationSetting.SliderValue = powerPlanIndex;\n \n // Create a separate ConfigurationItem for the config file\n var configItem = new ConfigurationItem\n {\n Name = \"Power Plan\", // Use a consistent name\n IsSelected = true, // Always enable the Power Plan\n ControlType = ControlType.ComboBox,\n CustomProperties = new Dictionary\n {\n { \"Id\", \"PowerPlanComboBox\" }, // Use a consistent ID\n { \"GroupName\", \"Power Management\" },\n { \"Description\", \"Select power plan for your system\" },\n { \"SliderValue\", powerPlanIndex }\n }\n };\n \n // Set the SelectedValue to the current power plan name\n if (powerPlanIndex >= 0 && powerPlanIndex < viewModel.PowerSettingsViewModel.PowerPlanLabels.Count)\n {\n string powerPlanName = viewModel.PowerSettingsViewModel.PowerPlanLabels[powerPlanIndex];\n \n // Set SelectedValue at the top level (this is what appears in the config file)\n configItem.SelectedValue = powerPlanName;\n \n // Add PowerPlanOptions to CustomProperties (similar to ThemeOptions in Windows Theme)\n configItem.CustomProperties[\"PowerPlanOptions\"] = viewModel.PowerSettingsViewModel.PowerPlanLabels.ToList();\n _logService.Log(LogLevel.Debug, $\"Set SelectedValue to {powerPlanName} for Power Plan ConfigItem\");\n }\n \n // Add this ConfigurationItem directly to the optimizeItems collection\n // We'll create a wrapper that implements ISettingItem\n var powerPlanSettingItem = new PowerPlanSettingItem(configItem, applicationSetting);\n \n // Add it to the collection if it doesn't already exist\n bool exists = false;\n foreach (var item in optimizeItems)\n {\n if (item is PowerPlanSettingItem)\n {\n exists = true;\n break;\n }\n }\n \n if (!exists)\n {\n optimizeItems.Add(powerPlanSettingItem);\n _logService.Log(LogLevel.Debug, $\"Added PowerPlanSettingItem to optimizeItems\");\n }\n }\n }\n else if (settingItem is ApplicationSettingViewModel applicationViewModel)\n {\n applicationViewModel.ControlType = ControlType.ComboBox;\n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ComboBox for Power Plan (ViewModel)\");\n \n // Get the current power plan value from the view model\n if (viewModel.PowerSettingsViewModel != null)\n {\n // Set the SliderValue to the current power plan index\n int powerPlanIndex = viewModel.PowerSettingsViewModel.PowerPlanValue;\n applicationViewModel.SliderValue = powerPlanIndex;\n _logService.Log(LogLevel.Debug, $\"Set SliderValue to {powerPlanIndex} for Power Plan (ViewModel)\");\n \n // Instead of replacing the item, update its properties\n applicationViewModel.ControlType = ControlType.ComboBox;\n applicationViewModel.SliderValue = powerPlanIndex;\n \n // Create a separate ConfigurationItem for the config file\n var configItem = new ConfigurationItem\n {\n Name = \"Power Plan\", // Use a consistent name\n IsSelected = true, // Always enable the Power Plan\n ControlType = ControlType.ComboBox,\n CustomProperties = new Dictionary\n {\n { \"Id\", \"PowerPlanComboBox\" }, // Use a consistent ID\n { \"GroupName\", \"Power Management\" },\n { \"Description\", \"Select power plan for your system\" },\n { \"SliderValue\", powerPlanIndex }\n }\n };\n \n // Set the SelectedValue to the current power plan name\n if (powerPlanIndex >= 0 && powerPlanIndex < viewModel.PowerSettingsViewModel.PowerPlanLabels.Count)\n {\n string powerPlanName = viewModel.PowerSettingsViewModel.PowerPlanLabels[powerPlanIndex];\n \n // Set SelectedValue at the top level (this is what appears in the config file)\n configItem.SelectedValue = powerPlanName;\n \n // Add PowerPlanOptions to CustomProperties (similar to ThemeOptions in Windows Theme)\n configItem.CustomProperties[\"PowerPlanOptions\"] = viewModel.PowerSettingsViewModel.PowerPlanLabels.ToList();\n _logService.Log(LogLevel.Debug, $\"Set SelectedValue to {powerPlanName} for Power Plan ConfigItem (ViewModel)\");\n }\n \n // Add this ConfigurationItem directly to the optimizeItems collection\n // We'll create a wrapper that implements ISettingItem\n var powerPlanSettingItem = new PowerPlanSettingItem(configItem, applicationViewModel);\n \n // Add it to the collection if it doesn't already exist\n bool exists = false;\n foreach (var item in optimizeItems)\n {\n if (item is PowerPlanSettingItem)\n {\n exists = true;\n break;\n }\n }\n \n if (!exists)\n {\n optimizeItems.Add(powerPlanSettingItem);\n _logService.Log(LogLevel.Debug, $\"Added PowerPlanSettingItem to optimizeItems (ViewModel)\");\n }\n }\n }\n }\n \n // Skip adding the original Power Plan item since we've already added our custom PowerPlanSettingItem\n if (!(settingItem.Id == \"PowerPlanComboBox\" || settingItem.Name.Contains(\"Power Plan\")))\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Power: {settingItem.Name}\");\n }\n else\n {\n _logService.Log(LogLevel.Debug, $\"Skipped adding original Power Plan item: {settingItem.Name}\");\n }\n }\n }\n }\n \n // Collect from ExplorerOptimizationsViewModel\n if (viewModel.ExplorerOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.ExplorerOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Explorer: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from NotificationOptimizationsViewModel\n if (viewModel.NotificationOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.NotificationOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Notifications: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from SoundOptimizationsViewModel\n if (viewModel.SoundOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.SoundOptimizationsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Sound: {settingItem.Name}\");\n }\n }\n }\n \n // Collect from WindowsSecuritySettingsViewModel\n if (viewModel.WindowsSecuritySettingsViewModel?.Settings != null)\n {\n foreach (var setting in viewModel.WindowsSecuritySettingsViewModel.Settings)\n {\n if (setting is ISettingItem settingItem)\n {\n // Special handling for UAC Slider\n if (settingItem.Id == \"UACSlider\" || settingItem.Name.Contains(\"User Account Control\"))\n {\n // Ensure it has the correct ControlType\n if (settingItem is ApplicationSettingItem applicationSetting)\n {\n applicationSetting.ControlType = ControlType.ThreeStateSlider;\n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ThreeStateSlider for UAC Slider\");\n }\n else if (settingItem is ApplicationSettingViewModel applicationViewModel)\n {\n applicationViewModel.ControlType = ControlType.ThreeStateSlider;\n _logService.Log(LogLevel.Debug, $\"Forced ControlType to ThreeStateSlider for UAC Slider (ViewModel)\");\n }\n }\n \n optimizeItems.Add(settingItem);\n _logService.Log(LogLevel.Debug, $\"Added setting item from Security: {settingItem.Name}\");\n }\n }\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Collected {optimizeItems.Count} optimize items\");\n \n // Always create a standalone Power Plan item and add it directly to the configuration file\n if (viewModel.PowerSettingsViewModel != null)\n {\n try\n {\n // Get the current power plan index and name\n int powerPlanIndex = viewModel.PowerSettingsViewModel.PowerPlanValue;\n string powerPlanName = null;\n \n if (powerPlanIndex >= 0 && powerPlanIndex < viewModel.PowerSettingsViewModel.PowerPlanLabels.Count)\n {\n powerPlanName = viewModel.PowerSettingsViewModel.PowerPlanLabels[powerPlanIndex];\n }\n \n // Create a ConfigurationItem for the Power Plan\n var configItem = new ConfigurationItem\n {\n Name = \"Power Plan\",\n PackageName = null,\n IsSelected = true,\n ControlType = ControlType.ComboBox,\n SelectedValue = powerPlanName, // Set SelectedValue directly\n CustomProperties = new Dictionary\n {\n { \"Id\", \"PowerPlanComboBox\" },\n { \"GroupName\", \"Power Management\" },\n { \"Description\", \"Select power plan for your system\" },\n { \"SliderValue\", powerPlanIndex },\n { \"PowerPlanOptions\", viewModel.PowerSettingsViewModel.PowerPlanLabels.ToList() }\n }\n };\n \n // Log the configuration item for debugging\n _logService.Log(LogLevel.Info, $\"Created Power Plan configuration item with SelectedValue: {powerPlanName}, SliderValue: {powerPlanIndex}\");\n _logService.Log(LogLevel.Info, $\"PowerPlanOptions: {string.Join(\", \", viewModel.PowerSettingsViewModel.PowerPlanLabels)}\");\n \n // Ensure SelectedValue is not null\n if (string.IsNullOrEmpty(configItem.SelectedValue) &&\n configItem.CustomProperties.ContainsKey(\"PowerPlanOptions\") &&\n configItem.CustomProperties[\"PowerPlanOptions\"] is List options &&\n options.Count > powerPlanIndex && powerPlanIndex >= 0)\n {\n configItem.SelectedValue = options[powerPlanIndex];\n _logService.Log(LogLevel.Info, $\"Set SelectedValue to {configItem.SelectedValue} from PowerPlanOptions\");\n }\n \n // Add the item directly to the configuration file\n var configService = _serviceProvider.GetService();\n if (configService != null)\n {\n // Use reflection to access the ConfigurationFile\n var configFileProperty = configService.GetType().GetProperty(\"CurrentConfiguration\");\n if (configFileProperty != null)\n {\n var configFile = configFileProperty.GetValue(configService) as ConfigurationFile;\n if (configFile != null && configFile.Items != null)\n {\n // Remove any existing Power Plan items\n configFile.Items.RemoveAll(item =>\n item.Name == \"Power Plan\" ||\n (item.CustomProperties != null && item.CustomProperties.TryGetValue(\"Id\", out var id) && id?.ToString() == \"PowerPlanComboBox\"));\n \n // Add the new Power Plan item\n configFile.Items.Add(configItem);\n _logService.Log(LogLevel.Info, $\"Added Power Plan item directly to the configuration file with SelectedValue: {powerPlanName}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not access ConfigurationFile.Items\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not access CurrentConfiguration property\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not get IConfigurationService from service provider\");\n }\n \n // Also create a wrapper that implements ISettingItem for the optimizeItems collection\n var powerPlanSettingItem = new PowerPlanSettingItem(configItem, null);\n \n // Remove any existing Power Plan items from optimizeItems\n optimizeItems.RemoveAll(item =>\n (item is PowerPlanSettingItem) ||\n (item is ApplicationSettingItem settingItem &&\n (settingItem.Id == \"PowerPlanComboBox\" || settingItem.Name.Contains(\"Power Plan\"))));\n \n // Add the new Power Plan item to optimizeItems\n optimizeItems.Add(powerPlanSettingItem);\n _logService.Log(LogLevel.Info, \"Added Power Plan item to optimizeItems\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating Power Plan item: {ex.Message}\");\n }\n }\n \n // Add the settings to the dictionary\n sectionSettings[\"Optimize\"] = optimizeItems;\n _logService.Log(LogLevel.Info, $\"Added Optimize section with {optimizeItems.Count} items\");\n \n // If we still have no items, log a warning\n if (optimizeItems.Count == 0)\n {\n _logService.Log(LogLevel.Warning, \"No optimize items were collected. This may indicate an initialization issue with the OptimizeViewModel or its child view models.\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error collecting Optimize settings: {ex.Message}\");\n \n // Add an empty list as fallback\n sectionSettings[\"Optimize\"] = new List();\n _logService.Log(LogLevel.Info, \"Added empty Optimize section due to error\");\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/StringToMaximizeIconConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing MaterialDesignThemes.Wpf;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class StringToMaximizeIconConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is string iconName)\n {\n switch (iconName)\n {\n case \"WindowMaximize\":\n return PackIconKind.WindowMaximize;\n case \"WindowRestore\":\n return PackIconKind.WindowRestore;\n default:\n return PackIconKind.WindowMaximize;\n }\n }\n \n return PackIconKind.WindowMaximize;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is PackIconKind kind)\n {\n switch (kind)\n {\n case PackIconKind.WindowMaximize:\n return \"WindowMaximize\";\n case PackIconKind.WindowRestore:\n return \"WindowRestore\";\n default:\n return \"WindowMaximize\";\n }\n }\n \n return \"WindowMaximize\";\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/ConfigurationService.cs", "using Microsoft.Win32;\nusing Newtonsoft.Json;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service for saving and loading application configuration files.\n /// \n public class ConfigurationService : IConfigurationService\n {\n private const string FileExtension = \".winhance\";\n private const string FileFilter = \"Winhance Configuration Files|*\" + FileExtension;\n private const string UnifiedFileFilter = \"Winhance Unified Configuration Files|*\" + FileExtension;\n private readonly ILogService _logService;\n \n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public ConfigurationService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Saves a configuration file containing the selected items.\n /// \n /// The type of items to save.\n /// The collection of items to save.\n /// The type of configuration being saved.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n public async Task SaveConfigurationAsync(IEnumerable items, string configType)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Starting to save {configType} configuration\");\n // Create a save file dialog\n var saveFileDialog = new SaveFileDialog\n {\n Filter = FileFilter,\n DefaultExt = FileExtension,\n Title = \"Save Configuration\",\n FileName = $\"{configType}_{DateTime.Now:yyyyMMdd}{FileExtension}\"\n };\n\n // Show the save file dialog\n if (saveFileDialog.ShowDialog() != true)\n {\n _logService.Log(LogLevel.Info, \"Save configuration canceled by user\");\n return false;\n }\n \n _logService.Log(LogLevel.Info, $\"Saving configuration to {saveFileDialog.FileName}\");\n\n // Create a configuration file\n var configFile = new ConfigurationFile\n {\n ConfigType = configType,\n CreatedAt = DateTime.UtcNow,\n Items = new List()\n };\n\n // Add selected items to the configuration file\n foreach (var item in items)\n {\n var properties = item.GetType().GetProperties();\n var nameProperty = properties.FirstOrDefault(p => p.Name == \"Name\");\n var packageNameProperty = properties.FirstOrDefault(p => p.Name == \"PackageName\");\n var isSelectedProperty = properties.FirstOrDefault(p => p.Name == \"IsSelected\");\n var controlTypeProperty = properties.FirstOrDefault(p => p.Name == \"ControlType\");\n var registrySettingProperty = properties.FirstOrDefault(p => p.Name == \"RegistrySetting\");\n var idProperty = properties.FirstOrDefault(p => p.Name == \"Id\");\n\n if (nameProperty != null && isSelectedProperty != null)\n {\n var name = nameProperty.GetValue(item)?.ToString();\n var packageName = packageNameProperty?.GetValue(item)?.ToString();\n var isSelected = (bool)(isSelectedProperty.GetValue(item) ?? false);\n \n // Create the configuration item\n var configItem = new ConfigurationItem\n {\n Name = name,\n PackageName = packageName,\n IsSelected = isSelected\n };\n \n // Add control type if available\n if (controlTypeProperty != null)\n {\n var controlType = controlTypeProperty.GetValue(item);\n if (controlType != null)\n {\n configItem.ControlType = (ControlType)controlType;\n }\n }\n \n // Store the Id in CustomProperties if available\n if (idProperty != null)\n {\n var id = idProperty.GetValue(item);\n if (id != null)\n {\n configItem.CustomProperties[\"Id\"] = id.ToString();\n _logService.Log(LogLevel.Info, $\"Stored Id for {configItem.Name}: {id}\");\n }\n }\n \n // Handle ComboBox and ThreeStateSlider control types\n if (configItem.ControlType == ControlType.ComboBox || configItem.ControlType == ControlType.ThreeStateSlider)\n {\n // For ComboBox, get the selected value\n var selectedThemeProperty = properties.FirstOrDefault(p => p.Name == \"SelectedTheme\");\n if (selectedThemeProperty != null)\n {\n configItem.SelectedValue = selectedThemeProperty.GetValue(item)?.ToString();\n _logService.Log(LogLevel.Info, $\"Setting SelectedValue for {configItem.Name} to '{configItem.SelectedValue}'\");\n }\n else\n {\n // Try to get the value from SliderLabels and SliderValue\n var sliderLabelsProperty = properties.FirstOrDefault(p => p.Name == \"SliderLabels\");\n var sliderValueProperty = properties.FirstOrDefault(p => p.Name == \"SliderValue\");\n \n if (sliderLabelsProperty != null && sliderValueProperty != null)\n {\n var sliderLabels = sliderLabelsProperty.GetValue(item) as System.Collections.IList;\n var sliderValue = sliderValueProperty.GetValue(item);\n \n if (sliderLabels != null && sliderValue != null && Convert.ToInt32(sliderValue) < sliderLabels.Count)\n {\n configItem.SelectedValue = sliderLabels[Convert.ToInt32(sliderValue)]?.ToString();\n _logService.Log(LogLevel.Info, $\"Derived SelectedValue for {configItem.Name} from SliderLabels[{sliderValue}]: '{configItem.SelectedValue}'\");\n }\n }\n }\n \n // Store the SliderValue for ComboBox or ThreeStateSlider\n // Note: In this application, ComboBox controls use SliderValue to store the selected index\n if (configItem.ControlType == ControlType.ComboBox || configItem.ControlType == ControlType.ThreeStateSlider)\n {\n var sliderValueProperty = properties.FirstOrDefault(p => p.Name == \"SliderValue\");\n if (sliderValueProperty != null)\n {\n var sliderValue = sliderValueProperty.GetValue(item);\n if (sliderValue != null)\n {\n configItem.CustomProperties[\"SliderValue\"] = sliderValue;\n _logService.Log(LogLevel.Info, $\"Stored SliderValue for {configItem.ControlType} {configItem.Name}: {sliderValue}\");\n }\n }\n \n // Also store SliderLabels if available\n var sliderLabelsProperty = properties.FirstOrDefault(p => p.Name == \"SliderLabels\");\n if (sliderLabelsProperty != null)\n {\n var sliderLabels = sliderLabelsProperty.GetValue(item) as System.Collections.IList;\n if (sliderLabels != null && sliderLabels.Count > 0)\n {\n // Store the labels as a comma-separated string\n var labelsString = string.Join(\",\", sliderLabels.Cast().Select(l => l.ToString()));\n configItem.CustomProperties[\"SliderLabels\"] = labelsString;\n _logService.Log(LogLevel.Info, $\"Stored SliderLabels for {configItem.ControlType} {configItem.Name}: {labelsString}\");\n \n // For Power Plan, also store the labels as PowerPlanOptions\n if (configItem.Name.Contains(\"Power Plan\") ||\n (configItem.CustomProperties.ContainsKey(\"Id\") &&\n configItem.CustomProperties[\"Id\"]?.ToString() == \"PowerPlanComboBox\"))\n {\n // Store the actual list of options\n configItem.CustomProperties[\"PowerPlanOptions\"] = sliderLabels.Cast().Select(l => l.ToString()).ToList();\n _logService.Log(LogLevel.Info, $\"Stored PowerPlanOptions for {configItem.Name}: {labelsString}\");\n }\n }\n }\n }\n }\n \n // Add custom properties from RegistrySetting if available\n if (registrySettingProperty != null)\n {\n var registrySetting = registrySettingProperty.GetValue(item);\n if (registrySetting != null)\n {\n // Get the CustomProperties property from RegistrySetting\n var customPropertiesProperty = registrySetting.GetType().GetProperty(\"CustomProperties\");\n if (customPropertiesProperty != null)\n {\n var customProperties = customPropertiesProperty.GetValue(registrySetting) as Dictionary;\n if (customProperties != null && customProperties.Count > 0)\n {\n // Copy custom properties to the configuration item\n foreach (var kvp in customProperties)\n {\n configItem.CustomProperties[kvp.Key] = kvp.Value;\n }\n }\n }\n }\n }\n \n // Ensure SelectedValue is set for ComboBox controls\n configItem.EnsureSelectedValueIsSet();\n \n // Add the configuration item to the file\n configFile.Items.Add(configItem);\n }\n }\n\n // Serialize the configuration file to JSON\n var json = JsonConvert.SerializeObject(configFile, Formatting.Indented);\n\n // Write the JSON to the file\n await File.WriteAllTextAsync(saveFileDialog.FileName, json);\n \n _logService.Log(LogLevel.Info, $\"Successfully saved {configType} configuration with {configFile.Items.Count} items to {saveFileDialog.FileName}\");\n \n // Log details about ComboBox items if any\n var comboBoxItems = configFile.Items.Where(i => i.ControlType == ControlType.ComboBox).ToList();\n if (comboBoxItems.Any())\n {\n _logService.Log(LogLevel.Info, $\"Saved {comboBoxItems.Count} ComboBox items:\");\n foreach (var item in comboBoxItems)\n {\n _logService.Log(LogLevel.Info, $\" - {item.Name}: SelectedValue={item.SelectedValue}, CustomProperties={string.Join(\", \", item.CustomProperties.Select(kv => $\"{kv.Key}={kv.Value}\"))}\");\n }\n }\n\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving configuration: {ex.Message}\");\n MessageBox.Show($\"Error saving configuration: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n return false;\n }\n }\n\n /// \n /// Loads a configuration file and returns the configuration file.\n /// \n /// The type of configuration being loaded.\n /// A task representing the asynchronous operation. Returns the configuration file if successful, null otherwise.\n public async Task LoadConfigurationAsync(string configType)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Starting to load {configType} configuration\");\n // Create an open file dialog\n var openFileDialog = new OpenFileDialog\n {\n Filter = FileFilter,\n DefaultExt = FileExtension,\n Title = \"Open Configuration\"\n };\n\n // Show the open file dialog\n if (openFileDialog.ShowDialog() != true)\n {\n _logService.Log(LogLevel.Info, \"Load configuration canceled by user\");\n return null;\n }\n \n _logService.Log(LogLevel.Info, $\"Loading configuration from {openFileDialog.FileName}\");\n\n // Read the JSON from the file\n var json = await File.ReadAllTextAsync(openFileDialog.FileName);\n\n // Deserialize the JSON to a configuration file\n var configFile = JsonConvert.DeserializeObject(json);\n \n // Ensure SelectedValue is set for all items\n foreach (var item in configFile.Items)\n {\n item.EnsureSelectedValueIsSet();\n }\n \n // Process the configuration items to ensure SelectedValue is set for ComboBox and ThreeStateSlider items\n foreach (var item in configFile.Items)\n {\n // Handle ComboBox items\n if (item.ControlType == ControlType.ComboBox && string.IsNullOrEmpty(item.SelectedValue))\n {\n // Try to get the SelectedTheme from CustomProperties\n if (item.CustomProperties.TryGetValue(\"SelectedTheme\", out var selectedTheme) && selectedTheme != null)\n {\n item.SelectedValue = selectedTheme.ToString();\n _logService.Log(LogLevel.Info, $\"Set SelectedValue for ComboBox {item.Name} from CustomProperties: {item.SelectedValue}\");\n }\n // If not available, try to derive it from SliderValue\n else if (item.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int sliderValueInt = Convert.ToInt32(sliderValue);\n item.SelectedValue = sliderValueInt == 1 ? \"Dark Mode\" : \"Light Mode\";\n _logService.Log(LogLevel.Info, $\"Derived SelectedValue for ComboBox {item.Name} from SliderValue: {sliderValueInt} -> {item.SelectedValue}\");\n }\n }\n \n // Handle ThreeStateSlider items\n if (item.ControlType == ControlType.ThreeStateSlider)\n {\n // Ensure SliderValue is available in CustomProperties\n if (item.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int sliderValueInt = Convert.ToInt32(sliderValue);\n \n // Try to derive SelectedValue from SliderLabels if available\n if (item.CustomProperties.TryGetValue(\"SliderLabels\", out var sliderLabelsString) &&\n sliderLabelsString != null)\n {\n var labels = sliderLabelsString.ToString().Split(',');\n if (sliderValueInt >= 0 && sliderValueInt < labels.Length)\n {\n item.SelectedValue = labels[sliderValueInt];\n _logService.Log(LogLevel.Info, $\"Derived SelectedValue for ThreeStateSlider {item.Name} from SliderLabels: {sliderValueInt} -> {item.SelectedValue}\");\n }\n }\n // If no labels available, use a generic approach\n else if (string.IsNullOrEmpty(item.SelectedValue))\n {\n // For UAC slider\n if (item.Name.Contains(\"User Account Control\") || item.Name.Contains(\"UAC\"))\n {\n item.SelectedValue = sliderValueInt switch\n {\n 0 => \"Low\",\n 1 => \"Moderate\",\n 2 => \"High\",\n _ => $\"Level {sliderValueInt}\"\n };\n }\n // For Power Plan slider\n else if (item.Name.Contains(\"Power Plan\"))\n {\n // First try to get the value from PowerPlanOptions if available\n if (item.CustomProperties.TryGetValue(\"PowerPlanOptions\", out var powerPlanOptions))\n {\n // Handle different types of PowerPlanOptions\n if (powerPlanOptions is List options && sliderValueInt >= 0 && sliderValueInt < options.Count)\n {\n item.SelectedValue = options[sliderValueInt];\n _logService.Log(LogLevel.Info, $\"Set SelectedValue for Power Plan from PowerPlanOptions (List): {item.SelectedValue}\");\n }\n else if (powerPlanOptions is Newtonsoft.Json.Linq.JArray jArray && sliderValueInt >= 0 && sliderValueInt < jArray.Count)\n {\n item.SelectedValue = jArray[sliderValueInt]?.ToString();\n _logService.Log(LogLevel.Info, $\"Set SelectedValue for Power Plan from PowerPlanOptions (JArray): {item.SelectedValue}\");\n }\n else\n {\n // If PowerPlanOptions exists but we can't use it, log the issue\n _logService.Log(LogLevel.Warning, $\"PowerPlanOptions exists but couldn't be used. Type: {powerPlanOptions?.GetType().Name}, SliderValue: {sliderValueInt}\");\n \n // Fall back to default values\n item.SelectedValue = sliderValueInt switch\n {\n 0 => \"Balanced\",\n 1 => \"High Performance\",\n 2 => \"Ultimate Performance\",\n _ => $\"Plan {sliderValueInt}\"\n };\n _logService.Log(LogLevel.Info, $\"Set SelectedValue for Power Plan from default mapping: {item.SelectedValue}\");\n \n // Add PowerPlanOptions if it doesn't exist in the right format\n string[] defaultOptions = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n item.CustomProperties[\"PowerPlanOptions\"] = new List(defaultOptions);\n _logService.Log(LogLevel.Info, $\"Added default PowerPlanOptions to CustomProperties\");\n }\n }\n else\n {\n // Fall back to default values\n item.SelectedValue = sliderValueInt switch\n {\n 0 => \"Balanced\",\n 1 => \"High Performance\",\n 2 => \"Ultimate Performance\",\n _ => $\"Plan {sliderValueInt}\"\n };\n _logService.Log(LogLevel.Info, $\"Set SelectedValue for Power Plan from default mapping: {item.SelectedValue}\");\n \n // Add PowerPlanOptions if it doesn't exist\n string[] defaultOptions = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n item.CustomProperties[\"PowerPlanOptions\"] = new List(defaultOptions);\n _logService.Log(LogLevel.Info, $\"Added default PowerPlanOptions to CustomProperties\");\n }\n }\n // Generic approach for other sliders\n else\n {\n item.SelectedValue = $\"Level {sliderValueInt}\";\n }\n \n _logService.Log(LogLevel.Info, $\"Set generic SelectedValue for ThreeStateSlider {item.Name}: {item.SelectedValue}\");\n }\n }\n }\n }\n\n // Verify the configuration type\n if (string.IsNullOrEmpty(configFile.ConfigType))\n {\n _logService.Log(LogLevel.Warning, $\"Configuration type is empty, setting it to {configType}\");\n configFile.ConfigType = configType;\n }\n else if (configFile.ConfigType != configType)\n {\n _logService.Log(LogLevel.Warning, $\"Configuration type mismatch. Expected {configType}, but found {configFile.ConfigType}. Proceeding anyway.\");\n // We'll proceed anyway, as this might be a unified configuration file\n }\n\n _logService.Log(LogLevel.Info, $\"Successfully loaded {configType} configuration with {configFile.Items.Count} items from {openFileDialog.FileName}\");\n \n // Log details about ComboBox items if any\n var comboBoxItems = configFile.Items.Where(i => i.ControlType == ControlType.ComboBox).ToList();\n if (comboBoxItems.Any())\n {\n _logService.Log(LogLevel.Info, $\"Loaded {comboBoxItems.Count} ComboBox items:\");\n foreach (var item in comboBoxItems)\n {\n _logService.Log(LogLevel.Info, $\" - {item.Name}: SelectedValue={item.SelectedValue}, CustomProperties={string.Join(\", \", item.CustomProperties.Select(kv => $\"{kv.Key}={kv.Value}\"))}\");\n }\n }\n\n // Return the configuration file directly\n // The ViewModel will handle matching these with existing items\n return configFile;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading configuration: {ex.Message}\");\n MessageBox.Show($\"Error loading configuration: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n return null;\n }\n }\n\n /// \n /// Saves a unified configuration file containing settings for multiple parts of the application.\n /// \n /// The unified configuration to save.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n public async Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile unifiedConfig)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Starting to save unified configuration\");\n \n // Create a save file dialog\n var saveFileDialog = new SaveFileDialog\n {\n Filter = UnifiedFileFilter,\n DefaultExt = FileExtension,\n Title = \"Save Unified Configuration\",\n FileName = $\"Winhance_Unified_Config_{DateTime.Now:yyyyMMdd}{FileExtension}\"\n };\n \n // Show the save file dialog\n if (saveFileDialog.ShowDialog() != true)\n {\n _logService.Log(LogLevel.Info, \"Save unified configuration canceled by user\");\n return false;\n }\n \n _logService.Log(LogLevel.Info, $\"Saving unified configuration to {saveFileDialog.FileName}\");\n \n // Ensure all sections are included by default\n unifiedConfig.WindowsApps.IsIncluded = true;\n unifiedConfig.ExternalApps.IsIncluded = true;\n unifiedConfig.Customize.IsIncluded = true;\n unifiedConfig.Optimize.IsIncluded = true;\n \n if (unifiedConfig.WindowsApps.Items == null)\n {\n unifiedConfig.WindowsApps.Items = new List();\n }\n \n // Serialize the configuration file to JSON\n var json = JsonConvert.SerializeObject(unifiedConfig, Formatting.Indented);\n \n // Write the JSON to the file\n await File.WriteAllTextAsync(saveFileDialog.FileName, json);\n \n _logService.Log(LogLevel.Info, \"Successfully saved unified configuration\");\n \n // Log details about included sections\n var includedSections = new List { \"WindowsApps\", \"ExternalApps\", \"Customize\", \"Optimize\" };\n _logService.Log(LogLevel.Info, $\"Included sections: {string.Join(\", \", includedSections)}\");\n \n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving unified configuration: {ex.Message}\");\n MessageBox.Show($\"Error saving unified configuration: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n return false;\n }\n }\n\n /// \n /// Loads a unified configuration file.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file if successful, null otherwise.\n public async Task LoadUnifiedConfigurationAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Starting to load unified configuration\");\n \n // Create an open file dialog\n var openFileDialog = new OpenFileDialog\n {\n Filter = UnifiedFileFilter,\n DefaultExt = FileExtension,\n Title = \"Open Unified Configuration\"\n };\n \n // Show the open file dialog\n if (openFileDialog.ShowDialog() != true)\n {\n _logService.Log(LogLevel.Info, \"Load unified configuration canceled by user\");\n return null;\n }\n \n _logService.Log(LogLevel.Info, $\"Loading unified configuration from {openFileDialog.FileName}\");\n \n // Read the JSON from the file\n var json = await File.ReadAllTextAsync(openFileDialog.FileName);\n \n // Deserialize the JSON to a unified configuration file\n var unifiedConfig = JsonConvert.DeserializeObject(json);\n \n // Always ensure WindowsApps are included\n unifiedConfig.WindowsApps.IsIncluded = true;\n if (unifiedConfig.WindowsApps.Items == null)\n {\n unifiedConfig.WindowsApps.Items = new List();\n }\n \n // Log details about included sections\n var includedSections = new List();\n if (unifiedConfig.WindowsApps.IsIncluded) includedSections.Add(\"WindowsApps\");\n if (unifiedConfig.ExternalApps.IsIncluded) includedSections.Add(\"ExternalApps\");\n if (unifiedConfig.Customize.IsIncluded) includedSections.Add(\"Customize\");\n if (unifiedConfig.Optimize.IsIncluded) includedSections.Add(\"Optimize\");\n \n _logService.Log(LogLevel.Info, $\"Loaded unified configuration with sections: {string.Join(\", \", includedSections)}\");\n \n return unifiedConfig;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading unified configuration: {ex.Message}\");\n MessageBox.Show($\"Error loading unified configuration: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n return null;\n }\n }\n\n /// \n /// Creates a unified configuration file from individual configuration sections.\n /// \n /// Dictionary of section names and their corresponding configuration items.\n /// List of section names to include in the unified configuration.\n /// A unified configuration file.\n public UnifiedConfigurationFile CreateUnifiedConfiguration(Dictionary> sections, IEnumerable includedSections)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Creating unified configuration\");\n \n var unifiedConfig = new UnifiedConfigurationFile\n {\n CreatedAt = DateTime.UtcNow\n };\n \n // Convert each section to ConfigurationItems and add to the appropriate section\n foreach (var sectionName in includedSections)\n {\n if (!sections.TryGetValue(sectionName, out var items) || items == null)\n {\n _logService.Log(LogLevel.Warning, $\"Section {sectionName} not found or has no items\");\n continue;\n }\n \n var configItems = ConvertToConfigurationItems(items);\n \n switch (sectionName)\n {\n case \"WindowsApps\":\n unifiedConfig.WindowsApps.IsIncluded = true;\n unifiedConfig.WindowsApps.Items = configItems;\n unifiedConfig.WindowsApps.Description = \"Windows built-in applications\";\n break;\n case \"ExternalApps\":\n unifiedConfig.ExternalApps.IsIncluded = true;\n unifiedConfig.ExternalApps.Items = configItems;\n unifiedConfig.ExternalApps.Description = \"Third-party applications\";\n break;\n case \"Customize\":\n unifiedConfig.Customize.IsIncluded = true;\n unifiedConfig.Customize.Items = configItems;\n unifiedConfig.Customize.Description = \"Windows UI customization settings\";\n break;\n case \"Optimize\":\n unifiedConfig.Optimize.IsIncluded = true;\n unifiedConfig.Optimize.Items = configItems;\n unifiedConfig.Optimize.Description = \"Windows optimization settings\";\n break;\n default:\n _logService.Log(LogLevel.Warning, $\"Unknown section name: {sectionName}\");\n break;\n }\n }\n \n // Always ensure WindowsApps are included, even if they weren't in the sections dictionary\n // or if they didn't have any items\n unifiedConfig.WindowsApps.IsIncluded = true;\n if (unifiedConfig.WindowsApps.Items == null)\n {\n unifiedConfig.WindowsApps.Items = new List();\n }\n if (string.IsNullOrEmpty(unifiedConfig.WindowsApps.Description))\n {\n unifiedConfig.WindowsApps.Description = \"Windows built-in applications\";\n }\n \n _logService.Log(LogLevel.Info, \"Successfully created unified configuration\");\n return unifiedConfig;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating unified configuration: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Extracts a specific section from a unified configuration file.\n /// \n /// The unified configuration file.\n /// The name of the section to extract.\n /// A configuration file containing only the specified section.\n public ConfigurationFile ExtractSectionFromUnifiedConfiguration(UnifiedConfigurationFile unifiedConfig, string sectionName)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Extracting section {sectionName} from unified configuration\");\n \n // Validate inputs\n if (unifiedConfig == null)\n {\n _logService.Log(LogLevel.Error, \"Unified configuration is null\");\n throw new ArgumentNullException(nameof(unifiedConfig));\n }\n \n if (string.IsNullOrEmpty(sectionName))\n {\n _logService.Log(LogLevel.Error, \"Section name is null or empty\");\n throw new ArgumentException(\"Section name cannot be null or empty\", nameof(sectionName));\n }\n \n var configFile = new ConfigurationFile\n {\n ConfigType = sectionName,\n CreatedAt = DateTime.UtcNow,\n Items = new List()\n };\n \n // Get the items from the appropriate section\n switch (sectionName)\n {\n case \"WindowsApps\":\n // Always include WindowsApps, regardless of IsIncluded flag\n configFile.Items = unifiedConfig.WindowsApps?.Items ?? new List();\n break;\n case \"ExternalApps\":\n if (unifiedConfig.ExternalApps?.IsIncluded == true)\n {\n configFile.Items = unifiedConfig.ExternalApps.Items ?? new List();\n }\n break;\n case \"Customize\":\n if (unifiedConfig.Customize?.IsIncluded == true)\n {\n configFile.Items = unifiedConfig.Customize.Items ?? new List();\n }\n break;\n case \"Optimize\":\n if (unifiedConfig.Optimize?.IsIncluded == true)\n {\n configFile.Items = unifiedConfig.Optimize.Items ?? new List();\n }\n break;\n default:\n _logService.Log(LogLevel.Warning, $\"Unknown section name: {sectionName}\");\n break;\n }\n \n // Ensure Items is not null\n if (configFile.Items == null)\n {\n configFile.Items = new List();\n }\n \n _logService.Log(LogLevel.Info, $\"Successfully extracted section {sectionName} with {configFile.Items.Count} items\");\n return configFile;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error extracting section from unified configuration: {ex.Message}\");\n \n // Return an empty configuration file instead of throwing\n var emptyConfigFile = new ConfigurationFile\n {\n ConfigType = sectionName,\n CreatedAt = DateTime.UtcNow,\n Items = new List()\n };\n \n _logService.Log(LogLevel.Info, $\"Returning empty configuration file for section {sectionName}\");\n return emptyConfigFile;\n }\n }\n\n /// \n /// Converts a collection of ISettingItem objects to a list of ConfigurationItem objects.\n /// \n /// The collection of ISettingItem objects to convert.\n /// A list of ConfigurationItem objects.\n private List ConvertToConfigurationItems(IEnumerable items)\n {\n var configItems = new List();\n \n foreach (var item in items)\n {\n var configItem = new ConfigurationItem\n {\n Name = item.Name,\n IsSelected = item.IsSelected,\n ControlType = item.ControlType,\n CustomProperties = new Dictionary()\n };\n \n // Add Id to custom properties\n if (!string.IsNullOrEmpty(item.Id))\n {\n configItem.CustomProperties[\"Id\"] = item.Id;\n }\n \n // Add GroupName to custom properties\n if (!string.IsNullOrEmpty(item.GroupName))\n {\n configItem.CustomProperties[\"GroupName\"] = item.GroupName;\n }\n \n // Add Description to custom properties\n if (!string.IsNullOrEmpty(item.Description))\n {\n configItem.CustomProperties[\"Description\"] = item.Description;\n }\n \n // Handle specific properties based on the item's type\n var itemType = item.GetType();\n var properties = itemType.GetProperties();\n \n // Check for PackageName property\n var packageNameProperty = properties.FirstOrDefault(p => p.Name == \"PackageName\");\n if (packageNameProperty != null)\n {\n configItem.PackageName = packageNameProperty.GetValue(item)?.ToString();\n }\n \n // Check for SelectedValue property\n var selectedValueProperty = properties.FirstOrDefault(p => p.Name == \"SelectedValue\");\n if (selectedValueProperty != null)\n {\n configItem.SelectedValue = selectedValueProperty.GetValue(item)?.ToString();\n }\n \n // Check for SliderValue property\n var sliderValueProperty = properties.FirstOrDefault(p => p.Name == \"SliderValue\");\n if (sliderValueProperty != null)\n {\n var sliderValue = sliderValueProperty.GetValue(item);\n if (sliderValue != null)\n {\n configItem.CustomProperties[\"SliderValue\"] = sliderValue;\n }\n }\n \n // Check for SliderLabels property\n var sliderLabelsProperty = properties.FirstOrDefault(p => p.Name == \"SliderLabels\");\n if (sliderLabelsProperty != null)\n {\n var sliderLabels = sliderLabelsProperty.GetValue(item) as System.Collections.IList;\n if (sliderLabels != null && sliderLabels.Count > 0)\n {\n // Store the labels as a comma-separated string\n var labelsString = string.Join(\",\", sliderLabels.Cast().Select(l => l.ToString()));\n configItem.CustomProperties[\"SliderLabels\"] = labelsString;\n \n // For Power Plan, also store the labels as PowerPlanOptions\n if (item.Name.Contains(\"Power Plan\") || item.Id == \"PowerPlanComboBox\")\n {\n // Store the actual list of options\n configItem.CustomProperties[\"PowerPlanOptions\"] = sliderLabels.Cast().Select(l => l.ToString()).ToList();\n }\n }\n }\n \n // Check for RegistrySetting property\n var registrySettingProperty = properties.FirstOrDefault(p => p.Name == \"RegistrySetting\");\n if (registrySettingProperty != null)\n {\n var registrySetting = registrySettingProperty.GetValue(item);\n if (registrySetting != null)\n {\n // Get the CustomProperties property from RegistrySetting\n var customPropertiesProperty = registrySetting.GetType().GetProperty(\"CustomProperties\");\n if (customPropertiesProperty != null)\n {\n var customProperties = customPropertiesProperty.GetValue(registrySetting) as Dictionary;\n if (customProperties != null && customProperties.Count > 0)\n {\n // Copy custom properties to the configuration item\n foreach (var kvp in customProperties)\n {\n configItem.CustomProperties[kvp.Key] = kvp.Value;\n }\n }\n }\n }\n }\n \n // Ensure SelectedValue is set for ComboBox controls\n configItem.EnsureSelectedValueIsSet();\n \n configItems.Add(configItem);\n }\n \n return configItems;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/RegistryValueStatusConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class RegistryValueStatusConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null)\n return DependencyProperty.UnsetValue;\n\n if (value is RegistrySettingStatus status)\n {\n return status switch\n {\n RegistrySettingStatus.NotApplied => \"Not Applied\",\n RegistrySettingStatus.Applied => \"Applied\",\n RegistrySettingStatus.Modified => \"Modified\",\n RegistrySettingStatus.Error => \"Error\",\n RegistrySettingStatus.Unknown => \"Unknown\",\n _ => \"Unknown\"\n };\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n\n public class RegistryValueStatusToColorConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null)\n return DependencyProperty.UnsetValue;\n\n if (value is RegistrySettingStatus status)\n {\n return status switch\n {\n RegistrySettingStatus.NotApplied => new SolidColorBrush(Colors.Gray),\n RegistrySettingStatus.Applied => new SolidColorBrush(Colors.Green),\n RegistrySettingStatus.Modified => new SolidColorBrush(Colors.Orange),\n RegistrySettingStatus.Error => new SolidColorBrush(Colors.Red),\n RegistrySettingStatus.Unknown => new SolidColorBrush(Colors.Gray),\n _ => new SolidColorBrush(Colors.Gray)\n };\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n\n public class RegistryValueStatusToIconConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null)\n return DependencyProperty.UnsetValue;\n\n if (value is RegistrySettingStatus status)\n {\n return status switch\n {\n RegistrySettingStatus.NotApplied => \"⚪\", // Empty circle\n RegistrySettingStatus.Applied => \"✅\", // Green checkmark\n RegistrySettingStatus.Modified => \"⚠️\", // Warning\n RegistrySettingStatus.Error => \"❌\", // Red X\n RegistrySettingStatus.Unknown => \"❓\", // Question mark\n _ => \"❓\"\n };\n }\n\n return DependencyProperty.UnsetValue;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToReinstallableIconConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing MaterialDesignThemes.Wpf;\n\nnamespace Winhance.WPF.Converters\n{\n /// \n /// Converts a boolean value indicating whether an item can be reinstalled to the appropriate MaterialDesign icon.\n /// \n public class BooleanToReinstallableIconConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // Return the appropriate MaterialDesign PackIconKind\n return (bool)value ? PackIconKind.Sync : PackIconKind.SyncDisabled;\n }\n\n public object ConvertBack(\n object value,\n Type targetType,\n object parameter,\n CultureInfo culture\n )\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BoolToChevronConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing MaterialDesignThemes.Wpf;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class BoolToChevronConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isExpanded)\n {\n return isExpanded ? PackIconKind.ChevronUp : PackIconKind.ChevronDown;\n }\n \n return PackIconKind.ChevronDown;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is PackIconKind kind)\n {\n return kind == PackIconKind.ChevronUp;\n }\n \n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/InverseBooleanToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean value to a Visibility value, with the boolean value inverted.\n /// True becomes Collapsed, False becomes Visible.\n /// \n public class InverseBooleanToVisibilityConverter : IValueConverter\n {\n /// \n /// Converts a boolean value to a Visibility value, with the boolean value inverted.\n /// \n /// The boolean value to convert.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// Visibility.Collapsed if the value is true, Visibility.Visible if the value is false.\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return boolValue ? Visibility.Collapsed : Visibility.Visible;\n }\n \n return Visibility.Visible;\n }\n \n /// \n /// Converts a Visibility value back to a boolean value, with the boolean value inverted.\n /// \n /// The Visibility value to convert back.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// False if the value is Visibility.Visible, true otherwise.\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is Visibility visibility)\n {\n return visibility != Visibility.Visible;\n }\n \n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BoolToArrowConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean value to an arrow character for UI display.\n /// True returns an up arrow, False returns a down arrow.\n /// \n public class BoolToArrowConverter : IValueConverter\n {\n public static BoolToArrowConverter Instance { get; } = new BoolToArrowConverter();\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isExpanded)\n {\n // Up arrow for expanded, down arrow for collapsed\n return isExpanded ? \"\\uE70E\" : \"\\uE70D\";\n }\n \n // Default to down arrow if value is not a boolean\n return \"\\uE70D\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // This converter doesn't support converting back\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/App.xaml.cs", "using System;\nusing System.IO;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Services;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\nusing Winhance.Infrastructure.Features.Common.Services;\nusing Winhance.Infrastructure.Features.Customize.Services;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Implementations;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.Common.Services.Configuration;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.Customize.ViewModels;\nusing Winhance.WPF.Features.Customize.Views;\nusing Winhance.WPF.Features.Optimize.ViewModels;\nusing Winhance.WPF.Features.Optimize.Views;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\nusing Winhance.WPF.Features.SoftwareApps.Views;\n\nnamespace Winhance.WPF\n{\n public partial class App : Application\n {\n private readonly IHost _host;\n\n public App()\n {\n // Add global unhandled exception handlers\n AppDomain.CurrentDomain.UnhandledException += (sender, args) =>\n {\n var ex = args.ExceptionObject as Exception;\n LogStartupError($\"Unhandled AppDomain exception: {ex?.Message}\", ex);\n };\n\n Current.DispatcherUnhandledException += (sender, args) =>\n {\n LogStartupError(\n $\"Unhandled Dispatcher exception: {args.Exception.Message}\",\n args.Exception\n );\n args.Handled = true; // Prevent the application from crashing\n };\n\n TaskScheduler.UnobservedTaskException += (sender, args) =>\n {\n LogStartupError(\n $\"Unobserved Task exception: {args.Exception.Message}\",\n args.Exception\n );\n args.SetObserved(); // Prevent the application from crashing\n };\n\n _host = Host.CreateDefaultBuilder()\n .ConfigureServices(\n (context, services) =>\n {\n ConfigureServices(services);\n }\n )\n .Build();\n\n LogStartupError(\"Application constructor completed\");\n }\n\n protected override async void OnStartup(StartupEventArgs e)\n {\n LogStartupError(\"OnStartup method beginning\");\n LoadingWindow? loadingWindow = null;\n\n // Ensure the application has administrator privileges\n try\n {\n LogStartupError(\"Checking for administrator privileges\");\n var systemServices = _host.Services.GetService();\n if (systemServices != null)\n {\n bool isAdmin = systemServices.RequireAdministrator();\n LogStartupError($\"Administrator privileges check result: {isAdmin}\");\n }\n else\n {\n LogStartupError(\"ISystemServices not available for admin check\");\n }\n }\n catch (Exception adminEx)\n {\n LogStartupError(\n \"Error checking administrator privileges: \" + adminEx.Message,\n adminEx\n );\n }\n\n // Set the application icon for all windows\n try\n {\n // We'll continue to use the original icon for the application icon (taskbar, shortcuts, etc.)\n var iconUri = new Uri(\"/Resources/AppIcons/winhance-rocket.ico\", UriKind.Relative);\n Current.Resources[\"ApplicationIcon\"] = new System.Windows.Media.Imaging.BitmapImage(\n iconUri\n );\n LogStartupError(\"Application icon set successfully\");\n }\n catch (Exception iconEx)\n {\n LogStartupError(\"Failed to set application icon: \" + iconEx.Message, iconEx);\n }\n\n try\n {\n // Create and show loading window first\n LogStartupError(\"Attempting to get theme manager\");\n var themeManager = _host.Services.GetRequiredService();\n LogStartupError(\"Got theme manager\");\n\n // Ensure the IsDarkTheme resource is set in the application resources\n Application.Current.Resources[\"IsDarkTheme\"] = themeManager.IsDarkTheme;\n LogStartupError($\"Set IsDarkTheme resource to {themeManager.IsDarkTheme}\");\n\n LogStartupError(\"Attempting to get task progress service\");\n var initialProgressService =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got task progress service\");\n\n LogStartupError(\"Creating loading window\");\n loadingWindow = new LoadingWindow(themeManager, initialProgressService);\n LogStartupError(\"Loading window created\");\n\n LogStartupError(\"Showing loading window\");\n loadingWindow.Show();\n LogStartupError(\"Loading window shown\");\n\n // Start the host and initialize services\n LogStartupError(\"Starting host\");\n await _host.StartAsync();\n LogStartupError(\"Host started\");\n\n // Get required services\n LogStartupError(\"Getting main window\");\n var mainWindow = _host.Services.GetRequiredService();\n LogStartupError(\"Got main window\");\n\n LogStartupError(\"Getting main view model\");\n var mainViewModel = _host.Services.GetRequiredService();\n LogStartupError(\"Got main view model\");\n\n LogStartupError(\"Getting software apps view model\");\n var windowsAppsViewModel =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got Windows apps view model\");\n\n // Set the DataContext\n LogStartupError(\"Setting main window DataContext\");\n mainWindow.DataContext = mainViewModel;\n LogStartupError(\"Main window DataContext set\");\n\n // Preload the SoftwareAppsViewModel data\n LogStartupError(\"Loading apps and checking installation status...\");\n\n // Create a progress handler to update the loading window\n var progressHandler = new EventHandler(\n (sender, args) =>\n {\n if (\n loadingWindow != null\n && loadingWindow.DataContext is LoadingWindowViewModel vm\n )\n {\n vm.Progress = args.Progress * 100;\n vm.StatusMessage = args.StatusText;\n vm.IsIndeterminate = args.IsIndeterminate;\n vm.ShowProgressText = !args.IsIndeterminate && args.IsTaskRunning;\n\n // Update detail message based on the current operation\n if (args.StatusText.Contains(\"Loading installable apps\"))\n {\n vm.DetailMessage = \"Discovering available applications...\";\n }\n else if (args.StatusText.Contains(\"Loading removable apps\"))\n {\n vm.DetailMessage = \"Identifying Windows applications...\";\n }\n else if (args.StatusText.Contains(\"Checking installation status\"))\n {\n vm.DetailMessage = \"Verifying which applications are installed...\";\n }\n else if (args.StatusText.Contains(\"Organizing apps\"))\n {\n vm.DetailMessage = \"Sorting applications for display...\";\n }\n }\n }\n );\n\n // Subscribe to progress events\n LogStartupError(\"Getting task progress service\");\n var taskProgressService = _host.Services.GetRequiredService();\n LogStartupError(\"Got task progress service\");\n\n LogStartupError(\"Subscribing to progress events\");\n taskProgressService.ProgressChanged += progressHandler;\n LogStartupError(\"Subscribed to progress events\");\n\n try\n {\n // Load apps and check installation status while showing the loading screen\n LogStartupError(\n \"Starting LoadAppsAndCheckInstallationStatusAsync for WindowsAppsViewModel\"\n );\n await windowsAppsViewModel.LoadAppsAndCheckInstallationStatusAsync();\n LogStartupError(\"WindowsApps loaded and installation status checked\");\n\n // Also preload the SoftwareAppsViewModel data\n LogStartupError(\"Getting SoftwareAppsViewModel\");\n var softwareAppsViewModel =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got SoftwareAppsViewModel\");\n\n LogStartupError(\"Starting Initialize for SoftwareAppsViewModel\");\n await softwareAppsViewModel.InitializeCommand.ExecuteAsync(null);\n LogStartupError(\"SoftwareAppsViewModel initialized\");\n\n // Preload the OptimizeViewModel to ensure all registry settings are loaded\n LogStartupError(\"Getting OptimizeViewModel\");\n var optimizeViewModel = _host.Services.GetRequiredService();\n LogStartupError(\"Got OptimizeViewModel\");\n\n // Initialize the OptimizeViewModel and wait for it to complete\n LogStartupError(\"Starting Initialize for OptimizeViewModel\");\n if (loadingWindow?.DataContext is LoadingWindowViewModel loadingVM)\n {\n loadingVM.StatusMessage = \"Loading system settings...\";\n loadingVM.DetailMessage = \"Checking registry settings...\";\n }\n await optimizeViewModel.InitializeCommand.ExecuteAsync(null);\n LogStartupError(\"OptimizeViewModel initialized\");\n\n // Preload the CustomizeViewModel to ensure all customization settings are loaded\n LogStartupError(\"Getting CustomizeViewModel\");\n var customizeViewModel =\n _host.Services.GetRequiredService();\n LogStartupError(\"Got CustomizeViewModel\");\n\n // Initialize the CustomizeViewModel and wait for it to complete\n LogStartupError(\"Starting Initialize for CustomizeViewModel\");\n if (loadingWindow?.DataContext is LoadingWindowViewModel loadingVMCustomize)\n {\n loadingVMCustomize.StatusMessage = \"Loading customization settings...\";\n loadingVMCustomize.DetailMessage = \"Checking customization options...\";\n }\n await customizeViewModel.InitializeCommand.ExecuteAsync(null);\n LogStartupError(\"CustomizeViewModel initialized\");\n }\n finally\n {\n // Unsubscribe from progress events\n LogStartupError(\"Unsubscribing from progress events\");\n taskProgressService.ProgressChanged -= progressHandler;\n LogStartupError(\"Unsubscribed from progress events\");\n }\n\n // Show the main window\n LogStartupError(\"Showing main window\");\n mainWindow.Show();\n LogStartupError(\"Main window shown\");\n\n // Close the loading window\n LogStartupError(\"Closing loading window\");\n loadingWindow.Close();\n loadingWindow = null;\n LogStartupError(\"Loading window closed\");\n\n // Check for updates\n await CheckForUpdatesAsync(mainWindow);\n\n LogStartupError(\"Calling base.OnStartup\");\n base.OnStartup(e);\n LogStartupError(\"OnStartup method completed successfully\");\n }\n catch (Exception ex)\n {\n LogStartupError(\"Error during startup\", ex);\n MessageBox.Show(\n $\"Error during startup: {ex.Message}\\n\\nStack Trace:\\n{ex.StackTrace}\",\n \"Startup Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error\n );\n\n // Ensure loading window is closed if there was an error\n if (loadingWindow != null)\n {\n loadingWindow.Close();\n }\n\n Current.Shutdown();\n }\n }\n\n private async Task CheckForUpdatesAsync(Window ownerWindow)\n {\n try\n {\n LogStartupError(\"Checking for updates...\");\n var versionService = _host.Services.GetRequiredService();\n var latestVersion = await versionService.CheckForUpdateAsync();\n\n if (latestVersion.IsUpdateAvailable)\n {\n LogStartupError($\"Update available: {latestVersion.Version}\");\n\n // Get current version\n var currentVersion = versionService.GetCurrentVersion();\n\n // Show the styled update dialog\n string message = \"Good News! A New Version of Winhance is available.\";\n\n // Create a download and install action\n Func downloadAndInstallAction = async () =>\n {\n await versionService.DownloadAndInstallUpdateAsync();\n\n // Close the application without showing a message\n System.Windows.Application.Current.Shutdown();\n };\n\n // Show the update dialog\n bool installNow = await UpdateDialog.ShowAsync(\n \"Update Available\",\n message,\n currentVersion,\n latestVersion,\n downloadAndInstallAction\n );\n\n if (installNow)\n {\n LogStartupError(\"User chose to download and install the update\");\n }\n else\n {\n LogStartupError(\"User chose to be reminded later\");\n }\n }\n else\n {\n LogStartupError(\"No updates available\");\n }\n }\n catch (Exception ex)\n {\n LogStartupError($\"Error checking for updates: {ex.Message}\", ex);\n // Don't show error to user, just log it\n }\n }\n\n protected override async void OnExit(ExitEventArgs e)\n {\n try\n {\n // Material Design resources are automatically unloaded\n\n // Dispose of the ThemeManager to clean up event subscriptions\n try\n {\n var themeManager = _host.Services.GetService();\n themeManager?.Dispose();\n }\n catch (Exception disposeEx)\n {\n LogStartupError(\"Error disposing ThemeManager\", disposeEx);\n }\n\n using (_host)\n {\n await _host.StopAsync();\n }\n }\n catch (Exception ex)\n {\n LogStartupError(\"Error during shutdown\", ex);\n }\n finally\n {\n base.OnExit(e);\n }\n }\n\n private void LogStartupError(string message, Exception? ex = null)\n {\n string fullMessage = $\"[{DateTime.Now}] {message}\";\n if (ex != null)\n {\n fullMessage += $\"\\nException: {ex.Message}\\nStack Trace: {ex.StackTrace}\";\n if (ex.InnerException != null)\n {\n fullMessage += $\"\\nInner Exception: {ex.InnerException.Message}\";\n }\n }\n\n try\n {\n string logPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\",\n \"WinhanceStartupLog.txt\"\n );\n\n // Ensure directory exists\n Directory.CreateDirectory(Path.GetDirectoryName(logPath));\n File.AppendAllText(logPath, $\"{fullMessage}\\n\");\n }\n catch\n {\n MessageBox.Show(\n fullMessage,\n \"Startup Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error\n );\n }\n }\n\n private void ConfigureServices(IServiceCollection services)\n {\n try\n {\n LogStartupError(\"Beginning service configuration...\");\n\n // Core Services\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton<\n Winhance.Core.Interfaces.Services.IFileSystemService,\n Winhance.Infrastructure.FileSystem.FileSystemService\n >();\n\n // Register the base services\n services.AddSingleton();\n services.AddSingleton(provider =>\n provider.GetRequiredService()\n );\n services.AddSingleton();\n services.AddSingleton(\n provider => new SpecialAppHandlerService(\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton<\n ISearchService,\n Winhance.Infrastructure.Features.Common.Services.SearchService\n >();\n services.AddSingleton<\n IConfigurationService,\n Winhance.Infrastructure.Features.Common.Services.ConfigurationService\n >();\n // Register UserPreferencesService as a singleton to ensure the same instance is used throughout the app\n services.AddSingleton(provider =>\n {\n var logService = provider.GetRequiredService();\n var userPreferencesService =\n new Features.Common.Services.UserPreferencesService(logService);\n\n // Log that the UserPreferencesService has been registered\n logService.Log(LogLevel.Info, \"UserPreferencesService registered as singleton\");\n\n return userPreferencesService;\n });\n services.AddSingleton(\n provider => new Winhance.WPF.Features.Common.Services.UnifiedConfigurationService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // Register configuration services\n services.AddConfigurationServices();\n\n // Keep the old service for backward compatibility during transition\n services.AddSingleton(\n provider => new Winhance.WPF.Features.Common.Services.ConfigurationCoordinatorService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton();\n\n // Register script generation services\n services.AddScriptGenerationServices();\n\n services.AddSingleton(\n provider => new PowerShellExecutionService(\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // Register power plan service\n services.AddSingleton<\n Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService,\n Winhance.Infrastructure.Features.Optimize.Services.PowerPlanService\n >();\n\n // Register the installation and removal services\n // Register WinGet verification methods\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n\n // Register the composite verifier\n services.AddSingleton();\n\n // Register the WinGet installer\n services.AddSingleton();\n\n // Register the adapter for backward compatibility\n services.AddSingleton<\n IWinGetInstallationService,\n WinGetInstallationServiceAdapter\n >();\n\n // Register the main installation service\n services.AddSingleton(\n provider => new AppInstallationService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton(provider => new AppRemovalService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n services.AddSingleton<\n ICapabilityInstallationService,\n CapabilityInstallationService\n >();\n services.AddSingleton(\n provider => new CapabilityRemovalService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n services.AddSingleton();\n services.AddSingleton(provider => new FeatureRemovalService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n // Register the orchestrator\n services.AddSingleton();\n\n // Register the PackageManager with its dependencies\n services.AddSingleton(provider => new PackageManager(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetService()\n ));\n\n // Register the InternetConnectivityService\n services.AddSingleton(\n provider => new Winhance.Infrastructure.Features.Common.Services.InternetConnectivityService(\n provider.GetRequiredService()\n )\n );\n\n // Register the AppInstallationCoordinatorService\n services.AddSingleton(\n provider => new Winhance.Infrastructure.Features.SoftwareApps.Services.AppInstallationCoordinatorService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetService(),\n provider.GetService()\n )\n );\n\n // Use fully qualified type name to resolve ambiguity between Winhance.Core.Models.WindowsService\n // and Winhance.Infrastructure.Features.Common.Services.WindowsSystemService\n services.AddSingleton(\n provider => new Winhance.Infrastructure.Features.Common.Services.WindowsSystemService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n null, // Intentionally not passing IThemeService to break circular dependency\n provider.GetRequiredService()\n )\n );\n\n // Register theme and wallpaper services\n services.AddSingleton();\n services.AddSingleton(provider => new ThemeService(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton<\n Core.Features.Common.Interfaces.IDialogService,\n Features.Common.Services.DialogService\n >();\n services.AddSingleton();\n services.AddSingleton();\n\n // Register the notification service\n services.AddSingleton<\n Core.Features.UI.Interfaces.INotificationService,\n Winhance.Infrastructure.Features.UI.Services.NotificationService\n >();\n\n // Register the messenger service\n services.AddSingleton<\n Core.Features.Common.Interfaces.IMessengerService,\n Features.Common.Services.MessengerService\n >();\n\n // Register navigation service\n services.AddSingleton(\n provider =>\n {\n var navigationService = new FrameNavigationService(\n provider,\n provider.GetRequiredService()\n );\n\n // Register view mappings\n navigationService.RegisterViewMapping(\n \"SoftwareApps\",\n typeof(Features.SoftwareApps.Views.SoftwareAppsView),\n typeof(Features.SoftwareApps.ViewModels.SoftwareAppsViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"WindowsApps\",\n typeof(Features.SoftwareApps.Views.WindowsAppsView),\n typeof(Features.SoftwareApps.ViewModels.WindowsAppsViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"ExternalApps\",\n typeof(Features.SoftwareApps.Views.ExternalAppsView),\n typeof(Features.SoftwareApps.ViewModels.ExternalAppsViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"Optimize\",\n typeof(Features.Optimize.Views.OptimizeView),\n typeof(Features.Optimize.ViewModels.OptimizeViewModel)\n );\n\n navigationService.RegisterViewMapping(\n \"Customize\",\n typeof(Features.Customize.Views.CustomizeView),\n typeof(Features.Customize.ViewModels.CustomizeViewModel)\n );\n\n return navigationService;\n }\n );\n\n services.AddSingleton<\n IParameterSerializer,\n Winhance.Infrastructure.Features.Common.Services.JsonParameterSerializer\n >();\n\n // Register ThemeManager with navigation service dependency\n services.AddSingleton(\n provider => new Features.Common.Resources.Theme.ThemeManager(\n provider.GetRequiredService()\n )\n );\n\n // Register design-time data service\n services.AddSingleton<\n Features.Common.Services.IDesignTimeDataService,\n Features.Common.Services.DesignTimeDataService\n >();\n\n // Register ViewModels with explicit factory methods for all view models\n services.AddSingleton(provider => new MainViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton(provider => new WindowsAppsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton(provider => new ExternalAppsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n // Register UacSettingsService\n services.AddSingleton(\n provider => new UacSettingsService(\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // Register child ViewModels for OptimizeViewModel\n services.AddSingleton(\n provider => new WindowsSecurityOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new PrivacyOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new GamingandPerformanceOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new UpdateOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new PowerOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n // ViewModels are registered above\n\n services.AddSingleton(provider => new OptimizeViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n // Register child ViewModels for CustomizeViewModel\n services.AddSingleton(\n provider => new TaskbarCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new StartMenuCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new ExplorerCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new ExplorerOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new NotificationOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new SoundOptimizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(\n provider => new WindowsThemeCustomizationsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n )\n );\n\n services.AddSingleton(provider => new CustomizeViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddSingleton(provider => new SoftwareAppsViewModel(\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider\n ));\n\n // Register Views\n services.AddTransient(provider => new MainWindow(\n provider.GetRequiredService(),\n provider,\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService(),\n provider.GetRequiredService()\n ));\n\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n\n // Register version service\n services.AddSingleton();\n services.AddSingleton();\n\n // Register ApplicationCloseService\n services.AddSingleton();\n\n // Register logging service\n services.AddHostedService();\n\n LogStartupError(\"Service configuration complete\");\n }\n catch (Exception ex)\n {\n LogStartupError(\"Error during service configuration\", ex);\n throw;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServicePowerShell.cs", "using Microsoft.Win32;\nusing System;\nusing System.Diagnostics;\nusing System.Text;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n public partial class RegistryService\n {\n /// \n /// Sets a registry value using PowerShell with elevated privileges.\n /// This is a fallback method for when the standard .NET Registry API fails.\n /// \n /// The full path to the registry key.\n /// The name of the registry value.\n /// The value to set.\n /// The type of the registry value.\n /// True if the value was successfully set, false otherwise.\n private bool SetValueUsingPowerShell(string keyPath, string valueName, object value, RegistryValueKind valueKind)\n {\n try\n {\n _logService.LogInformation($\"Attempting to set registry value using PowerShell: {keyPath}\\\\{valueName}\");\n\n // Format the PowerShell command based on the value type\n string psCommand = FormatPowerShellCommand(keyPath, valueName, value, valueKind);\n\n // Create a PowerShell process with elevated privileges\n var startInfo = new ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-NoProfile -ExecutionPolicy Bypass -Command \\\"{psCommand}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n Verb = \"runas\" // Run as administrator\n };\n\n _logService.LogInformation($\"Executing PowerShell command: {psCommand}\");\n\n using var process = new Process { StartInfo = startInfo };\n \n try\n {\n process.Start();\n }\n catch (Exception ex)\n {\n _logService.LogWarning($\"Failed to start PowerShell with admin rights: {ex.Message}. Trying without elevation...\");\n \n // Try again without elevation\n startInfo.Verb = null;\n using var nonElevatedProcess = new Process { StartInfo = startInfo };\n nonElevatedProcess.Start();\n \n string nonElevatedOutput = nonElevatedProcess.StandardOutput.ReadToEnd();\n string nonElevatedError = nonElevatedProcess.StandardError.ReadToEnd();\n \n nonElevatedProcess.WaitForExit();\n \n if (nonElevatedProcess.ExitCode == 0)\n {\n _logService.LogSuccess($\"Successfully set registry value using non-elevated PowerShell: {keyPath}\\\\{valueName}\");\n \n // Clear the cache for this value\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueCache)\n {\n if (_valueCache.ContainsKey(fullValuePath))\n {\n _valueCache.Remove(fullValuePath);\n }\n }\n \n return true;\n }\n \n _logService.LogWarning($\"Non-elevated PowerShell also failed: {nonElevatedError}\");\n return false;\n }\n \n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n \n process.WaitForExit();\n\n if (process.ExitCode == 0)\n {\n _logService.LogSuccess($\"Successfully set registry value using PowerShell: {keyPath}\\\\{valueName}\");\n \n // Clear the cache for this value\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueCache)\n {\n if (_valueCache.ContainsKey(fullValuePath))\n {\n _valueCache.Remove(fullValuePath);\n }\n }\n \n return true;\n }\n else\n {\n _logService.LogWarning($\"PowerShell failed to set registry value: {error}\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error using PowerShell to set registry value: {ex.Message}\", ex);\n return false;\n }\n }\n\n /// \n /// Formats a PowerShell command to set a registry value.\n /// \n private string FormatPowerShellCommand(string keyPath, string valueName, object value, RegistryValueKind valueKind)\n {\n // Split the key path into hive and subkey\n string[] pathParts = keyPath.Split('\\\\');\n string hive = pathParts[0];\n string subKey = string.Join('\\\\', pathParts.Skip(1));\n\n // Map the registry hive to PowerShell drive\n string psDrive = hive switch\n {\n \"HKCU\" or \"HKEY_CURRENT_USER\" => \"HKCU:\",\n \"HKLM\" or \"HKEY_LOCAL_MACHINE\" => \"HKLM:\",\n \"HKCR\" or \"HKEY_CLASSES_ROOT\" => \"HKCR:\",\n \"HKU\" or \"HKEY_USERS\" => \"HKU:\",\n \"HKCC\" or \"HKEY_CURRENT_CONFIG\" => \"HKCC:\",\n _ => throw new ArgumentException($\"Unsupported registry hive: {hive}\")\n };\n\n // Format the value based on its type\n string valueArg = FormatValueForPowerShell(value, valueKind);\n string typeArg = GetPowerShellTypeArg(valueKind);\n\n // Build the PowerShell command with enhanced error handling and permissions\n var sb = new StringBuilder();\n \n // Add error handling\n sb.Append(\"$ErrorActionPreference = 'Stop'; \");\n sb.Append(\"try { \");\n \n // First, ensure the key exists with proper permissions\n sb.Append($\"if (-not (Test-Path -Path '{psDrive}\\\\{subKey}')) {{ \");\n \n // Create the key with force to ensure all parent keys are created\n sb.Append($\"New-Item -Path '{psDrive}\\\\{subKey}' -Force | Out-Null; \");\n \n // For policy keys, try to set appropriate permissions\n if (subKey.Contains(\"Policies\", StringComparison.OrdinalIgnoreCase))\n {\n sb.Append($\"$acl = Get-Acl -Path '{psDrive}\\\\{subKey}'; \");\n sb.Append(\"$rule = New-Object System.Security.AccessControl.RegistryAccessRule('CURRENT_USER', 'FullControl', 'Allow'); \");\n sb.Append(\"$acl.SetAccessRule($rule); \");\n sb.Append($\"try {{ Set-Acl -Path '{psDrive}\\\\{subKey}' -AclObject $acl }} catch {{ Write-Host 'Could not set ACL, continuing anyway...' }}; \");\n }\n \n sb.Append(\"} \");\n \n // Then set the value\n sb.Append($\"Set-ItemProperty -Path '{psDrive}\\\\{subKey}' -Name '{valueName}' -Value {valueArg} {typeArg} -Force; \");\n \n // Verify the value was set correctly\n sb.Append($\"$setVal = Get-ItemProperty -Path '{psDrive}\\\\{subKey}' -Name '{valueName}' -ErrorAction SilentlyContinue; \");\n sb.Append(\"if ($setVal -eq $null) { throw 'Value was not set properly' }; \");\n \n // Close the try block and add catch\n sb.Append(\"} catch { Write-Error $_.Exception.Message; exit 1 }\");\n\n return sb.ToString();\n }\n\n /// \n /// Formats a value for use with PowerShell.\n /// \n private string FormatValueForPowerShell(object value, RegistryValueKind valueKind)\n {\n return valueKind switch\n {\n RegistryValueKind.DWord or RegistryValueKind.QWord => value.ToString(),\n RegistryValueKind.String or RegistryValueKind.ExpandString => $\"'{value}'\",\n RegistryValueKind.MultiString => $\"@('{string.Join(\"','\", (string[])value)})'\",\n RegistryValueKind.Binary => $\"([byte[]]@({string.Join(\",\", (byte[])value)}))\",\n _ => $\"'{value}'\"\n };\n }\n\n /// \n /// Gets the PowerShell type argument for a registry value kind.\n /// \n private string GetPowerShellTypeArg(RegistryValueKind valueKind)\n {\n return valueKind switch\n {\n RegistryValueKind.String => \"-Type String\",\n RegistryValueKind.ExpandString => \"-Type ExpandString\",\n RegistryValueKind.Binary => \"-Type Binary\",\n RegistryValueKind.DWord => \"-Type DWord\",\n RegistryValueKind.MultiString => \"-Type MultiString\",\n RegistryValueKind.QWord => \"-Type QWord\",\n _ => \"\"\n };\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/ScriptStatusToColorConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean script status to a color.\n /// \n public class ScriptStatusToColorConverter : IValueConverter\n {\n /// \n /// Converts a boolean value to a color.\n /// \n /// The boolean value indicating if scripts are active.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// A color based on the script status.\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isActive)\n {\n // Return green if scripts are active, gray if not\n return isActive \n ? new SolidColorBrush(Color.FromRgb(0, 200, 83)) // Green for active\n : new SolidColorBrush(Color.FromRgb(150, 150, 150)); // Gray for inactive\n }\n \n return new SolidColorBrush(Colors.Gray);\n }\n \n /// \n /// Converts a color back to a boolean value.\n /// \n /// The color to convert back.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// A boolean value based on the color.\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/UserPreferencesService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading.Tasks;\nusing Newtonsoft.Json;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for managing user preferences\n /// \n public class UserPreferencesService\n {\n private const string PreferencesFileName = \"UserPreferences.json\";\n private readonly ILogService _logService;\n\n public UserPreferencesService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Gets the path to the user preferences file\n /// \n /// The full path to the user preferences file\n private string GetPreferencesFilePath()\n {\n try\n {\n // Get the LocalApplicationData folder (e.g., C:\\Users\\Username\\AppData\\Local)\n string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n \n if (string.IsNullOrEmpty(localAppData))\n {\n _logService.Log(LogLevel.Error, \"LocalApplicationData folder path is empty\");\n // Fallback to a default path\n localAppData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), \"AppData\", \"Local\");\n _logService.Log(LogLevel.Info, $\"Using fallback path: {localAppData}\");\n }\n \n // Combine with Winhance/Config\n string appDataPath = Path.Combine(localAppData, \"Winhance\", \"Config\");\n \n // Log the path\n _logService.Log(LogLevel.Debug, $\"Preferences directory path: {appDataPath}\");\n \n // Ensure the directory exists\n if (!Directory.Exists(appDataPath))\n {\n Directory.CreateDirectory(appDataPath);\n _logService.Log(LogLevel.Info, $\"Created preferences directory: {appDataPath}\");\n }\n \n // Get the full file path\n string filePath = Path.Combine(appDataPath, PreferencesFileName);\n _logService.Log(LogLevel.Debug, $\"Preferences file path: {filePath}\");\n \n return filePath;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting preferences file path: {ex.Message}\");\n \n // Fallback to a temporary file\n string tempPath = Path.Combine(Path.GetTempPath(), \"Winhance\", \"Config\");\n Directory.CreateDirectory(tempPath);\n string tempFilePath = Path.Combine(tempPath, PreferencesFileName);\n \n _logService.Log(LogLevel.Warning, $\"Using fallback temporary path: {tempFilePath}\");\n return tempFilePath;\n }\n }\n\n /// \n /// Gets the user preferences\n /// \n /// A dictionary containing the user preferences\n public async Task> GetPreferencesAsync()\n {\n try\n {\n string filePath = GetPreferencesFilePath();\n \n // Log the file path\n _logService.Log(LogLevel.Debug, $\"Getting preferences from '{filePath}'\");\n \n if (!File.Exists(filePath))\n {\n _logService.Log(LogLevel.Info, $\"User preferences file does not exist at '{filePath}', returning empty preferences\");\n return new Dictionary();\n }\n \n // Read the file\n string json = await File.ReadAllTextAsync(filePath);\n \n // Log a sample of the JSON (first 100 characters)\n if (!string.IsNullOrEmpty(json))\n {\n string sample = json.Length > 100 ? json.Substring(0, 100) + \"...\" : json;\n _logService.Log(LogLevel.Debug, $\"JSON sample: {sample}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Preferences file exists but is empty\");\n return new Dictionary();\n }\n \n // Use more robust deserialization settings\n var settings = new JsonSerializerSettings\n {\n NullValueHandling = NullValueHandling.Include,\n TypeNameHandling = TypeNameHandling.None,\n ReferenceLoopHandling = ReferenceLoopHandling.Ignore\n };\n \n // Use a custom converter to properly handle boolean values\n var preferences = JsonConvert.DeserializeObject>(json, settings);\n \n // Log the raw type of the DontShowSupport value if it exists\n if (preferences != null && preferences.TryGetValue(\"DontShowSupport\", out var dontShowValue))\n {\n _logService.Log(LogLevel.Debug, $\"DontShowSupport raw value type: {dontShowValue?.GetType().FullName}, value: {dontShowValue}\");\n }\n \n if (preferences != null)\n {\n _logService.Log(LogLevel.Info, $\"Successfully loaded {preferences.Count} preferences\");\n \n // Log the keys for debugging\n if (preferences.Count > 0)\n {\n _logService.Log(LogLevel.Debug, $\"Preference keys: {string.Join(\", \", preferences.Keys)}\");\n }\n \n return preferences;\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Deserialized preferences is null, returning empty dictionary\");\n return new Dictionary();\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting user preferences: {ex.Message}\");\n if (ex.InnerException != null)\n {\n _logService.Log(LogLevel.Error, $\"Inner exception: {ex.InnerException.Message}\");\n }\n return new Dictionary();\n }\n }\n\n /// \n /// Saves the user preferences\n /// \n /// The preferences to save\n /// True if successful, false otherwise\n public async Task SavePreferencesAsync(Dictionary preferences)\n {\n try\n {\n string filePath = GetPreferencesFilePath();\n \n // Log the file path and preferences count\n _logService.Log(LogLevel.Debug, $\"Saving preferences to '{filePath}', count: {preferences.Count}\");\n \n // Use more robust serialization settings\n var settings = new JsonSerializerSettings\n {\n Formatting = Formatting.Indented,\n NullValueHandling = NullValueHandling.Include,\n TypeNameHandling = TypeNameHandling.None,\n ReferenceLoopHandling = ReferenceLoopHandling.Ignore\n };\n \n string json = JsonConvert.SerializeObject(preferences, settings);\n \n // Log a sample of the JSON (first 100 characters)\n if (json.Length > 0)\n {\n string sample = json.Length > 100 ? json.Substring(0, 100) + \"...\" : json;\n _logService.Log(LogLevel.Debug, $\"JSON sample: {sample}\");\n }\n \n // Ensure the directory exists\n string directory = Path.GetDirectoryName(filePath);\n if (!Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n _logService.Log(LogLevel.Debug, $\"Created directory: {directory}\");\n }\n \n // Write the file\n await File.WriteAllTextAsync(filePath, json);\n \n // Verify the file was written\n if (File.Exists(filePath))\n {\n _logService.Log(LogLevel.Info, $\"User preferences saved successfully to '{filePath}'\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"File not found after writing: '{filePath}'\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving user preferences: {ex.Message}\");\n if (ex.InnerException != null)\n {\n _logService.Log(LogLevel.Error, $\"Inner exception: {ex.InnerException.Message}\");\n }\n return false;\n }\n }\n\n /// \n /// Gets a specific preference value\n /// \n /// The type of the preference value\n /// The preference key\n /// The default value to return if the preference does not exist\n /// The preference value, or the default value if not found\n public async Task GetPreferenceAsync(string key, T defaultValue)\n {\n var preferences = await GetPreferencesAsync();\n \n if (preferences.TryGetValue(key, out var value))\n {\n try\n {\n // Log the actual type and value for debugging\n _logService.Log(LogLevel.Debug, $\"GetPreferenceAsync for key '{key}': value type = {value?.GetType().FullName}, value = {value}\");\n \n // Special case for DontShowSupport boolean preference\n if (key == \"DontShowSupport\" && typeof(T) == typeof(bool))\n {\n // Direct string comparison for known boolean values\n if (value != null)\n {\n string valueStr = value.ToString().ToLowerInvariant();\n if (valueStr == \"true\" || valueStr == \"1\")\n {\n _logService.Log(LogLevel.Debug, $\"DontShowSupport detected as TRUE\");\n return (T)(object)true;\n }\n else if (valueStr == \"false\" || valueStr == \"0\")\n {\n _logService.Log(LogLevel.Debug, $\"DontShowSupport detected as FALSE\");\n return (T)(object)false;\n }\n }\n }\n \n if (value is T typedValue)\n {\n return typedValue;\n }\n \n // Handle JToken conversion for primitive types\n if (value is Newtonsoft.Json.Linq.JToken jToken)\n {\n // For boolean JToken values, handle them explicitly\n if (typeof(T) == typeof(bool))\n {\n if (jToken.Type == Newtonsoft.Json.Linq.JTokenType.Boolean)\n {\n // Use ToObject instead of Value\n bool boolValue = (bool)jToken.ToObject(typeof(bool));\n _logService.Log(LogLevel.Debug, $\"JToken boolean value: {boolValue}\");\n return (T)(object)boolValue;\n }\n else if (jToken.Type == Newtonsoft.Json.Linq.JTokenType.String)\n {\n // Use ToString() instead of Value\n string strValue = jToken.ToString();\n if (bool.TryParse(strValue, out bool boolResult))\n {\n _logService.Log(LogLevel.Debug, $\"JToken string parsed as boolean: {boolResult}\");\n return (T)(object)boolResult;\n }\n }\n else if (jToken.Type == Newtonsoft.Json.Linq.JTokenType.Integer)\n {\n // Use ToObject instead of Value\n int intValue = (int)jToken.ToObject(typeof(int));\n bool boolValue = intValue != 0;\n _logService.Log(LogLevel.Debug, $\"JToken integer converted to boolean: {boolValue}\");\n return (T)(object)boolValue;\n }\n }\n \n var result = jToken.ToObject();\n _logService.Log(LogLevel.Debug, $\"JToken converted to {typeof(T).Name}: {result}\");\n return result;\n }\n \n // Special handling for boolean values\n if (typeof(T) == typeof(bool) && value != null)\n {\n // Handle string representations of boolean values\n if (value is string strValue)\n {\n if (bool.TryParse(strValue, out bool boolResult))\n {\n _logService.Log(LogLevel.Debug, $\"String value '{strValue}' parsed as boolean: {boolResult}\");\n return (T)(object)boolResult;\n }\n \n // Also check for \"1\" and \"0\" string values\n if (strValue == \"1\")\n {\n _logService.Log(LogLevel.Debug, $\"String value '1' converted to boolean: true\");\n return (T)(object)true;\n }\n else if (strValue == \"0\")\n {\n _logService.Log(LogLevel.Debug, $\"String value '0' converted to boolean: false\");\n return (T)(object)false;\n }\n }\n \n // Handle numeric representations (0 = false, non-zero = true)\n if (value is long || value is int || value is double || value is float)\n {\n double numValue = Convert.ToDouble(value);\n bool boolResult2 = numValue != 0; // Renamed to avoid conflict\n _logService.Log(LogLevel.Debug, $\"Numeric value {numValue} converted to boolean: {boolResult2}\");\n return (T)(object)boolResult2;\n }\n \n // Handle direct boolean values\n if (value is bool boolValue)\n {\n _logService.Log(LogLevel.Debug, $\"Direct boolean value: {boolValue}\");\n return (T)(object)boolValue;\n }\n }\n \n // Try to convert the value to the requested type\n var convertedValue = (T)Convert.ChangeType(value, typeof(T));\n _logService.Log(LogLevel.Debug, $\"Converted value to {typeof(T).Name}: {convertedValue}\");\n return convertedValue;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error converting preference value for key '{key}': {ex.Message}\");\n if (ex.InnerException != null)\n {\n _logService.Log(LogLevel.Error, $\"Inner exception: {ex.InnerException.Message}\");\n }\n _logService.Log(LogLevel.Error, $\"Stack trace: {ex.StackTrace}\");\n return defaultValue;\n }\n }\n \n _logService.Log(LogLevel.Debug, $\"Preference '{key}' not found, returning default value: {defaultValue}\");\n return defaultValue;\n }\n\n /// \n /// Sets a specific preference value\n /// \n /// The type of the preference value\n /// The preference key\n /// The preference value\n /// True if successful, false otherwise\n public async Task SetPreferenceAsync(string key, T value)\n {\n try\n {\n var preferences = await GetPreferencesAsync();\n \n // Log the preference being set\n _logService.Log(LogLevel.Debug, $\"Setting preference '{key}' to '{value}'\");\n \n preferences[key] = value;\n \n bool result = await SavePreferencesAsync(preferences);\n \n // Log the result\n if (result)\n {\n _logService.Log(LogLevel.Info, $\"Successfully saved preference '{key}'\");\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to save preference '{key}'\");\n }\n \n return result;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting preference '{key}': {ex.Message}\");\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/UnifiedConfigurationDialog.xaml.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Windows;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Interaction logic for UnifiedConfigurationDialog.xaml\n /// \n public partial class UnifiedConfigurationDialog : Window\n {\n private readonly UnifiedConfigurationDialogViewModel _viewModel;\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The title of the dialog.\n /// The description of the dialog.\n /// The dictionary of section names, their availability, and item counts.\n /// Whether this is a save dialog (true) or an import dialog (false).\n public UnifiedConfigurationDialog(\n string title,\n string description,\n Dictionary sections,\n bool isSaveDialog)\n {\n try\n {\n InitializeComponent();\n\n // Try to get the log service from the application using reflection\n try\n {\n if (Application.Current is App appInstance)\n {\n // Use reflection to access the _host.Services property\n var hostField = appInstance.GetType().GetField(\"_host\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (hostField != null)\n {\n var host = hostField.GetValue(appInstance);\n var servicesProperty = host.GetType().GetProperty(\"Services\");\n if (servicesProperty != null)\n {\n var services = servicesProperty.GetValue(host);\n var getServiceMethod = services.GetType().GetMethod(\"GetService\", new[] { typeof(Type) });\n if (getServiceMethod != null)\n {\n _logService = getServiceMethod.Invoke(services, new object[] { typeof(ILogService) }) as ILogService;\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine($\"Error getting log service: {ex.Message}\");\n // Continue without logging\n }\n \n LogInfo($\"Creating {(isSaveDialog ? \"save\" : \"import\")} dialog with title: {title}\");\n LogInfo($\"Sections: {string.Join(\", \", sections.Keys)}\");\n\n // Create the view model\n _viewModel = new UnifiedConfigurationDialogViewModel(title, description, sections, isSaveDialog);\n \n // Set the data context\n DataContext = _viewModel;\n\n // Set the window title\n this.Title = title;\n \n // Ensure the dialog is shown as a modal dialog\n this.WindowStartupLocation = WindowStartupLocation.CenterOwner;\n this.ResizeMode = ResizeMode.NoResize;\n this.ShowInTaskbar = false;\n \n // Handle the OK and Cancel commands directly\n _viewModel.OkCommand = new RelayCommand(() =>\n {\n // Validate that at least one section is selected\n if (_viewModel.Sections.Any(s => s.IsSelected))\n {\n LogInfo(\"OK button clicked, at least one section selected\");\n this.DialogResult = true;\n }\n else\n {\n LogInfo(\"OK button clicked, but no sections selected\");\n MessageBox.Show(\n \"Please select at least one section to continue.\",\n \"No Sections Selected\",\n MessageBoxButton.OK,\n MessageBoxImage.Warning);\n }\n });\n \n _viewModel.CancelCommand = new RelayCommand(() =>\n {\n LogInfo(\"Cancel button clicked\");\n this.DialogResult = false;\n });\n \n LogInfo(\"Dialog initialization completed\");\n }\n catch (Exception ex)\n {\n LogError($\"Error initializing dialog: {ex.Message}\");\n Debug.WriteLine($\"Error initializing dialog: {ex}\");\n \n // Show error message\n MessageBox.Show($\"Error initializing dialog: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n \n // Set dialog result to false\n DialogResult = false;\n }\n }\n\n /// \n /// Gets the result of the dialog as a dictionary of section names and their selection state.\n /// \n /// A dictionary of section names and their selection state.\n public Dictionary GetResult()\n {\n try\n {\n var result = _viewModel.GetResult();\n LogInfo($\"GetResult called, returning {result.Count} sections\");\n return result;\n }\n catch (Exception ex)\n {\n LogError($\"Error getting result: {ex.Message}\");\n return new Dictionary();\n }\n }\n \n private void LogInfo(string message)\n {\n _logService?.Log(LogLevel.Info, $\"UnifiedConfigurationDialog: {message}\");\n Debug.WriteLine($\"UnifiedConfigurationDialog: {message}\");\n }\n \n private void LogError(string message)\n {\n _logService?.Log(LogLevel.Error, $\"UnifiedConfigurationDialog: {message}\");\n Debug.WriteLine($\"UnifiedConfigurationDialog ERROR: {message}\");\n }\n \n /// \n /// Handles the mouse left button down event on the title bar to enable window dragging.\n /// \n private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n if (e.ChangedButton == MouseButton.Left)\n {\n this.DragMove();\n }\n }\n \n /// \n /// Handles the close button click event.\n /// \n private void CloseButton_Click(object sender, RoutedEventArgs e)\n {\n LogInfo(\"Close button clicked\");\n this.DialogResult = false;\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Implementations/WinGetInstaller.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.Logging;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Verification;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.Extensions;\nusing Winhance.Infrastructure.Features.Common.Utilities;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Utilities;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Implementations\n{\n /// \n /// Implements the interface for managing packages with WinGet.\n /// \n public class WinGetInstaller : IWinGetInstaller\n {\n private const string WinGetExe = \"winget.exe\";\n private readonly IPowerShellExecutionService _powerShellService;\n private readonly ITaskProgressService _taskProgressService;\n private readonly IInstallationVerifier _installationVerifier;\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The PowerShell factory for executing commands.\n /// The task progress service for reporting progress.\n /// The installation verifier to check if packages are installed.\n /// The logging service for logging messages.\n public WinGetInstaller(\n IPowerShellExecutionService powerShellService,\n ITaskProgressService taskProgressService,\n IInstallationVerifier installationVerifier = null,\n ILogService logService = null\n )\n {\n _powerShellService =\n powerShellService ?? throw new ArgumentNullException(nameof(powerShellService));\n _taskProgressService =\n taskProgressService ?? throw new ArgumentNullException(nameof(taskProgressService));\n _installationVerifier =\n installationVerifier\n ?? new CompositeInstallationVerifier(GetDefaultVerificationMethods());\n _logService = logService;\n }\n\n /// \n public async Task InstallPackageAsync(\n string packageId,\n InstallationOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n options ??= new InstallationOptions();\n var arguments = new StringBuilder(\n $\"install --id {EscapeArgument(packageId)} --accept-package-agreements --accept-source-agreements --disable-interactivity --silent --force\"\n );\n\n if (!string.IsNullOrWhiteSpace(options.Version))\n arguments.Append($\" --version {EscapeArgument(options.Version)}\");\n\n // Force parameter is now always included\n // Interactive is disabled with --disable-interactivity\n // Silent is now always included\n\n try\n {\n // Create a wrapper function that will be passed to the extension method\n Func, Task> operation = async (\n progress\n ) =>\n {\n var commandResult = await ExecuteWinGetCommandAsync(\n WinGetExe,\n arguments.ToString(),\n progress,\n cancellationToken\n )\n .ConfigureAwait(false);\n\n // Convert the command result to an InstallationResult\n return new InstallationResult\n {\n Success = commandResult.ExitCode == 0,\n Message =\n commandResult.ExitCode == 0\n ? $\"Successfully installed {packageId}\"\n : $\"Failed to install {packageId}. Exit code: {commandResult.ExitCode}. Error: {commandResult.Error}\",\n PackageId = packageId,\n Version = options?.Version,\n };\n };\n\n // Use the display name if provided, otherwise use packageId\n string nameToDisplay = displayName ?? packageId;\n\n // Use the extension method to track progress\n var result = await _taskProgressService\n .TrackWinGetInstallationAsync(operation, nameToDisplay, cancellationToken)\n .ConfigureAwait(false);\n\n if (result.ExitCode != 0)\n {\n return new InstallationResult\n {\n Success = false,\n Message =\n $\"Failed to install {packageId}. Exit code: {result.ExitCode}. Error: {result.Error}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n\n // For Microsoft Store apps, trust the WinGet exit code as the primary indicator of success\n bool isMicrosoftStoreApp =\n packageId.All(char.IsLetterOrDigit) && !packageId.Contains('.');\n\n if (isMicrosoftStoreApp)\n {\n _logService?.LogInformation(\n $\"Microsoft Store app detected: {packageId}. Using WinGet exit code for success determination.\"\n );\n\n // For Microsoft Store apps, trust the exit code\n return new InstallationResult\n {\n Success = true, // WinGet command succeeded, so consider the installation successful\n Message = $\"Successfully installed {packageId} {options.Version}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n\n // For regular apps, try verification with a longer delay\n try\n {\n // Add a longer delay for verification to allow Windows to complete registration\n await Task.Delay(TimeSpan.FromSeconds(3), cancellationToken)\n .ConfigureAwait(false);\n\n var verification = await _installationVerifier\n .VerifyInstallationAsync(packageId, options.Version, cancellationToken)\n .ConfigureAwait(false);\n\n // If verification succeeds, great! If not, but WinGet reported success, trust WinGet\n bool success = verification.IsVerified || result.ExitCode == 0;\n\n return new InstallationResult\n {\n Success = success,\n Message = success\n ? $\"Successfully installed {packageId} {options.Version}\"\n : $\"Installation may have failed: {verification.Message}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n catch (Exception ex)\n {\n _logService?.LogWarning(\n $\"Verification failed with error: {ex.Message}. Using WinGet exit code for success determination.\"\n );\n\n // If verification throws an exception, trust the WinGet exit code\n return new InstallationResult\n {\n Success = true, // WinGet command succeeded, so consider the installation successful\n Message =\n $\"Successfully installed {packageId} {options.Version} (verification skipped due to error)\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n return new InstallationResult\n {\n Success = false,\n Message = $\"Error installing {packageId}: {ex.Message}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n }\n\n /// \n public async Task UpgradePackageAsync(\n string packageId,\n UpgradeOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n options ??= new UpgradeOptions();\n var arguments = new StringBuilder(\n $\"upgrade --id {EscapeArgument(packageId)} --accept-package-agreements --accept-source-agreements --disable-interactivity --silent --force\"\n );\n\n // Force parameter is now always included\n // Interactive is disabled with --disable-interactivity\n // Silent is now always included\n\n try\n {\n // Create a wrapper function that will be passed to the extension method\n Func, Task> operation = async (\n progress\n ) =>\n {\n // Create an adapter since ExecuteWinGetCommandAsync expects InstallationProgress\n var progressAdapter = new Progress(p =>\n {\n // Convert InstallationProgress to UpgradeProgress\n progress.Report(\n new UpgradeProgress\n {\n Percentage = p.Percentage,\n Status = p.Status,\n IsIndeterminate = p.IsIndeterminate,\n }\n );\n });\n\n var commandResult = await ExecuteWinGetCommandAsync(\n WinGetExe,\n arguments.ToString(),\n progressAdapter,\n cancellationToken\n )\n .ConfigureAwait(false);\n\n // Convert the command result to an UpgradeResult\n return new UpgradeResult\n {\n Success = commandResult.ExitCode == 0,\n Message =\n commandResult.ExitCode == 0\n ? $\"Successfully upgraded {packageId}\"\n : $\"Failed to upgrade {packageId}. Exit code: {commandResult.ExitCode}. Error: {commandResult.Error}\",\n PackageId = packageId,\n Version = options?.Version,\n };\n };\n\n // Use the display name if provided, otherwise use packageId\n string nameToDisplay = displayName ?? packageId;\n\n // Use the extension method to track progress\n var result = await _taskProgressService\n .TrackWinGetUpgradeAsync(operation, nameToDisplay, cancellationToken)\n .ConfigureAwait(false);\n\n if (result.ExitCode != 0)\n {\n return new UpgradeResult\n {\n Success = false,\n Message =\n $\"Failed to upgrade {packageId}. Exit code: {result.ExitCode}. Error: {result.Error}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n\n // For Microsoft Store apps, trust the WinGet exit code as the primary indicator of success\n bool isMicrosoftStoreApp =\n packageId.All(char.IsLetterOrDigit) && !packageId.Contains('.');\n\n if (isMicrosoftStoreApp)\n {\n _logService?.LogInformation(\n $\"Microsoft Store app detected: {packageId}. Using WinGet exit code for success determination.\"\n );\n\n // For Microsoft Store apps, trust the exit code\n return new UpgradeResult\n {\n Success = true, // WinGet command succeeded, so consider the upgrade successful\n Message = $\"Successfully upgraded {packageId} to {options.Version}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n\n // For regular apps, try verification with a longer delay\n try\n {\n // Add a longer delay for verification to allow Windows to complete registration\n await Task.Delay(TimeSpan.FromSeconds(3), cancellationToken)\n .ConfigureAwait(false);\n\n var verificationResult = await _installationVerifier\n .VerifyInstallationAsync(packageId, options.Version, cancellationToken)\n .ConfigureAwait(false);\n\n // If verification succeeds, great! If not, but WinGet reported success, trust WinGet\n bool success = verificationResult.IsVerified || result.ExitCode == 0;\n\n return new UpgradeResult\n {\n Success = success,\n Message = success\n ? $\"Successfully upgraded {packageId} to {options.Version}\"\n : $\"Upgrade may have failed: {verificationResult.Message}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n catch (Exception ex)\n {\n _logService?.LogWarning(\n $\"Verification failed with error: {ex.Message}. Using WinGet exit code for success determination.\"\n );\n\n // If verification throws an exception, trust the WinGet exit code\n return new UpgradeResult\n {\n Success = true, // WinGet command succeeded, so consider the upgrade successful\n Message =\n $\"Successfully upgraded {packageId} to {options.Version} (verification skipped due to error)\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n }\n catch (Exception ex)\n {\n return new UpgradeResult\n {\n Success = false,\n Message = $\"Error upgrading {packageId}: {ex.Message}\",\n PackageId = packageId,\n Version = options.Version,\n };\n }\n }\n\n /// \n public async Task UninstallPackageAsync(\n string packageId,\n UninstallationOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n options ??= new UninstallationOptions();\n var arguments = new StringBuilder(\n $\"uninstall --id {EscapeArgument(packageId)} --accept-package-agreements --accept-source-agreements --disable-interactivity --silent --force\"\n );\n\n // Force parameter is now always included\n // Interactive is disabled with --disable-interactivity\n // Silent is now always included\n\n try\n {\n // Create a wrapper function that will be passed to the extension method\n Func, Task> operation =\n async (progress) =>\n {\n // Create an adapter since ExecuteWinGetCommandAsync expects InstallationProgress\n var progressAdapter = new Progress(p =>\n {\n // Convert InstallationProgress to UninstallationProgress\n progress.Report(\n new UninstallationProgress\n {\n Percentage = p.Percentage,\n Status = p.Status,\n IsIndeterminate = p.IsIndeterminate,\n }\n );\n });\n\n var commandResult = await ExecuteWinGetCommandAsync(\n WinGetExe,\n arguments.ToString(),\n progressAdapter,\n cancellationToken\n )\n .ConfigureAwait(false);\n\n // Convert the command result to an UninstallationResult\n return new UninstallationResult\n {\n Success = commandResult.ExitCode == 0,\n Message =\n commandResult.ExitCode == 0\n ? $\"Successfully uninstalled {packageId}\"\n : $\"Failed to uninstall {packageId}. Exit code: {commandResult.ExitCode}. Error: {commandResult.Error}\",\n PackageId = packageId,\n };\n };\n\n // Use the display name if provided, otherwise use packageId\n string nameToDisplay = displayName ?? packageId;\n\n // Use the extension method to track progress\n var result = await _taskProgressService\n .TrackWinGetUninstallationAsync(operation, nameToDisplay, cancellationToken)\n .ConfigureAwait(false);\n\n if (result.ExitCode != 0)\n {\n return new UninstallationResult\n {\n Success = false,\n Message =\n $\"Failed to uninstall {packageId}. Exit code: {result.ExitCode}. Error: {result.Error}\",\n PackageId = packageId,\n };\n }\n\n // Verify uninstallation (should return false if successfully uninstalled)\n var verification = await _installationVerifier\n .VerifyInstallationAsync(packageId, null, cancellationToken)\n .ConfigureAwait(false);\n\n return new UninstallationResult\n {\n Success = !verification.IsVerified,\n Message = !verification.IsVerified\n ? $\"Successfully uninstalled {packageId}\"\n : $\"Uninstallation may have failed: {verification.Message}\",\n PackageId = packageId,\n };\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n return new UninstallationResult\n {\n Success = false,\n Message = $\"Error uninstalling {packageId}: {ex.Message}\",\n PackageId = packageId,\n };\n }\n }\n\n /// \n public async Task GetPackageInfoAsync(\n string packageId,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n try\n {\n var arguments = $\"show --id {EscapeArgument(packageId)} --accept-source-agreements\";\n var result = await ExecuteWinGetCommandAsync(\n WinGetExe,\n arguments,\n null,\n cancellationToken\n )\n .ConfigureAwait(false);\n\n if (result.ExitCode != 0)\n {\n return null;\n }\n\n return ParsePackageInfo(result.Output);\n }\n catch (Exception)\n {\n return null;\n }\n }\n\n /// \n public async Task> SearchPackagesAsync(\n string query,\n SearchOptions options = null,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(query))\n throw new ArgumentException(\n \"Search query cannot be null or whitespace.\",\n nameof(query)\n );\n\n options ??= new SearchOptions();\n var arguments = new StringBuilder(\n $\"search {EscapeArgument(query)} --accept-source-agreements\"\n );\n\n if (options.IncludeAvailable)\n arguments.Append(\" --available\");\n\n if (options.Count > 0)\n arguments.Append($\" --max {options.Count}\");\n\n try\n {\n var result = await ExecuteWinGetCommandAsync(\n WinGetExe,\n arguments.ToString(),\n null,\n cancellationToken\n )\n .ConfigureAwait(false);\n\n if (result.ExitCode != 0)\n {\n return Enumerable.Empty();\n }\n\n return ParsePackageList(result.Output);\n }\n catch (Exception)\n {\n return Enumerable.Empty();\n }\n }\n\n private IEnumerable GetDefaultVerificationMethods()\n {\n return new IVerificationMethod[]\n {\n new WinGetVerificationMethod(),\n new AppxPackageVerificationMethod(),\n new RegistryVerificationMethod(),\n new FileSystemVerificationMethod(),\n };\n }\n\n /// \n /// Checks if WinGet is available in the PATH.\n /// \n /// True if WinGet is in the PATH, false otherwise.\n private bool IsWinGetInPath()\n {\n var pathEnv = Environment.GetEnvironmentVariable(\"PATH\") ?? string.Empty;\n return pathEnv\n .Split(Path.PathSeparator)\n .Any(p => !string.IsNullOrEmpty(p) && File.Exists(Path.Combine(p, WinGetExe)));\n }\n \n /// \n /// Tries to verify WinGet is working by running a simple command (winget -v)\n /// \n /// True if WinGet command works, false otherwise\n private bool TryVerifyWinGetCommand()\n {\n try\n {\n _logService?.LogInformation(\"Verifying WinGet by running 'winget -v' command\");\n \n // Create a process to run WinGet version command\n var processStartInfo = new ProcessStartInfo\n {\n FileName = WinGetExe,\n Arguments = \"-v\",\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n UseShellExecute = false,\n CreateNoWindow = true,\n };\n \n using (var process = new Process { StartInfo = processStartInfo })\n {\n try\n {\n if (process.Start())\n {\n // Wait for the process to exit with a timeout\n if (process.WaitForExit(5000)) // 5 second timeout\n {\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n \n // If we got output and no error, WinGet is working\n if (!string.IsNullOrWhiteSpace(output) && string.IsNullOrWhiteSpace(error))\n {\n _logService?.LogInformation($\"WinGet command verification successful, version: {output.Trim()}\");\n return true;\n }\n else if (!string.IsNullOrWhiteSpace(error))\n {\n _logService?.LogWarning($\"WinGet command verification failed with error: {error.Trim()}\");\n }\n }\n else\n {\n // Process didn't exit within timeout\n _logService?.LogWarning(\"WinGet command verification timed out\");\n try { process.Kill(); } catch { }\n }\n }\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error verifying WinGet command: {ex.Message}\");\n }\n }\n \n // Try an alternative approach - using WindowsApps path directly\n string windowsAppsPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Microsoft\\\\WindowsApps\"\n );\n \n if (Directory.Exists(windowsAppsPath))\n {\n processStartInfo.FileName = Path.Combine(windowsAppsPath, WinGetExe);\n _logService?.LogInformation($\"Trying alternative WinGet path: {processStartInfo.FileName}\");\n \n if (File.Exists(processStartInfo.FileName))\n {\n using (var process = new Process { StartInfo = processStartInfo })\n {\n try\n {\n if (process.Start())\n {\n if (process.WaitForExit(5000))\n {\n string output = process.StandardOutput.ReadToEnd();\n string error = process.StandardError.ReadToEnd();\n \n if (!string.IsNullOrWhiteSpace(output) && string.IsNullOrWhiteSpace(error))\n {\n _logService?.LogInformation($\"Alternative WinGet path verification successful, version: {output.Trim()}\");\n return true;\n }\n }\n }\n }\n catch { }\n }\n }\n }\n \n return false;\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error in TryVerifyWinGetCommand: {ex.Message}\", ex);\n return false;\n }\n }\n\n private async Task TryInstallWinGetAsync(CancellationToken cancellationToken)\n {\n try\n {\n _logService?.LogInformation(\"WinGet not found. Attempting to install WinGet...\");\n\n // Create a progress adapter for the task progress service\n var progressAdapter = new Progress(progress =>\n {\n _taskProgressService?.UpdateDetailedProgress(progress);\n });\n\n // Use the WinGetInstallationScript to install WinGet\n var result = await WinGetInstallationScript.InstallWinGetAsync(\n progressAdapter,\n _logService,\n cancellationToken\n );\n\n bool success = result.Success;\n string message = result.Message;\n\n if (success)\n {\n _logService?.LogInformation(\"WinGet was successfully installed.\");\n return true;\n }\n else\n {\n _logService?.LogError($\"Failed to install WinGet: {message}\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error installing WinGet: {ex.Message}\", ex);\n return false;\n }\n }\n\n private async Task<(string WinGetPath, bool JustInstalled)> FindWinGetPathAsync(\n CancellationToken cancellationToken = default\n )\n {\n // First try to verify WinGet by running a command\n if (TryVerifyWinGetCommand())\n {\n _logService?.LogInformation(\"WinGet command verified and working\");\n return (WinGetExe, false);\n }\n\n // Check if winget is in the PATH\n if (IsWinGetInPath())\n {\n return (WinGetExe, false);\n }\n\n // Check common installation paths\n var possiblePaths = new[]\n {\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n @\"Microsoft\\WindowsApps\\winget.exe\"\n ),\n @\"C:\\Program Files\\WindowsApps\\Microsoft.DesktopAppInstaller_*\\winget.exe\",\n };\n\n // Try to find WinGet in common locations\n string foundPath = null;\n foreach (var pathPattern in possiblePaths)\n {\n if (pathPattern.Contains(\"*\"))\n {\n // Handle wildcard paths\n var directory = Path.GetDirectoryName(pathPattern);\n var filePattern = Path.GetFileName(pathPattern);\n \n if (Directory.Exists(directory))\n {\n var matchingFiles = Directory.GetFiles(directory, filePattern, SearchOption.AllDirectories);\n if (matchingFiles.Length > 0)\n {\n foundPath = matchingFiles[0];\n _logService?.LogInformation($\"Found WinGet at: {foundPath}\");\n return (foundPath, false);\n }\n }\n }\n else if (File.Exists(pathPattern))\n {\n foundPath = pathPattern;\n _logService?.LogInformation($\"Found WinGet at: {foundPath}\");\n return (foundPath, false);\n }\n }\n\n // If WinGet is not found, try to install it\n if (await TryInstallWinGetAsync(cancellationToken))\n {\n _logService?.LogInformation(\"WinGet installation completed, verifying installation\");\n \n // First try to verify WinGet by running a command after installation\n if (TryVerifyWinGetCommand())\n {\n _logService?.LogInformation(\"WinGet command verified and working after installation\");\n return (WinGetExe, true);\n }\n \n // After installation, check if it's now in the PATH\n if (IsWinGetInPath())\n {\n return (WinGetExe, true);\n }\n\n // Check the common paths again\n foreach (var pathPattern in possiblePaths)\n {\n if (pathPattern.Contains(\"*\"))\n {\n // Handle wildcard paths\n var directory = Path.GetDirectoryName(pathPattern);\n var filePattern = Path.GetFileName(pathPattern);\n \n if (Directory.Exists(directory))\n {\n var matchingFiles = Directory.GetFiles(directory, filePattern, SearchOption.AllDirectories);\n if (matchingFiles.Length > 0)\n {\n foundPath = matchingFiles[0];\n _logService?.LogInformation($\"Found WinGet at: {foundPath}\");\n return (foundPath, true);\n }\n }\n }\n else if (File.Exists(pathPattern))\n {\n foundPath = pathPattern;\n _logService?.LogInformation($\"Found WinGet at: {foundPath}\");\n return (foundPath, true);\n }\n }\n }\n\n // If we still can't find it, throw an exception\n throw new InvalidOperationException(\"WinGet not found and installation failed.\");\n }\n\n private string FindWinGetPath()\n {\n try\n {\n // Call the async method synchronously\n var result = FindWinGetPathAsync().GetAwaiter().GetResult();\n return result.WinGetPath;\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error finding WinGet: {ex.Message}\", ex);\n throw;\n }\n }\n\n // Installation states have been moved to WinGetOutputParser.InstallationState\n\n private async Task<(int ExitCode, string Output, string Error)> ExecuteWinGetCommandAsync(\n string command,\n string arguments,\n IProgress progressAdapter = null,\n CancellationToken cancellationToken = default\n )\n {\n var commandLine = $\"{command} {arguments}\";\n _logService?.LogInformation($\"Executing WinGet command: {commandLine}\");\n\n try\n {\n // Find WinGet path or install it if not found\n string winGetPath;\n bool justInstalled = false;\n try\n {\n (winGetPath, justInstalled) = await FindWinGetPathAsync(cancellationToken);\n }\n catch (InvalidOperationException ex)\n {\n _logService?.LogError($\"WinGet error: {ex.Message}\");\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = $\"Error: {ex.Message}\",\n Percentage = 0,\n IsIndeterminate = false,\n }\n );\n return (1, string.Empty, ex.Message);\n }\n \n // If WinGet was just installed, we might need to wait a moment for permissions to be set up\n // This is especially important on LTSC editions where there can be a delay\n if (justInstalled)\n {\n _logService?.LogInformation(\"WinGet was just installed. Waiting briefly before proceeding...\");\n await Task.Delay(2000, cancellationToken); // Wait 2 seconds\n \n // Notify the user that WinGet was installed and we're continuing with the app installation\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"WinGet was successfully installed. Continuing with application installation...\",\n Percentage = 30,\n IsIndeterminate = false,\n }\n );\n \n // For LTSC editions, we need to use a different approach after installation\n // Try to use the full path to WinGet if it's not just \"winget.exe\"\n if (!string.Equals(winGetPath, WinGetExe, StringComparison.OrdinalIgnoreCase))\n {\n _logService?.LogInformation($\"Using full path to WinGet: {winGetPath}\");\n \n // Check if the file exists and is accessible\n if (File.Exists(winGetPath))\n {\n try\n {\n // Test file access permissions\n using (File.OpenRead(winGetPath)) { }\n _logService?.LogInformation(\"Successfully verified file access to WinGet executable\");\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Access issue with WinGet executable: {ex.Message}\");\n _logService?.LogInformation(\"Falling back to using 'winget.exe' command\");\n winGetPath = WinGetExe; // Fall back to using just the command name\n }\n }\n }\n }\n\n // Create a process to run WinGet directly\n var processStartInfo = new ProcessStartInfo\n {\n FileName = winGetPath,\n Arguments = arguments,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n UseShellExecute = false,\n CreateNoWindow = true,\n };\n\n _logService?.LogInformation(\n $\"Starting process: {processStartInfo.FileName} {processStartInfo.Arguments}\"\n );\n\n var process = new Process\n {\n StartInfo = processStartInfo,\n EnableRaisingEvents = true,\n };\n\n var outputBuilder = new StringBuilder();\n var errorBuilder = new StringBuilder();\n\n // Progress tracking is now handled by WinGetOutputParser\n\n // Create an output parser for processing WinGet output\n var outputParser = new WinGetOutputParser(_logService);\n \n // Report initial progress with more detailed status\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Searching for package...\",\n Percentage = 5,\n IsIndeterminate = false,\n }\n );\n\n process.OutputDataReceived += (sender, e) =>\n {\n if (e.Data != null)\n {\n outputBuilder.AppendLine(e.Data);\n \n // Parse the output line and get progress update\n var progress = outputParser.ParseOutputLine(e.Data);\n \n // Report progress if available\n if (progress != null)\n {\n progressAdapter?.Report(progress);\n }\n }\n };\n \n // The parsing functionality has been moved to WinGetOutputParser\n\n process.ErrorDataReceived += (sender, e) =>\n {\n if (e.Data != null)\n {\n errorBuilder.AppendLine(e.Data);\n _logService?.LogError($\"WinGet error: {e.Data}\");\n }\n };\n\n // Start the process\n if (!process.Start())\n {\n _logService?.LogError(\"Failed to start WinGet process\");\n return (1, string.Empty, \"Failed to start WinGet process\");\n }\n\n // Begin reading output and error streams\n process.BeginOutputReadLine();\n process.BeginErrorReadLine();\n\n // Create a task that completes when the process exits\n var processExitTask = Task.Run(\n () =>\n {\n process.WaitForExit();\n return process.ExitCode;\n },\n cancellationToken\n );\n\n // Wait for the process to exit or cancellation\n int exitCode;\n try\n {\n // Create a flag to track whether cancellation was due to user action or connectivity issues\n bool isCancellationDueToConnectivity = false;\n \n // Register cancellation callback to kill the process when cancellation is requested\n using var cancelRegistration = cancellationToken.Register(() =>\n {\n _logService?.LogWarning(\"Cancellation requested, attempting to kill WinGet process\");\n try\n {\n // Check if cancellation is due to connectivity issues\n // This is determined by examining the cancellation token's source\n // The AppInstallationCoordinatorService will set this flag when cancelling due to connectivity\n if (cancellationToken.IsCancellationRequested)\n {\n // We can't directly check the reason for cancellation from the token itself,\n // but the AppInstallationCoordinatorService will handle this distinction\n _logService?.LogWarning(\"WinGet process cancellation requested\");\n }\n \n if (!process.HasExited)\n {\n // Report cancellation progress immediately\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Cancelling installation...\",\n Percentage = 0,\n IsIndeterminate = true,\n IsCancelled = true\n }\n );\n \n // Kill the process and all child processes in a background task\n // to prevent UI stalling\n Task.Run(() => \n {\n try \n {\n KillProcessAndChildren(process.Id);\n _logService?.LogWarning(\"WinGet process and all child processes were killed due to cancellation\");\n \n // Update progress after killing processes\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Installation was cancelled\",\n Percentage = 0,\n IsIndeterminate = false,\n IsCancelled = true\n }\n );\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error killing processes: {ex.Message}\");\n }\n });\n }\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error killing WinGet process: {ex.Message}\");\n }\n });\n \n exitCode = await processExitTask;\n _logService?.LogInformation($\"WinGet process exited with code: {exitCode}\");\n\n // Report completion progress\n if (exitCode == 0)\n {\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Installation completed successfully\",\n Percentage = 100,\n IsIndeterminate = false,\n }\n );\n }\n else\n {\n // Report failure progress\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = $\"Installation failed with exit code: {exitCode}\",\n Percentage = 100,\n IsIndeterminate = false,\n IsError = true\n }\n );\n }\n }\n catch (OperationCanceledException)\n {\n _logService?.LogWarning(\"WinGet process execution was cancelled\");\n\n // Try to kill the process if it's still running\n if (!process.HasExited)\n {\n try\n {\n // Report cancellation progress immediately\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Cancelling installation...\",\n Percentage = 0,\n IsIndeterminate = true,\n IsCancelled = true\n }\n );\n \n // Kill the process and all child processes in a background task\n Task.Run(() => \n {\n try \n {\n KillProcessAndChildren(process.Id);\n _logService?.LogWarning(\n \"WinGet process and all child processes were killed due to cancellation\"\n );\n \n // Update progress after killing processes\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Installation was cancelled\",\n Percentage = 0,\n IsIndeterminate = false,\n IsCancelled = true\n }\n );\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error killing processes: {ex.Message}\");\n }\n });\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error killing WinGet process: {ex.Message}\");\n }\n }\n \n // Report cancellation progress\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = \"Installation was cancelled\",\n Percentage = 0,\n IsIndeterminate = false,\n IsCancelled = true\n }\n );\n\n throw;\n }\n\n string output = outputBuilder.ToString();\n string error = errorBuilder.ToString();\n\n return (exitCode, output, error);\n }\n catch (Exception ex) when (!(ex is OperationCanceledException))\n {\n _logService?.LogError($\"Error executing WinGet command: {ex.Message}\", ex);\n\n // Report error progress\n progressAdapter?.Report(\n new InstallationProgress\n {\n Status = $\"Error: {ex.Message}\",\n Percentage = 0,\n IsIndeterminate = false,\n }\n );\n\n return (1, string.Empty, ex.Message);\n }\n }\n\n // These methods have been moved to WinGetOutputParser class:\n // - DetermineInstallationState\n // - CalculateProgressPercentage\n // - GetStatusMessage\n\n // Original FindWinGetPath method removed to avoid duplication\n\n /// \n /// Kills a process and all of its children recursively with optimizations to prevent UI stalling.\n /// \n /// The process ID to kill.\n private void KillProcessAndChildren(int pid)\n {\n try\n {\n // First, directly kill any Windows Store processes that might be related to the installation\n // This is a more direct approach to ensure the installation is cancelled\n KillWindowsStoreProcesses();\n \n // Get the process by ID\n Process process = null;\n try\n {\n process = Process.GetProcessById(pid);\n }\n catch (ArgumentException)\n {\n _logService?.LogWarning($\"Process with ID {pid} not found\");\n return;\n }\n \n // Use a more efficient approach to kill the process and its children\n // with a timeout to prevent hanging\n using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)))\n {\n try\n {\n // Kill the process directly first\n if (!process.HasExited)\n {\n try\n {\n process.Kill(true); // true = kill entire process tree (Windows 10 1809+)\n _logService?.LogInformation($\"Killed process tree {process.ProcessName} (ID: {pid})\");\n return; // If this works, we're done\n }\n catch (PlatformNotSupportedException)\n {\n // Process.Kill(true) is not supported on this platform, continue with fallback\n _logService?.LogInformation(\"Process.Kill(true) not supported, using fallback method\");\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error killing process tree: {ex.Message}, using fallback method\");\n }\n }\n \n // Fallback: Kill the process and its children manually\n KillProcessTree(pid, cts.Token);\n }\n catch (OperationCanceledException)\n {\n _logService?.LogWarning(\"Process killing operation timed out\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error in KillProcessAndChildren for PID {pid}: {ex.Message}\");\n }\n }\n \n /// \n /// Kills the Windows Store processes that might be related to the installation.\n /// \n private void KillWindowsStoreProcesses()\n {\n try\n {\n // Target specific processes known to be related to Windows Store installations\n string[] targetProcessNames = new[] { \n \"WinStore.App\", \n \"WinStore.Mobile\", \n \"WindowsPackageManagerServer\", \n \"AppInstaller\",\n \"Microsoft.WindowsStore\"\n };\n \n foreach (var processName in targetProcessNames)\n {\n try\n {\n var processes = Process.GetProcessesByName(processName);\n foreach (var process in processes)\n {\n try\n {\n if (!process.HasExited)\n {\n process.Kill();\n _logService?.LogInformation($\"Killed Windows Store process: {processName}\");\n }\n }\n finally\n {\n process.Dispose();\n }\n }\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error killing Windows Store process {processName}: {ex.Message}\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error killing Windows Store processes: {ex.Message}\");\n }\n }\n \n /// \n /// Kills a process tree efficiently with cancellation support.\n /// \n /// The process ID to kill.\n /// Cancellation token to prevent hanging.\n private void KillProcessTree(int pid, CancellationToken cancellationToken)\n {\n try\n {\n // Get direct child processes using a more efficient method\n var childProcessIds = GetChildProcessIds(pid);\n \n // Kill child processes first\n foreach (var childPid in childProcessIds)\n {\n cancellationToken.ThrowIfCancellationRequested();\n \n try\n {\n // Recursively kill child process trees\n KillProcessTree(childPid, cancellationToken);\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error killing child process {childPid}: {ex.Message}\");\n }\n }\n \n // Kill the parent process\n try\n {\n var process = Process.GetProcessById(pid);\n if (!process.HasExited)\n {\n process.Kill();\n _logService?.LogInformation($\"Killed process {process.ProcessName} (ID: {pid})\");\n }\n process.Dispose();\n }\n catch (ArgumentException)\n {\n // Process already exited\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error killing process {pid}: {ex.Message}\");\n }\n }\n catch (OperationCanceledException)\n {\n throw; // Rethrow to be handled by the caller\n }\n catch (Exception ex)\n {\n _logService?.LogError($\"Error in KillProcessTree for PID {pid}: {ex.Message}\");\n }\n }\n \n /// \n /// Gets the child process IDs for a given process ID efficiently.\n /// \n /// The parent process ID.\n /// A list of child process IDs.\n private List GetChildProcessIds(int parentId)\n {\n var result = new List();\n \n try\n {\n // Use a more efficient query that only gets the data we need\n using (var searcher = new System.Management.ManagementObjectSearcher(\n $\"SELECT ProcessId FROM Win32_Process WHERE ParentProcessId = {parentId}\"))\n {\n searcher.Options.Timeout = TimeSpan.FromSeconds(1); // Set a timeout to prevent hanging\n \n foreach (var obj in searcher.Get())\n {\n try\n {\n result.Add(Convert.ToInt32(obj[\"ProcessId\"]));\n }\n catch\n {\n // Skip this entry if conversion fails\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService?.LogWarning($\"Error getting child process IDs: {ex.Message}\");\n }\n \n return result;\n }\n \n private string EscapeArgument(string arg)\n {\n if (string.IsNullOrEmpty(arg))\n return \"\\\"\\\"\";\n\n // Escape any double quotes\n arg = arg.Replace(\"\\\"\", \"\\\\\\\"\");\n\n // Surround with quotes if it contains spaces\n if (arg.Contains(\" \"))\n arg = $\"\\\"{arg}\\\"\";\n\n return arg;\n }\n\n private PackageInfo ParsePackageInfo(string output)\n {\n if (string.IsNullOrWhiteSpace(output))\n return null;\n\n var info = new PackageInfo();\n var lines = output.Split(\n new[] { \"\\r\\n\", \"\\r\", \"\\n\" },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n foreach (var line in lines)\n {\n if (!line.Contains(\":\"))\n continue;\n\n var parts = line.Split(new[] { ':' }, 2);\n if (parts.Length != 2)\n continue;\n\n var key = parts[0].Trim().ToLowerInvariant();\n var value = parts[1].Trim();\n\n switch (key)\n {\n case \"id\":\n info.Id = value;\n break;\n case \"name\":\n info.Name = value;\n break;\n case \"version\":\n info.Version = value;\n break;\n // Description property doesn't exist in PackageInfo\n case \"description\":\n // info.Description = value;\n break;\n }\n }\n\n return info;\n }\n\n private IEnumerable ParsePackageList(string output)\n {\n if (string.IsNullOrWhiteSpace(output))\n yield break;\n\n var lines = output.Split(\n new[] { \"\\r\\n\", \"\\r\", \"\\n\" },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n // Skip header lines\n bool headerPassed = false;\n for (int i = 0; i < lines.Length; i++)\n {\n var line = lines[i].Trim();\n\n // Skip empty lines\n if (string.IsNullOrWhiteSpace(line))\n continue;\n\n // Skip until we find a line with dashes (header separator)\n if (!headerPassed)\n {\n if (line.Contains(\"---\"))\n {\n headerPassed = true;\n }\n continue;\n }\n\n // Parse package info from the line\n var parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (parts.Length < 3)\n continue;\n\n yield return new PackageInfo\n {\n Name = parts[0],\n Id = parts[1],\n Version = parts[2],\n Source = parts.Length > 3 ? parts[3] : string.Empty,\n IsInstalled = line.Contains(\"[Installed]\"),\n };\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/OptimizeView.xaml.cs", "using System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing MaterialDesignThemes.Wpf;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Messages;\nusing Winhance.WPF.Features.Optimize.ViewModels;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n public partial class OptimizeView : UserControl\n {\n private IMessengerService? _messengerService; // Changed from readonly to allow assignment\n \n // References to the child views\n private UIElement _windowsSecurityOptimizationsView;\n private UIElement _privacySettingsView;\n private UIElement _gamingandPerformanceOptimizationsView;\n private UIElement _updateOptimizationsView;\n private UIElement _powerSettingsView;\n private UIElement _explorerOptimizationsView;\n private UIElement _notificationOptimizationsView;\n private UIElement _soundOptimizationsView;\n\n public OptimizeView()\n {\n InitializeComponent();\n Loaded += OptimizeView_Loaded;\n\n // Initialize section visibility and click handlers - all visible by default\n // WindowsSecurityContent will be initialized in the Loaded event\n\n // Add click handlers to the header border elements\n WindowsSecurityHeaderBorder.MouseDown += WindowsSecurityHeader_MouseDown;\n PrivacyHeaderBorder.MouseDown += PrivacyHeader_MouseDown;\n GamingHeaderBorder.MouseDown += GamingHeader_MouseDown;\n UpdatesHeaderBorder.MouseDown += UpdatesHeader_MouseDown;\n PowerHeaderBorder.MouseDown += PowerHeader_MouseDown;\n ExplorerHeaderBorder.MouseDown += ExplorerHeader_MouseDown;\n NotificationHeaderBorder.MouseDown += NotificationHeader_MouseDown;\n SoundHeaderBorder.MouseDown += SoundHeader_MouseDown;\n \n // Subscribe to DataContextChanged event to get the messenger service\n DataContextChanged += OptimizeView_DataContextChanged;\n }\n \n private void OptimizeView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n // Unregister from old messenger service if exists\n if (_messengerService != null)\n {\n _messengerService.Unregister(this);\n _messengerService = null;\n }\n\n // Register with new messenger service if available\n if (e.NewValue is OptimizeViewModel viewModel &&\n viewModel.MessengerService is IMessengerService messengerService)\n {\n _messengerService = messengerService;\n \n // Subscribe to the message that signals resetting expansion states\n _messengerService.Register(this, OnResetExpansionState);\n }\n }\n \n private void OnResetExpansionState(ResetExpansionStateMessage message)\n {\n // Reset all section expansion states to expanded\n if (_windowsSecurityOptimizationsView != null)\n {\n _windowsSecurityOptimizationsView.Visibility = Visibility.Visible;\n WindowsSecurityHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_privacySettingsView != null)\n {\n _privacySettingsView.Visibility = Visibility.Visible;\n PrivacyHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_gamingandPerformanceOptimizationsView != null)\n {\n _gamingandPerformanceOptimizationsView.Visibility = Visibility.Visible;\n GamingHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_updateOptimizationsView != null)\n {\n _updateOptimizationsView.Visibility = Visibility.Visible;\n UpdatesHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_powerSettingsView != null)\n {\n _powerSettingsView.Visibility = Visibility.Visible;\n PowerHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_explorerOptimizationsView != null)\n {\n _explorerOptimizationsView.Visibility = Visibility.Visible;\n ExplorerHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_notificationOptimizationsView != null)\n {\n _notificationOptimizationsView.Visibility = Visibility.Visible;\n NotificationHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n \n if (_soundOptimizationsView != null)\n {\n _soundOptimizationsView.Visibility = Visibility.Visible;\n SoundHeaderIcon.Kind = PackIconKind.ChevronUp;\n }\n }\n\n private async void OptimizeView_Loaded(object sender, RoutedEventArgs e)\n {\n if (DataContext is Winhance.WPF.Features.Optimize.ViewModels.OptimizeViewModel viewModel)\n {\n try\n {\n // Find the child views\n _windowsSecurityOptimizationsView = FindChildByType(this);\n _privacySettingsView = FindChildByType(this);\n _gamingandPerformanceOptimizationsView = FindChildByType(this);\n _updateOptimizationsView = FindChildByType(this);\n _powerSettingsView = FindChildByType(this);\n _explorerOptimizationsView = FindChildByType(this);\n _notificationOptimizationsView = FindChildByType(this);\n _soundOptimizationsView = FindChildByType(this);\n\n // Set initial visibility\n if (_windowsSecurityOptimizationsView != null) _windowsSecurityOptimizationsView.Visibility = Visibility.Visible;\n if (_privacySettingsView != null) _privacySettingsView.Visibility = Visibility.Visible;\n if (_gamingandPerformanceOptimizationsView != null) _gamingandPerformanceOptimizationsView.Visibility = Visibility.Visible;\n if (_updateOptimizationsView != null) _updateOptimizationsView.Visibility = Visibility.Visible;\n if (_powerSettingsView != null) _powerSettingsView.Visibility = Visibility.Visible;\n if (_explorerOptimizationsView != null) _explorerOptimizationsView.Visibility = Visibility.Visible;\n if (_notificationOptimizationsView != null) _notificationOptimizationsView.Visibility = Visibility.Visible;\n if (_soundOptimizationsView != null) _soundOptimizationsView.Visibility = Visibility.Visible;\n\n // Set header icons\n WindowsSecurityHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n PrivacyHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n GamingHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n UpdatesHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n PowerHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n ExplorerHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n NotificationHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n SoundHeaderIcon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n\n // Initialize data if needed\n if (viewModel.InitializeCommand != null)\n {\n Console.WriteLine(\"OptimizeView: Executing InitializeCommand\");\n await viewModel.InitializeCommand.ExecuteAsync(null);\n Console.WriteLine(\"OptimizeView: InitializeCommand completed successfully\");\n }\n else\n {\n MessageBox.Show(\"InitializeCommand is null in OptimizeViewModel\",\n \"Initialization Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error);\n }\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"OptimizeView: Error initializing - {ex.Message}\");\n MessageBox.Show($\"Error initializing Optimize view: {ex.Message}\",\n \"Initialization Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error);\n }\n }\n else\n {\n Console.WriteLine(\"OptimizeView: DataContext is not OptimizeViewModel\");\n MessageBox.Show(\"DataContext is not OptimizeViewModel\",\n \"Initialization Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error);\n }\n }\n\n private void WindowsSecurityHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n try\n {\n // Toggle section visibility\n ToggleSectionVisibility(_windowsSecurityOptimizationsView, WindowsSecurityHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n WindowsSecurityToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true; // Mark as handled to prevent the event from bubbling up\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Error toggling Windows Security Settings section: {ex.Message}\",\n \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n }\n }\n\n private void PrivacyHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n try\n {\n // Toggle section visibility\n ToggleSectionVisibility(_privacySettingsView, PrivacyHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n PrivacyToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true; // Mark as handled to prevent the event from bubbling up\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Error toggling Privacy Settings section: {ex.Message}\",\n \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n }\n }\n\n private void GamingHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_gamingandPerformanceOptimizationsView, GamingHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n GamingToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void UpdatesHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_updateOptimizationsView, UpdatesHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n UpdatesToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void PowerHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_powerSettingsView, PowerHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n PowerToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void ExplorerHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_explorerOptimizationsView, ExplorerHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n ExplorerToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void NotificationHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_notificationOptimizationsView, NotificationHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n NotificationToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void SoundHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n // Toggle section visibility\n ToggleSectionVisibility(_soundOptimizationsView, SoundHeaderIcon);\n\n // Toggle the selection state by clicking the hidden button\n if (e.OriginalSource is not Button) // Don't trigger if we clicked the hidden button\n {\n SoundToggleButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));\n }\n\n e.Handled = true;\n }\n\n private void ToggleSectionVisibility(UIElement content, PackIcon icon)\n {\n if (content == null) return;\n\n if (content.Visibility == Visibility.Collapsed)\n {\n content.Visibility = Visibility.Visible;\n icon.Kind = PackIconKind.ChevronUp; // Upward arrow for expanded state\n }\n else\n {\n content.Visibility = Visibility.Collapsed;\n icon.Kind = PackIconKind.ChevronDown; // Downward arrow for collapsed state\n }\n }\n\n /// \n /// Finds a child element of the specified type in the visual tree.\n /// \n /// The type of element to find.\n /// The parent element to search in.\n /// The first child element of the specified type, or null if not found.\n private T FindChildByType(DependencyObject parent) where T : DependencyObject\n {\n // Confirm parent and type are valid\n if (parent == null) return null;\n\n // Get child count\n int childCount = VisualTreeHelper.GetChildrenCount(parent);\n\n // Check all children\n for (int i = 0; i < childCount; i++)\n {\n var child = VisualTreeHelper.GetChild(parent, i);\n\n // If the child is the type we're looking for, return it\n if (child is T typedChild)\n {\n return typedChild;\n }\n\n // Otherwise, recursively check this child's children\n var result = FindChildByType(child);\n if (result != null)\n {\n return result;\n }\n }\n\n // If we get here, we didn't find a match\n return null;\n }\n }\n\n // Extension method to check if a visual element is a descendant of another\n public static class VisualExtensions\n {\n public static bool IsDescendantOf(this System.Windows.DependencyObject element, System.Windows.DependencyObject parent)\n {\n if (element == parent)\n return true;\n\n var currentParent = System.Windows.Media.VisualTreeHelper.GetParent(element);\n while (currentParent != null)\n {\n if (currentParent == parent)\n return true;\n currentParent = System.Windows.Media.VisualTreeHelper.GetParent(currentParent);\n }\n\n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScriptUpdateService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\n/// \n/// Implementation of IScriptUpdateService that provides methods for updating script content.\n/// \npublic class ScriptUpdateService : IScriptUpdateService\n{\n private readonly ILogService _logService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IScriptContentModifier _scriptContentModifier;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The app discovery service.\n /// The script content modifier.\n public ScriptUpdateService(\n ILogService logService,\n IAppDiscoveryService appDiscoveryService,\n IScriptContentModifier scriptContentModifier)\n {\n _logService = logService;\n _appDiscoveryService = appDiscoveryService;\n _scriptContentModifier = scriptContentModifier;\n }\n\n /// \n public async Task UpdateExistingBloatRemovalScriptAsync(\n List appNames,\n Dictionary> appsWithRegistry,\n Dictionary appSubPackages,\n bool isInstallOperation = false)\n {\n try\n {\n string bloatRemovalScriptPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n \"Winhance\",\n \"Scripts\",\n \"BloatRemoval.ps1\"\n );\n \n _logService.LogInformation($\"Checking for BloatRemoval.ps1 at path: {bloatRemovalScriptPath}\");\n \n string scriptContent;\n \n if (!File.Exists(bloatRemovalScriptPath))\n {\n _logService.LogWarning($\"BloatRemoval.ps1 file not found at: {bloatRemovalScriptPath}\");\n \n // Create the directory if it doesn't exist\n string scriptDirectory = Path.GetDirectoryName(bloatRemovalScriptPath);\n if (!Directory.Exists(scriptDirectory))\n {\n _logService.LogInformation($\"Creating directory: {scriptDirectory}\");\n Directory.CreateDirectory(scriptDirectory);\n }\n \n // Create a basic BloatRemoval.ps1 file if it doesn't exist\n _logService.LogInformation(\"Creating a new BloatRemoval.ps1 file\");\n string basicScriptContent = @\"\n# BloatRemoval.ps1\n# This script removes Windows bloatware apps and prevents them from reinstalling\n# Source: Winhance (https://github.com/memstechtips/Winhance)\n# Generated by Winhance on \" + DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\") + @\"\n\n#region Definitions\n# Capabilities to remove\n$capabilities = @(\n)\n\n# Packages to remove\n$packages = @(\n)\n\n# Optional Features to disable\n$optionalFeatures = @(\n)\n#endregion\n\n#region Process Capabilities\nWrite-Host \"\"=== Removing Windows Capabilities ===\"\" -ForegroundColor Cyan\nforeach ($capability in $capabilities) {\n Write-Host \"\"Removing capability: $capability\"\" -ForegroundColor Yellow\n Remove-WindowsCapability -Online -Name $capability | Out-Null\n}\n#endregion\n\n#region Process Packages\nWrite-Host \"\"=== Removing Windows Apps ===\"\" -ForegroundColor Cyan\nforeach ($package in $packages) {\n Write-Host \"\"Removing package: $package\"\" -ForegroundColor Yellow\n Get-AppxPackage -Name $package -AllUsers | ForEach-Object {\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }\n}\n#endregion\n\n#region Process Optional Features\nWrite-Host \"\"=== Disabling Optional Features ===\"\" -ForegroundColor Cyan\nforeach ($feature in $optionalFeatures) {\n Write-Host \"\"Disabling optional feature: $feature\"\" -ForegroundColor Yellow\n Disable-WindowsOptionalFeature -Online -FeatureName $feature -NoRestart | Out-Null\n}\n#endregion\n\n#region Registry Settings\n# Registry settings\n#endregion\n\n# Prevent apps from reinstalling\nreg add \"\"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\CloudContent\"\" /v \"\"DisableWindowsConsumerFeatures\"\" /t REG_DWORD /d 1 /f | Out-Null\n\n\";\n await File.WriteAllTextAsync(bloatRemovalScriptPath, basicScriptContent);\n scriptContent = basicScriptContent;\n _logService.LogInformation(\"Created new BloatRemoval.ps1 file\");\n }\n else\n {\n _logService.LogInformation(\"BloatRemoval.ps1 file found, reading content\");\n scriptContent = await File.ReadAllTextAsync(bloatRemovalScriptPath);\n }\n\n // Separate capabilities, packages, and optional features\n var capabilities = new List();\n var packages = new List();\n var optionalFeatures = new List();\n\n foreach (var appName in appNames)\n {\n if (\n !appName.Equals(\"Edge\", StringComparison.OrdinalIgnoreCase)\n && !appName.Equals(\"OneDrive\", StringComparison.OrdinalIgnoreCase)\n )\n {\n // Check if this is an OptionalFeature\n bool isOptionalFeature = false;\n bool isCapability = false;\n\n // Get app info from the catalog\n var allRemovableApps = (\n await _appDiscoveryService.GetStandardAppsAsync()\n ).ToList();\n var appInfo = allRemovableApps.FirstOrDefault(a =>\n a.PackageName.Equals(appName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (appInfo != null)\n {\n isOptionalFeature = appInfo.Type == AppType.OptionalFeature;\n isCapability = appInfo.Type == AppType.Capability;\n }\n\n // Check if this app has registry settings\n if (appsWithRegistry.TryGetValue(appName, out var registrySettings))\n {\n // Look for a special metadata registry setting that indicates if this is a capability\n var capabilitySetting = registrySettings.FirstOrDefault(s =>\n s.Name.Equals(\"IsCapability\", StringComparison.OrdinalIgnoreCase)\n );\n\n if (\n capabilitySetting != null\n && capabilitySetting.Value is bool capabilityValue\n )\n {\n isCapability = capabilityValue;\n }\n }\n\n // Extract the base name without version for capability detection\n string baseAppName = appName;\n if (appName.Contains(\"~~~~\"))\n {\n // Extract the base name before the version (~~~~)\n baseAppName = appName.Split('~')[0];\n _logService.LogInformation($\"Extracted base capability name '{baseAppName}' from '{appName}'\");\n }\n \n // Check if this is a known Windows optional feature\n if (\n appName.Equals(\"Recall\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"NetFx3\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"Microsoft-Hyper-V-All\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"Microsoft-Hyper-V-Tools-All\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"Microsoft-Hyper-V-Hypervisor\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"Microsoft-Windows-Subsystem-Linux\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"MicrosoftCorporationII.WindowsSubsystemForAndroid\", StringComparison.OrdinalIgnoreCase) ||\n appName.Equals(\"Containers-DisposableClientVM\", StringComparison.OrdinalIgnoreCase) ||\n isOptionalFeature\n )\n {\n _logService.LogInformation($\"Adding {appName} to optional features array\");\n optionalFeatures.Add(appName);\n continue;\n }\n \n // Known capabilities have specific formats\n if (\n isCapability\n || baseAppName.Equals(\n \"Browser.InternetExplorer\",\n StringComparison.OrdinalIgnoreCase\n )\n || baseAppName.Equals(\"MathRecognizer\", StringComparison.OrdinalIgnoreCase)\n || baseAppName.Equals(\"OpenSSH.Client\", StringComparison.OrdinalIgnoreCase)\n || baseAppName.Equals(\"OpenSSH.Server\", StringComparison.OrdinalIgnoreCase)\n || baseAppName.Equals(\n \"Microsoft.Windows.PowerShell.ISE\",\n StringComparison.OrdinalIgnoreCase\n )\n || baseAppName.Equals(\"App.StepsRecorder\", StringComparison.OrdinalIgnoreCase)\n || baseAppName.Equals(\n \"Media.WindowsMediaPlayer\",\n StringComparison.OrdinalIgnoreCase\n )\n || baseAppName.Equals(\n \"App.Support.QuickAssist\",\n StringComparison.OrdinalIgnoreCase\n )\n || baseAppName.Equals(\n \"Microsoft.Windows.WordPad\",\n StringComparison.OrdinalIgnoreCase\n )\n || baseAppName.Equals(\n \"Microsoft.Windows.MSPaint\",\n StringComparison.OrdinalIgnoreCase\n )\n // Check if the app name contains version numbers in the format ~~~~0.0.1.0\n || appName.Contains(\"~~~~\")\n )\n {\n _logService.LogInformation($\"Adding {appName} to capabilities array\");\n capabilities.Add(appName);\n }\n else\n {\n // Explicitly handle Copilot and Xbox packages\n bool isCopilotOrXbox =\n appName.Contains(\"Copilot\", StringComparison.OrdinalIgnoreCase)\n || appName.Contains(\"Xbox\", StringComparison.OrdinalIgnoreCase);\n \n _logService.LogInformation($\"Adding {appName} to packages array\");\n packages.Add(appName);\n }\n }\n }\n\n // Process subpackages and add them to the packages list\n if (appSubPackages != null && appSubPackages.Count > 0)\n {\n _logService.LogInformation(\n $\"Processing {appSubPackages.Count} app entries with subpackages\"\n );\n\n foreach (var packageEntry in appSubPackages)\n {\n string parentPackage = packageEntry.Key;\n string[] subPackages = packageEntry.Value;\n\n // Only process subpackages if the parent package is in the packages list\n // or if it's a special case like Copilot or Xbox\n bool isSpecialApp =\n parentPackage.Contains(\"Copilot\", StringComparison.OrdinalIgnoreCase)\n || parentPackage.Contains(\"Xbox\", StringComparison.OrdinalIgnoreCase)\n || parentPackage.Equals(\n \"Microsoft.GamingApp\",\n StringComparison.OrdinalIgnoreCase\n );\n\n if (packages.Contains(parentPackage) || isSpecialApp)\n {\n if (subPackages != null && subPackages.Length > 0)\n {\n _logService.LogInformation(\n $\"Adding {subPackages.Length} subpackages for {parentPackage}\"\n );\n\n foreach (var subPackage in subPackages)\n {\n if (\n !packages.Contains(subPackage, StringComparer.OrdinalIgnoreCase)\n )\n {\n _logService.LogInformation(\n $\"Adding subpackage: {subPackage} for {parentPackage}\"\n );\n packages.Add(subPackage);\n }\n }\n }\n }\n }\n }\n\n // Update the script content with new entries\n if (capabilities.Count > 0)\n {\n scriptContent = UpdateCapabilitiesArrayInScript(scriptContent, capabilities, isInstallOperation);\n }\n\n if (optionalFeatures.Count > 0)\n {\n scriptContent = UpdateOptionalFeaturesInScript(scriptContent, optionalFeatures, isInstallOperation);\n }\n\n if (packages.Count > 0)\n {\n scriptContent = UpdatePackagesArrayInScript(scriptContent, packages, isInstallOperation);\n }\n\n if (appsWithRegistry.Count > 0)\n {\n scriptContent = UpdateRegistrySettingsInScript(scriptContent, appsWithRegistry);\n }\n\n // Save the updated script\n await File.WriteAllTextAsync(bloatRemovalScriptPath, scriptContent);\n\n // Return the updated script\n return new RemovalScript\n {\n Name = \"BloatRemoval\",\n Content = scriptContent,\n TargetScheduledTaskName = \"Winhance\\\\BloatRemoval\",\n RunOnStartup = true,\n };\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating existing BloatRemoval script: {ex.Message}\", ex);\n _logService.LogError($\"Stack trace: {ex.StackTrace}\");\n \n // Create a basic error report\n try\n {\n string errorReportPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.Desktop),\n \"WinhanceScriptUpdateError.txt\"\n );\n \n string errorReport = $@\"\nScript Update Error Report\nTime: {DateTime.Now}\nError: {ex.Message}\nStack Trace: {ex.StackTrace}\nInner Exception: {ex.InnerException?.Message}\n\nApp Names: {string.Join(\", \", appNames)}\nApps with Registry: {appsWithRegistry.Count}\nApp SubPackages: {appSubPackages.Count}\n\";\n \n await File.WriteAllTextAsync(errorReportPath, errorReport);\n _logService.LogInformation($\"Error report written to: {errorReportPath}\");\n }\n catch (Exception reportEx)\n {\n _logService.LogError($\"Failed to write error report: {reportEx.Message}\");\n }\n \n throw;\n }\n }\n\n /// \n public string UpdateCapabilitiesArrayInScript(string scriptContent, List capabilities, bool isInstallOperation = false)\n {\n try\n {\n _logService.LogInformation($\"Updating capabilities array with {capabilities.Count} capabilities\");\n\n // Find the capabilities array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$capabilities = @(\");\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $capabilities array in BloatRemoval.ps1\");\n \n // If this is an install operation, we don't need to add anything\n if (isInstallOperation)\n {\n _logService.LogInformation(\"Install operation with no capabilities array found - nothing to remove\");\n return scriptContent;\n }\n \n // For removal operations, we need to add the capabilities array and processing code\n _logService.LogInformation(\"Creating capabilities array in BloatRemoval.ps1\");\n \n // Find a good place to insert the section (at the beginning of the script or before packages)\n int insertIndex = scriptContent.IndexOf(\"$packages = @(\");\n if (insertIndex == -1)\n {\n // If no packages array, find the first non-comment line\n var scriptLines = scriptContent.Split('\\n');\n for (int i = 0; i < scriptLines.Length; i++)\n {\n if (!scriptLines[i].TrimStart().StartsWith(\"#\") && !string.IsNullOrWhiteSpace(scriptLines[i]))\n {\n insertIndex = scriptContent.IndexOf(scriptLines[i]);\n break;\n }\n }\n \n // If still not found, insert at the beginning\n if (insertIndex == -1)\n {\n insertIndex = 0;\n }\n }\n \n // Create the capabilities section\n var capabilitiesSection = new StringBuilder();\n capabilitiesSection.AppendLine(\"# Capabilities to remove\");\n capabilitiesSection.AppendLine(\"$capabilities = @(\");\n \n // Add capabilities without trailing comma on the last item\n for (int i = 0; i < capabilities.Count; i++)\n {\n string capability = capabilities[i];\n if (i < capabilities.Count - 1)\n {\n capabilitiesSection.AppendLine($\" '{capability}',\");\n }\n else\n {\n capabilitiesSection.AppendLine($\" '{capability}'\");\n }\n }\n \n capabilitiesSection.AppendLine(\")\");\n capabilitiesSection.AppendLine();\n capabilitiesSection.AppendLine(\"# Process capabilities\");\n capabilitiesSection.AppendLine(\"foreach ($capability in $capabilities) {\");\n capabilitiesSection.AppendLine(\" Write-Host \\\"Removing capability: $capability\\\" -ForegroundColor Yellow\");\n capabilitiesSection.AppendLine(\" Remove-WindowsCapability -Online -Name $capability | Out-Null\");\n capabilitiesSection.AppendLine(\"}\");\n capabilitiesSection.AppendLine();\n \n // Insert the section\n return scriptContent.Substring(0, insertIndex) \n + capabilitiesSection.ToString() \n + scriptContent.Substring(insertIndex);\n }\n\n // Find the end of the capabilities array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find end of $capabilities array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the capabilities in the array\n var existingCapabilities = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var capability = trimmedLine.Trim('\\'', '\"', ' ', ',');\n existingCapabilities.Add(capability);\n }\n }\n\n bool modified = false;\n \n if (isInstallOperation)\n {\n // For install operations, REMOVE the capability from the list\n foreach (var capability in capabilities)\n {\n // Extract the base name without version for capability matching\n string baseCapabilityName = capability;\n if (capability.Contains(\"~~~~\"))\n {\n // Extract the base name before the version (~~~~)\n baseCapabilityName = capability.Split('~')[0];\n _logService.LogInformation($\"Extracted base capability name '{baseCapabilityName}' from '{capability}' for removal\");\n }\n \n // Find any capability in the list that matches the base name (regardless of version)\n var matchingCapabilities = existingCapabilities\n .Where(c => c.StartsWith(baseCapabilityName, StringComparison.OrdinalIgnoreCase) || \n (c.Contains(\"~~~~\") && c.Split('~')[0].Equals(baseCapabilityName, StringComparison.OrdinalIgnoreCase)))\n .ToList();\n \n foreach (var matchingCapability in matchingCapabilities)\n {\n existingCapabilities.Remove(matchingCapability);\n _logService.LogInformation($\"Removed capability: {matchingCapability} from BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n // Even if no capabilities were found to remove, we should still return the updated script\n // This ensures the method doesn't exit early when no matches are found\n if (!modified)\n {\n _logService.LogInformation(\"No capabilities to remove from BloatRemoval.ps1\");\n }\n }\n else\n {\n // For removal operations, ADD the capability to the list\n foreach (var capability in capabilities)\n {\n if (!existingCapabilities.Contains(capability, StringComparer.OrdinalIgnoreCase))\n {\n existingCapabilities.Add(capability);\n _logService.LogInformation($\"Added capability: {capability} to BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n if (!modified)\n {\n _logService.LogInformation(\"No new capabilities to add to BloatRemoval.ps1\");\n return scriptContent;\n }\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$capabilities = @(\");\n\n // Add capabilities without trailing comma on the last item\n for (int i = 0; i < existingCapabilities.Count; i++)\n {\n string capability = existingCapabilities[i];\n if (i < existingCapabilities.Count - 1)\n {\n newArrayContent.AppendLine($\" '{capability}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{capability}'\");\n }\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error updating capabilities array in script\", ex);\n return scriptContent;\n }\n }\n\n /// \n public string UpdatePackagesArrayInScript(string scriptContent, List packages, bool isInstallOperation = false)\n {\n try\n {\n _logService.LogInformation($\"Updating packages array with {packages.Count} packages\");\n\n // Find the packages array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$packages = @(\");\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the packages array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find end of $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the packages in the array\n var existingPackages = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var package = trimmedLine.Trim('\\'', '\"', ' ', ',');\n existingPackages.Add(package);\n }\n }\n\n bool modified = false;\n \n if (isInstallOperation)\n {\n // For install operations, REMOVE the package from the list\n foreach (var package in packages)\n {\n // Extract the base name without version for package matching\n string basePackageName = package;\n if (package.Contains(\"~~~~\"))\n {\n // Extract the base name before the version (~~~~)\n basePackageName = package.Split('~')[0];\n _logService.LogInformation($\"Extracted base package name '{basePackageName}' from '{package}' for removal\");\n }\n \n // Find any package in the list that matches the base name (regardless of version)\n var matchingPackages = existingPackages\n .Where(p => p.StartsWith(basePackageName, StringComparison.OrdinalIgnoreCase) || \n (p.Contains(\"~~~~\") && p.Split('~')[0].Equals(basePackageName, StringComparison.OrdinalIgnoreCase)))\n .ToList();\n \n foreach (var matchingPackage in matchingPackages)\n {\n existingPackages.Remove(matchingPackage);\n _logService.LogInformation($\"Removed package: {matchingPackage} from BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n if (!modified)\n {\n _logService.LogInformation(\"No packages to remove from BloatRemoval.ps1\");\n }\n }\n else\n {\n // For removal operations, ADD the package to the list\n foreach (var package in packages)\n {\n if (!existingPackages.Contains(package, StringComparer.OrdinalIgnoreCase))\n {\n existingPackages.Add(package);\n _logService.LogInformation($\"Added package: {package} to BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n if (!modified)\n {\n _logService.LogInformation(\"No new packages to add to BloatRemoval.ps1\");\n return scriptContent;\n }\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$packages = @(\");\n\n // Add packages without trailing comma on the last item\n for (int i = 0; i < existingPackages.Count; i++)\n {\n string package = existingPackages[i];\n if (i < existingPackages.Count - 1)\n {\n newArrayContent.AppendLine($\" '{package}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{package}'\");\n }\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error updating packages array in script\", ex);\n return scriptContent;\n }\n }\n\n /// \n public string UpdateOptionalFeaturesInScript(string scriptContent, List features, bool isInstallOperation = false)\n {\n try\n {\n _logService.LogInformation($\"Updating optional features with {features.Count} features\");\n\n // Check if the optional features section exists\n int sectionStartIndex = scriptContent.IndexOf(\"# Disable Optional Features\");\n \n // If the section doesn't exist, create it\n if (sectionStartIndex == -1)\n {\n _logService.LogInformation(\"Creating Optional Features section in BloatRemoval.ps1\");\n \n // Find a good place to insert the section (after the packages section)\n int packagesEndIndex = -1;\n \n // First, try to find the #endregion marker after the packages section\n int processPackagesIndex = scriptContent.IndexOf(\"# Process Packages\");\n if (processPackagesIndex != -1)\n {\n int endRegionIndex = scriptContent.IndexOf(\"#endregion\", processPackagesIndex);\n if (endRegionIndex != -1)\n {\n // Find the end of the line after the #endregion\n int newlineIndex = scriptContent.IndexOf('\\n', endRegionIndex);\n if (newlineIndex != -1)\n {\n packagesEndIndex = newlineIndex + 1; // Include the newline\n }\n else\n {\n packagesEndIndex = scriptContent.Length;\n }\n }\n }\n \n // If we couldn't find the #endregion marker, look for the Registry settings section\n if (packagesEndIndex == -1)\n {\n int registryIndex = scriptContent.IndexOf(\"# Registry settings\");\n if (registryIndex != -1)\n {\n packagesEndIndex = registryIndex;\n }\n }\n \n // If we still can't find a good insertion point, look for the end of the packages foreach loop\n if (packagesEndIndex == -1)\n {\n int packagesForEachIndex = scriptContent.IndexOf(\"foreach ($package in $packages)\");\n if (packagesForEachIndex != -1)\n {\n // Find the matching closing brace for the foreach loop\n int openBraces = 0;\n int closeBraces = 0;\n int currentIndex = packagesForEachIndex;\n \n while (currentIndex < scriptContent.Length)\n {\n if (scriptContent[currentIndex] == '{')\n {\n openBraces++;\n }\n else if (scriptContent[currentIndex] == '}')\n {\n closeBraces++;\n if (closeBraces == openBraces && openBraces > 0)\n {\n // Found the matching closing brace\n int braceIndex = currentIndex;\n \n // Find the end of the line after the closing brace\n int newlineIndex = scriptContent.IndexOf('\\n', braceIndex);\n if (newlineIndex != -1)\n {\n packagesEndIndex = newlineIndex + 1; // Include the newline\n }\n else\n {\n packagesEndIndex = scriptContent.Length;\n }\n break;\n }\n }\n currentIndex++;\n }\n }\n }\n \n // If we still couldn't find a good insertion point, just append to the end of the script\n if (packagesEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find a good insertion point for optional features section, appending to the end\");\n packagesEndIndex = scriptContent.Length;\n }\n \n // Create the optional features section\n var optionalFeaturesSection = new StringBuilder();\n optionalFeaturesSection.AppendLine();\n optionalFeaturesSection.AppendLine(\"# Disable Optional Features\");\n optionalFeaturesSection.AppendLine(\"$optionalFeatures = @(\");\n \n // Add features without trailing comma on the last item\n for (int i = 0; i < features.Count; i++)\n {\n string feature = features[i];\n if (i < features.Count - 1)\n {\n optionalFeaturesSection.AppendLine($\" '{feature}',\");\n }\n else\n {\n optionalFeaturesSection.AppendLine($\" '{feature}'\");\n }\n }\n \n optionalFeaturesSection.AppendLine(\")\");\n optionalFeaturesSection.AppendLine();\n optionalFeaturesSection.AppendLine(\"foreach ($feature in $optionalFeatures) {\");\n optionalFeaturesSection.AppendLine(\" Write-Host \\\"Disabling optional feature: $feature\\\" -ForegroundColor Yellow\");\n optionalFeaturesSection.AppendLine(\" Disable-WindowsOptionalFeature -Online -FeatureName $feature -NoRestart | Out-Null\");\n optionalFeaturesSection.AppendLine(\"}\");\n \n // Insert the section\n return scriptContent.Substring(0, packagesEndIndex) \n + optionalFeaturesSection.ToString() \n + scriptContent.Substring(packagesEndIndex);\n }\n \n // If the section exists, update it\n int arrayStartIndex = scriptContent.IndexOf(\"$optionalFeatures = @(\", sectionStartIndex);\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $optionalFeatures array in BloatRemoval.ps1\");\n return scriptContent;\n }\n \n // Find the end of the optional features array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find end of $optionalFeatures array in BloatRemoval.ps1\");\n return scriptContent;\n }\n \n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n \n // Parse the optional features in the array\n var optionalFeatures = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var feature = trimmedLine.Trim('\\'', '\"', ' ', ',');\n optionalFeatures.Add(feature);\n }\n }\n \n bool modified = false;\n \n if (isInstallOperation)\n {\n // For install operations, REMOVE the optional feature from the list\n foreach (var feature in features)\n {\n // Extract the base name without version for feature matching\n string baseFeatureName = feature;\n if (feature.Contains(\"~~~~\"))\n {\n // Extract the base name before the version (~~~~)\n baseFeatureName = feature.Split('~')[0];\n _logService.LogInformation($\"Extracted base feature name '{baseFeatureName}' from '{feature}' for removal\");\n }\n \n // Find any feature in the list that matches the base name (regardless of version)\n var matchingFeatures = optionalFeatures\n .Where(f => f.StartsWith(baseFeatureName, StringComparison.OrdinalIgnoreCase) || \n (f.Contains(\"~~~~\") && f.Split('~')[0].Equals(baseFeatureName, StringComparison.OrdinalIgnoreCase)))\n .ToList();\n \n foreach (var matchingFeature in matchingFeatures)\n {\n optionalFeatures.Remove(matchingFeature);\n _logService.LogInformation($\"Removed optional feature: {matchingFeature} from BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n if (!modified)\n {\n _logService.LogInformation(\"No optional features to remove from BloatRemoval.ps1\");\n }\n }\n else\n {\n // For removal operations, ADD the optional feature to the list\n foreach (var feature in features)\n {\n if (!optionalFeatures.Contains(feature, StringComparer.OrdinalIgnoreCase))\n {\n optionalFeatures.Add(feature);\n _logService.LogInformation($\"Added optional feature: {feature} to BloatRemoval.ps1\");\n modified = true;\n }\n }\n \n if (!modified)\n {\n _logService.LogInformation(\"No new optional features to add to BloatRemoval.ps1\");\n }\n }\n \n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$optionalFeatures = @(\");\n \n // Add features without trailing comma on the last item\n for (int i = 0; i < optionalFeatures.Count; i++)\n {\n string feature = optionalFeatures[i];\n if (i < optionalFeatures.Count - 1)\n {\n newArrayContent.AppendLine($\" '{feature}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{feature}'\");\n }\n }\n \n newArrayContent.Append(\")\");\n \n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error updating optional features in script\", ex);\n return scriptContent;\n }\n }\n\n /// \n public string UpdateRegistrySettingsInScript(string scriptContent, Dictionary> appsWithRegistry)\n {\n try\n {\n _logService.LogInformation($\"Updating registry settings for {appsWithRegistry.Count} apps\");\n\n // Find the registry settings section\n int registrySectionIndex = scriptContent.IndexOf(\"# Registry settings\");\n if (registrySectionIndex == -1)\n {\n // If the registry settings section doesn't exist, create it\n _logService.LogInformation(\"Creating Registry settings section in BloatRemoval.ps1\");\n \n // Find a good place to insert the section (at the end of the script)\n int insertIndex = scriptContent.Length;\n \n // Create the registry settings section\n var registrySection = new StringBuilder();\n registrySection.AppendLine();\n registrySection.AppendLine(\"# Registry settings\");\n \n // Add registry settings for each app\n foreach (var appEntry in appsWithRegistry)\n {\n string appName = appEntry.Key;\n List settings = appEntry.Value;\n \n if (settings == null || settings.Count == 0)\n {\n continue;\n }\n \n registrySection.AppendLine();\n registrySection.AppendLine($\"# Registry settings for {appName}\");\n \n foreach (var setting in settings)\n {\n if (setting.Path == null || setting.Name == null)\n {\n continue;\n }\n \n string regType = RegistryScriptHelper.GetRegTypeString(setting.ValueKind);\n string regValue = FormatRegistryValue(setting.Value, setting.ValueKind);\n \n registrySection.AppendLine($\"reg add \\\"{setting.Path}\\\" /v \\\"{setting.Name}\\\" /t {regType} /d {regValue} /f\");\n }\n }\n \n // Insert the section\n return scriptContent + registrySection.ToString();\n }\n \n // If the registry settings section exists, update it\n StringBuilder updatedContent = new StringBuilder(scriptContent);\n \n // Add registry settings for each app\n foreach (var appEntry in appsWithRegistry)\n {\n string appName = appEntry.Key;\n List settings = appEntry.Value;\n \n if (settings == null || settings.Count == 0)\n {\n continue;\n }\n \n // Check if this app already has registry settings in the script\n string appSectionHeader = $\"# Registry settings for {appName}\";\n int appSectionIndex = updatedContent.ToString().IndexOf(appSectionHeader, registrySectionIndex);\n \n if (appSectionIndex == -1)\n {\n // App doesn't have registry settings yet, add them\n _logService.LogInformation($\"Adding registry settings for {appName} to BloatRemoval.ps1\");\n \n // Find the end of the registry settings section or the start of the next major section\n int endOfRegistrySection = updatedContent.ToString().IndexOf(\"# Prevent apps from reinstalling\", registrySectionIndex);\n if (endOfRegistrySection == -1)\n {\n endOfRegistrySection = updatedContent.Length;\n }\n \n // Create the app registry settings section\n var appRegistrySection = new StringBuilder();\n appRegistrySection.AppendLine();\n appRegistrySection.AppendLine(appSectionHeader);\n \n foreach (var setting in settings)\n {\n if (setting.Path == null || setting.Name == null)\n {\n continue;\n }\n \n string regType = RegistryScriptHelper.GetRegTypeString(setting.ValueKind);\n string regValue = FormatRegistryValue(setting.Value, setting.ValueKind);\n \n appRegistrySection.AppendLine($\"reg add \\\"{setting.Path}\\\" /v \\\"{setting.Name}\\\" /t {regType} /d {regValue} /f\");\n }\n \n // Insert the app registry settings section\n updatedContent.Insert(endOfRegistrySection, appRegistrySection.ToString());\n }\n else\n {\n // App already has registry settings, update them\n _logService.LogInformation($\"Updating registry settings for {appName} in BloatRemoval.ps1\");\n \n // Find the end of the app section (next app section or end of registry section)\n int nextAppSectionIndex = updatedContent.ToString().IndexOf(\"# Registry settings for\", appSectionIndex + appSectionHeader.Length);\n if (nextAppSectionIndex == -1)\n {\n nextAppSectionIndex = updatedContent.ToString().IndexOf(\"# Prevent apps from reinstalling\", appSectionIndex);\n if (nextAppSectionIndex == -1)\n {\n nextAppSectionIndex = updatedContent.Length;\n }\n }\n \n // Create the updated app registry settings section\n var updatedAppRegistrySection = new StringBuilder();\n updatedAppRegistrySection.AppendLine(appSectionHeader);\n \n foreach (var setting in settings)\n {\n if (setting.Path == null || setting.Name == null)\n {\n continue;\n }\n \n string regType = RegistryScriptHelper.GetRegTypeString(setting.ValueKind);\n string regValue = FormatRegistryValue(setting.Value, setting.ValueKind);\n \n updatedAppRegistrySection.AppendLine($\"reg add \\\"{setting.Path}\\\" /v \\\"{setting.Name}\\\" /t {regType} /d {regValue} /f\");\n }\n \n // Replace the old app registry settings section with the new one\n updatedContent.Remove(appSectionIndex, nextAppSectionIndex - appSectionIndex);\n updatedContent.Insert(appSectionIndex, updatedAppRegistrySection.ToString());\n }\n }\n \n return updatedContent.ToString();\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error updating registry settings in script\", ex);\n return scriptContent;\n }\n }\n\n /// \n /// Formats a registry value for use in a reg.exe command.\n /// \n /// The value to format.\n /// The registry value kind.\n /// The formatted value.\n private string FormatRegistryValue(object value, RegistryValueKind valueKind)\n {\n if (value == null)\n {\n return \"\\\"\\\"\";\n }\n\n switch (valueKind)\n {\n case RegistryValueKind.String:\n case RegistryValueKind.ExpandString:\n return $\"\\\"{value}\\\"\";\n case RegistryValueKind.DWord:\n case RegistryValueKind.QWord:\n return value.ToString();\n case RegistryValueKind.Binary:\n if (value is byte[] bytes)\n {\n return BitConverter.ToString(bytes).Replace(\"-\", \",\");\n }\n return \"\\\"\\\"\";\n case RegistryValueKind.MultiString:\n if (value is string[] strings)\n {\n return $\"\\\"{string.Join(\"\\\\0\", strings)}\\\\0\\\"\";\n }\n return \"\\\"\\\"\";\n default:\n return $\"\\\"{value}\\\"\";\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/ScriptStatusToTextConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean script status to a descriptive text.\n /// \n public class ScriptStatusToTextConverter : IValueConverter\n {\n /// \n /// Converts a boolean value to a descriptive text.\n /// \n /// The boolean value indicating if scripts are active.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// A descriptive text based on the script status.\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isActive)\n {\n return isActive \n ? \"Winhance Removing Apps\" \n : \"No Active Removals\";\n }\n \n return \"Unknown Status\";\n }\n \n /// \n /// Converts a descriptive text back to a boolean value.\n /// \n /// The text to convert back.\n /// The type of the binding target property.\n /// The converter parameter to use.\n /// The culture to use in the converter.\n /// A boolean value based on the text.\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/ApplicationSettingViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.WPF.Features.Common.Extensions;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// Base view model for application settings.\n /// \n public partial class ApplicationSettingViewModel : ObservableObject, ISettingItem\n {\n protected readonly IRegistryService? _registryService;\n protected readonly IDialogService? _dialogService;\n protected readonly ILogService? _logService;\n protected readonly IDependencyManager? _dependencyManager;\n protected readonly Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService? _powerPlanService;\n protected bool _isUpdatingFromCode;\n\n /// \n /// Gets or sets a value indicating whether the IsSelected property is being updated from code.\n /// This is used to prevent automatic application of settings when loading.\n /// \n public bool IsUpdatingFromCode\n {\n get => _isUpdatingFromCode;\n set => _isUpdatingFromCode = value;\n }\n\n [ObservableProperty]\n private string _id = string.Empty;\n\n [ObservableProperty]\n private string _name = string.Empty;\n\n [ObservableProperty]\n private string _description = string.Empty;\n\n [ObservableProperty]\n private bool _isSelected;\n\n [ObservableProperty]\n private string _groupName = string.Empty;\n\n [ObservableProperty]\n private bool _isGroupHeader;\n\n [ObservableProperty]\n private bool _isGroupedSetting;\n\n [ObservableProperty]\n private bool _isVisible = true;\n\n [ObservableProperty]\n private ObservableCollection _childSettings = new();\n\n [ObservableProperty]\n private ControlType _controlType = ControlType.BinaryToggle;\n\n [ObservableProperty]\n private int? _sliderSteps;\n\n [ObservableProperty]\n private int _sliderValue;\n\n [ObservableProperty]\n private ObservableCollection _sliderLabels = new();\n\n [ObservableProperty]\n private RegistrySettingStatus _status = RegistrySettingStatus.Unknown;\n\n [ObservableProperty]\n private object? _currentValue;\n\n /// \n /// Gets a value indicating whether this setting is command-based rather than registry-based.\n /// \n public bool IsCommandBasedSetting\n {\n get\n {\n // Check if this setting has PowerCfg commands in its CustomProperties\n return CustomProperties != null &&\n CustomProperties.ContainsKey(\"PowerCfgSettings\") &&\n CustomProperties[\"PowerCfgSettings\"] is List powerCfgSettings &&\n powerCfgSettings.Count > 0;\n }\n }\n \n /// \n /// Gets a list of PowerCfg commands for display in tooltips.\n /// \n public ObservableCollection PowerCfgCommands\n {\n get\n {\n var commands = new ObservableCollection();\n \n if (IsCommandBasedSetting &&\n CustomProperties.ContainsKey(\"PowerCfgSettings\") &&\n CustomProperties[\"PowerCfgSettings\"] is List powerCfgSettings)\n {\n foreach (var setting in powerCfgSettings)\n {\n commands.Add(setting.Command);\n }\n }\n \n return commands;\n }\n }\n\n /// \n /// Gets a value indicating whether the registry value is null.\n /// \n public bool IsRegistryValueNull\n {\n get\n {\n // Don't show warning for command-based settings\n if (IsCommandBasedSetting)\n {\n return false;\n }\n \n // Don't show warning for settings with ActionType = Remove\n if (RegistrySetting != null && RegistrySetting.ActionType == RegistryActionType.Remove)\n {\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Returning false because ActionType is Remove\");\n return false;\n }\n \n // Also check linked registry settings for ActionType = Remove\n if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n // If all linked settings have ActionType = Remove, don't show warning\n bool allRemove = LinkedRegistrySettings.Settings.All(s => s.ActionType == RegistryActionType.Remove);\n if (allRemove)\n {\n // For Remove actions, we don't want to show the warning if all values are null (which means keys don't exist)\n bool allNull = LinkedRegistrySettingsWithValues.All(lv => lv.CurrentValue == null);\n if (allNull)\n {\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Returning false because all Remove settings have null values (keys don't exist)\");\n return false;\n }\n \n // If any key exists when it shouldn't, we might want to show a warning\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Continuing because some Remove settings have non-null values (keys exist)\");\n }\n }\n \n // Add debug logging to help diagnose the issue\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': CurrentValue = {(CurrentValue == null ? \"null\" : CurrentValue.ToString())}\");\n \n // Check if the registry value is null or a special value that indicates it doesn't exist\n if (CurrentValue == null)\n {\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Returning true because CurrentValue is null\");\n return true;\n }\n \n // Check if the registry setting exists\n if (RegistrySetting != null)\n {\n // If we have a registry setting but no current value, it might be null\n if (Status == RegistrySettingStatus.Unknown)\n {\n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Returning true because Status is Unknown\");\n return true;\n }\n }\n \n Console.WriteLine($\"DEBUG - IsRegistryValueNull for '{Name}': Returning false\");\n return false;\n }\n }\n\n [ObservableProperty]\n private string _statusMessage = string.Empty;\n\n [ObservableProperty]\n private bool _isApplying;\n\n /// \n /// Gets or sets the registry setting associated with this view model.\n /// \n public RegistrySetting? RegistrySetting { get; set; }\n\n /// \n /// Gets or sets the linked registry settings associated with this view model.\n /// \n public LinkedRegistrySettings LinkedRegistrySettings { get; set; } = new LinkedRegistrySettings();\n\n /// \n /// Gets or sets the linked registry settings with their current values for display in tooltips.\n /// \n [ObservableProperty]\n private ObservableCollection _linkedRegistrySettingsWithValues = new();\n\n /// \n /// Gets or sets the dependencies between settings.\n /// \n public List Dependencies { get; set; } = new List();\n\n /// \n /// Gets or sets custom properties for this setting.\n /// This can be used to store additional data specific to certain optimization types,\n /// such as PowerCfg settings.\n /// \n public Dictionary CustomProperties { get; set; } = new Dictionary();\n\n /// \n /// Gets or sets the command to apply the setting.\n /// \n public ICommand ApplySettingCommand { get; set; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n public ApplicationSettingViewModel()\n {\n // Default constructor for design-time use\n ApplySettingCommand = new RelayCommand(async () => await ApplySetting());\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The registry service.\n /// The dialog service.\n /// The log service.\n /// The dependency manager.\n public ApplicationSettingViewModel(\n IRegistryService registryService,\n IDialogService? dialogService,\n ILogService logService,\n IDependencyManager? dependencyManager = null,\n Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService? powerPlanService = null)\n {\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n _dialogService = dialogService; // Allow null for dialogService\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _dependencyManager = dependencyManager; // Allow null for backward compatibility\n _powerPlanService = powerPlanService; // Allow null for backward compatibility\n \n // Initialize the ApplySettingCommand\n ApplySettingCommand = new RelayCommand(async () => await ApplySetting());\n\n // Set up property changed handlers for immediate application\n this.PropertyChanged += (s, e) => {\n if ((e.PropertyName == nameof(IsSelected) || e.PropertyName == nameof(SliderValue)) && !IsUpdatingFromCode)\n {\n _logService?.Log(LogLevel.Info, $\"Property {e.PropertyName} changed for {Name}, applying setting\");\n\n // Check dependencies when enabling a setting\n if (e.PropertyName == nameof(IsSelected))\n {\n if (IsSelected)\n {\n // Check if this setting can be enabled based on its dependencies\n var allSettings = GetAllSettings();\n if (allSettings != null && _dependencyManager != null)\n {\n if (!_dependencyManager.CanEnableSetting(Id, allSettings))\n {\n _logService?.Log(LogLevel.Info, $\"Setting {Name} has unsatisfied dependencies, attempting to enable them\");\n \n // Find the dependencies that need to be enabled\n var unsatisfiedDependencies = new List();\n foreach (var dependency in Dependencies)\n {\n if (dependency.DependencyType == SettingDependencyType.RequiresEnabled)\n {\n var requiredSetting = allSettings.FirstOrDefault(s => s.Id == dependency.RequiredSettingId);\n if (requiredSetting != null && !requiredSetting.IsSelected)\n {\n unsatisfiedDependencies.Add(requiredSetting);\n }\n }\n }\n \n if (unsatisfiedDependencies.Count > 0)\n {\n // Automatically enable the dependencies without asking\n bool enableDependencies = true;\n \n // Log what we're doing\n var dependencyNames = string.Join(\", \", unsatisfiedDependencies.Select(d => $\"'{d.Name}'\"));\n _logService?.Log(LogLevel.Info, $\"'{Name}' requires {dependencyNames} to be enabled. Automatically enabling dependencies.\");\n \n if (enableDependencies)\n {\n // Enable all dependencies\n foreach (var dependency in unsatisfiedDependencies)\n {\n _logService?.Log(LogLevel.Info, $\"Automatically enabling dependency: {dependency.Name}\");\n \n // Enable the dependency\n if (dependency is ApplicationSettingViewModel depViewModel)\n {\n depViewModel.IsUpdatingFromCode = true;\n try\n {\n depViewModel.IsSelected = true;\n }\n finally\n {\n depViewModel.IsUpdatingFromCode = false;\n }\n \n // Apply the setting\n depViewModel.ApplySettingCommand.Execute(null);\n }\n }\n }\n else\n {\n // User chose not to enable dependencies, so don't enable this setting\n IsUpdatingFromCode = true;\n try\n {\n IsSelected = false;\n }\n finally\n {\n IsUpdatingFromCode = false;\n }\n return;\n }\n }\n else\n {\n // No dependencies found, show a generic message\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"'{Name}' cannot be enabled because one of its dependencies is not satisfied.\",\n \"Setting Dependency\");\n }\n \n // Prevent enabling this setting\n IsUpdatingFromCode = true;\n try\n {\n IsSelected = false;\n }\n finally\n {\n IsUpdatingFromCode = false;\n }\n return;\n }\n }\n \n // Automatically enable any required settings\n _dependencyManager.HandleSettingEnabled(Id, allSettings);\n }\n }\n else\n {\n // Handle disabling a setting\n var allSettings = GetAllSettings();\n if (allSettings != null && _dependencyManager != null)\n {\n _dependencyManager.HandleSettingDisabled(Id, allSettings);\n }\n }\n }\n\n ApplySettingCommand.Execute(null);\n }\n else if ((e.PropertyName == nameof(IsSelected) || e.PropertyName == nameof(SliderValue)) && IsUpdatingFromCode)\n {\n _logService?.Log(LogLevel.Info, $\"Property {e.PropertyName} changed for {Name}, but not applying setting because IsUpdatingFromCode is true\");\n }\n };\n }\n\n /// \n /// Called when the IsSelected property changes.\n /// \n /// The new value.\n partial void OnIsSelectedChanged(bool value)\n {\n // If this is a grouped setting, update all child settings\n if (IsGroupedSetting && ChildSettings.Count > 0)\n {\n _isUpdatingFromCode = true;\n try\n {\n foreach (var child in ChildSettings)\n {\n child.IsSelected = value;\n }\n }\n finally\n {\n _isUpdatingFromCode = false;\n }\n }\n }\n\n /// \n /// Applies the setting immediately.\n /// \n protected virtual async Task ApplySetting()\n {\n if (IsApplying || _registryService == null || _logService == null)\n return;\n\n try\n {\n IsApplying = true;\n\n // Check if this is a command-based setting (PowerCfg commands)\n if (IsCommandBasedSetting)\n {\n _logService.Log(LogLevel.Info, $\"Applying command-based setting: {Name}, IsSelected={IsSelected}\");\n \n // Get the PowerPlanService from the application services\n var powerPlanService = GetPowerPlanService();\n if (powerPlanService == null)\n {\n _logService.Log(LogLevel.Error, $\"Cannot apply command-based setting: {Name} - PowerPlanService not found\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = \"Failed to apply setting: PowerPlanService not found\";\n return;\n }\n \n // Get the PowerCfg settings from CustomProperties\n var powerCfgSettings = CustomProperties[\"PowerCfgSettings\"] as List;\n if (powerCfgSettings == null || powerCfgSettings.Count == 0)\n {\n _logService.Log(LogLevel.Error, $\"Cannot apply command-based setting: {Name} - PowerCfgSettings is null or empty\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = \"Failed to apply setting: PowerCfgSettings is null or empty\";\n return;\n }\n \n bool success;\n \n if (IsSelected)\n {\n // Apply the PowerCfg settings when enabling\n _logService.Log(LogLevel.Info, $\"Enabling command-based setting: {Name}\");\n success = await powerPlanService.ApplyPowerCfgSettingsAsync(powerCfgSettings);\n }\n else\n {\n // Apply the disabled values when disabling\n _logService.Log(LogLevel.Info, $\"Disabling command-based setting: {Name}\");\n \n // Create a list of PowerCfgSetting objects with disabled values\n var disabledSettings = new List();\n foreach (var powerCfgSetting in powerCfgSettings)\n {\n if (!string.IsNullOrEmpty(powerCfgSetting.DisabledValue))\n {\n disabledSettings.Add(new Winhance.Core.Features.Optimize.Models.PowerCfgSetting\n {\n Command = powerCfgSetting.DisabledValue.StartsWith(\"powercfg \")\n ? powerCfgSetting.DisabledValue\n : \"powercfg \" + powerCfgSetting.DisabledValue,\n Description = \"Restore default: \" + powerCfgSetting.Description,\n EnabledValue = powerCfgSetting.DisabledValue,\n DisabledValue = powerCfgSetting.EnabledValue\n });\n }\n }\n \n // Apply the disabled settings\n if (disabledSettings.Count > 0)\n {\n success = await powerPlanService.ApplyPowerCfgSettingsAsync(disabledSettings);\n }\n else\n {\n // If no disabled settings are defined, consider it a success\n _logService.Log(LogLevel.Warning, $\"No disabled values defined for command-based setting: {Name}\");\n success = true;\n }\n }\n \n if (success)\n {\n _logService.Log(LogLevel.Info, $\"Successfully applied command-based setting: {Name}\");\n Status = IsSelected ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n StatusMessage = IsSelected ? \"Setting applied successfully\" : \"Setting disabled successfully\";\n \n // Set a dummy current value to prevent warning icon\n CurrentValue = IsSelected ? \"Enabled\" : \"Disabled\";\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to apply command-based setting: {Name}\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = \"Failed to apply setting\";\n }\n \n return;\n }\n\n // Check if we have linked registry settings\n if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Applying linked registry settings for {Name}\");\n var linkedResult = await _registryService.ApplyLinkedSettingsAsync(LinkedRegistrySettings, IsSelected);\n\n if (linkedResult)\n {\n _logService.Log(LogLevel.Info, $\"Successfully applied linked settings for {Name}\");\n Status = RegistrySettingStatus.Applied;\n StatusMessage = \"Settings applied successfully\";\n\n // Update tooltip data for linked settings\n if (_registryService != null && LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n // Update the tooltip data\n LinkedRegistrySettingsWithValues.Clear();\n\n // For linked settings, get fresh values from registry\n foreach (var regSetting in LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = _registryService.GetValue(\n RegistryExtensions.GetRegistryHiveString(regSetting.Hive) + \"\\\\\" + regSetting.SubKey,\n regSetting.Name);\n LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n\n // Update the main current value display with the primary or first setting\n var primarySetting = LinkedRegistrySettings.Settings.FirstOrDefault(s => s.IsPrimary) ??\n LinkedRegistrySettings.Settings.FirstOrDefault();\n if (primarySetting != null)\n {\n var primaryValue = _registryService.GetValue(\n RegistryExtensions.GetRegistryHiveString(primarySetting.Hive) + \"\\\\\" + primarySetting.SubKey,\n primarySetting.Name);\n CurrentValue = primaryValue;\n }\n }\n\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to apply linked settings for {Name}\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = \"Failed to apply settings\";\n }\n return;\n }\n\n // Fall back to single registry setting if no linked settings\n if (RegistrySetting == null)\n {\n _logService.Log(LogLevel.Error, $\"Cannot apply setting: {Name} - Registry setting is null\");\n return;\n }\n\n string valueToSet = string.Empty;\n object valueObject;\n\n // Determine value to set based on control type\n switch (ControlType)\n {\n case ControlType.BinaryToggle:\n if (IsSelected)\n {\n // When toggle is ON, use EnabledValue if available, otherwise fall back to RecommendedValue\n valueObject = RegistrySetting.EnabledValue ?? RegistrySetting.RecommendedValue;\n }\n else\n {\n // When toggle is OFF, use DisabledValue if available, otherwise fall back to DefaultValue\n valueObject = RegistrySetting.DisabledValue ?? RegistrySetting.DefaultValue;\n }\n break;\n\n case ControlType.ThreeStateSlider:\n // Map slider value to appropriate setting value\n valueObject = SliderValue;\n break;\n\n case ControlType.Custom:\n default:\n // Custom handling would go here\n valueObject = IsSelected ?\n (RegistrySetting.EnabledValue ?? RegistrySetting.RecommendedValue) :\n (RegistrySetting.DisabledValue ?? RegistrySetting.DefaultValue);\n break;\n }\n\n // Check if this registry setting requires special handling\n if (RegistrySetting.RequiresSpecialHandling() && \n RegistrySetting.ApplySpecialHandling(_registryService, IsSelected))\n {\n // Special handling was applied successfully\n _logService.Log(LogLevel.Info, $\"Special handling applied for {RegistrySetting.Name}\");\n Status = RegistrySettingStatus.Applied;\n StatusMessage = \"Setting applied successfully\";\n \n // Update current value for tooltip display\n if (_registryService != null)\n {\n // Get the current value after special handling\n var currentValue = _registryService.GetValue(\n RegistryExtensions.GetRegistryHiveString(RegistrySetting.Hive) + \"\\\\\" + RegistrySetting.SubKey,\n RegistrySetting.Name);\n \n CurrentValue = currentValue;\n \n // Update the tooltip data\n LinkedRegistrySettingsWithValues.Clear();\n LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(RegistrySetting, currentValue));\n }\n \n return;\n }\n else\n {\n // Apply the registry change normally\n var result = _registryService.SetValue(\n RegistryExtensions.GetRegistryHiveString(RegistrySetting.Hive) + \"\\\\\" + RegistrySetting.SubKey,\n RegistrySetting.Name,\n valueObject,\n RegistrySetting.ValueType);\n\n if (result)\n {\n _logService.Log(LogLevel.Info, $\"Setting applied: {Name}\");\n Status = RegistrySettingStatus.Applied;\n StatusMessage = \"Setting applied successfully\";\n\n // Update current value for tooltip display\n if (_registryService != null)\n {\n // Update the current value\n CurrentValue = valueObject;\n\n // Update the tooltip data\n LinkedRegistrySettingsWithValues.Clear();\n if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n // For linked settings\n foreach (var regSetting in LinkedRegistrySettings.Settings)\n {\n // For the setting that was just changed, use the new value\n if (regSetting.SubKey == RegistrySetting.SubKey &&\n regSetting.Name == RegistrySetting.Name &&\n regSetting.Hive == RegistrySetting.Hive)\n {\n LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, valueObject));\n }\n else\n {\n // For other linked settings, get the current value from registry\n var regCurrentValue = _registryService.GetValue(\n RegistryExtensions.GetRegistryHiveString(regSetting.Hive) + \"\\\\\" + regSetting.SubKey,\n regSetting.Name);\n LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n }\n }\n else if (RegistrySetting != null)\n {\n // For single setting\n LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(RegistrySetting, valueObject));\n }\n }\n\n // Check if restart is required\n bool requiresRestart = Name.Contains(\"restart\", StringComparison.OrdinalIgnoreCase);\n if (requiresRestart && _dialogService != null)\n {\n _dialogService.ShowMessage(\n \"This change requires a system restart to take effect.\",\n \"Restart Required\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to apply setting: {Name}\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = \"Failed to apply setting\";\n\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"Failed to apply {Name}. This may require administrator privileges.\",\n \"Error\");\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying setting: {ex.Message}\");\n Status = RegistrySettingStatus.Error;\n StatusMessage = $\"Error: {ex.Message}\";\n\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"An error occurred: {ex.Message}\",\n \"Error\");\n }\n }\n finally\n {\n IsApplying = false;\n }\n }\n\n /// \n /// Gets all settings from all view models in the application.\n /// \n /// A list of all settings, or null if none found.\n protected virtual List? GetAllSettings()\n {\n try\n {\n _logService?.Log(LogLevel.Info, $\"Getting all settings for dependency check\");\n \n // Check if we have a dependency manager with a settings registry\n if (_dependencyManager is IDependencyManager dependencyManager && \n dependencyManager.GetType().GetProperty(\"SettingsRegistry\")?.GetValue(dependencyManager) is ISettingsRegistry settingsRegistry)\n {\n var settings = settingsRegistry.GetAllSettings();\n if (settings.Count > 0)\n {\n _logService?.Log(LogLevel.Info, $\"Found {settings.Count} settings in settings registry via dependency manager\");\n return settings;\n }\n }\n \n // If no settings registry is available or it's empty, fall back to the original implementation\n var result = new List();\n var app = System.Windows.Application.Current;\n if (app == null) return null;\n\n // Try to find all settings view models\n foreach (System.Windows.Window window in app.Windows)\n {\n if (window.DataContext != null)\n {\n // Look for view models that have a Settings property\n var settingsProperties = window.DataContext.GetType().GetProperties()\n .Where(p => p.Name == \"Settings\" || p.Name.EndsWith(\"Settings\"));\n\n foreach (var prop in settingsProperties)\n {\n var value = prop.GetValue(window.DataContext);\n if (value is IEnumerable settings)\n {\n result.AddRange(settings);\n _logService?.Log(LogLevel.Info, $\"Found {settings.Count()} settings in {prop.Name}\");\n }\n }\n\n // Also look for view models that might contain other view models with settings\n var viewModelProperties = window.DataContext.GetType().GetProperties()\n .Where(p => p.Name.EndsWith(\"ViewModel\") && p.Name != \"DataContext\");\n\n foreach (var prop in viewModelProperties)\n {\n var viewModel = prop.GetValue(window.DataContext);\n if (viewModel != null)\n {\n var nestedSettingsProps = viewModel.GetType().GetProperties()\n .Where(p => p.Name == \"Settings\" || p.Name.EndsWith(\"Settings\"));\n\n foreach (var nestedProp in nestedSettingsProps)\n {\n var value = nestedProp.GetValue(viewModel);\n if (value is IEnumerable settings)\n {\n result.AddRange(settings);\n _logService?.Log(LogLevel.Info, $\"Found {settings.Count()} settings in {prop.Name}.{nestedProp.Name}\");\n }\n }\n }\n }\n }\n }\n\n // If we found settings, return them\n if (result.Count > 0)\n {\n _logService?.Log(LogLevel.Info, $\"Found a total of {result.Count} settings through property scanning\");\n \n // Log the settings we found\n foreach (var setting in result)\n {\n _logService?.Log(LogLevel.Info, $\"Found setting: {setting.Id} - {setting.Name}\");\n }\n \n // If we found a settings registry earlier, register these settings for future use\n if (_dependencyManager is IDependencyManager dependencyManager2 && \n dependencyManager2.GetType().GetProperty(\"SettingsRegistry\")?.GetValue(dependencyManager2) is ISettingsRegistry settingsRegistry2)\n {\n foreach (var setting in result)\n {\n settingsRegistry2.RegisterSetting(setting);\n }\n _logService?.Log(LogLevel.Info, $\"Registered {result.Count} settings in settings registry for future use\");\n }\n \n return result;\n }\n\n _logService?.Log(LogLevel.Warning, \"Could not find any settings for dependency check\");\n return null;\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Error getting all settings: {ex.Message}\");\n return null;\n }\n }\n \n /// \n /// Gets the PowerPlanService from the application services.\n /// \n /// The PowerPlanService, or null if not found.\n protected Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService? GetPowerPlanService()\n {\n // If we already have a PowerPlanService, return it\n if (_powerPlanService != null)\n {\n return _powerPlanService;\n }\n \n try\n {\n // Try to get the PowerPlanService from the application services\n var app = System.Windows.Application.Current;\n if (app == null) return null;\n \n // Check if the application has a GetService method\n var getServiceMethod = app.GetType().GetMethod(\"GetService\", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);\n if (getServiceMethod != null)\n {\n // Call the GetService method to get the PowerPlanService\n var powerPlanService = getServiceMethod.Invoke(app, new object[] { typeof(Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService) });\n return powerPlanService as Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService;\n }\n \n // If the application doesn't have a GetService method, try to find the PowerPlanService in the application resources\n foreach (System.Windows.Window window in app.Windows)\n {\n if (window.DataContext != null)\n {\n // Look for view models that might have a PowerPlanService property\n var powerPlanServiceProperty = window.DataContext.GetType().GetProperty(\"PowerPlanService\");\n if (powerPlanServiceProperty != null)\n {\n var powerPlanService = powerPlanServiceProperty.GetValue(window.DataContext);\n if (powerPlanService is Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService)\n {\n return powerPlanService as Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService;\n }\n }\n \n // Look for view models that might contain other view models with a PowerPlanService property\n var viewModelProperties = window.DataContext.GetType().GetProperties()\n .Where(p => p.Name.EndsWith(\"ViewModel\") && p.Name != \"DataContext\");\n \n foreach (var prop in viewModelProperties)\n {\n var viewModel = prop.GetValue(window.DataContext);\n if (viewModel != null)\n {\n var nestedPowerPlanServiceProperty = viewModel.GetType().GetProperty(\"PowerPlanService\");\n if (nestedPowerPlanServiceProperty != null)\n {\n var powerPlanService = nestedPowerPlanServiceProperty.GetValue(viewModel);\n if (powerPlanService is Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService)\n {\n return powerPlanService as Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService;\n }\n }\n \n // Check if this view model has a _powerPlanService field\n var powerPlanServiceField = viewModel.GetType().GetField(\"_powerPlanService\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n if (powerPlanServiceField != null)\n {\n var powerPlanService = powerPlanServiceField.GetValue(viewModel);\n if (powerPlanService is Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService)\n {\n return powerPlanService as Winhance.Core.Features.Optimize.Interfaces.IPowerPlanService;\n }\n }\n }\n }\n }\n }\n \n return null;\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Error getting PowerPlanService: {ex.Message}\");\n return null;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/MainViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Input;\nusing System.Windows.Interop;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Resources.Theme;\nusing Winhance.WPF.Features.Common.Utilities;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n public partial class MainViewModel : BaseViewModel\n {\n // Window control is now handled through messaging\n\n private readonly IThemeManager _themeManager;\n private readonly INavigationService _navigationService;\n private readonly IMessengerService _messengerService;\n private readonly IUnifiedConfigurationService _unifiedConfigService;\n private readonly IDialogService _dialogService;\n private readonly Features.Common.Services.UserPreferencesService _userPreferencesService;\n\n public INavigationService NavigationService => _navigationService;\n\n [ObservableProperty]\n private object _currentViewModel;\n\n // Helper method to log window actions for debugging\n private void LogWindowAction(string message)\n {\n string formattedMessage = $\"Window Action: {message}\";\n\n // Send to application logging system\n _messengerService.Send(\n new LogMessage { Message = formattedMessage, Level = LogLevel.Debug }\n );\n\n // Also log to diagnostic file for troubleshooting\n FileLogger.Log(\"MainViewModel\", formattedMessage);\n }\n\n private string _currentViewName = string.Empty;\n public string CurrentViewName\n {\n get => _currentViewName;\n set => SetProperty(ref _currentViewName, value);\n }\n\n [ObservableProperty]\n private string _maximizeButtonContent = \"\\uE739\";\n\n /// \n /// Gets the ViewModel for the More menu functionality\n /// \n public MoreMenuViewModel MoreMenuViewModel { get; }\n\n /// \n /// Gets the command to save a unified configuration.\n /// \n public ICommand SaveUnifiedConfigCommand { get; }\n\n /// \n /// Gets the command to import a unified configuration.\n /// \n public ICommand ImportUnifiedConfigCommand { get; }\n\n /// \n /// Gets the command to open the donation page in a browser.\n /// \n public ICommand OpenDonateCommand { get; }\n\n public MainViewModel(\n IThemeManager themeManager,\n INavigationService navigationService,\n ITaskProgressService progressService,\n IMessengerService messengerService,\n IDialogService dialogService,\n IUnifiedConfigurationService unifiedConfigService,\n Features.Common.Services.UserPreferencesService userPreferencesService,\n ILogService logService,\n IVersionService versionService,\n IApplicationCloseService applicationCloseService\n )\n : base(progressService, messengerService)\n {\n _themeManager = themeManager ?? throw new ArgumentNullException(nameof(themeManager));\n _navigationService =\n navigationService ?? throw new ArgumentNullException(nameof(navigationService));\n _messengerService =\n messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n _dialogService =\n dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _unifiedConfigService =\n unifiedConfigService\n ?? throw new ArgumentNullException(nameof(unifiedConfigService));\n _userPreferencesService =\n userPreferencesService\n ?? throw new ArgumentNullException(nameof(userPreferencesService));\n\n // Initialize the MoreMenuViewModel\n MoreMenuViewModel = new MoreMenuViewModel(logService, versionService, _messengerService, applicationCloseService, _dialogService);\n\n // Initialize command properties\n _minimizeWindowCommand = new RelayCommand(MinimizeWindow);\n _maximizeRestoreWindowCommand = new RelayCommand(MaximizeRestoreWindow);\n // Use AsyncRelayCommand instead of RelayCommand for async methods\n _closeWindowCommand = new AsyncRelayCommand(CloseWindowAsync);\n SaveUnifiedConfigCommand = new RelayCommand(SaveUnifiedConfig);\n ImportUnifiedConfigCommand = new RelayCommand(ImportUnifiedConfig);\n OpenDonateCommand = new RelayCommand(OpenDonate);\n\n // Note: View mappings are now registered in App.xaml.cs when configuring the FrameNavigationService\n\n // Subscribe to navigation events\n _navigationService.Navigated += NavigationService_Navigated;\n\n // We'll initialize with the default view later, after the window is loaded\n // This will be called from MainWindow.xaml.cs after the window is loaded\n // This will be called from MainWindow.xaml.cs after the window is loaded\n }\n\n private void NavigationService_Navigated(object sender, NavigationEventArgs e)\n {\n CurrentViewName = e.Route;\n\n // The NavigationService sets e.Parameter to the ViewModel instance\n // This ensures the CurrentViewModel is properly set\n if (e.Parameter != null && e.Parameter is IViewModel)\n {\n CurrentViewModel = e.Parameter;\n }\n else if (e.ViewModelType != null)\n {\n // If for some reason the parameter is not set, try to get the ViewModel from the service provider\n try\n {\n // Get the view model from the navigation event parameter\n if (e.Parameter != null)\n {\n CurrentViewModel = e.Parameter;\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error getting current view model: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n }\n\n [RelayCommand]\n private void Navigate(string viewName)\n {\n try\n {\n _navigationService.NavigateTo(viewName);\n }\n catch (Exception ex)\n {\n // Log the error using the messaging system\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Navigation error to {viewName}: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n\n MessageBox.Show(\n $\"Navigation error while attempting to navigate to {viewName}.\\nError: {ex.Message}\",\n \"Navigation Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error\n );\n }\n }\n\n [RelayCommand]\n private void ToggleTheme()\n {\n _themeManager.ToggleTheme();\n }\n\n // Explicit command property for MinimizeWindow\n private ICommand _minimizeWindowCommand;\n public ICommand MinimizeWindowCommand\n {\n get\n {\n if (_minimizeWindowCommand == null)\n {\n _minimizeWindowCommand = new RelayCommand(MinimizeWindow);\n }\n return _minimizeWindowCommand;\n }\n }\n\n private void MinimizeWindow()\n {\n LogWindowAction(\"MinimizeWindow command called\");\n\n var mainWindow = Application.Current.MainWindow;\n if (mainWindow == null)\n {\n LogWindowAction(\"MainWindow is null\");\n return;\n }\n\n // Try to minimize the window directly\n try\n {\n mainWindow.WindowState = WindowState.Minimized;\n LogWindowAction(\"Directly set WindowState to Minimized\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"Error setting WindowState directly: {ex.Message}\");\n\n // Fall back to messaging\n _messengerService.Send(\n new WindowStateMessage\n {\n Action = WindowStateMessage.WindowStateAction.Minimize,\n }\n );\n }\n }\n\n // Explicit command property for MaximizeRestoreWindow\n private ICommand _maximizeRestoreWindowCommand;\n public ICommand MaximizeRestoreWindowCommand\n {\n get\n {\n if (_maximizeRestoreWindowCommand == null)\n {\n _maximizeRestoreWindowCommand = new RelayCommand(MaximizeRestoreWindow);\n }\n return _maximizeRestoreWindowCommand;\n }\n }\n\n private void MaximizeRestoreWindow()\n {\n LogWindowAction(\"MaximizeRestoreWindow command called\");\n\n var mainWindow = Application.Current.MainWindow;\n if (mainWindow == null)\n {\n LogWindowAction(\"MainWindow is null\");\n return;\n }\n\n if (mainWindow.WindowState == WindowState.Maximized)\n {\n // Try to restore the window directly\n try\n {\n mainWindow.WindowState = WindowState.Normal;\n LogWindowAction(\"Directly set WindowState to Normal\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"Error setting WindowState directly: {ex.Message}\");\n\n // Fall back to messaging\n _messengerService.Send(\n new WindowStateMessage\n {\n Action = WindowStateMessage.WindowStateAction.Restore,\n }\n );\n }\n\n // Update the button icon\n MaximizeButtonContent = \"\\uE739\";\n LogWindowAction(\"Updated MaximizeButtonContent to Maximize icon\");\n }\n else\n {\n // Try to maximize the window directly\n try\n {\n mainWindow.WindowState = WindowState.Maximized;\n LogWindowAction(\"Directly set WindowState to Maximized\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"Error setting WindowState directly: {ex.Message}\");\n\n // Fall back to messaging\n _messengerService.Send(\n new WindowStateMessage\n {\n Action = WindowStateMessage.WindowStateAction.Maximize,\n }\n );\n }\n\n // Update the button icon\n MaximizeButtonContent = \"\\uE923\";\n LogWindowAction(\"Updated MaximizeButtonContent to Restore icon\");\n }\n }\n\n // Explicit command property for CloseWindow\n private ICommand _closeWindowCommand;\n public ICommand CloseWindowCommand\n {\n get\n {\n if (_closeWindowCommand == null)\n {\n // Use AsyncRelayCommand instead of RelayCommand for async methods\n _closeWindowCommand = new AsyncRelayCommand(CloseWindowAsync);\n }\n return _closeWindowCommand;\n }\n }\n\n // Make sure this method is public so it can be called directly for testing\n public async Task CloseWindowAsync()\n {\n LogWindowAction(\"CloseWindowAsync method called\");\n\n // Log basic information\n _messengerService.Send(\n new LogMessage\n {\n Message = \"CloseWindow method executing in MainViewModel\",\n Level = LogLevel.Debug,\n }\n );\n\n var mainWindow = Application.Current.MainWindow;\n if (mainWindow == null)\n {\n LogWindowAction(\"ERROR: MainWindow is null\");\n return;\n }\n\n // The donation dialog is now handled in MainWindow.CloseButton_Click\n // so we can simply close the window here\n\n try\n {\n LogWindowAction(\"About to call mainWindow.Close()\");\n mainWindow.Close();\n LogWindowAction(\"mainWindow.Close() called successfully\");\n }\n catch (Exception ex)\n {\n LogWindowAction($\"ERROR closing window directly: {ex.Message}\");\n\n // Fall back to messaging\n LogWindowAction(\"Falling back to WindowStateMessage.Close\");\n _messengerService.Send(\n new WindowStateMessage { Action = WindowStateMessage.WindowStateAction.Close }\n );\n }\n\n LogWindowAction(\"CloseWindowAsync method completed\");\n }\n\n /// \n /// Saves a unified configuration by delegating to the current view model.\n /// \n private async void SaveUnifiedConfig()\n {\n try\n {\n // Use the injected unified configuration service\n var unifiedConfigService = _unifiedConfigService;\n\n if (unifiedConfigService == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"UnifiedConfigurationService not available\",\n Level = LogLevel.Error,\n }\n );\n return;\n }\n\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Using UnifiedConfigurationService to save unified configuration\",\n Level = LogLevel.Info,\n }\n );\n\n // Create a unified configuration with settings from all view models\n var unifiedConfig = await unifiedConfigService.CreateUnifiedConfigurationAsync();\n\n // Get the configuration service from the application\n IConfigurationService configService = null;\n\n // Try to get the service from the application\n if (Application.Current is App appInstance3)\n {\n try\n {\n // Use reflection to access the _host.Services property\n var hostField = appInstance3\n .GetType()\n .GetField(\"_host\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (hostField != null)\n {\n var host = hostField.GetValue(appInstance3);\n var servicesProperty = host.GetType().GetProperty(\"Services\");\n if (servicesProperty != null)\n {\n var services = servicesProperty.GetValue(host);\n var getServiceMethod = services\n .GetType()\n .GetMethod(\"GetService\", new[] { typeof(Type) });\n if (getServiceMethod != null)\n {\n configService =\n getServiceMethod.Invoke(\n services,\n new object[] { typeof(IConfigurationService) }\n ) as IConfigurationService;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error accessing ConfigurationService: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n\n if (configService == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"ConfigurationService not available\",\n Level = LogLevel.Error,\n }\n );\n return;\n }\n\n // Save the unified configuration\n bool saveResult = await unifiedConfigService.SaveUnifiedConfigurationAsync(\n unifiedConfig\n );\n\n if (saveResult)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Unified configuration saved successfully\",\n Level = LogLevel.Info,\n }\n );\n\n // Show a single success dialog using CustomDialog to match the application style\n var sections = new List();\n if (unifiedConfig.WindowsApps.Items.Any())\n sections.Add(\"Windows Apps\");\n if (unifiedConfig.ExternalApps.Items.Any())\n sections.Add(\"External Apps\");\n if (unifiedConfig.Customize.Items.Any())\n sections.Add(\"Customizations\");\n if (unifiedConfig.Optimize.Items.Any())\n sections.Add(\"Optimizations\");\n\n Winhance.WPF.Features.Common.Views.CustomDialog.ShowInformation(\n \"Configuration Saved\",\n \"Configuration saved successfully.\",\n sections,\n \"You can now import this configuration on another system.\"\n );\n }\n else\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Save unified configuration canceled by user\",\n Level = LogLevel.Info,\n }\n );\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error saving unified configuration: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n\n // FallbackToViewModelImplementation method removed as part of unified configuration cleanup\n\n /// \n /// Imports a unified configuration by delegating to the current view model.\n /// \n private async void ImportUnifiedConfig()\n {\n try\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Starting unified configuration import process\",\n Level = LogLevel.Info,\n }\n );\n\n // Use the injected unified configuration service\n var unifiedConfigService = _unifiedConfigService;\n\n _messengerService.Send(\n new LogMessage\n {\n Message =\n \"Using UnifiedConfigurationService to import unified configuration\",\n Level = LogLevel.Info,\n }\n );\n\n // Get the configuration service from the application\n IConfigurationService configService = null;\n\n // Try to get the service from the application\n if (Application.Current is App appInstance2)\n {\n try\n {\n // Use reflection to access the _host.Services property\n var hostField = appInstance2\n .GetType()\n .GetField(\"_host\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (hostField != null)\n {\n var host = hostField.GetValue(appInstance2);\n var servicesProperty = host.GetType().GetProperty(\"Services\");\n if (servicesProperty != null)\n {\n var services = servicesProperty.GetValue(host);\n var getServiceMethod = services\n .GetType()\n .GetMethod(\"GetService\", new[] { typeof(Type) });\n if (getServiceMethod != null)\n {\n configService =\n getServiceMethod.Invoke(\n services,\n new object[] { typeof(IConfigurationService) }\n ) as IConfigurationService;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error accessing ConfigurationService: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n }\n }\n\n if (configService == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"ConfigurationService not available\",\n Level = LogLevel.Error,\n }\n );\n return;\n }\n\n // Load the unified configuration\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Showing file dialog to select configuration file\",\n Level = LogLevel.Info,\n }\n );\n\n var unifiedConfig = await unifiedConfigService.LoadUnifiedConfigurationAsync();\n\n if (unifiedConfig == null)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Import unified configuration canceled by user\",\n Level = LogLevel.Info,\n }\n );\n return;\n }\n\n _messengerService.Send(\n new LogMessage\n {\n Message =\n $\"Configuration loaded with sections: WindowsApps ({unifiedConfig.WindowsApps.Items.Count} items), \"\n + $\"ExternalApps ({unifiedConfig.ExternalApps.Items.Count} items), \"\n + $\"Customize ({unifiedConfig.Customize.Items.Count} items), \"\n + $\"Optimize ({unifiedConfig.Optimize.Items.Count} items)\",\n Level = LogLevel.Info,\n }\n );\n\n // Show the unified configuration dialog to let the user select which sections to import\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Showing unified configuration dialog for section selection\",\n Level = LogLevel.Info,\n }\n );\n\n // Show the unified configuration dialog to let the user select which sections to import\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Showing unified configuration dialog for section selection\",\n Level = LogLevel.Info,\n }\n );\n\n // Create a dictionary of sections with their availability and item counts\n var sectionInfo = new Dictionary<\n string,\n (bool IsSelected, bool IsAvailable, int ItemCount)\n >\n {\n {\n \"WindowsApps\",\n (\n true,\n unifiedConfig.WindowsApps.Items.Count > 0,\n unifiedConfig.WindowsApps.Items.Count\n )\n },\n {\n \"ExternalApps\",\n (\n true,\n unifiedConfig.ExternalApps.Items.Count > 0,\n unifiedConfig.ExternalApps.Items.Count\n )\n },\n {\n \"Customize\",\n (\n true,\n unifiedConfig.Customize.Items.Count > 0,\n unifiedConfig.Customize.Items.Count\n )\n },\n {\n \"Optimize\",\n (\n true,\n unifiedConfig.Optimize.Items.Count > 0,\n unifiedConfig.Optimize.Items.Count\n )\n },\n };\n\n // Create and show the dialog\n var dialog = new Views.UnifiedConfigurationDialog(\n \"Select Configuration Sections\",\n \"Select which sections you want to import from the unified configuration.\",\n sectionInfo,\n false\n );\n\n // Only set the Owner if the dialog is not the main window itself\n if (dialog != Application.Current.MainWindow)\n {\n try\n {\n dialog.Owner = Application.Current.MainWindow;\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error setting dialog owner: {ex.Message}\",\n Level = LogLevel.Warning,\n }\n );\n // Continue without setting the owner\n }\n }\n bool? dialogResult = dialog.ShowDialog();\n\n if (dialogResult != true)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"User canceled unified configuration import\",\n Level = LogLevel.Info,\n }\n );\n return;\n }\n\n // Get the selected sections from the dialog\n var result = dialog.GetResult();\n var selectedSections = result\n .Where(kvp => kvp.Value)\n .Select(kvp => kvp.Key)\n .ToList();\n\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Selected sections: {string.Join(\", \", selectedSections)}\",\n Level = LogLevel.Info,\n }\n );\n\n if (!selectedSections.Any())\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"No sections selected for import\",\n Level = LogLevel.Info,\n }\n );\n _dialogService.ShowMessage(\n \"Please select at least one section to import from the unified configuration.\",\n \"No sections selected\"\n );\n return;\n }\n\n // Apply the configuration to the selected sections\n _messengerService.Send(\n new LogMessage\n {\n Message =\n $\"Applying configuration to selected sections: {string.Join(\", \", selectedSections)}\",\n Level = LogLevel.Info,\n }\n );\n\n // Apply the configuration to the selected sections\n await unifiedConfigService.ApplyUnifiedConfigurationAsync(\n unifiedConfig,\n selectedSections\n );\n\n // Always show a success message since the settings are being applied correctly\n // even if the updatedCount is 0\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Unified configuration imported successfully\",\n Level = LogLevel.Info,\n }\n );\n\n // Show a success message using CustomDialog to match the application style\n var importedSections = new List();\n foreach (var section in selectedSections)\n {\n switch (section)\n {\n case \"WindowsApps\":\n importedSections.Add(\"Windows Apps\");\n break;\n case \"ExternalApps\":\n importedSections.Add(\"External Apps\");\n break;\n case \"Customize\":\n importedSections.Add(\"Customizations\");\n break;\n case \"Optimize\":\n importedSections.Add(\"Optimizations\");\n break;\n }\n }\n\n Winhance.WPF.Features.Common.Views.CustomDialog.ShowInformation(\n \"Configuration Imported\",\n \"The unified configuration has been imported successfully.\",\n importedSections,\n \"The selected settings have been applied to your system.\"\n );\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error importing unified configuration: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n\n // Show an error message to the user\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"An error occurred while importing the configuration: {ex.Message}\",\n \"Import Error\"\n );\n }\n }\n }\n\n // FallbackToViewModelImportImplementation method removed as part of unified configuration cleanup\n\n /// \n /// Opens the donation page in the default browser.\n /// \n private void OpenDonate()\n {\n try\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = \"Opening donation page in browser\",\n Level = LogLevel.Info,\n }\n );\n\n // Use ProcessStartInfo to open the URL in the default browser\n var psi = new ProcessStartInfo\n {\n FileName = \"https://ko-fi.com/memstechtips\",\n UseShellExecute = true,\n };\n Process.Start(psi);\n }\n catch (Exception ex)\n {\n _messengerService.Send(\n new LogMessage\n {\n Message = $\"Error opening donation page: {ex.Message}\",\n Level = LogLevel.Error,\n Exception = ex,\n }\n );\n\n // Show an error message to the user\n if (_dialogService != null)\n {\n _dialogService.ShowMessage(\n $\"An error occurred while opening the donation page: {ex.Message}\",\n \"Error\"\n );\n }\n }\n }\n\n\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Customize/Services/WallpaperService.cs", "using System;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Customize.Interfaces;\nusing Winhance.Core.Features.Customize.Models;\n\nnamespace Winhance.Infrastructure.Features.Customize.Services\n{\n /// \n /// Service for wallpaper operations.\n /// \n public class WallpaperService : IWallpaperService\n {\n private readonly ILogService _logService;\n\n // P/Invoke constants\n private const int SPI_SETDESKWALLPAPER = 0x0014;\n private const int SPIF_UPDATEINIFILE = 0x01;\n private const int SPIF_SENDCHANGE = 0x02;\n\n [DllImport(\"user32.dll\", SetLastError = true, CharSet = CharSet.Auto)]\n private static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public WallpaperService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string GetDefaultWallpaperPath(bool isWindows11, bool isDarkMode)\n {\n return WindowsThemeSettings.Wallpaper.GetDefaultWallpaperPath(isWindows11, isDarkMode);\n }\n\n /// \n public async Task SetDefaultWallpaperAsync(bool isWindows11, bool isDarkMode)\n {\n string wallpaperPath = GetDefaultWallpaperPath(isWindows11, isDarkMode);\n return await SetWallpaperAsync(wallpaperPath);\n }\n\n /// \n public async Task SetWallpaperAsync(string wallpaperPath)\n {\n try\n {\n bool success = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, wallpaperPath,\n SPIF_UPDATEINIFILE | SPIF_SENDCHANGE) != 0;\n\n if (success)\n {\n _logService.Log(LogLevel.Info, $\"Wallpaper set to {wallpaperPath}\");\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to set wallpaper: {Marshal.GetLastWin32Error()}\");\n }\n\n await Task.CompletedTask; // To keep the async signature\n return success;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting wallpaper: {ex.Message}\");\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/EnumToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts an enum value to a Visibility value based on whether it matches the parameter.\n /// \n public class EnumToVisibilityConverter : IValueConverter\n {\n /// \n /// Converts an enum value to a Visibility value.\n /// \n /// The enum value to convert.\n /// The type of the binding target property.\n /// The parameter to compare against.\n /// The culture to use in the converter.\n /// \n /// Visibility.Visible if the value matches the parameter; otherwise, Visibility.Collapsed.\n /// \n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null || parameter == null)\n {\n return Visibility.Collapsed;\n }\n\n // Check if the value is equal to the parameter\n bool isEqual = value.Equals(parameter);\n return isEqual ? Visibility.Visible : Visibility.Collapsed;\n }\n\n /// \n /// Converts a Visibility value back to an enum value.\n /// \n /// The Visibility value to convert back.\n /// The type of the binding source property.\n /// The parameter to use in the converter.\n /// The culture to use in the converter.\n /// \n /// The parameter if the value is Visibility.Visible; otherwise, null.\n /// \n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is Visibility visibility && visibility == Visibility.Visible)\n {\n return parameter;\n }\n\n return Binding.DoNothing;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/LogLevelToColorConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a LogLevel to a color for display in the UI.\n /// \n public class LogLevelToColorConverter : IValueConverter\n {\n /// \n /// Converts a LogLevel to a color.\n /// \n /// The LogLevel value.\n /// The target type.\n /// The converter parameter.\n /// The culture information.\n /// A color brush based on the log level.\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is LogLevel level)\n {\n switch (level)\n {\n case LogLevel.Error:\n return new SolidColorBrush(Colors.Red);\n case LogLevel.Warning:\n return new SolidColorBrush(Colors.Orange);\n case LogLevel.Debug:\n return new SolidColorBrush(Colors.Gray);\n default:\n return new SolidColorBrush(Colors.White);\n }\n }\n return new SolidColorBrush(Colors.White);\n }\n\n /// \n /// Converts a color back to a LogLevel (not implemented).\n /// \n /// The color value.\n /// The target type.\n /// The converter parameter.\n /// The culture information.\n /// Not implemented.\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Security.AccessControl;\nusing System.Security.Principal;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Provides access to the Windows registry.\n /// This is the main file for the RegistryService, which is split into multiple partial files:\n /// - RegistryServiceCore.cs - Core functionality and constructor\n /// - RegistryServiceKeyOperations.cs - Key creation, deletion, and navigation\n /// - RegistryServiceValueOperations.cs - Value reading and writing\n /// - RegistryServiceStatusMethods.cs - Status checking methods\n /// - RegistryServiceEnsureKey.cs - Key creation with security settings\n /// - RegistryServicePowerShell.cs - PowerShell fallback methods\n /// - RegistryServiceTestMethods.cs - Testing methods\n /// - RegistryServiceCompletion.cs - Helper methods\n /// - RegistryServiceUtilityOperations.cs - Additional utility operations (export, backup, restore)\n /// \n [SupportedOSPlatform(\"windows\")]\n public partial class RegistryService : IRegistryService\n {\n // Cache for registry key existence to avoid repeated checks\n private readonly Dictionary _keyExistsCache = new Dictionary();\n\n // Cache for registry value existence to avoid repeated checks\n private readonly Dictionary _valueExistsCache =\n new Dictionary();\n\n // Cache for registry values to avoid repeated reads\n private readonly Dictionary _valueCache =\n new Dictionary();\n\n /// \n /// Clears all registry caches to ensure fresh reads\n /// \n public void ClearRegistryCaches()\n {\n lock (_keyExistsCache)\n {\n _keyExistsCache.Clear();\n }\n\n lock (_valueExistsCache)\n {\n _valueExistsCache.Clear();\n }\n\n lock (_valueCache)\n {\n _valueCache.Clear();\n }\n\n _logService.Log(LogLevel.Info, \"Registry caches cleared\");\n }\n\n /// \n /// Applies a registry setting.\n /// \n /// The registry setting to apply.\n /// Whether to enable or disable the setting.\n /// True if the operation succeeded; otherwise, false.\n public async Task ApplySettingAsync(RegistrySetting setting, bool isEnabled)\n {\n if (setting == null)\n return false;\n\n try\n {\n string keyPath = $\"{setting.Hive}\\\\{setting.SubKey}\";\n object? valueToSet = null;\n\n _logService.Log(\n LogLevel.Info,\n $\"Applying registry setting: {setting.Name}, IsEnabled={isEnabled}, Path={keyPath}\"\n );\n\n if (isEnabled)\n {\n // When enabling, use EnabledValue if available, otherwise fall back to RecommendedValue\n valueToSet = setting.EnabledValue ?? setting.RecommendedValue;\n _logService.Log(\n LogLevel.Debug,\n $\"Setting {setting.Name} - EnabledValue: {setting.EnabledValue}, RecommendedValue: {setting.RecommendedValue}, Using: {valueToSet}\"\n );\n }\n else\n {\n // When disabling, use DisabledValue if available, otherwise fall back to DefaultValue\n valueToSet = setting.DisabledValue ?? setting.DefaultValue;\n _logService.Log(\n LogLevel.Debug,\n $\"Setting {setting.Name} - DisabledValue: {setting.DisabledValue}, DefaultValue: {setting.DefaultValue}, Using: {valueToSet}\"\n );\n }\n\n if (valueToSet == null)\n {\n // If the value to set is null, delete the value\n _logService.Log(\n LogLevel.Warning,\n $\"Value to set for {setting.Name} is null, deleting the value\"\n );\n return await DeleteValue(setting.Hive, setting.SubKey, setting.Name);\n }\n else\n {\n // Otherwise, set the value\n _logService.Log(\n LogLevel.Info,\n $\"Setting {keyPath}\\\\{setting.Name} to {valueToSet} ({setting.ValueType})\"\n );\n \n // Ensure the key exists before setting the value\n bool keyCreated = CreateKeyIfNotExists(keyPath);\n if (!keyCreated)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to create registry key: {keyPath}, attempting PowerShell fallback\"\n );\n \n // Try to use PowerShell to create the key if direct creation failed\n if (keyPath.Contains(\"Policies\", StringComparison.OrdinalIgnoreCase))\n {\n _logService.Log(\n LogLevel.Info,\n $\"Attempting to create policy registry key using PowerShell: {keyPath}\"\n );\n \n // Use SetValueUsingPowerShell which will create the key as part of setting the value\n return SetValueUsingPowerShell(keyPath, setting.Name, valueToSet, setting.ValueType);\n }\n \n return false;\n }\n \n // Verify the key exists before proceeding\n if (!KeyExists(keyPath))\n {\n _logService.Log(\n LogLevel.Error,\n $\"Registry key still does not exist after creation attempt: {keyPath}\"\n );\n return false;\n }\n \n // Try to set the value\n bool result = SetValue(keyPath, setting.Name, valueToSet, setting.ValueType);\n \n // Verify the value was set correctly\n if (result)\n {\n object? verifyValue = GetValue(keyPath, setting.Name);\n if (verifyValue == null)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Value verification failed - value is null after setting: {keyPath}\\\\{setting.Name}\"\n );\n \n // Try one more time with PowerShell\n return SetValueUsingPowerShell(keyPath, setting.Name, valueToSet, setting.ValueType);\n }\n \n _logService.Log(\n LogLevel.Success,\n $\"Successfully set and verified registry value: {keyPath}\\\\{setting.Name}\"\n );\n }\n else\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to set {keyPath}\\\\{setting.Name} to {valueToSet}\"\n );\n }\n return result;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Error,\n $\"Error applying registry setting {setting.Name}: {ex.Message}\"\n );\n return false;\n }\n }\n\n /// \n /// Applies linked registry settings.\n /// \n /// The linked registry settings to apply.\n /// Whether to enable or disable the settings.\n /// True if the operation succeeded; otherwise, false.\n public async Task ApplyLinkedSettingsAsync(\n LinkedRegistrySettings linkedSettings,\n bool isEnabled\n )\n {\n if (linkedSettings == null || linkedSettings.Settings.Count == 0)\n return false;\n\n try\n {\n _logService.Log(\n LogLevel.Info,\n $\"Applying {linkedSettings.Settings.Count} linked registry settings, IsEnabled={isEnabled}\"\n );\n\n bool allSuccess = true;\n int settingCount = 0;\n int totalSettings = linkedSettings.Settings.Count;\n\n foreach (var setting in linkedSettings.Settings)\n {\n settingCount++;\n _logService.Log(\n LogLevel.Debug,\n $\"Processing linked setting {settingCount}/{totalSettings}: {setting.Name}\"\n );\n\n // Ensure the registry key path exists before applying the setting\n string keyPath = $\"{setting.Hive}\\\\{setting.SubKey}\";\n bool keyExists = KeyExists(keyPath);\n \n if (!keyExists)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Registry key does not exist: {keyPath}, creating it\"\n );\n \n // Try to create the key\n bool keyCreated = CreateKeyIfNotExists(keyPath);\n \n if (!keyCreated)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to create registry key: {keyPath} using standard method, trying PowerShell\"\n );\n \n // If we couldn't create the key, try using PowerShell to create it\n // This will be handled in the ApplySettingAsync method\n }\n }\n\n bool success = await ApplySettingAsync(setting, isEnabled);\n\n if (!success)\n {\n _logService.Log(\n LogLevel.Warning,\n $\"Failed to apply linked setting: {setting.Name}\"\n );\n\n // If the logic is All, we need all settings to succeed\n if (linkedSettings.Logic == LinkedSettingsLogic.All)\n {\n allSuccess = false;\n }\n }\n else\n {\n _logService.Log(\n LogLevel.Success,\n $\"Successfully applied linked setting {settingCount}/{totalSettings}: {setting.Name}\"\n );\n }\n }\n\n _logService.Log(\n allSuccess ? LogLevel.Success : LogLevel.Warning,\n $\"Completed applying linked settings with result: {(allSuccess ? \"Success\" : \"Some settings failed\")}\"\n );\n\n return allSuccess;\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Error,\n $\"Error applying linked registry settings: {ex.Message}\"\n );\n return false;\n }\n }\n\n /// \n /// Exports a registry key to a string.\n /// \n /// The registry key path.\n /// The exported registry key as a string, or null if the operation failed.\n public string? ExportKey(string keyPath)\n {\n if (!CheckWindowsPlatform())\n return null;\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Exporting registry key: {keyPath}\");\n\n // Create a temporary file to export the registry key to\n string tempFile = Path.GetTempFileName();\n\n // Export the registry key using reg.exe\n var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"export \\\"{keyPath}\\\" \\\"{tempFile}\\\" /y\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n },\n };\n\n process.Start();\n process.WaitForExit();\n\n if (process.ExitCode != 0)\n {\n string error = process.StandardError.ReadToEnd();\n _logService.Log(\n LogLevel.Error,\n $\"Error exporting registry key {keyPath}: {error}\"\n );\n return null;\n }\n\n // Read the exported registry key from the temporary file\n string exportedKey = File.ReadAllText(tempFile);\n\n // Delete the temporary file\n File.Delete(tempFile);\n\n return exportedKey;\n }\n catch (Exception ex)\n {\n _logService.Log(\n LogLevel.Error,\n $\"Error exporting registry key {keyPath}: {ex.Message}\"\n );\n return null;\n }\n }\n\n /// \n /// Imports a registry key from a string.\n /// \n /// The registry content to import.\n /// True if the operation succeeded; otherwise, false.\n public bool ImportKey(string registryContent)\n {\n if (!CheckWindowsPlatform())\n return false;\n\n try\n {\n _logService.Log(LogLevel.Info, \"Importing registry key\");\n\n // Create a temporary file to import the registry key from\n string tempFile = Path.GetTempFileName();\n\n // Write the registry content to the temporary file\n File.WriteAllText(tempFile, registryContent);\n\n // Import the registry key using reg.exe\n var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"import \\\"{tempFile}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n },\n };\n\n process.Start();\n process.WaitForExit();\n\n // Delete the temporary file\n File.Delete(tempFile);\n\n if (process.ExitCode != 0)\n {\n string error = process.StandardError.ReadToEnd();\n _logService.Log(LogLevel.Error, $\"Error importing registry key: {error}\");\n return false;\n }\n\n // Clear all caches to ensure fresh reads\n ClearRegistryCaches();\n\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing registry key: {ex.Message}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/Methods/WinGetVerificationMethod.cs", "using System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods\n{\n /// \n /// Verifies software installations by querying WinGet.\n /// \n public class WinGetVerificationMethod : VerificationMethodBase\n {\n private const string WinGetExe = \"winget.exe\";\n private static readonly string[] WinGetPaths = new[]\n {\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n @\"Microsoft\\WindowsApps\"\n ),\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n @\"WindowsApps\\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe\"\n ),\n };\n\n /// \n /// Initializes a new instance of the class.\n /// \n public WinGetVerificationMethod()\n : base(\"WinGet\", priority: 5) // Higher priority as it's the most reliable source\n { }\n\n /// \n protected override async Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken\n )\n {\n // First try with the exact match approach using winget list\n try\n {\n var exactMatchResult = await ExecuteWinGetCommandAsync(\n \"list\",\n $\"--id {packageId} --exact\",\n cancellationToken\n );\n\n // Check if the package is found in the output\n if (\n exactMatchResult.ExitCode == 0\n && !string.IsNullOrWhiteSpace(exactMatchResult.Output)\n && exactMatchResult.Output.Contains(packageId)\n )\n {\n // Extract version if possible\n string version = \"unknown\";\n string source = \"unknown\";\n\n var lines = exactMatchResult.Output.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n if (lines.Length >= 2)\n {\n var parts = lines[1]\n .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (parts.Length > 1)\n version = parts[1];\n if (parts.Length > 2)\n source = parts[2];\n }\n\n return new VerificationResult\n {\n IsVerified = true,\n Message =\n $\"Found in WinGet: {packageId} (Version: {version}, Source: {source})\",\n MethodUsed = \"WinGet\",\n AdditionalInfo = new\n {\n PackageId = packageId,\n Version = version,\n Source = source,\n },\n };\n }\n\n // If exact match failed, try a more flexible approach with just the package ID\n var flexibleResult = await ExecuteWinGetCommandAsync(\n \"list\",\n $\"\\\"{packageId}\\\"\",\n cancellationToken\n );\n\n if (\n flexibleResult.ExitCode == 0\n && !string.IsNullOrWhiteSpace(flexibleResult.Output)\n )\n {\n // Check if any line contains the package ID\n var lines = flexibleResult.Output.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n\n foreach (var line in lines)\n {\n if (line.IndexOf(packageId, StringComparison.OrdinalIgnoreCase) >= 0)\n {\n // Found a match\n var parts = line.Split(\n new[] { ' ' },\n StringSplitOptions.RemoveEmptyEntries\n );\n string version = parts.Length > 1 ? parts[1] : \"unknown\";\n string source = parts.Length > 2 ? parts[2] : \"unknown\";\n\n return new VerificationResult\n {\n IsVerified = true,\n Message =\n $\"Found in WinGet: {packageId} (Version: {version}, Source: {source})\",\n MethodUsed = \"WinGet\",\n AdditionalInfo = new\n {\n PackageId = packageId,\n Version = version,\n Source = source,\n },\n };\n }\n }\n }\n\n // If we got here, the package wasn't found\n return VerificationResult.Failure($\"Package '{packageId}' not found via WinGet\");\n }\n catch (Exception ex)\n {\n return VerificationResult.Failure($\"Error querying WinGet: {ex.Message}\");\n }\n }\n\n /// \n protected override async Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken\n )\n {\n var result = await VerifyPresenceAsync(packageId, cancellationToken)\n .ConfigureAwait(false);\n if (!result.IsVerified)\n return result;\n\n // Extract the version from the additional info\n var installedVersion = (string)((dynamic)result.AdditionalInfo)?.Version;\n if (string.IsNullOrEmpty(installedVersion))\n return VerificationResult.Failure(\n $\"Could not determine installed version for '{packageId}'\",\n \"WinGet\"\n );\n\n // Simple version comparison (this could be enhanced with proper version comparison logic)\n if (!installedVersion.Equals(version, StringComparison.OrdinalIgnoreCase))\n return VerificationResult.Failure(\n $\"Version mismatch for '{packageId}'. Installed: {installedVersion}, Expected: {version}\",\n \"WinGet\"\n );\n\n return result;\n }\n\n private static async Task<(int ExitCode, string Output)> ExecuteWinGetCommandAsync(\n string command,\n string arguments,\n CancellationToken cancellationToken\n )\n {\n var winGetPath = FindWinGetPath();\n if (string.IsNullOrEmpty(winGetPath))\n throw new InvalidOperationException(\n \"WinGet is not installed or could not be found\"\n );\n\n var startInfo = new ProcessStartInfo\n {\n FileName = winGetPath,\n Arguments = $\"{command} {arguments}\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n StandardOutputEncoding = Encoding.UTF8,\n StandardErrorEncoding = Encoding.UTF8,\n };\n\n using (var process = new Process { StartInfo = startInfo })\n using (var outputWaitHandle = new System.Threading.ManualResetEvent(false))\n using (var errorWaitHandle = new System.Threading.ManualResetEvent(false))\n {\n var output = new StringBuilder();\n var error = new StringBuilder();\n\n process.OutputDataReceived += (sender, e) =>\n {\n if (e.Data != null)\n output.AppendLine(e.Data);\n else\n outputWaitHandle.Set();\n };\n\n process.ErrorDataReceived += (sender, e) =>\n {\n if (e.Data != null)\n error.AppendLine(e.Data);\n else\n errorWaitHandle.Set();\n };\n\n process.Start();\n process.BeginOutputReadLine();\n process.BeginErrorReadLine();\n\n // Wait for the process to exit or the cancellation token to be triggered\n await Task.Run(\n () =>\n {\n while (!process.WaitForExit(100))\n {\n if (cancellationToken.IsCancellationRequested)\n {\n try\n {\n process.Kill();\n }\n catch\n { /* Ignore */\n }\n cancellationToken.ThrowIfCancellationRequested();\n }\n }\n },\n cancellationToken\n )\n .ConfigureAwait(false);\n\n outputWaitHandle.WaitOne(TimeSpan.FromSeconds(5));\n errorWaitHandle.WaitOne(TimeSpan.FromSeconds(5));\n\n // If there was an error, include it in the output\n if (!string.IsNullOrWhiteSpace(error.ToString()))\n output.AppendLine(\"Error: \").Append(error);\n\n return (process.ExitCode, output.ToString().Trim());\n }\n }\n\n private static string FindWinGetPath()\n {\n // Check if winget is in the PATH\n var pathEnv = Environment.GetEnvironmentVariable(\"PATH\") ?? string.Empty;\n if (\n pathEnv\n .Split(Path.PathSeparator)\n .Any(p => !string.IsNullOrEmpty(p) && File.Exists(Path.Combine(p, WinGetExe)))\n )\n {\n return WinGetExe;\n }\n\n // Check common installation paths\n foreach (var basePath in WinGetPaths)\n {\n var fullPath = Path.Combine(basePath, WinGetExe);\n if (File.Exists(fullPath))\n return fullPath;\n }\n\n return null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/InverseBooleanConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean value to its inverse (true to false, false to true)\n /// \n public class InverseBooleanConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return !boolValue;\n }\n \n return value;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return !boolValue;\n }\n \n return value;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToGridSpanConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Converters\n{\n /// \n /// Converts a boolean value to an integer grid span - true returns 4 (full width), false returns 1\n /// \n public class BooleanToGridSpanConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return boolValue ? 4 : 1; // Return 4 for true (header spans full width), 1 for false\n }\n return 1;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceStatusMethods.cs", "using Microsoft.Win32;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n public partial class RegistryService\n {\n public async Task GetSettingStatusAsync(RegistrySetting setting)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return RegistrySettingStatus.Error;\n }\n\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot get status for null registry setting\");\n return RegistrySettingStatus.Unknown;\n }\n\n string hiveString = RegistryExtensions.GetRegistryHiveString(setting.Hive);\n string fullPath = $\"{hiveString}\\\\{setting.SubKey}\";\n string fullValuePath = $\"{fullPath}\\\\{setting.Name}\";\n\n _logService.Log(LogLevel.Info, $\"Checking registry setting status: {fullValuePath}\");\n\n // Check if the key exists (using cache)\n bool keyExists;\n lock (_keyExistsCache)\n {\n if (!_keyExistsCache.TryGetValue(fullPath, out keyExists))\n {\n keyExists = KeyExists(fullPath);\n _keyExistsCache[fullPath] = keyExists;\n }\n }\n\n // Handle non-existence of the key\n if (!keyExists)\n {\n // For Remove actions, non-existence of the key is considered \"Applied\"\n if (setting.ActionType == RegistryActionType.Remove)\n {\n return RegistrySettingStatus.Applied;\n }\n\n // For settings where absence means enabled (like HttpAcceptLanguageOptOut)\n if (setting.AbsenceMeansEnabled)\n {\n _logService.Log(LogLevel.Info, $\"Key does not exist and AbsenceMeansEnabled is true - marking as Applied\");\n return RegistrySettingStatus.Applied;\n }\n\n // Default behavior: absence means not applied\n return RegistrySettingStatus.NotApplied;\n }\n\n // Check if the value exists (using cache)\n bool valueExists;\n lock (_valueExistsCache)\n {\n if (!_valueExistsCache.TryGetValue(fullValuePath, out valueExists))\n {\n valueExists = ValueExists(fullPath, setting.Name);\n _valueExistsCache[fullValuePath] = valueExists;\n }\n }\n\n // Handle non-existence of the value\n if (!valueExists)\n {\n // For Remove actions, non-existence of the value is considered \"Applied\"\n if (setting.ActionType == RegistryActionType.Remove)\n {\n return RegistrySettingStatus.Applied;\n }\n\n // For settings where absence means enabled (like HttpAcceptLanguageOptOut)\n if (setting.AbsenceMeansEnabled)\n {\n _logService.Log(LogLevel.Info, $\"Value does not exist and AbsenceMeansEnabled is true - marking as Applied\");\n return RegistrySettingStatus.Applied;\n }\n\n // Default behavior: absence means not applied\n return RegistrySettingStatus.NotApplied;\n }\n\n // If we're here and the action type is Remove, the key/value still exists\n if (setting.ActionType == RegistryActionType.Remove)\n {\n // Special case for 3D Objects toggle which is opposite of normal Remove action\n // When the key exists, 3D Objects is shown (Applied)\n if (setting.Name == \"{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}\")\n {\n _logService.Log(LogLevel.Info, $\"3D Objects key exists - marking as Applied\");\n return RegistrySettingStatus.Applied;\n }\n \n // For normal Remove actions, key existing means not applied\n return RegistrySettingStatus.NotApplied;\n }\n\n // Get the current value (using cache)\n object? currentValue;\n lock (_valueCache)\n {\n if (!_valueCache.TryGetValue(fullValuePath, out currentValue))\n {\n currentValue = GetValue(fullPath, setting.Name);\n _valueCache[fullValuePath] = currentValue;\n }\n }\n\n // If the value is null, consider it not applied\n if (currentValue == null)\n {\n return RegistrySettingStatus.NotApplied;\n }\n\n // Compare with enabled value (use EnabledValue if available, otherwise fall back to RecommendedValue)\n object valueToCompare = setting.EnabledValue ?? setting.RecommendedValue;\n bool matchesEnabled = CompareValues(currentValue, valueToCompare);\n if (matchesEnabled)\n {\n return RegistrySettingStatus.Applied;\n }\n\n // If there's a disabled value specified, check if it matches that\n object? disabledValue = setting.DisabledValue ?? setting.DefaultValue;\n if (disabledValue != null)\n {\n bool matchesDisabled = CompareValues(currentValue, disabledValue);\n if (matchesDisabled)\n {\n return RegistrySettingStatus.NotApplied;\n }\n }\n\n // If it doesn't match recommended or default, it's modified\n return RegistrySettingStatus.Modified;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking registry setting status: {ex.Message}\");\n return RegistrySettingStatus.Error;\n }\n }\n\n public async Task> GetSettingsStatusAsync(IEnumerable settings)\n {\n var results = new Dictionary();\n\n if (settings == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot get status for null registry settings collection\");\n return results;\n }\n\n foreach (var setting in settings)\n {\n if (setting == null || string.IsNullOrEmpty(setting.Name))\n {\n continue;\n }\n\n var status = await GetSettingStatusAsync(setting);\n results[setting.Name] = status;\n }\n\n return results;\n }\n\n public async Task GetLinkedSettingsStatusAsync(LinkedRegistrySettings linkedSettings)\n {\n if (linkedSettings == null || linkedSettings.Settings.Count == 0)\n return RegistrySettingStatus.Unknown;\n\n try\n {\n List statuses = new List();\n \n // Special case: If all settings have ActionType = Remove, we need to handle differently\n bool allRemoveActions = linkedSettings.Settings.All(s => s.ActionType == RegistryActionType.Remove);\n \n if (allRemoveActions)\n {\n // For Remove actions, we need to check if all keys/values don't exist (for All logic)\n // or if any key/value doesn't exist (for Any logic)\n bool allKeysRemoved = true;\n bool anyKeyRemoved = false;\n \n foreach (var setting in linkedSettings.Settings)\n {\n string fullPath = $\"{RegistryExtensions.GetRegistryHiveString(setting.Hive)}\\\\{setting.SubKey}\";\n string fullValuePath = $\"{fullPath}\\\\{setting.Name}\";\n \n // Check if the key exists\n bool keyExists = KeyExists(fullPath);\n \n // For Remove actions, if the key doesn't exist, it's considered \"removed\" (Applied)\n if (!keyExists)\n {\n anyKeyRemoved = true;\n }\n else\n {\n // Key exists, now check if the value exists\n bool valueExists = ValueExists(fullPath, setting.Name);\n \n if (!valueExists)\n {\n anyKeyRemoved = true;\n }\n else\n {\n // Special case for 3D Objects toggle which is opposite of normal Remove action\n // When the key exists, 3D Objects is shown (should be considered Applied)\n if (setting.Name == \"{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}\")\n {\n _logService.Log(LogLevel.Info, $\"3D Objects key exists in linked settings - special handling\");\n // For 3D Objects, we want to return Applied when the key exists\n // So we don't set allKeysRemoved to false here\n continue;\n }\n \n allKeysRemoved = false;\n }\n }\n }\n \n // Determine status based on the logic\n if (linkedSettings.Logic == LinkedSettingsLogic.All)\n {\n return allKeysRemoved ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n }\n else\n {\n return anyKeyRemoved ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n }\n }\n \n // Normal case: Process each setting individually\n foreach (var setting in linkedSettings.Settings)\n {\n var status = await GetSettingStatusAsync(setting);\n statuses.Add(status);\n }\n\n // Check if any settings have an error status\n if (statuses.Contains(RegistrySettingStatus.Error))\n {\n return RegistrySettingStatus.Error;\n }\n\n // Check if any settings have an unknown status\n if (statuses.Contains(RegistrySettingStatus.Unknown))\n {\n return RegistrySettingStatus.Unknown;\n }\n\n // Count how many settings are applied\n int appliedCount = statuses.Count(s => s == RegistrySettingStatus.Applied);\n int notAppliedCount = statuses.Count(s => s == RegistrySettingStatus.NotApplied);\n int modifiedCount = statuses.Count(s => s == RegistrySettingStatus.Modified);\n\n // Determine the overall status based on the logic type\n switch (linkedSettings.Logic)\n {\n case LinkedSettingsLogic.All:\n // All settings must be applied for the overall status to be Applied\n if (appliedCount == statuses.Count)\n {\n return RegistrySettingStatus.Applied;\n }\n else if (notAppliedCount == statuses.Count)\n {\n return RegistrySettingStatus.NotApplied;\n }\n else\n {\n return RegistrySettingStatus.Modified;\n }\n\n case LinkedSettingsLogic.Any:\n // Any applied setting means the overall status is Applied\n if (appliedCount > 0)\n {\n return RegistrySettingStatus.Applied;\n }\n else if (notAppliedCount == statuses.Count)\n {\n return RegistrySettingStatus.NotApplied;\n }\n else\n {\n return RegistrySettingStatus.Modified;\n }\n\n case LinkedSettingsLogic.Primary:\n // Find the primary setting\n var primarySetting = linkedSettings.Settings.FirstOrDefault(s => s.IsPrimary);\n if (primarySetting != null)\n {\n // Return the status of the primary setting\n return await GetSettingStatusAsync(primarySetting);\n }\n else\n {\n // If no primary setting is found, fall back to All logic\n if (appliedCount == statuses.Count)\n {\n return RegistrySettingStatus.Applied;\n }\n else if (notAppliedCount == statuses.Count)\n {\n return RegistrySettingStatus.NotApplied;\n }\n else\n {\n return RegistrySettingStatus.Modified;\n }\n }\n\n default:\n // Default to Any logic\n if (appliedCount > 0)\n {\n return RegistrySettingStatus.Applied;\n }\n else if (notAppliedCount == statuses.Count)\n {\n return RegistrySettingStatus.NotApplied;\n }\n else\n {\n return RegistrySettingStatus.Modified;\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking linked registry settings status: {ex.Message}\");\n return RegistrySettingStatus.Error;\n }\n }\n\n public async Task GetOptimizationSettingStatusAsync(Winhance.Core.Features.Optimize.Models.OptimizationSetting setting)\n {\n if (setting == null)\n {\n return RegistrySettingStatus.Unknown;\n }\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Checking status for optimization setting: {setting.Name}\");\n\n // If the setting has registry settings collection, create a LinkedRegistrySettings and use that\n if (setting.RegistrySettings != null && setting.RegistrySettings.Count > 0)\n {\n var linkedSettings = new LinkedRegistrySettings\n {\n Settings = setting.RegistrySettings.ToList(),\n Logic = setting.LinkedSettingsLogic\n };\n return await GetLinkedSettingsStatusAsync(linkedSettings);\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Optimization setting {setting.Name} has no registry settings\");\n return RegistrySettingStatus.Unknown;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking optimization setting status: {ex.Message}\");\n return RegistrySettingStatus.Error;\n }\n }\n\n /// \n /// Helper method to compare registry values, handling different types.\n /// \n private bool CompareValues(object? currentValue, object? desiredValue)\n {\n if (currentValue == null && desiredValue == null)\n {\n return true;\n }\n\n if (currentValue == null || desiredValue == null)\n {\n return false;\n }\n\n // Handle different types of registry values\n if (currentValue is int intValue && desiredValue is int desiredIntValue)\n {\n return intValue == desiredIntValue;\n }\n else if (currentValue is string strValue && desiredValue is string desiredStrValue)\n {\n return strValue.Equals(desiredStrValue, StringComparison.OrdinalIgnoreCase);\n }\n else if (currentValue is byte[] byteArrayValue && desiredValue is byte[] desiredByteArrayValue)\n {\n return byteArrayValue.SequenceEqual(desiredByteArrayValue);\n }\n else\n {\n // For other types, use the default Equals method\n return currentValue.Equals(desiredValue);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/StatusToColorConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing System.Windows.Media;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class StatusToColorConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // Handle RegistrySettingStatus\n if (value is RegistrySettingStatus status)\n {\n return status switch\n {\n RegistrySettingStatus.Applied => new SolidColorBrush(Color.FromRgb(0, 255, 60)), // Electric Green (#00FF3C)\n RegistrySettingStatus.NotApplied => new SolidColorBrush(Color.FromRgb(255, 40, 0)), // Ferrari Red (#FF2800)\n RegistrySettingStatus.Modified => new SolidColorBrush(Colors.Orange),\n RegistrySettingStatus.Error => new SolidColorBrush(Colors.Gray),\n _ => new SolidColorBrush(Colors.Gray)\n };\n }\n \n // Handle boolean for reinstallability status\n if (value is bool canBeReinstalled)\n {\n return canBeReinstalled \n ? new SolidColorBrush(Color.FromRgb(0, 165, 255)) // Blue (#00A5FF)\n : new SolidColorBrush(Color.FromRgb(255, 40, 0)); // Ferrari Red (#FF2800)\n }\n\n return new SolidColorBrush(Colors.Gray);\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceTestMethods.cs", "using Microsoft.Win32;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n public partial class RegistryService\n {\n public async Task TestValue(string keyPath, string valueName, object expectedValue, RegistryValueKind valueKind)\n {\n var result = new RegistryTestResult\n {\n KeyPath = keyPath,\n ValueName = valueName,\n ExpectedValue = expectedValue,\n Category = \"Registry Test\"\n };\n\n try\n {\n if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n result.IsSuccess = false;\n result.Message = \"Registry operations are only supported on Windows\";\n return result;\n }\n\n _logService.LogInformation($\"Testing registry value: {keyPath}\\\\{valueName}\");\n\n // Check if the key exists\n var keyExists = KeyExists(keyPath); // Removed await\n if (!keyExists)\n {\n result.IsSuccess = false;\n result.Message = $\"Registry key not found: {keyPath}\";\n return result;\n }\n\n // Check if the value exists\n var valueExists = ValueExists(keyPath, valueName); // Removed await\n if (!valueExists)\n {\n result.IsSuccess = false;\n result.Message = $\"Registry value not found: {keyPath}\\\\{valueName}\";\n return result;\n }\n\n // Get the actual value\n var actualValue = GetValue(keyPath, valueName); // Removed await\n result.ActualValue = actualValue;\n\n // Check if the value kind matches\n // var actualValueKind = await GetValueKind(keyPath, valueName); // Method doesn't exist\n // if (actualValueKind != valueKind)\n // {\n // result.IsSuccess = false;\n // result.Message = $\"Value kind mismatch. Expected: {valueKind}, Actual: {actualValueKind}\";\n // return result;\n // }\n\n // Compare the values\n if (expectedValue is int expectedInt && actualValue is int actualInt)\n {\n result.IsSuccess = expectedInt == actualInt;\n }\n else if (expectedValue is string expectedString && actualValue is string actualString)\n {\n result.IsSuccess = string.Equals(expectedString, actualString, StringComparison.OrdinalIgnoreCase);\n }\n else if (expectedValue is byte[] expectedBytes && actualValue is byte[] actualBytes)\n {\n result.IsSuccess = expectedBytes.SequenceEqual(actualBytes);\n }\n else\n {\n // For other types, use Equals\n result.IsSuccess = expectedValue?.Equals(actualValue) ?? (actualValue == null);\n }\n\n if (!result.IsSuccess)\n {\n result.Message = $\"Value mismatch. Expected: {expectedValue}, Actual: {actualValue}\";\n }\n else\n {\n result.Message = \"Value matches expected value\";\n }\n\n return result;\n }\n catch (Exception ex)\n {\n result.IsSuccess = false;\n result.Message = $\"Error testing registry value: {ex.Message}\";\n _logService.LogError($\"Error testing registry value {keyPath}\\\\{valueName}\", ex);\n return result;\n }\n }\n\n public async Task> TestMultipleValues(IEnumerable settings)\n {\n var results = new List();\n\n try\n {\n if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n _logService.LogError(\"Registry operations are only supported on Windows\");\n return results;\n }\n\n _logService.LogInformation(\"Testing multiple registry values\");\n\n foreach (var setting in settings)\n {\n var keyPath = $\"{setting.Hive}\\\\{setting.SubKey}\";\n // Use EnabledValue if available, otherwise fall back to RecommendedValue for backward compatibility\n object valueToTest = setting.EnabledValue ?? setting.RecommendedValue;\n var result = await TestValue(keyPath, setting.Name, valueToTest, setting.ValueType);\n result.Category = setting.Category;\n result.Description = setting.Description;\n results.Add(result);\n }\n\n var passCount = results.Count(r => r.IsSuccess);\n _logService.LogInformation($\"Registry test results: {passCount}/{results.Count} passed\");\n\n return results;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error testing multiple registry values: {ex.Message}\", ex);\n return results;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/PowerOptimizationsViewModel.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Reflection;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Interfaces;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Infrastructure.Features.Common.Registry;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for power optimizations.\n /// \n public partial class PowerOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IPowerPlanService _powerPlanService;\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n [ObservableProperty]\n private int _powerPlanValue;\n\n [ObservableProperty]\n private bool _isApplyingPowerPlan;\n\n [ObservableProperty]\n private string _statusText = \"Power settings\";\n\n [ObservableProperty]\n private ObservableCollection _powerPlanLabels = new()\n {\n \"Balanced\",\n \"High Performance\",\n \"Ultimate Performance\"\n };\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The power plan service.\n /// The view model locator.\n /// The settings registry.\n public PowerOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IPowerPlanService powerPlanService,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService));\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n }\n\n /// \n /// Loads the power settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, \"Loading power settings\");\n\n // Initialize Power settings from PowerOptimizations.GetPowerOptimizations()\n Settings.Clear();\n\n // The Power Plan ComboBox is already defined in the XAML, so we don't need to add it to the Settings collection\n _logService.Log(LogLevel.Info, \"Power Plan ComboBox is defined in XAML\");\n\n // Get power optimizations from the new method\n var powerOptimizations = PowerOptimizations.GetPowerOptimizations();\n \n // Add items for each optimization setting\n foreach (var setting in powerOptimizations.Settings)\n {\n // Skip settings that use PowerCfg commands\n if (setting.CustomProperties != null &&\n setting.CustomProperties.ContainsKey(\"PowerCfgSettings\"))\n {\n _logService.Log(LogLevel.Info, $\"Skipping PowerCfg setting: {setting.Name} - hiding from UI\");\n continue; // Skip this setting\n }\n \n // Create a view model for each setting\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsUpdatingFromCode = true, // Set this to true to allow RefreshStatus to set the correct state\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = setting.ControlType\n };\n \n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Register the setting in the settings registry if available\n if (_settingsRegistry != null && !string.IsNullOrEmpty(settingItem.Id))\n {\n _settingsRegistry.RegisterSetting(settingItem);\n _logService.Log(LogLevel.Info, $\"Registered setting {settingItem.Id} in settings registry during creation\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Refresh status for all settings to populate LinkedRegistrySettingsWithValues\n foreach (var setting in Settings)\n {\n await setting.RefreshStatus();\n }\n\n // Set up power plan ComboBox\n await LoadCurrentPowerPlanAsync();\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading power settings: {ex.Message}\");\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Loads the current power plan and sets the ComboBox value accordingly.\n /// \n private async Task LoadCurrentPowerPlanAsync()\n {\n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));\n var cancellationToken = cancellationTokenSource.Token;\n \n try\n {\n _logService.Log(LogLevel.Info, \"Starting to load current power plan\");\n \n // Get the current active power plan GUID using the service with timeout\n var getPlanTask = _powerPlanService.GetActivePowerPlanGuidAsync();\n await Task.WhenAny(getPlanTask, Task.Delay(5000, cancellationToken));\n \n string activePlanGuid;\n if (getPlanTask.IsCompleted)\n {\n activePlanGuid = await getPlanTask;\n _logService.Log(LogLevel.Info, $\"Active power plan GUID: {activePlanGuid}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"GetActivePowerPlanGuidAsync timed out, defaulting to Balanced\");\n activePlanGuid = PowerOptimizations.PowerPlans.Balanced.Guid;\n cancellationTokenSource.Cancel();\n }\n \n // Get the Ultimate Performance GUID from the service\n string ultimatePerformanceGuid;\n var field = typeof(Winhance.Infrastructure.Features.Optimize.Services.PowerPlanService)\n .GetField(\"ULTIMATE_PERFORMANCE_PLAN_GUID\", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);\n \n if (field != null)\n {\n ultimatePerformanceGuid = (string)field.GetValue(null);\n _logService.Log(LogLevel.Info, $\"Ultimate Performance GUID from service: {ultimatePerformanceGuid}\");\n }\n else\n {\n ultimatePerformanceGuid = PowerOptimizations.PowerPlans.UltimatePerformance.Guid;\n _logService.Log(LogLevel.Warning, $\"Could not get Ultimate Performance GUID from service, using value from PowerOptimizations: {ultimatePerformanceGuid}\");\n }\n \n // Set the slider value based on the active plan\n if (activePlanGuid == PowerOptimizations.PowerPlans.Balanced.Guid)\n {\n // Use IsApplyingPowerPlan to prevent triggering ApplyPowerPlanAsync\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 0; // Balanced\n IsApplyingPowerPlan = wasApplying;\n _logService.Log(LogLevel.Info, \"Detected Balanced power plan\");\n }\n else if (activePlanGuid == PowerOptimizations.PowerPlans.HighPerformance.Guid)\n {\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 1; // High Performance\n IsApplyingPowerPlan = wasApplying;\n _logService.Log(LogLevel.Info, \"Detected High Performance power plan\");\n }\n else if (activePlanGuid == ultimatePerformanceGuid)\n {\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 2; // Ultimate Performance\n IsApplyingPowerPlan = wasApplying;\n _logService.Log(LogLevel.Info, \"Detected Ultimate Performance power plan\");\n }\n else\n {\n // Check if the active plan name contains \"Ultimate Performance\"\n var getPlansTask = _powerPlanService.GetAvailablePowerPlansAsync();\n await Task.WhenAny(getPlansTask, Task.Delay(5000, cancellationToken));\n \n if (getPlansTask.IsCompleted)\n {\n var allPlans = await getPlansTask;\n var activePlan = allPlans.FirstOrDefault(p => p.Guid == activePlanGuid);\n \n if (activePlan != null && activePlan.Name.Contains(\"Ultimate Performance\", StringComparison.OrdinalIgnoreCase))\n {\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 2; // Ultimate Performance\n IsApplyingPowerPlan = wasApplying;\n _logService.Log(LogLevel.Info, $\"Detected Ultimate Performance power plan by name: {activePlan.Name}\");\n \n // Update the static GUID for future reference\n if (field != null)\n {\n field.SetValue(null, activePlanGuid);\n _logService.Log(LogLevel.Info, $\"Updated Ultimate Performance GUID to: {activePlanGuid}\");\n }\n }\n else\n {\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 0; // Default to Balanced if unknown\n IsApplyingPowerPlan = wasApplying;\n _logService.Log(LogLevel.Warning, $\"Unknown power plan GUID: {activePlanGuid}, defaulting to Balanced\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"GetAvailablePowerPlansAsync timed out, defaulting to Balanced\");\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 0; // Default to Balanced\n IsApplyingPowerPlan = wasApplying;\n cancellationTokenSource.Cancel();\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Current power plan: {PowerPlanLabels[PowerPlanValue]} (Value: {PowerPlanValue})\");\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"Power plan loading was canceled due to timeout\");\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 0; // Default to Balanced on timeout\n IsApplyingPowerPlan = wasApplying;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading current power plan: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n bool wasApplying = IsApplyingPowerPlan;\n IsApplyingPowerPlan = true;\n PowerPlanValue = 0; // Default to Balanced on error\n IsApplyingPowerPlan = wasApplying;\n }\n }\n\n /// \n /// Called when the PowerPlanValue property changes.\n /// \n /// The new value.\n partial void OnPowerPlanValueChanged(int value)\n {\n // Only apply the power plan when not in the middle of applying a power plan\n // This prevents recursive calls and allows for importing without applying\n if (!IsApplyingPowerPlan)\n {\n _logService.Log(LogLevel.Info, $\"PowerPlanValue changed to {value}, applying power plan\");\n try\n {\n // Use ConfigureAwait(false) to avoid deadlocks\n ApplyPowerPlanAsync(value).ConfigureAwait(false);\n _logService.Log(LogLevel.Info, $\"Successfully initiated power plan change to {value}\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error initiating power plan change: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Info, $\"PowerPlanValue changed to {value}, but not applying because IsApplyingPowerPlan is true\");\n _logService.Log(LogLevel.Debug, $\"Stack trace at PowerPlanValue change: {Environment.StackTrace}\");\n }\n }\n\n /// \n /// Applies the selected power plan.\n /// \n /// The power plan index (0=Balanced, 1=High Performance, 2=Ultimate Performance).\n /// A task representing the asynchronous operation.\n [RelayCommand]\n private async Task ApplyPowerPlanAsync(int planIndex)\n {\n // Double-check to prevent recursive calls\n if (IsApplyingPowerPlan)\n {\n _logService.Log(LogLevel.Warning, $\"ApplyPowerPlanAsync called while IsApplyingPowerPlan is true, ignoring\");\n return;\n }\n \n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(15));\n var cancellationToken = cancellationTokenSource.Token;\n \n try\n {\n IsApplyingPowerPlan = true;\n StatusText = $\"Applying {PowerPlanLabels[planIndex]} power plan...\";\n \n // Get the appropriate GUID based on the selected plan\n string planGuid;\n \n // Special handling for Ultimate Performance plan\n if (planIndex == 2) // Ultimate Performance\n {\n // Get the GUID from the service directly\n // This ensures we're using the most up-to-date GUID that might have been created dynamically\n var field = typeof(Winhance.Infrastructure.Features.Optimize.Services.PowerPlanService)\n .GetField(\"ULTIMATE_PERFORMANCE_PLAN_GUID\", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);\n \n if (field != null)\n {\n planGuid = (string)field.GetValue(null);\n _logService.Log(LogLevel.Info, $\"Using Ultimate Performance GUID from service: {planGuid}\");\n }\n else\n {\n // Fallback to the value from PowerOptimizations\n planGuid = PowerOptimizations.PowerPlans.UltimatePerformance.Guid;\n _logService.Log(LogLevel.Warning, $\"Could not get GUID from service, using value from PowerOptimizations: {planGuid}\");\n }\n }\n else\n {\n // For other plans, use the standard GUIDs\n planGuid = planIndex switch\n {\n 0 => PowerOptimizations.PowerPlans.Balanced.Guid,\n 1 => PowerOptimizations.PowerPlans.HighPerformance.Guid,\n _ => PowerOptimizations.PowerPlans.Balanced.Guid // Default to Balanced\n };\n }\n \n _logService.Log(LogLevel.Info, $\"Applying power plan: {PowerPlanLabels[planIndex]} with GUID: {planGuid}\");\n \n // Use the service to set the power plan with timeout\n var setPlanTask = _powerPlanService.SetPowerPlanAsync(planGuid);\n var timeoutTask = Task.Delay(10000, cancellationToken); // 10 second timeout\n \n await Task.WhenAny(setPlanTask, timeoutTask);\n \n if (setPlanTask.IsCompleted)\n {\n bool success = await setPlanTask;\n \n if (success)\n {\n _logService.Log(LogLevel.Info, $\"Power plan set to {PowerPlanLabels[planIndex]} ({planGuid})\");\n StatusText = $\"{PowerPlanLabels[planIndex]} power plan applied\";\n \n // Refresh the current power plan to ensure the UI is updated correctly\n var loadTask = LoadCurrentPowerPlanAsync();\n await Task.WhenAny(loadTask, Task.Delay(5000, cancellationToken));\n \n if (!loadTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"LoadCurrentPowerPlanAsync timed out, continuing anyway\");\n }\n \n // Refresh all PowerCfg settings to reflect the new power plan\n _logService.Log(LogLevel.Info, \"Refreshing PowerCfg settings after power plan change\");\n var checkTask = CheckSettingStatusesAsync();\n await Task.WhenAny(checkTask, Task.Delay(5000, cancellationToken));\n \n if (!checkTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"CheckSettingStatusesAsync timed out, continuing anyway\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Failed to set power plan to {PowerPlanLabels[planIndex]} ({planGuid})\");\n StatusText = $\"Failed to apply {PowerPlanLabels[planIndex]} power plan\";\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Setting power plan timed out after 10 seconds\");\n StatusText = $\"Timeout while applying {PowerPlanLabels[planIndex]} power plan\";\n \n // Cancel the operation\n cancellationTokenSource.Cancel();\n }\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"Power plan application was canceled due to timeout\");\n StatusText = \"Power plan application timed out\";\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying power plan: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n StatusText = $\"Error applying power plan: {ex.Message}\";\n }\n finally\n {\n // Make sure we always reset IsApplyingPowerPlan to false when done\n IsApplyingPowerPlan = false;\n _logService.Log(LogLevel.Info, \"Reset IsApplyingPowerPlan to false in ApplyPowerPlanAsync\");\n }\n }\n\n /// \n /// Checks the status of all power settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, $\"Checking status for {Settings.Count} power settings\");\n\n foreach (var setting in Settings)\n {\n try\n {\n // Check if this is a command-based setting with PowerCfg settings\n bool isCommandBasedSetting = setting.CustomProperties != null &&\n setting.CustomProperties.ContainsKey(\"PowerCfgSettings\") &&\n setting.CustomProperties[\"PowerCfgSettings\"] is List;\n\n if (isCommandBasedSetting)\n {\n _logService.Log(LogLevel.Info, $\"Checking command-based setting status for: {setting.Name}\");\n \n // Get PowerCfg settings from CustomProperties\n var powerCfgSettings = setting.CustomProperties[\"PowerCfgSettings\"] as List;\n \n try\n {\n // Special handling for Desktop Slideshow setting\n bool isDesktopSlideshowSetting = setting.Name.Contains(\"Desktop Slideshow\", StringComparison.OrdinalIgnoreCase);\n \n // Check if all PowerCfg settings are applied\n bool allApplied = await _powerPlanService.AreAllPowerCfgSettingsAppliedAsync(powerCfgSettings);\n \n // Update setting status based on PowerCfg settings\n setting.Status = allApplied ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n \n // Set a more descriptive current value\n if (isDesktopSlideshowSetting)\n {\n // For Desktop Slideshow, the value is counter-intuitive\n // When enabled (IsSelected=true), the slideshow is \"Available\" (value=0)\n // When disabled (IsSelected=false), the slideshow is \"Paused\" (value=1)\n setting.CurrentValue = allApplied ? \"Available\" : \"Paused\";\n }\n else\n {\n setting.CurrentValue = allApplied ? \"Enabled\" : \"Disabled\";\n }\n \n // Set status message with more detailed information\n setting.StatusMessage = allApplied\n ? \"This setting is currently applied.\"\n : \"This setting is not currently applied.\";\n \n _logService.Log(LogLevel.Info, $\"Command-based setting {setting.Name} status: {setting.Status}, isApplied={allApplied}, currentValue={setting.CurrentValue}\");\n \n // Update IsSelected to match the detected state\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = allApplied;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking PowerCfg setting status for {setting.Name}: {ex.Message}\");\n \n // On error, assume the setting is in its default state\n setting.Status = RegistrySettingStatus.NotApplied;\n setting.CurrentValue = \"Unknown\";\n setting.StatusMessage = \"Could not determine the current status of this setting.\";\n }\n }\n else if (setting.RegistrySetting != null)\n {\n _logService.Log(LogLevel.Info, $\"Checking registry-based setting status for: {setting.Name}\");\n\n // Get the status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // Get the current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name}: {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n setting.LinkedRegistrySettingsWithValues.Clear();\n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Checking linked registry settings status for: {setting.Name} with {setting.LinkedRegistrySettings.Settings.Count} registry entries\");\n\n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(regSetting.Hive);\n string fullPath = $\"{hiveString}\\\\{regSetting.SubKey}\";\n _logService.Log(LogLevel.Info, $\"Registry entry: {fullPath}\\\\{regSetting.Name}, EnabledValue={regSetting.EnabledValue}, DisabledValue={regSetting.DisabledValue}\");\n\n // Check if the key exists\n bool keyExists = _registryService.KeyExists(fullPath);\n _logService.Log(LogLevel.Info, $\"Key exists: {keyExists}\");\n\n if (keyExists)\n {\n // Check if the value exists and get its current value\n var currentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value: {currentValue ?? \"null\"}\");\n }\n }\n\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n _logService.Log(LogLevel.Info, $\"Combined status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name} (first entry): {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value for linked setting {regSetting.Name}: {regCurrentValue ?? \"null\"}\");\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry setting or command-based setting found for {setting.Name}\");\n setting.Status = RegistrySettingStatus.Unknown;\n setting.StatusMessage = \"Setting information is missing\";\n }\n\n // If this is a grouped setting, update child settings too\n if (setting.IsGroupedSetting && setting.ChildSettings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Updating {setting.ChildSettings.Count} child settings for {setting.Name}\");\n foreach (var childSetting in setting.ChildSettings)\n {\n // Check if this is a command-based child setting\n bool isCommandBasedChildSetting = childSetting.CustomProperties != null &&\n childSetting.CustomProperties.ContainsKey(\"PowerCfgSettings\") &&\n childSetting.CustomProperties[\"PowerCfgSettings\"] is List;\n\n if (isCommandBasedChildSetting)\n {\n try\n {\n var powerCfgSettings = childSetting.CustomProperties[\"PowerCfgSettings\"] as List;\n \n // Special handling for Desktop Slideshow setting\n bool isDesktopSlideshowSetting = childSetting.Name.Contains(\"Desktop Slideshow\", StringComparison.OrdinalIgnoreCase);\n \n bool allApplied = await _powerPlanService.AreAllPowerCfgSettingsAppliedAsync(powerCfgSettings);\n \n childSetting.Status = allApplied ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n \n // Set a more descriptive current value\n if (isDesktopSlideshowSetting)\n {\n childSetting.CurrentValue = allApplied ? \"Available\" : \"Paused\";\n }\n else\n {\n childSetting.CurrentValue = allApplied ? \"Enabled\" : \"Disabled\";\n }\n \n childSetting.StatusMessage = allApplied\n ? \"This setting is currently applied.\"\n : \"This setting is not currently applied.\";\n \n // Update IsSelected based on status\n childSetting.IsUpdatingFromCode = true;\n try\n {\n childSetting.IsSelected = allApplied;\n }\n finally\n {\n childSetting.IsUpdatingFromCode = false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking PowerCfg setting status for child setting {childSetting.Name}: {ex.Message}\");\n \n // On error, assume the setting is in its default state\n childSetting.Status = RegistrySettingStatus.NotApplied;\n childSetting.CurrentValue = \"Unknown\";\n childSetting.StatusMessage = \"Could not determine the current status of this setting.\";\n }\n }\n else if (childSetting.RegistrySetting != null)\n {\n var status = await _registryService.GetSettingStatusAsync(childSetting.RegistrySetting);\n childSetting.Status = status;\n\n var currentValue = await _registryService.GetCurrentValueAsync(childSetting.RegistrySetting);\n childSetting.CurrentValue = currentValue;\n\n childSetting.StatusMessage = GetStatusMessage(childSetting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Child setting {childSetting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n childSetting.IsUpdatingFromCode = true;\n try\n {\n childSetting.IsSelected = shouldBeSelected;\n }\n finally\n {\n childSetting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating status for setting {setting.Name}: {ex.Message}\");\n setting.Status = RegistrySettingStatus.Error;\n setting.StatusMessage = $\"Error: {ex.Message}\";\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking power setting statuses: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0)\n return;\n\n var selectedCount = Settings.Count(setting => setting.IsSelected);\n IsSelected = selectedCount == Settings.Count;\n }\n\n /// \n /// Applies a registry setting with the specified value.\n /// \n /// The registry setting to apply.\n /// The value to set.\n /// A task representing the asynchronous operation.\n private async Task ApplyRegistrySetting(RegistrySetting registrySetting, object value)\n {\n string hiveString = registrySetting.Hive.ToString();\n if (hiveString == \"LocalMachine\") hiveString = \"HKLM\";\n else if (hiveString == \"CurrentUser\") hiveString = \"HKCU\";\n else if (hiveString == \"ClassesRoot\") hiveString = \"HKCR\";\n else if (hiveString == \"Users\") hiveString = \"HKU\";\n else if (hiveString == \"CurrentConfig\") hiveString = \"HKCC\";\n\n string fullPath = $\"{hiveString}\\\\{registrySetting.SubKey}\";\n \n if (value == null)\n {\n await _registryService.DeleteValue(registrySetting.Hive, registrySetting.SubKey, registrySetting.Name);\n }\n else\n {\n _registryService.SetValue(fullPath, registrySetting.Name, value, registrySetting.ValueType);\n }\n }\n\n /// \n /// Gets a user-friendly status message for a setting.\n /// \n /// The setting to get the status message for.\n /// A user-friendly status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied =>\n \"This setting is already applied with the recommended value.\",\n\n RegistrySettingStatus.NotApplied =>\n setting.CurrentValue == null\n ? \"This setting is not applied (registry value does not exist).\"\n : \"This setting is using the default value.\",\n\n RegistrySettingStatus.Modified =>\n \"This setting has a custom value that differs from the recommended value.\",\n\n RegistrySettingStatus.Error =>\n \"An error occurred while checking this setting's status.\",\n\n _ => \"The status of this setting is unknown.\"\n };\n }\n\n /// \n /// Converts a tuple to a RegistrySetting object.\n /// \n /// The key for the setting.\n /// The tuple containing the setting information.\n /// A RegistrySetting object.\n private RegistrySetting ConvertToRegistrySetting(string key, (string Path, string Name, object Value, Microsoft.Win32.RegistryValueKind ValueKind) settingTuple)\n {\n // Determine the registry hive from the path\n RegistryHive hive = RegistryHive.LocalMachine; // Default to HKLM\n if (settingTuple.Path.StartsWith(\"HKEY_CURRENT_USER\") || settingTuple.Path.StartsWith(\"HKCU\") || settingTuple.Path.StartsWith(\"Software\\\\\"))\n {\n hive = RegistryHive.CurrentUser;\n }\n else if (settingTuple.Path.StartsWith(\"HKEY_LOCAL_MACHINE\") || settingTuple.Path.StartsWith(\"HKLM\"))\n {\n hive = RegistryHive.LocalMachine;\n }\n else if (settingTuple.Path.StartsWith(\"HKEY_CLASSES_ROOT\") || settingTuple.Path.StartsWith(\"HKCR\"))\n {\n hive = RegistryHive.ClassesRoot;\n }\n else if (settingTuple.Path.StartsWith(\"HKEY_USERS\") || settingTuple.Path.StartsWith(\"HKU\"))\n {\n hive = RegistryHive.Users;\n }\n else if (settingTuple.Path.StartsWith(\"HKEY_CURRENT_CONFIG\") || settingTuple.Path.StartsWith(\"HKCC\"))\n {\n hive = RegistryHive.CurrentConfig;\n }\n\n // Clean up the path to remove any hive prefix\n string subKey = settingTuple.Path;\n if (subKey.StartsWith(\"HKEY_CURRENT_USER\\\\\") || subKey.StartsWith(\"HKCU\\\\\"))\n {\n subKey = subKey.Replace(\"HKEY_CURRENT_USER\\\\\", \"\").Replace(\"HKCU\\\\\", \"\");\n }\n else if (subKey.StartsWith(\"HKEY_LOCAL_MACHINE\\\\\") || subKey.StartsWith(\"HKLM\\\\\"))\n {\n subKey = subKey.Replace(\"HKEY_LOCAL_MACHINE\\\\\", \"\").Replace(\"HKLM\\\\\", \"\");\n }\n else if (subKey.StartsWith(\"HKEY_CLASSES_ROOT\\\\\") || subKey.StartsWith(\"HKCR\\\\\"))\n {\n subKey = subKey.Replace(\"HKEY_CLASSES_ROOT\\\\\", \"\").Replace(\"HKCR\\\\\", \"\");\n }\n else if (subKey.StartsWith(\"HKEY_USERS\\\\\") || subKey.StartsWith(\"HKU\\\\\"))\n {\n subKey = subKey.Replace(\"HKEY_USERS\\\\\", \"\").Replace(\"HKU\\\\\", \"\");\n }\n else if (subKey.StartsWith(\"HKEY_CURRENT_CONFIG\\\\\") || subKey.StartsWith(\"HKCC\\\\\"))\n {\n subKey = subKey.Replace(\"HKEY_CURRENT_CONFIG\\\\\", \"\").Replace(\"HKCC\\\\\", \"\");\n }\n\n // Create and return the RegistrySetting object\n var registrySetting = new RegistrySetting\n {\n Category = \"Power\",\n Hive = hive,\n SubKey = subKey,\n Name = settingTuple.Name,\n EnabledValue = settingTuple.Value, // Recommended value becomes EnabledValue\n DisabledValue = settingTuple.Value,\n ValueType = settingTuple.ValueKind,\n // Keep these for backward compatibility\n RecommendedValue = settingTuple.Value,\n DefaultValue = settingTuple.Value,\n Description = $\"Power setting: {key}\"\n };\n\n return registrySetting;\n }\n\n /// \n /// Gets a friendly name for a power setting.\n /// \n /// The power setting key.\n /// A user-friendly name for the power setting.\n private string GetFriendlyNameForPowerSetting(string key)\n {\n return key switch\n {\n \"HibernateEnabled\" => \"Disable Hibernate\",\n \"HibernateEnabledDefault\" => \"Disable Hibernate by Default\",\n \"VideoQuality\" => \"High Video Quality on Battery\",\n \"LockOption\" => \"Hide Lock Option\",\n \"FastBoot\" => \"Disable Fast Boot\",\n \"CpuUnpark\" => \"CPU Core Unparking\",\n \"PowerThrottling\" => \"Disable Power Throttling\",\n _ => key\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceValueOperations.cs", "using Microsoft.Win32;\nusing System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Registry service implementation for value operations.\n /// \n public partial class RegistryService\n {\n /// \n /// Sets a value in the registry.\n /// \n /// The registry key path.\n /// The name of the value to set.\n /// The value to set.\n /// The type of the value.\n /// True if the operation succeeded; otherwise, false.\n public bool SetValue(string keyPath, string valueName, object value, RegistryValueKind valueKind)\n {\n try\n {\n if (!CheckWindowsPlatform())\n return false;\n\n _logService.Log(LogLevel.Info, $\"Setting registry value: {keyPath}\\\\{valueName}\");\n\n // First ensure the key exists with full access rights\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return false;\n }\n\n string subKeyPath = string.Join('\\\\', pathParts.Skip(1));\n\n // Create the key with direct Registry API and security settings\n // This will also attempt to take ownership if needed\n RegistryKey? targetKey = EnsureKeyWithFullAccess(rootKey, subKeyPath);\n\n if (targetKey == null)\n {\n _logService.Log(LogLevel.Warning, $\"Could not open or create registry key: {keyPath}\");\n \n // Try using PowerShell as a fallback for policy keys\n if (keyPath.Contains(\"Policies\", StringComparison.OrdinalIgnoreCase))\n {\n _logService.Log(LogLevel.Info, $\"Attempting to set policy registry value using PowerShell: {keyPath}\\\\{valueName}\");\n return SetValueUsingPowerShell(keyPath, valueName, value, valueKind);\n }\n \n return false;\n }\n\n using (targetKey)\n {\n try\n {\n targetKey.SetValue(valueName, value, valueKind);\n\n // Clear the cache for this value\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueCache)\n {\n if (_valueCache.ContainsKey(fullValuePath))\n {\n _valueCache.Remove(fullValuePath);\n }\n }\n\n _logService.Log(LogLevel.Success, $\"Successfully set registry value: {keyPath}\\\\{valueName}\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Failed to set registry value even after taking ownership: {ex.Message}\");\n\n // Try using PowerShell as a fallback\n return SetValueUsingPowerShell(keyPath, valueName, value, valueKind);\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting registry value {keyPath}\\\\{valueName}: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Gets a value from the registry.\n /// \n /// The registry key path.\n /// The name of the value to get.\n /// The value from the registry, or null if it doesn't exist.\n public object? GetValue(string keyPath, string valueName)\n {\n try\n {\n if (!CheckWindowsPlatform())\n return null;\n\n // Check the cache first\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueCache)\n {\n if (_valueCache.TryGetValue(fullValuePath, out object? cachedValue))\n {\n return cachedValue;\n }\n }\n\n // Open the key for reading\n using (RegistryKey? key = OpenRegistryKey(keyPath, false))\n {\n if (key == null)\n {\n _logService.Log(LogLevel.Debug, $\"Registry key does not exist: {keyPath}\");\n \n // Cache the null result\n lock (_valueCache)\n {\n _valueCache[fullValuePath] = null;\n }\n \n return null;\n }\n\n // Get the value\n object? value = key.GetValue(valueName);\n \n // Cache the result\n lock (_valueCache)\n {\n _valueCache[fullValuePath] = value;\n }\n \n return value;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting registry value {keyPath}\\\\{valueName}: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Deletes a value from the registry.\n /// \n /// The registry key path.\n /// The name of the value to delete.\n /// True if the operation succeeded; otherwise, false.\n public bool DeleteValue(string keyPath, string valueName)\n {\n try\n {\n if (!CheckWindowsPlatform())\n return false;\n\n _logService.Log(LogLevel.Info, $\"Deleting registry value: {keyPath}\\\\{valueName}\");\n\n // Open the key for writing\n using (RegistryKey? key = OpenRegistryKey(keyPath, true))\n {\n if (key == null)\n {\n _logService.Log(LogLevel.Warning, $\"Registry key does not exist: {keyPath}\");\n return false;\n }\n\n // Delete the value\n key.DeleteValue(valueName, false);\n \n // Clear the cache for this value\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueCache)\n {\n if (_valueCache.ContainsKey(fullValuePath))\n {\n _valueCache.Remove(fullValuePath);\n }\n }\n \n // Also clear the value exists cache\n lock (_valueExistsCache)\n {\n if (_valueExistsCache.ContainsKey(fullValuePath))\n {\n _valueExistsCache.Remove(fullValuePath);\n }\n }\n\n _logService.Log(LogLevel.Success, $\"Successfully deleted registry value: {keyPath}\\\\{valueName}\");\n return true;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error deleting registry value {keyPath}\\\\{valueName}: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Deletes a value from the registry using hive and subkey.\n /// \n /// The registry hive.\n /// The registry subkey.\n /// The name of the value to delete.\n /// True if the operation succeeded; otherwise, false.\n public async Task DeleteValue(RegistryHive hive, string subKey, string valueName)\n {\n string keyPath = $\"{RegistryExtensions.GetRegistryHiveString(hive)}\\\\{subKey}\";\n return DeleteValue(keyPath, valueName);\n }\n\n /// \n /// Checks if a registry value exists.\n /// \n /// The registry key path.\n /// The name of the value to check.\n /// True if the value exists; otherwise, false.\n public bool ValueExists(string keyPath, string valueName)\n {\n try\n {\n if (!CheckWindowsPlatform())\n return false;\n\n // Check the cache first\n string fullValuePath = $\"{keyPath}\\\\{valueName}\";\n lock (_valueExistsCache)\n {\n if (_valueExistsCache.TryGetValue(fullValuePath, out bool exists))\n {\n return exists;\n }\n }\n\n // Open the key for reading\n using (RegistryKey? key = OpenRegistryKey(keyPath, false))\n {\n if (key == null)\n {\n // Cache the result\n lock (_valueExistsCache)\n {\n _valueExistsCache[fullValuePath] = false;\n }\n \n return false;\n }\n\n // Check if the value exists\n string[] valueNames = key.GetValueNames();\n bool exists = valueNames.Contains(valueName, StringComparer.OrdinalIgnoreCase);\n \n // Cache the result\n lock (_valueExistsCache)\n {\n _valueExistsCache[fullValuePath] = exists;\n }\n \n return exists;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking if registry value exists {keyPath}\\\\{valueName}: {ex.Message}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/DialogService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n public class DialogService : IDialogService\n {\n public void ShowMessage(string message, string title = \"\")\n {\n // Use CustomDialog for all messages\n CustomDialog.ShowInformation(title, title, message, \"\");\n }\n\n public Task ShowConfirmationAsync(\n string message,\n string title = \"\",\n string okButtonText = \"OK\",\n string cancelButtonText = \"Cancel\"\n )\n {\n // For regular confirmation messages without app lists\n if (\n !message.Contains(\"following\")\n || (!message.Contains(\"install\") && !message.Contains(\"remove\"))\n )\n {\n return Task.FromResult(\n MessageBox.Show(\n message,\n title,\n MessageBoxButton.YesNo,\n MessageBoxImage.Question\n ) == MessageBoxResult.Yes\n );\n }\n\n // Parse apps from the message\n var lines = message.Split('\\n');\n var apps = lines\n .Where(line => line.StartsWith(\"+\") || line.StartsWith(\"-\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line =>\n line.Contains(\"cannot be\")\n || line.Contains(\"action cannot\")\n || line.Contains(\"Some selected\")\n )\n .Select(line => line.Trim())\n );\n\n var result = CustomDialog.ShowConfirmation(title, headerText, apps, footerText);\n return Task.FromResult(result ?? false);\n }\n\n public Task ShowErrorAsync(string message, string title = \"Error\", string buttonText = \"OK\")\n {\n // Use CustomDialog for all error messages\n CustomDialog.ShowInformation(title, title, message, \"\");\n return Task.CompletedTask;\n }\n\n public Task ShowInformationAsync(\n string message,\n string title = \"Information\",\n string buttonText = \"OK\"\n )\n {\n // For messages with app lists (special handling)\n if (message.Contains(\"following\") && \n (message.Contains(\"installed\") || message.Contains(\"removed\")))\n {\n // Parse apps from the message\n var lines = message.Split('\\n');\n var apps = lines\n .Where(line => line.StartsWith(\"+\") || line.StartsWith(\"-\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line => line.Contains(\"Failed\") || line.Contains(\"startup task\"))\n .Select(line => line.Trim())\n );\n\n CustomDialog.ShowInformation(title, headerText, apps, footerText);\n return Task.CompletedTask;\n }\n \n // For all other information messages, use CustomDialog\n CustomDialog.ShowInformation(title, title, message, \"\");\n return Task.CompletedTask;\n }\n\n public Task ShowWarningAsync(\n string message,\n string title = \"Warning\",\n string buttonText = \"OK\"\n )\n {\n MessageBox.Show(message, title, MessageBoxButton.OK, MessageBoxImage.Warning);\n return Task.CompletedTask;\n }\n\n public Task ShowInputAsync(\n string message,\n string title = \"\",\n string defaultValue = \"\"\n )\n {\n var result = MessageBox.Show(\n message,\n title,\n MessageBoxButton.OKCancel,\n MessageBoxImage.Question\n );\n return Task.FromResult(result == MessageBoxResult.OK ? defaultValue : null);\n }\n\n public Task ShowYesNoCancelAsync(string message, string title = \"\")\n {\n // For theme change messages (special case for \"Choose Your Mode\" combobox)\n if (message.Contains(\"theme wallpaper\") || title.Contains(\"Theme\"))\n {\n // Create a list with a single item for the message\n var messageList = new List { message };\n\n // Use the CustomDialog.ShowConfirmation method (Yes/No only)\n var themeDialogResult = CustomDialog.ShowConfirmation(\n title,\n \"Theme Change\",\n messageList,\n \"\"\n );\n\n // Convert to bool? (Yes/No only, no Cancel)\n return Task.FromResult(themeDialogResult);\n }\n // For regular messages without app lists\n else if (\n !message.Contains(\"following\")\n || (!message.Contains(\"install\") && !message.Contains(\"remove\"))\n )\n {\n var result = MessageBox.Show(\n message,\n title,\n MessageBoxButton.YesNoCancel,\n MessageBoxImage.Question\n );\n bool? boolResult = result switch\n {\n MessageBoxResult.Yes => true,\n MessageBoxResult.No => false,\n _ => null,\n };\n return Task.FromResult(boolResult);\n }\n\n // Parse apps from the message\n var lines = message.Split('\\n');\n var apps = lines\n .Where(line => line.StartsWith(\"+\") || line.StartsWith(\"-\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line =>\n line.Contains(\"cannot be\")\n || line.Contains(\"action cannot\")\n || line.Contains(\"Some selected\")\n )\n .Select(line => line.Trim())\n );\n\n // Use the CustomDialog.ShowYesNoCancel method\n var dialogResult = CustomDialog.ShowYesNoCancel(title, headerText, apps, footerText);\n return Task.FromResult(dialogResult);\n }\n\n public async Task> ShowUnifiedConfigurationSaveDialogAsync(\n string title,\n string description,\n Dictionary sections\n )\n {\n // Create the dialog\n var dialog = new UnifiedConfigurationDialog(title, description, sections, true);\n\n // Set the owner to the current active window\n dialog.Owner = Application.Current.MainWindow;\n\n // Show the dialog\n var result = dialog.ShowDialog();\n\n // Return the result if the user clicked OK, otherwise return null\n if (result == true)\n {\n return dialog.GetResult();\n }\n\n return null;\n }\n\n public async Task> ShowUnifiedConfigurationImportDialogAsync(\n string title,\n string description,\n Dictionary sections\n )\n {\n // Create the dialog\n var dialog = new UnifiedConfigurationDialog(title, description, sections, false);\n\n // Set the owner to the current active window\n dialog.Owner = Application.Current.MainWindow;\n\n // Show the dialog\n var result = dialog.ShowDialog();\n\n // Return the result if the user clicked OK, otherwise return null\n if (result == true)\n {\n return dialog.GetResult();\n }\n\n return null;\n }\n\n /// \n /// Displays a donation dialog.\n /// \n /// The title of the dialog box.\n /// The support message to display.\n /// The footer text.\n /// A task representing the asynchronous operation, with a tuple containing the dialog result (whether the user clicked Yes or No) and whether the \"Don't show again\" checkbox was checked.\n public async Task<(bool? Result, bool DontShowAgain)> ShowDonationDialogAsync(\n string title,\n string supportMessage,\n string footerText\n )\n {\n try\n {\n // Use the DonationDialog.ShowDonationDialogAsync method\n var dialog = await DonationDialog.ShowDonationDialogAsync(\n title,\n supportMessage,\n footerText\n );\n\n // Return the dialog result and the DontShowAgain value as a tuple\n return (dialog?.DialogResult, dialog?.DontShowAgain ?? false);\n }\n catch (Exception ex)\n {\n // Log the error\n System.Diagnostics.Debug.WriteLine($\"Error showing donation dialog: {ex.Message}\");\n return (false, false);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/FrameNavigationService.cs", "using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service for navigating between views in the application using ContentPresenter-based navigation.\n /// \n public class FrameNavigationService\n : Winhance.Core.Features.Common.Interfaces.INavigationService\n {\n private readonly Stack _backStack = new();\n private readonly Stack<(Type ViewModelType, object Parameter)> _forwardStack = new();\n private readonly List _navigationHistory = new();\n private readonly Dictionary _viewMappings =\n new();\n private readonly IServiceProvider _serviceProvider;\n private readonly IParameterSerializer _parameterSerializer;\n private readonly SemaphoreSlim _navigationLock = new(1, 1);\n private readonly ConcurrentQueue<(\n Type ViewType,\n Type ViewModelType,\n object Parameter,\n TaskCompletionSource CompletionSource\n )> _navigationQueue = new();\n private object _currentParameter;\n private string _currentRoute;\n private const int MaxHistorySize = 50;\n private CancellationTokenSource _currentNavigationCts;\n private ICommand _navigateCommand;\n\n /// \n /// Gets the command for navigation.\n /// \n public ICommand NavigateCommand =>\n _navigateCommand ??= new RelayCommand(route => NavigateTo(route));\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The parameter serializer.\n public FrameNavigationService(\n IServiceProvider serviceProvider,\n IParameterSerializer parameterSerializer\n )\n {\n _serviceProvider = serviceProvider;\n _parameterSerializer =\n parameterSerializer ?? throw new ArgumentNullException(nameof(parameterSerializer));\n }\n\n /// \n /// Determines whether navigation back is possible.\n /// \n public bool CanGoBack => _backStack.Count > 1;\n\n /// \n /// Gets a list of navigation history.\n /// \n public IReadOnlyList NavigationHistory => _navigationHistory.AsReadOnly();\n\n /// \n /// Gets the current view name.\n /// \n public string CurrentView => _currentRoute;\n\n /// \n /// Event raised when navigation occurs.\n /// \n public event EventHandler Navigated;\n\n /// \n /// Event raised before navigation occurs.\n /// \n public event EventHandler Navigating;\n\n /// \n /// Event raised when navigation fails.\n /// \n public event EventHandler NavigationFailed;\n\n /// \n /// Initializes the navigation service.\n /// \n public void Initialize()\n {\n // No initialization needed for ContentPresenter-based navigation\n }\n\n /// \n /// Registers a view mapping.\n /// \n /// The route.\n /// The view type.\n /// The view model type.\n public void RegisterViewMapping(string route, Type viewType, Type viewModelType)\n {\n if (string.IsNullOrWhiteSpace(route))\n throw new ArgumentException(\"Route cannot be empty\", nameof(route));\n\n _viewMappings[route] = (viewType, viewModelType);\n }\n\n /// \n /// Checks if navigation to a route is possible.\n /// \n /// The route to check.\n /// True if navigation is possible; otherwise, false.\n public bool CanNavigateTo(string route) => _viewMappings.ContainsKey(route);\n\n /// \n /// Navigates to a view by route.\n /// \n /// The route to navigate to.\n /// True if navigation was successful; otherwise, false.\n public bool NavigateTo(string viewName)\n {\n try\n {\n NavigateToAsync(viewName).GetAwaiter().GetResult();\n return true;\n }\n catch (Exception ex)\n {\n // Log the error\n System.Diagnostics.Debug.WriteLine($\"Navigation error: {ex.Message}\");\n\n var args = new Winhance.Core.Features.Common.Interfaces.NavigationEventArgs(\n CurrentView,\n viewName,\n null,\n false\n );\n NavigationFailed?.Invoke(this, args);\n return false;\n }\n }\n\n /// \n /// Navigates to a view by route with a parameter.\n /// \n /// The route to navigate to.\n /// The navigation parameter.\n /// True if navigation was successful; otherwise, false.\n public bool NavigateTo(string viewName, object parameter)\n {\n try\n {\n NavigateToAsync(viewName, parameter).GetAwaiter().GetResult();\n return true;\n }\n catch (Exception ex)\n {\n // Log the error\n System.Diagnostics.Debug.WriteLine($\"Navigation error: {ex.Message}\");\n\n var args = new Winhance.Core.Features.Common.Interfaces.NavigationEventArgs(\n CurrentView,\n viewName,\n parameter,\n false\n );\n NavigationFailed?.Invoke(this, args);\n return false;\n }\n }\n\n /// \n /// Navigates back to the previous view.\n /// \n /// True if navigation was successful; otherwise, false.\n public bool NavigateBack()\n {\n try\n {\n GoBackAsync().GetAwaiter().GetResult();\n return true;\n }\n catch (Exception ex)\n {\n // Log the error\n System.Diagnostics.Debug.WriteLine($\"Navigation back error: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Navigates to a view model type.\n /// \n /// The view model type.\n /// The navigation parameter.\n /// A task representing the asynchronous operation.\n public async Task NavigateToAsync(object parameter = null)\n where TViewModel : class => await NavigateToAsync(typeof(TViewModel), parameter);\n\n /// \n /// Navigates to a view model type.\n /// \n /// The view model type.\n /// The navigation parameter.\n /// A task representing the asynchronous operation.\n public async Task NavigateToAsync(Type viewModelType, object parameter = null)\n {\n var viewType = GetViewTypeForViewModel(viewModelType);\n var tcs = new TaskCompletionSource();\n _navigationQueue.Enqueue((viewType, viewModelType, parameter, tcs));\n\n await ProcessNavigationQueueAsync();\n await tcs.Task;\n }\n\n /// \n /// Navigates to a route.\n /// \n /// The route to navigate to.\n /// The navigation parameter.\n /// A task representing the asynchronous operation.\n public async Task NavigateToAsync(string route, object parameter = null)\n {\n if (!_viewMappings.TryGetValue(route, out var mapping))\n throw new InvalidOperationException($\"No view mapping found for route: {route}\");\n\n await NavigateInternalAsync(mapping.ViewType, mapping.ViewModelType, parameter);\n }\n\n private async Task ProcessNavigationQueueAsync()\n {\n if (!await _navigationLock.WaitAsync(TimeSpan.FromMilliseconds(100)))\n return;\n\n try\n {\n while (_navigationQueue.TryDequeue(out var navigationRequest))\n {\n _currentNavigationCts?.Cancel();\n _currentNavigationCts = new CancellationTokenSource(TimeSpan.FromSeconds(30));\n\n try\n {\n await NavigateInternalAsync(\n navigationRequest.ViewType,\n navigationRequest.ViewModelType,\n navigationRequest.Parameter,\n _currentNavigationCts.Token\n );\n navigationRequest.CompletionSource.SetResult(true);\n }\n catch (Exception ex)\n {\n navigationRequest.CompletionSource.SetException(ex);\n }\n }\n }\n finally\n {\n _navigationLock.Release();\n }\n }\n\n private async Task NavigateInternalAsync(\n Type viewType,\n Type viewModelType,\n object parameter,\n CancellationToken cancellationToken = default\n )\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n // Find the route for this view/viewmodel for event args\n string route = null;\n foreach (var mapping in _viewMappings)\n {\n if (mapping.Value.ViewType == viewType)\n {\n route = mapping.Key;\n break;\n }\n }\n\n var sourceView = _currentRoute;\n var targetView = route;\n\n var args = new Winhance.Core.Features.Common.Interfaces.NavigationEventArgs(\n sourceView,\n targetView,\n parameter,\n true\n );\n Navigating?.Invoke(this, args);\n\n if (args.Cancel)\n {\n return;\n }\n\n _currentParameter = parameter;\n\n // Get the view model from the service provider - we don't need the view when using ContentPresenter\n object viewModel;\n\n try\n {\n viewModel = _serviceProvider.GetRequiredService(viewModelType);\n if (viewModel == null)\n {\n throw new InvalidOperationException(\n $\"Failed to create view model of type {viewModelType.FullName}. The service provider returned null.\"\n );\n }\n }\n catch (Exception ex)\n {\n throw new InvalidOperationException($\"Error creating view model: {ex.Message}\", ex);\n }\n\n // Update the current route and view model\n _currentRoute = route;\n _currentViewModel = viewModel;\n\n // Update the navigation stacks\n while (_backStack.Count >= MaxHistorySize)\n {\n var tempStack = new Stack(_backStack.Skip(1).Reverse());\n _backStack.Clear();\n foreach (var item in tempStack)\n {\n _backStack.Push(item);\n }\n }\n _backStack.Push(viewModelType);\n\n // Call OnNavigatedTo on the view model if it implements IViewModel\n if (viewModel is IViewModel vm)\n {\n vm.OnNavigatedTo(parameter);\n }\n\n // Update navigation history\n if (!string.IsNullOrEmpty(_currentRoute))\n {\n _navigationHistory.Add(_currentRoute);\n }\n\n // Raise the Navigated event which will update the UI\n var navigatedArgs = new Winhance.Core.Features.Common.Interfaces.NavigationEventArgs(\n sourceView,\n targetView,\n viewModel,\n false\n );\n Navigated?.Invoke(this, navigatedArgs);\n }\n\n /// \n /// Navigates back to the previous view.\n /// \n /// A task representing the asynchronous operation.\n public async Task GoBackAsync()\n {\n if (!CanGoBack)\n return;\n\n var tcs = new TaskCompletionSource();\n _navigationQueue.Enqueue((null, null, null, tcs));\n\n await ProcessNavigationQueueAsync();\n await tcs.Task;\n\n var currentViewModelType = _backStack.Peek();\n\n var currentType = _backStack.Pop();\n _forwardStack.Push((currentType, _currentParameter));\n var previousViewModelType = _backStack.Peek();\n var previousParameter =\n _backStack.Count > 1 ? _backStack.ElementAt(_backStack.Count - 2) : null;\n await NavigateToAsync(previousViewModelType, previousParameter);\n }\n\n /// \n /// Navigates forward to the next view.\n /// \n /// A task representing the asynchronous operation.\n public async Task GoForwardAsync()\n {\n if (_forwardStack.Count == 0)\n return;\n\n var tcs = new TaskCompletionSource();\n _navigationQueue.Enqueue((null, null, null, tcs));\n\n await ProcessNavigationQueueAsync();\n await tcs.Task;\n\n var (nextType, nextParameter) = _forwardStack.Pop();\n\n _backStack.Push(nextType);\n await NavigateToAsync(nextType, nextParameter);\n }\n\n /// \n /// Clears the navigation history.\n /// \n /// A task representing the asynchronous operation.\n public async Task ClearHistoryAsync()\n {\n await _navigationLock.WaitAsync();\n try\n {\n _backStack.Clear();\n _forwardStack.Clear();\n _navigationHistory.Clear();\n }\n finally\n {\n _navigationLock.Release();\n }\n }\n\n /// \n /// Cancels the current navigation.\n /// \n public void CancelCurrentNavigation()\n {\n _currentNavigationCts?.Cancel();\n }\n\n // We track the current view model directly now instead of getting it from the Frame\n private object _currentViewModel;\n\n /// \n /// Gets the current view model.\n /// \n public object CurrentViewModel => _currentViewModel;\n\n private Type GetViewTypeForViewModel(Type viewModelType)\n {\n // First, check if we have a mapping for this view model type\n foreach (var mapping in _viewMappings)\n {\n if (mapping.Value.ViewModelType == viewModelType)\n {\n return mapping.Value.ViewType;\n }\n }\n\n // If no mapping found, try the old way as fallback\n var viewName = viewModelType.FullName.Replace(\"ViewModel\", \"View\");\n var viewType = Type.GetType(viewName);\n\n if (viewType == null)\n {\n // Try to find the view type in the loaded assemblies\n foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())\n {\n viewType = assembly\n .GetTypes()\n .FirstOrDefault(t =>\n t.FullName != null\n && t.FullName.Equals(viewName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (viewType != null)\n break;\n }\n }\n\n return viewType\n ?? throw new InvalidOperationException(\n $\"View type for {viewModelType.FullName} not found. Tried looking for {viewName}\"\n );\n }\n\n private string GetRouteForViewType(Type viewType)\n {\n foreach (var mapping in _viewMappings)\n {\n if (mapping.Value.ViewType == viewType)\n {\n return mapping.Key;\n }\n }\n throw new InvalidOperationException(\n $\"No route found for view type: {viewType.FullName}\"\n );\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/RegistryHiveToFullNameConverter.cs", "using Microsoft.Win32;\nusing System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a RegistryHive enum to its full string representation (HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, etc.)\n /// \n public class RegistryHiveToFullNameConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKEY_CLASSES_ROOT\",\n RegistryHive.CurrentUser => \"HKEY_CURRENT_USER\",\n RegistryHive.LocalMachine => \"HKEY_LOCAL_MACHINE\",\n RegistryHive.Users => \"HKEY_USERS\",\n RegistryHive.CurrentConfig => \"HKEY_CURRENT_CONFIG\",\n _ => value.ToString()\n };\n }\n \n return value?.ToString() ?? string.Empty;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/CommandService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service for executing system commands related to optimizations.\n /// \n public class CommandService : ICommandService\n {\n private readonly ILogService _logService;\n private readonly ISystemServices _systemServices;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The system services.\n public CommandService(ILogService logService, ISystemServices systemServices)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _systemServices =\n systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n }\n\n /// \n public async Task<(bool Success, string Output, string Error)> ExecuteCommandAsync(\n string command,\n bool requiresElevation = true\n )\n {\n try\n {\n _logService.LogInformation($\"Executing command: {command}\");\n\n // Create a PowerShell instance using the factory\n var powerShell = PowerShellFactory.CreateWindowsPowerShell(\n _logService,\n _systemServices\n );\n\n // Add the command to execute\n powerShell.AddScript(command);\n\n // Execute the command\n var results = await Task.Run(() => powerShell.Invoke());\n\n // Process the results\n var output = string.Join(Environment.NewLine, results.Select(r => r.ToString()));\n var error = string.Join(\n Environment.NewLine,\n powerShell.Streams.Error.ReadAll().Select(e => e.ToString())\n );\n\n // Log the results\n if (string.IsNullOrEmpty(error))\n {\n _logService.LogInformation($\"Command executed successfully: {command}\");\n _logService.LogInformation($\"Command output: {output}\");\n return (true, output, string.Empty);\n }\n else\n {\n _logService.LogWarning($\"Command execution failed: {command}\");\n _logService.LogWarning($\"Error: {error}\");\n return (false, output, error);\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Exception executing command: {command}\");\n _logService.LogError($\"Exception: {ex}\");\n return (false, string.Empty, ex.ToString());\n }\n }\n\n /// \n public async Task<(bool Success, string Message)> ApplyCommandSettingsAsync(\n IEnumerable settings,\n bool isEnabled\n )\n {\n if (settings == null || !settings.Any())\n {\n return (true, \"No command settings to apply.\");\n }\n\n var successCount = 0;\n var failureCount = 0;\n var messages = new List();\n\n foreach (var setting in settings)\n {\n var commandToExecute = isEnabled ? setting.EnabledCommand : setting.DisabledCommand;\n\n if (string.IsNullOrWhiteSpace(commandToExecute))\n {\n _logService.LogWarning($\"Empty command for setting: {setting.Id}\");\n continue;\n }\n\n var (success, output, error) = await ExecuteCommandAsync(\n commandToExecute,\n setting.RequiresElevation\n );\n\n if (success)\n {\n successCount++;\n messages.Add($\"Successfully applied command setting: {setting.Id}\");\n }\n else\n {\n failureCount++;\n messages.Add($\"Failed to apply command setting: {setting.Id}. Error: {error}\");\n }\n }\n\n var overallSuccess = failureCount == 0;\n var message =\n $\"Applied {successCount} command settings successfully, {failureCount} failed.\";\n\n if (messages.Any())\n {\n message += Environment.NewLine + string.Join(Environment.NewLine, messages);\n }\n\n return (overallSuccess, message);\n }\n\n /// \n public async Task IsCommandSettingEnabledAsync(CommandSetting setting)\n {\n try\n {\n _logService.LogInformation($\"Checking state for command setting: {setting.Id}\");\n\n // Check if this is a bcdedit command\n if (setting.EnabledCommand.Contains(\"bcdedit\"))\n {\n return await IsBcdeditSettingEnabledAsync(setting);\n }\n\n // For other types of commands, implement specific checking logic here\n // For now, return false as a default for unhandled command types\n _logService.LogWarning(\n $\"No state checking implementation for command type: {setting.Id}\"\n );\n return false;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking command setting state: {setting.Id}\", ex);\n return false;\n }\n }\n\n /// \n /// Checks if a bcdedit setting is in its enabled state.\n /// \n /// The command setting to check.\n /// True if the setting is in its enabled state, false otherwise.\n private async Task IsBcdeditSettingEnabledAsync(CommandSetting setting)\n {\n // Extract the setting name and value from the command\n string settingName = ExtractBcdeditSettingName(setting.EnabledCommand);\n string expectedValue = ExtractBcdeditSettingValue(setting.EnabledCommand);\n\n if (string.IsNullOrEmpty(settingName))\n {\n _logService.LogWarning(\n $\"Could not extract setting name from bcdedit command: {setting.EnabledCommand}\"\n );\n return false;\n }\n\n // Query the current boot configuration\n var (success, output, error) = await ExecuteCommandAsync(\"bcdedit /enum {current}\");\n\n if (!success || string.IsNullOrEmpty(output))\n {\n _logService.LogWarning($\"Failed to query boot configuration: {error}\");\n return false;\n }\n\n // Parse the output to find the setting\n bool settingExists = output.Contains(settingName, StringComparison.OrdinalIgnoreCase);\n\n // For settings that should be deleted when disabled\n if (setting.DisabledCommand.Contains(\"/deletevalue\"))\n {\n // If the setting exists, check if it has the expected value\n if (settingExists)\n {\n // Find the line containing the setting\n var lines = output.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n var settingLine = lines.FirstOrDefault(l =>\n l.Contains(settingName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (settingLine != null)\n {\n // Extract the current value\n var parts = settingLine.Split(\n new[] { ' ' },\n StringSplitOptions.RemoveEmptyEntries\n );\n if (parts.Length >= 2)\n {\n string currentValue = parts[parts.Length - 1].Trim().ToLowerInvariant();\n expectedValue = expectedValue.ToLowerInvariant();\n\n _logService.LogInformation(\n $\"Found bcdedit setting {settingName} with value {currentValue}, expected {expectedValue}\"\n );\n return currentValue == expectedValue;\n }\n }\n }\n\n // If the setting doesn't exist or we couldn't parse the value, it's not in the enabled state\n return false;\n }\n // For settings that should be set to a different value when disabled\n else if (setting.DisabledCommand.Contains(\"/set\"))\n {\n string disabledValue = ExtractBcdeditSettingValue(setting.DisabledCommand);\n\n // Find the line containing the setting\n if (settingExists)\n {\n var lines = output.Split(\n new[] { '\\r', '\\n' },\n StringSplitOptions.RemoveEmptyEntries\n );\n var settingLine = lines.FirstOrDefault(l =>\n l.Contains(settingName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (settingLine != null)\n {\n // Extract the current value\n var parts = settingLine.Split(\n new[] { ' ' },\n StringSplitOptions.RemoveEmptyEntries\n );\n if (parts.Length >= 2)\n {\n string currentValue = parts[parts.Length - 1].Trim().ToLowerInvariant();\n expectedValue = expectedValue.ToLowerInvariant();\n disabledValue = disabledValue.ToLowerInvariant();\n\n _logService.LogInformation(\n $\"Found bcdedit setting {settingName} with value {currentValue}, expected {expectedValue} for enabled state\"\n );\n return currentValue == expectedValue && currentValue != disabledValue;\n }\n }\n }\n\n return false;\n }\n\n // Default case\n return false;\n }\n\n /// \n /// Extracts the setting name from a bcdedit command.\n /// \n /// The bcdedit command.\n /// The setting name.\n private string ExtractBcdeditSettingName(string command)\n {\n // Handle /set command\n if (command.Contains(\"/set \"))\n {\n var parts = command.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (parts.Length >= 3)\n {\n return parts[2]; // The setting name is the third part in \"bcdedit /set settingname value\"\n }\n }\n // Handle /deletevalue command\n else if (command.Contains(\"/deletevalue \"))\n {\n var parts = command.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (parts.Length >= 3)\n {\n return parts[2]; // The setting name is the third part in \"bcdedit /deletevalue settingname\"\n }\n }\n\n return string.Empty;\n }\n\n /// \n /// Extracts the setting value from a bcdedit command.\n /// \n /// The bcdedit command.\n /// The setting value.\n private string ExtractBcdeditSettingValue(string command)\n {\n // Only handle /set command as /deletevalue doesn't have a value\n if (command.Contains(\"/set \"))\n {\n var parts = command.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (parts.Length >= 4)\n {\n return parts[3]; // The value is the fourth part in \"bcdedit /set settingname value\"\n }\n }\n\n return string.Empty;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Optimize/Services/PowerPlanService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Optimize.Interfaces;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Infrastructure.Features.Optimize.Services\n{\n /// \n /// Service for managing Windows power plans.\n /// \n public class PowerPlanService : IPowerPlanService\n {\n private readonly IPowerShellExecutionService _powerShellService;\n private readonly ILogService _logService;\n \n // Dictionary to cache applied settings state\n private Dictionary AppliedSettings { get; } = new Dictionary();\n\n /// \n /// GUID for the Balanced power plan.\n /// \n public static readonly string BALANCED_PLAN_GUID = \"381b4222-f694-41f0-9685-ff5bb260df2e\";\n\n /// \n /// GUID for the High Performance power plan.\n /// \n public static readonly string HIGH_PERFORMANCE_PLAN_GUID = \"8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c\";\n\n /// \n /// GUID for the Ultimate Performance power plan.\n /// This is not readonly because it may be updated at runtime when the plan is created.\n /// \n public static string ULTIMATE_PERFORMANCE_PLAN_GUID = \"e9a42b02-d5df-448d-aa00-03f14749eb61\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The PowerShell execution service.\n /// The log service.\n public PowerPlanService(IPowerShellExecutionService powerShellService, ILogService logService)\n {\n _powerShellService = powerShellService ?? throw new ArgumentNullException(nameof(powerShellService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public async Task GetActivePowerPlanGuidAsync()\n {\n try\n {\n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5));\n var cancellationToken = cancellationTokenSource.Token;\n \n // Execute powercfg /getactivescheme to get the active power plan\n var executeTask = _powerShellService.ExecuteScriptAsync(\"powercfg /getactivescheme\");\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(executeTask, Task.Delay(5000, cancellationToken));\n \n if (!executeTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Getting active power plan timed out, defaulting to Balanced\");\n return BALANCED_PLAN_GUID;\n }\n \n var result = await executeTask;\n \n // Parse the output to extract the GUID\n // Example output: \"Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)\"\n if (result.Contains(\"GUID:\"))\n {\n int guidStart = result.IndexOf(\"GUID:\") + 5;\n int guidEnd = result.IndexOf(\" (\", guidStart);\n if (guidEnd > guidStart)\n {\n string guid = result.Substring(guidStart, guidEnd - guidStart).Trim();\n return guid;\n }\n }\n \n _logService.Log(LogLevel.Warning, \"Failed to parse active power plan GUID, defaulting to Balanced\");\n return BALANCED_PLAN_GUID; // Default to Balanced if parsing fails\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"Operation timed out while getting active power plan, defaulting to Balanced\");\n return BALANCED_PLAN_GUID;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting active power plan: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return BALANCED_PLAN_GUID; // Default to Balanced on error\n }\n }\n\n /// \n public async Task SetPowerPlanAsync(string planGuid)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Setting power plan to GUID: {planGuid}\");\n \n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(10));\n var cancellationToken = cancellationTokenSource.Token;\n \n // Special handling for Ultimate Performance plan\n if (planGuid == ULTIMATE_PERFORMANCE_PLAN_GUID)\n {\n _logService.Log(LogLevel.Info, \"Ultimate Performance plan selected, applying with custom GUID and settings\");\n \n // Use the custom GUID for Ultimate Performance plan\n const string customUltimateGuid = \"99999999-9999-9999-9999-999999999999\";\n \n try\n {\n // Create the plan with the custom GUID\n var createTask = _powerShellService.ExecuteScriptAsync(\n $\"powercfg {PowerOptimizations.UltimatePerformancePowerPlan.PowerCfgCommands[\"CreateUltimatePlan\"]}\");\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(createTask, Task.Delay(5000, cancellationToken));\n \n if (!createTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Creating Ultimate Performance plan timed out\");\n return false;\n }\n \n var createResult = await createTask;\n if (createResult.Contains(\"Error\") || createResult.Contains(\"error\"))\n {\n _logService.Log(LogLevel.Error, $\"Error creating Ultimate Performance plan: {createResult}\");\n return false;\n }\n \n // Set it as the active plan\n var setActiveTask = _powerShellService.ExecuteScriptAsync(\n $\"powercfg {PowerOptimizations.UltimatePerformancePowerPlan.PowerCfgCommands[\"SetActivePlan\"]}\");\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(setActiveTask, Task.Delay(5000, cancellationToken));\n \n if (!setActiveTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Setting Ultimate Performance plan as active timed out\");\n return false;\n }\n \n var setActiveResult = await setActiveTask;\n if (setActiveResult.Contains(\"Error\") || setActiveResult.Contains(\"error\"))\n {\n _logService.Log(LogLevel.Error, $\"Error setting Ultimate Performance plan as active: {setActiveResult}\");\n return false;\n }\n \n // Apply all the powercfg commands\n _logService.Log(LogLevel.Info, $\"Applying {PowerOptimizations.UltimatePerformancePowerPlan.PowerCfgCommands.Count} Ultimate Performance settings\");\n \n bool allCommandsSucceeded = true;\n foreach (var command in PowerOptimizations.UltimatePerformancePowerPlan.PowerCfgCommands)\n {\n // Check for cancellation\n if (cancellationToken.IsCancellationRequested)\n {\n _logService.Log(LogLevel.Warning, \"Operation timed out while applying Ultimate Performance settings\");\n return false;\n }\n \n // Skip the CreateUltimatePlan and SetActivePlan commands as we've already executed them\n if (command.Key == \"CreateUltimatePlan\" || command.Key == \"SetActivePlan\")\n continue;\n \n var cmdTask = _powerShellService.ExecuteScriptAsync($\"powercfg {command.Value}\");\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(cmdTask, Task.Delay(2000, cancellationToken));\n \n if (!cmdTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, $\"Command {command.Key} timed out\");\n allCommandsSucceeded = false;\n continue;\n }\n \n var cmdResult = await cmdTask;\n if (cmdResult.Contains(\"Error\") || cmdResult.Contains(\"error\"))\n {\n _logService.Log(LogLevel.Warning, $\"Error applying Ultimate Performance setting {command.Key}: {cmdResult}\");\n allCommandsSucceeded = false;\n }\n }\n \n if (!allCommandsSucceeded)\n {\n _logService.Log(LogLevel.Warning, \"Some Ultimate Performance settings could not be applied\");\n }\n \n // Update the static GUID to use our custom one\n ULTIMATE_PERFORMANCE_PLAN_GUID = customUltimateGuid;\n \n // Also update the PowerOptimizations class to use this new GUID\n var field = typeof(PowerOptimizations.PowerPlans).GetField(\"UltimatePerformance\");\n if (field != null)\n {\n var ultimatePerformancePlan = field.GetValue(null) as PowerPlan;\n if (ultimatePerformancePlan != null)\n {\n // Use reflection to update the Guid property\n var guidProperty = typeof(PowerPlan).GetProperty(\"Guid\");\n if (guidProperty != null)\n {\n guidProperty.SetValue(ultimatePerformancePlan, customUltimateGuid);\n _logService.Log(LogLevel.Info, \"Updated PowerOptimizations.PowerPlans.UltimatePerformance.Guid\");\n }\n }\n }\n \n // Verify the plan was set correctly\n var verifyTask = GetActivePowerPlanGuidAsync();\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(verifyTask, Task.Delay(3000, cancellationToken));\n \n if (!verifyTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Verifying active power plan timed out\");\n return false;\n }\n \n var currentPlan = await verifyTask;\n if (currentPlan != customUltimateGuid)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to set Ultimate Performance plan. Expected: {customUltimateGuid}, Actual: {currentPlan}\");\n return false;\n }\n \n _logService.Log(LogLevel.Info, $\"Successfully set Ultimate Performance plan with GUID: {customUltimateGuid}\");\n return true;\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"Operation timed out while setting Ultimate Performance plan\");\n return false;\n }\n }\n else\n {\n try\n {\n // For other plans, ensure they exist before trying to set them\n var ensureTask = EnsurePowerPlanExistsAsync(planGuid);\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(ensureTask, Task.Delay(5000, cancellationToken));\n \n if (!ensureTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Ensuring power plan exists timed out\");\n return false;\n }\n \n bool planExists = await ensureTask;\n if (!planExists)\n {\n _logService.Log(LogLevel.Error, $\"Failed to ensure power plan exists: {planGuid}\");\n return false;\n }\n \n // Set the active power plan\n var setTask = _powerShellService.ExecuteScriptAsync($\"powercfg /setactive {planGuid}\");\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(setTask, Task.Delay(5000, cancellationToken));\n \n if (!setTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Setting power plan timed out\");\n return false;\n }\n \n var result = await setTask;\n \n // Check for errors in the result\n if (result.Contains(\"Error\") || result.Contains(\"error\"))\n {\n _logService.Log(LogLevel.Error, $\"Error setting power plan: {result}\");\n return false;\n }\n \n // Verify the plan was set correctly\n var verifyTask = GetActivePowerPlanGuidAsync();\n \n // Wait for the task to complete with a timeout\n await Task.WhenAny(verifyTask, Task.Delay(3000, cancellationToken));\n \n if (!verifyTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Verifying active power plan timed out\");\n return false;\n }\n \n var currentPlan = await verifyTask;\n if (currentPlan != planGuid)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to set power plan. Expected: {planGuid}, Actual: {currentPlan}\");\n return false;\n }\n \n _logService.Log(LogLevel.Info, $\"Successfully set power plan to GUID: {planGuid}\");\n return true;\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"Operation timed out while setting power plan\");\n return false;\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error setting power plan: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n\n /// \n public async Task EnsurePowerPlanExistsAsync(string planGuid, string sourcePlanGuid = null)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Ensuring power plan exists: {planGuid}\");\n\n // Check if the plan exists\n var plansResult = await _powerShellService.ExecuteScriptAsync(\"powercfg /list\");\n \n if (!plansResult.Contains(planGuid))\n {\n _logService.Log(LogLevel.Info, $\"Power plan {planGuid} does not exist, creating it\");\n\n // Plan doesn't exist, create it based on the plan type\n if (planGuid == BALANCED_PLAN_GUID)\n {\n // Restore default schemes to ensure Balanced plan exists\n await _powerShellService.ExecuteScriptAsync(\"powercfg -restoredefaultschemes\");\n _logService.Log(LogLevel.Info, \"Restored default power schemes to ensure Balanced plan exists\");\n }\n else if (planGuid == HIGH_PERFORMANCE_PLAN_GUID)\n {\n // Restore default schemes to ensure High Performance plan exists\n await _powerShellService.ExecuteScriptAsync(\"powercfg -restoredefaultschemes\");\n _logService.Log(LogLevel.Info, \"Restored default power schemes to ensure High Performance plan exists\");\n }\n else if (planGuid == ULTIMATE_PERFORMANCE_PLAN_GUID)\n {\n // Ultimate Performance is a hidden power plan that needs to be created with a special command\n // First restore default schemes to ensure we have a clean state\n await _powerShellService.ExecuteScriptAsync(\"powercfg -restoredefaultschemes\");\n \n // Create the Ultimate Performance plan using the Windows built-in command\n // This is the official way to create this plan\n var result = await _powerShellService.ExecuteScriptAsync(\"powercfg -duplicatescheme 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c\");\n \n // Extract the GUID of the newly created plan from the result\n // Example output: \"Power Scheme GUID: 11111111-2222-3333-4444-555555555555 (Copy of High Performance)\"\n string newGuid = string.Empty;\n if (result.Contains(\"Power Scheme GUID:\"))\n {\n int guidStart = result.IndexOf(\"Power Scheme GUID:\") + 18;\n int guidEnd = result.IndexOf(\" (\", guidStart);\n if (guidEnd > guidStart)\n {\n newGuid = result.Substring(guidStart, guidEnd - guidStart).Trim();\n _logService.Log(LogLevel.Info, $\"Created new power plan with GUID: {newGuid}\");\n }\n }\n \n if (!string.IsNullOrEmpty(newGuid))\n {\n // Rename it to \"Ultimate Performance\"\n await _powerShellService.ExecuteScriptAsync($\"powercfg -changename {newGuid} \\\"Ultimate Performance\\\" \\\"Provides ultimate performance on Windows.\\\"\");\n \n // Update our constant to use this new GUID for future operations\n // Note: This is a static field, so it will be updated for the lifetime of the application\n ULTIMATE_PERFORMANCE_PLAN_GUID = newGuid;\n \n // Also update the PowerOptimizations class to use this new GUID\n // This is needed because the PowerOptimizationsViewModel uses PowerOptimizations.PowerPlans\n var field = typeof(PowerOptimizations.PowerPlans).GetField(\"UltimatePerformance\");\n if (field != null)\n {\n var ultimatePerformancePlan = field.GetValue(null) as PowerPlan;\n if (ultimatePerformancePlan != null)\n {\n // Use reflection to update the Guid property\n var guidProperty = typeof(PowerPlan).GetProperty(\"Guid\");\n if (guidProperty != null)\n {\n guidProperty.SetValue(ultimatePerformancePlan, newGuid);\n _logService.Log(LogLevel.Info, \"Updated PowerOptimizations.PowerPlans.UltimatePerformance.Guid\");\n }\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Created and renamed Ultimate Performance power plan with GUID: {newGuid}\");\n \n // Return true since we've created the plan, but with a different GUID\n return true;\n }\n \n _logService.Log(LogLevel.Warning, \"Failed to create Ultimate Performance power plan\");\n }\n else if (sourcePlanGuid != null)\n {\n // Create a custom plan from the source plan\n await _powerShellService.ExecuteScriptAsync($\"powercfg /duplicatescheme {sourcePlanGuid} {planGuid}\");\n _logService.Log(LogLevel.Info, $\"Created custom power plan with GUID {planGuid} from source {sourcePlanGuid}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Cannot create power plan with GUID {planGuid} - no source plan specified\");\n return false;\n }\n \n // Verify the plan was created\n plansResult = await _powerShellService.ExecuteScriptAsync(\"powercfg /list\");\n if (!plansResult.Contains(planGuid))\n {\n _logService.Log(LogLevel.Warning, $\"Failed to create power plan with GUID {planGuid}\");\n return false;\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Power plan {planGuid} exists\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error ensuring power plan exists: {ex.Message}\");\n return false;\n }\n }\n\n /// \n public async Task> GetAvailablePowerPlansAsync()\n {\n var powerPlans = new List();\n \n try\n {\n _logService.Log(LogLevel.Info, \"Getting available power plans\");\n var result = await _powerShellService.ExecuteScriptAsync(\"powercfg /list\");\n \n // Parse the output to extract power plans\n // Example output:\n // Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)\n // Power Scheme GUID: 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c (High Performance)\n \n string[] lines = result.Split(new[] { '\\r', '\\n' }, StringSplitOptions.RemoveEmptyEntries);\n foreach (var line in lines)\n {\n if (line.Contains(\"Power Scheme GUID:\"))\n {\n int guidStart = line.IndexOf(\"GUID:\") + 5;\n int guidEnd = line.IndexOf(\" (\", guidStart);\n if (guidEnd > guidStart)\n {\n string guid = line.Substring(guidStart, guidEnd - guidStart).Trim();\n \n int nameStart = line.IndexOf(\"(\", guidEnd) + 1;\n int nameEnd = line.IndexOf(\")\", nameStart);\n if (nameEnd > nameStart)\n {\n string name = line.Substring(nameStart, nameEnd - nameStart).Trim();\n \n powerPlans.Add(new PowerPlan { Guid = guid, Name = name });\n _logService.Log(LogLevel.Info, $\"Found power plan: {name} ({guid})\");\n }\n }\n }\n }\n \n return powerPlans;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting available power plans: {ex.Message}\");\n return powerPlans;\n }\n }\n \n /// \n public async Task ExecutePowerCfgCommandAsync(string command)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Executing PowerCfg command: {command}\");\n \n // Execute the PowerCfg command\n var result = await _powerShellService.ExecuteScriptAsync($\"powercfg {command}\");\n \n // Check for errors in the result\n if (result.Contains(\"Error\") || result.Contains(\"error\"))\n {\n // Check if this is a hardware-dependent setting that doesn't exist\n if (result.Contains(\"specified does not exist\"))\n {\n _logService.Log(LogLevel.Warning, $\"Hardware-dependent setting not available on this system: {result}\");\n // Return true because this is an expected condition, not a failure\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Error executing PowerCfg command: {result}\");\n return false;\n }\n }\n \n _logService.Log(LogLevel.Info, $\"PowerCfg command executed successfully: {command}\");\n return true;\n }\n catch (Exception ex)\n {\n // Check if this is a hardware-dependent setting that doesn't exist\n if (ex.Message.Contains(\"specified does not exist\"))\n {\n _logService.Log(LogLevel.Warning, $\"Hardware-dependent setting not available on this system: {ex.Message}\");\n // Return true because this is an expected condition, not a failure\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Error executing PowerCfg command: {ex.Message}\");\n return false;\n }\n }\n }\n \n /// \n public async Task ApplyPowerSettingAsync(string subgroupGuid, string settingGuid, string value, bool isAcSetting)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Applying power setting: subgroup={subgroupGuid}, setting={settingGuid}, value={value}, isAC={isAcSetting}\");\n \n // Determine the command prefix based on whether this is an AC or DC setting\n string prefix = isAcSetting ? \"/setacvalueindex\" : \"/setdcvalueindex\";\n \n // Get the active power plan GUID\n string planGuid = await GetActivePowerPlanGuidAsync();\n \n // Execute the PowerCfg command to set the value\n var result = await _powerShellService.ExecuteScriptAsync($\"powercfg {prefix} {planGuid} {subgroupGuid} {settingGuid} {value}\");\n \n // Check for errors in the result\n if (result.Contains(\"Error\") || result.Contains(\"error\"))\n {\n // Check if this is a hardware-dependent setting that doesn't exist\n if (result.Contains(\"specified does not exist\"))\n {\n _logService.Log(LogLevel.Warning, $\"Hardware-dependent setting not available on this system: subgroup={subgroupGuid}, setting={settingGuid}\");\n // Return true because this is an expected condition, not a failure\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Error applying power setting: {result}\");\n return false;\n }\n }\n \n _logService.Log(LogLevel.Info, $\"Power setting applied successfully\");\n return true;\n }\n catch (Exception ex)\n {\n // Check if this is a hardware-dependent setting that doesn't exist\n if (ex.Message.Contains(\"specified does not exist\"))\n {\n _logService.Log(LogLevel.Warning, $\"Hardware-dependent setting not available on this system: {ex.Message}\");\n // Return true because this is an expected condition, not a failure\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Error applying power setting: {ex.Message}\");\n return false;\n }\n }\n }\n \n /// \n public async Task IsPowerCfgSettingAppliedAsync(PowerCfgSetting setting)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Checking if PowerCfg setting is applied: {setting.Description}\");\n \n // Extract the command type from the setting\n string command = setting.Command;\n \n // Get the active power plan GUID\n string activePlanGuid = await GetActivePowerPlanGuidAsync();\n \n // Replace placeholder GUID with active power plan GUID\n command = command.Replace(\"{active_guid}\", activePlanGuid);\n \n // Create a unique key for this setting\n string settingKey = $\"{setting.Description}:{setting.EnabledValue}\";\n \n // Special handling for Desktop Slideshow setting\n if (setting.Description.Contains(\"desktop slideshow\"))\n {\n // Extract subgroup and setting GUIDs\n var parts = command.Split(' ');\n if (parts.Length >= 5)\n {\n string subgroupGuid = parts[2];\n string settingGuid = parts[3];\n string expectedValue = parts[4];\n \n // Query the current value\n var result = await _powerShellService.ExecuteScriptAsync($\"powercfg /query {activePlanGuid} {subgroupGuid} {settingGuid}\");\n \n // For Desktop Slideshow, value 0 means \"Available\" (slideshow enabled)\n // and value 1 means \"Paused\" (slideshow disabled)\n // This is counter-intuitive, so we need special handling\n \n // Extract the current value\n string currentValue = ExtractPowerSettingValue(result, command.Contains(\"setacvalueindex\"));\n \n if (!string.IsNullOrEmpty(currentValue))\n {\n // Normalize the values for comparison\n string normalizedCurrentValue = NormalizeHexValue(currentValue);\n string normalizedExpectedValue = NormalizeHexValue(expectedValue);\n \n // For Desktop Slideshow, we need to check if the current value matches the expected value\n // Value 0 means \"Available\" (slideshow enabled)\n // Value 1 means \"Paused\" (slideshow disabled)\n bool settingApplied = string.Equals(normalizedCurrentValue, normalizedExpectedValue, StringComparison.OrdinalIgnoreCase);\n \n _logService.Log(LogLevel.Info, $\"Desktop Slideshow setting check: current={normalizedCurrentValue}, expected={normalizedExpectedValue}, isApplied={settingApplied}\");\n \n // Cache the result\n AppliedSettings[settingKey] = settingApplied;\n return settingApplied;\n }\n }\n }\n \n if (command.Contains(\"hibernate\"))\n {\n // Check hibernate state\n var result = await _powerShellService.ExecuteScriptAsync(\"powercfg /a\");\n \n if (command.Contains(\"off\"))\n {\n // If command is to disable hibernate, check if hibernate is not available\n bool isHibernateDisabled = result.Contains(\"Hibernation has been disabled\");\n _logService.Log(LogLevel.Info, $\"Hibernate state check: disabled={isHibernateDisabled}\");\n \n // Cache the result\n AppliedSettings[settingKey] = isHibernateDisabled;\n return isHibernateDisabled;\n }\n else\n {\n // If command is to enable hibernate, check if hibernate is available\n bool isHibernateEnabled = result.Contains(\"Hibernation\") && !result.Contains(\"Hibernation has been disabled\");\n _logService.Log(LogLevel.Info, $\"Hibernate state check: enabled={isHibernateEnabled}\");\n \n // Cache the result\n AppliedSettings[settingKey] = isHibernateEnabled;\n return isHibernateEnabled;\n }\n }\n else if (command.Contains(\"setacvalueindex\") || command.Contains(\"setdcvalueindex\"))\n {\n // Extract subgroup, setting, and value GUIDs\n var parts = command.Split(' ');\n if (parts.Length >= 5)\n {\n string subgroupGuid = parts[2];\n string settingGuid = parts[3];\n string expectedValue = parts[4];\n \n // Query the current value\n var result = await _powerShellService.ExecuteScriptAsync($\"powercfg /query {activePlanGuid} {subgroupGuid} {settingGuid}\");\n _logService.Log(LogLevel.Debug, $\"Query result for {subgroupGuid} {settingGuid}: {result}\");\n \n // Extract the current value\n bool isAcSetting = command.Contains(\"setacvalueindex\");\n string currentValue = ExtractPowerSettingValue(result, isAcSetting);\n \n if (!string.IsNullOrEmpty(currentValue))\n {\n // Normalize the values for comparison\n string normalizedCurrentValue = NormalizeHexValue(currentValue);\n string normalizedExpectedValue = NormalizeHexValue(expectedValue);\n \n // Compare case-insensitive\n bool settingApplied = string.Equals(normalizedCurrentValue, normalizedExpectedValue, StringComparison.OrdinalIgnoreCase);\n _logService.Log(LogLevel.Info, $\"PowerCfg setting check: current={normalizedCurrentValue}, expected={normalizedExpectedValue}, isApplied={settingApplied}\");\n \n // Cache the result\n AppliedSettings[settingKey] = settingApplied;\n return settingApplied;\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Could not find current value in query result for {subgroupGuid} {settingGuid}\");\n \n // For settings we can't determine, check if the setting exists in the power plan\n var queryResult = await _powerShellService.ExecuteScriptAsync($\"powercfg /query {activePlanGuid} {subgroupGuid} {settingGuid}\");\n \n // If the query returns information about the setting, it exists\n bool settingExists = !queryResult.Contains(\"does not exist\") && queryResult.Contains(settingGuid);\n \n _logService.Log(LogLevel.Info, $\"PowerCfg setting existence check: {settingExists}\");\n \n if (settingExists)\n {\n // If the setting exists but we couldn't extract the value,\n // assume it's not applied so the user can apply it\n AppliedSettings[settingKey] = false;\n return false;\n }\n else\n {\n // If the setting doesn't exist, it might be hardware-dependent\n // In this case, we should return false so the user can apply it if needed\n AppliedSettings[settingKey] = false;\n return false;\n }\n }\n }\n }\n else if (command.Contains(\"CHANGEPOWERPLAN\"))\n {\n // For CHANGEPOWERPLAN commands, we can't easily check the state\n // Assume they're applied if we've tried to apply them before\n _logService.Log(LogLevel.Info, $\"CHANGEPOWERPLAN command detected, assuming applied: {setting.Description}\");\n \n // Cache the result\n AppliedSettings[settingKey] = true;\n return true;\n }\n \n // For any other commands we can't determine, make a best effort check\n _logService.Log(LogLevel.Warning, $\"Could not determine state for PowerCfg setting: {setting.Description}, checking via command output\");\n \n // Execute a query command to get all power settings\n var allPowerSettings = await _powerShellService.ExecuteScriptAsync(\"powercfg /q\");\n \n // Try to extract the command parameters to check if they're in the query result\n string[] cmdParts = command.Split(' ');\n bool isApplied = false;\n \n // If the command has parameters, check if they appear in the query result\n if (cmdParts.Length > 1)\n {\n // Check if any of the command parameters appear in the query result\n // This is a heuristic approach but better than assuming always applied\n for (int i = 1; i < cmdParts.Length; i++)\n {\n if (cmdParts[i].Length > 8 && allPowerSettings.Contains(cmdParts[i]))\n {\n isApplied = true;\n break;\n }\n }\n }\n \n // Cache the result\n AppliedSettings[settingKey] = isApplied;\n return isApplied;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking PowerCfg setting state: {ex.Message}\");\n \n // On error, assume not applied so user can reapply\n return false;\n }\n }\n \n /// \n /// Extracts the power setting value from the query result.\n /// \n /// The result of the powercfg /query command.\n /// Whether this is an AC setting (true) or DC setting (false).\n /// The extracted value, or empty string if not found.\n private string ExtractPowerSettingValue(string queryResult, bool isAcSetting)\n {\n try\n {\n _logService.Log(LogLevel.Debug, $\"Extracting power setting value from query result (isAC={isAcSetting})\");\n \n // Try multiple patterns to extract the current value\n \n // Pattern 1: Standard format \"Current AC/DC Power Setting Index: 0x00000000\"\n string acPattern = \"Current AC Power Setting Index: (.+)\";\n string dcPattern = \"Current DC Power Setting Index: (.+)\";\n \n string pattern = isAcSetting ? acPattern : dcPattern;\n var match = System.Text.RegularExpressions.Regex.Match(queryResult, pattern);\n \n if (match.Success)\n {\n string value = match.Groups[1].Value.Trim();\n _logService.Log(LogLevel.Debug, $\"Found value using pattern 1: {value}\");\n return value;\n }\n \n // Pattern 2: Alternative format \"Power Setting Index: 0x00000000\"\n pattern = \"Power Setting Index: (.+)\";\n match = System.Text.RegularExpressions.Regex.Match(queryResult, pattern);\n \n if (match.Success)\n {\n string value = match.Groups[1].Value.Trim();\n _logService.Log(LogLevel.Debug, $\"Found value using pattern 2: {value}\");\n return value;\n }\n \n // Pattern 3: Look for AC/DC value specifically\n if (isAcSetting)\n {\n pattern = \"AC:\\\\s*0x[0-9A-Fa-f]+\";\n match = System.Text.RegularExpressions.Regex.Match(queryResult, pattern);\n \n if (match.Success)\n {\n string fullMatch = match.Value.Trim();\n string value = fullMatch.Substring(fullMatch.IndexOf(\"0x\"));\n _logService.Log(LogLevel.Debug, $\"Found value using AC pattern: {value}\");\n return value;\n }\n }\n else\n {\n pattern = \"DC:\\\\s*0x[0-9A-Fa-f]+\";\n match = System.Text.RegularExpressions.Regex.Match(queryResult, pattern);\n \n if (match.Success)\n {\n string fullMatch = match.Value.Trim();\n string value = fullMatch.Substring(fullMatch.IndexOf(\"0x\"));\n _logService.Log(LogLevel.Debug, $\"Found value using DC pattern: {value}\");\n return value;\n }\n }\n \n // Pattern 4: Look for any line with a hex value\n pattern = \"0x[0-9A-Fa-f]+\";\n match = System.Text.RegularExpressions.Regex.Match(queryResult, pattern);\n \n if (match.Success)\n {\n string value = match.Value.Trim();\n _logService.Log(LogLevel.Debug, $\"Found value using hex pattern: {value}\");\n return value;\n }\n \n // If no pattern matches, return empty string\n _logService.Log(LogLevel.Warning, \"Could not extract power setting value from query result\");\n return string.Empty;\n }\n catch (Exception ex)\n {\n // If an error occurs, log it and return empty string\n _logService.Log(LogLevel.Error, $\"Error extracting power setting value: {ex.Message}\");\n return string.Empty;\n }\n }\n \n /// \n /// Normalizes a hex value for comparison.\n /// \n /// The hex value to normalize.\n /// The normalized value.\n private string NormalizeHexValue(string value)\n {\n if (string.IsNullOrEmpty(value))\n {\n return \"0\";\n }\n \n // Remove 0x prefix if present\n if (value.StartsWith(\"0x\", StringComparison.OrdinalIgnoreCase))\n {\n value = value.Substring(2);\n }\n \n // Remove leading zeros\n value = value.TrimStart('0');\n \n // If the value is empty after trimming zeros, it's zero\n if (string.IsNullOrEmpty(value))\n {\n return \"0\";\n }\n \n return value;\n }\n \n /// \n public async Task AreAllPowerCfgSettingsAppliedAsync(List settings)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Checking if all PowerCfg settings are applied: {settings.Count} settings\");\n \n // Get the active power plan GUID once for all settings\n string activePlanGuid = await GetActivePowerPlanGuidAsync();\n _logService.Log(LogLevel.Info, $\"Active power plan GUID: {activePlanGuid}\");\n \n // Track which settings are not applied\n List notAppliedSettings = new List();\n \n foreach (var setting in settings)\n {\n bool isApplied = await IsPowerCfgSettingAppliedAsync(setting);\n \n if (!isApplied)\n {\n _logService.Log(LogLevel.Info, $\"PowerCfg setting not applied: {setting.Description}\");\n notAppliedSettings.Add(setting.Description);\n }\n }\n \n if (notAppliedSettings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"{notAppliedSettings.Count} PowerCfg settings not applied: {string.Join(\", \", notAppliedSettings)}\");\n return false;\n }\n \n _logService.Log(LogLevel.Info, $\"All PowerCfg settings are applied\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking PowerCfg settings: {ex.Message}\");\n return false;\n }\n }\n \n /// \n public async Task ApplyPowerCfgSettingsAsync(List settings)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Applying {settings.Count} PowerCfg settings\");\n \n bool allSucceeded = true;\n \n // Get the active power plan GUID\n string activePlanGuid = await GetActivePowerPlanGuidAsync();\n _logService.Log(LogLevel.Info, $\"Using active power plan GUID: {activePlanGuid}\");\n \n foreach (var setting in settings)\n {\n _logService.Log(LogLevel.Info, $\"Applying PowerCfg setting: {setting.Description}\");\n \n // Extract the command without the \"powercfg \" prefix\n string command = setting.Command;\n if (command.StartsWith(\"powercfg \"))\n {\n command = command.Substring(9);\n }\n \n // Replace placeholder GUID with active power plan GUID\n command = command.Replace(\"{active_guid}\", activePlanGuid);\n \n // Execute the command\n bool success = await ExecutePowerCfgCommandAsync(command);\n \n if (!success)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to apply PowerCfg setting: {setting.Description}\");\n allSucceeded = false;\n }\n }\n \n return allSucceeded;\n }\n catch (Exception ex)\n {\n // Check if this is a hardware-dependent setting that doesn't exist\n if (ex.Message.Contains(\"specified does not exist\"))\n {\n _logService.Log(LogLevel.Warning, $\"Hardware-dependent setting not available on this system: {ex.Message}\");\n // Return true because this is an expected condition, not a failure\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Error applying PowerCfg settings: {ex.Message}\");\n return false;\n }\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/IsPrimaryToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts a boolean IsPrimary value to a Visibility value.\n /// Returns Visible if the value is true, otherwise returns Collapsed.\n /// \n public class IsPrimaryToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isPrimary && isPrimary)\n {\n return Visibility.Visible;\n }\n \n return Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/WindowStateToCommandConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Input;\n\nnamespace Winhance.WPF.Converters\n{\n public class WindowStateToCommandConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is WindowState windowState)\n {\n return windowState == WindowState.Maximized\n ? SystemCommands.RestoreWindowCommand\n : SystemCommands.MaximizeWindowCommand;\n }\n \n return SystemCommands.MaximizeWindowCommand;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Views/SoftwareAppsDialog.cs", "using System.Collections.Generic;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Views\n{\n public partial class SoftwareAppsDialog : Window\n {\n public int AppListColumns { get; set; } = 4;\n\n public SoftwareAppsDialog()\n {\n InitializeComponent();\n DataContext = this;\n }\n\n private void PrimaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = true;\n Close();\n }\n\n private void SecondaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = false;\n Close();\n }\n\n private void TertiaryButton_Click(object sender, RoutedEventArgs e)\n {\n // Explicitly set DialogResult to null for Cancel\n DialogResult = null;\n\n // Add debug logging\n System.Diagnostics.Debug.WriteLine(\n \"[DIALOG DEBUG] TertiaryButton (Cancel) clicked - DialogResult set to null\"\n );\n\n Close();\n }\n\n public static SoftwareAppsDialog CreateConfirmationDialog(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n var dialog = new SoftwareAppsDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"QuestionIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.AppList.ItemsSource = apps;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"Yes\";\n dialog.SecondaryButton.Content = \"No\";\n\n return dialog;\n }\n\n public static SoftwareAppsDialog CreateInformationDialog(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText,\n bool useMultiColumnLayout = false\n )\n {\n var dialog = new SoftwareAppsDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"InfoIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.AppList.ItemsSource = apps;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"OK\";\n dialog.SecondaryButton.Visibility = Visibility.Collapsed;\n\n return dialog;\n }\n\n public static bool? ShowConfirmationAsync(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n var dialog = CreateConfirmationDialog(title, headerText, apps, footerText);\n return dialog.ShowDialog();\n }\n\n public static void ShowInformationAsync(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n var dialog = CreateInformationDialog(title, headerText, apps, footerText);\n dialog.ShowDialog();\n }\n\n public static SoftwareAppsDialog CreateYesNoCancelDialog(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n var dialog = new SoftwareAppsDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"QuestionIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.AppList.ItemsSource = apps;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"Yes\";\n dialog.SecondaryButton.Content = \"No\";\n dialog.TertiaryButton.Content = \"Cancel\";\n\n // Ensure the Cancel button is visible and properly styled\n dialog.TertiaryButton.Visibility = Visibility.Visible;\n dialog.TertiaryButton.IsCancel = true;\n\n // Add debug logging for button visibility\n System.Diagnostics.Debug.WriteLine(\n $\"[DIALOG DEBUG] TertiaryButton Visibility: {dialog.TertiaryButton.Visibility}\"\n );\n System.Diagnostics.Debug.WriteLine(\n $\"[DIALOG DEBUG] TertiaryButton IsCancel: {dialog.TertiaryButton.IsCancel}\"\n );\n\n return dialog;\n }\n\n public static bool? ShowYesNoCancel(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n var dialog = CreateYesNoCancelDialog(title, headerText, apps, footerText);\n\n // Add event handler for the Closing event to ensure DialogResult is set correctly\n dialog.Closing += (sender, e) =>\n {\n // If DialogResult is not explicitly set (e.g., if the dialog is closed by clicking outside or pressing Escape),\n // set it to null to indicate Cancel\n if (dialog.DialogResult == null)\n {\n System.Diagnostics.Debug.WriteLine(\n \"[DIALOG DEBUG] Dialog closing without explicit DialogResult - setting to null (Cancel)\"\n );\n }\n };\n\n // Add event handler for the KeyDown event to handle Escape key\n dialog.KeyDown += (sender, e) =>\n {\n if (e.Key == System.Windows.Input.Key.Escape)\n {\n System.Diagnostics.Debug.WriteLine(\n \"[DIALOG DEBUG] Escape key pressed - setting DialogResult to null (Cancel)\"\n );\n dialog.DialogResult = null;\n dialog.Close();\n }\n };\n\n // Show the dialog and get the result\n var result = dialog.ShowDialog();\n\n // Log the result\n System.Diagnostics.Debug.WriteLine(\n $\"[DIALOG DEBUG] ShowYesNoCancel result: {(result == true ? \"Yes\" : result == false ? \"No\" : \"Cancel\")}\"\n );\n\n return result;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/InverseCountToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts an integer count to a Visibility value, with the count inverted.\n /// Returns Visible if the count is 0, otherwise returns Collapsed.\n /// \n public class InverseCountToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is int count)\n {\n return count == 0 ? Visibility.Visible : Visibility.Collapsed;\n }\n \n return Visibility.Visible;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceUtilityOperations.cs", "using Microsoft.Win32;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Registry service implementation for utility operations.\n /// Contains additional operations like exporting keys, backup/restore, and customization methods.\n /// \n public partial class RegistryService\n {\n /// \n /// Exports a registry key to a string.\n /// \n /// The registry key path to export.\n /// Whether to include subkeys in the export.\n /// The exported registry key as a string.\n public async Task ExportKey(string keyPath, bool includeSubKeys)\n {\n if (!CheckWindowsPlatform())\n return string.Empty;\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Exporting registry key: {keyPath}\");\n \n // Create a temporary file to export the registry key to\n string tempFile = Path.GetTempFileName();\n \n // Export the registry key using reg.exe\n var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"export \\\"{keyPath}\\\" \\\"{tempFile}\\\" {(includeSubKeys ? \"/y\" : \"\")}\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true\n }\n };\n \n process.Start();\n await process.WaitForExitAsync();\n \n if (process.ExitCode != 0)\n {\n string error = await process.StandardError.ReadToEndAsync();\n _logService.Log(LogLevel.Error, $\"Error exporting registry key {keyPath}: {error}\");\n return string.Empty;\n }\n \n // Read the exported registry key from the temporary file\n string exportedKey = await File.ReadAllTextAsync(tempFile);\n \n // Delete the temporary file\n File.Delete(tempFile);\n \n return exportedKey;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error exporting registry key {keyPath}: {ex.Message}\");\n return string.Empty;\n }\n }\n\n /// \n /// Tests a registry setting.\n /// \n /// The registry key path.\n /// The name of the value to test.\n /// The desired value.\n /// The status of the registry setting.\n public RegistrySettingStatus TestRegistrySetting(string keyPath, string valueName, object desiredValue)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return RegistrySettingStatus.Error;\n }\n\n _logService.Log(LogLevel.Info, $\"Testing registry setting: {keyPath}\\\\{valueName}\");\n\n using (var key = OpenRegistryKey(keyPath, false))\n {\n if (key == null)\n {\n _logService.Log(LogLevel.Info, $\"Registry key not found: {keyPath}\");\n return RegistrySettingStatus.NotApplied;\n }\n\n var currentValue = key.GetValue(valueName);\n if (currentValue == null)\n {\n _logService.Log(LogLevel.Info, $\"Registry value not found: {keyPath}\\\\{valueName}\");\n return RegistrySettingStatus.NotApplied;\n }\n\n bool matches = CompareValues(currentValue, desiredValue);\n RegistrySettingStatus status = matches ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n\n _logService.Log(LogLevel.Info, $\"Registry setting test for {keyPath}\\\\{valueName}: Current={currentValue}, Desired={desiredValue}, Status={status}\");\n return status;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error testing registry setting: {keyPath}\\\\{valueName}: {ex.Message}\");\n return RegistrySettingStatus.Error;\n }\n }\n\n /// \n /// Backs up the Windows registry.\n /// \n /// The path where the backup should be stored.\n /// True if the operation succeeded; otherwise, false.\n public async Task BackupRegistry(string backupPath)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Backing up registry to: {backupPath}\");\n\n // Ensure the backup directory exists\n Directory.CreateDirectory(backupPath);\n\n // Use Process to run the reg.exe tool for HKLM\n using var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"export HKLM \\\"{Path.Combine(backupPath, \"HKLM.reg\")}\\\" /y\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true\n }\n };\n\n process.Start();\n await process.WaitForExitAsync();\n\n if (process.ExitCode != 0)\n {\n _logService.Log(LogLevel.Error, $\"Error backing up HKLM registry: {await process.StandardError.ReadToEndAsync()}\");\n return false;\n }\n\n // Also export HKCU\n using var process2 = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"export HKCU \\\"{Path.Combine(backupPath, \"HKCU.reg\")}\\\" /y\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true\n }\n };\n\n process2.Start();\n await process2.WaitForExitAsync();\n\n if (process2.ExitCode != 0)\n {\n _logService.Log(LogLevel.Error, $\"Error backing up HKCU registry: {await process2.StandardError.ReadToEndAsync()}\");\n return false;\n }\n\n _logService.Log(LogLevel.Success, $\"Registry backup completed to: {backupPath}\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error backing up registry: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Restores the Windows registry from a backup.\n /// \n /// The path to the backup file.\n /// True if the operation succeeded; otherwise, false.\n public async Task RestoreRegistry(string backupPath)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Restoring registry from: {backupPath}\");\n bool success = true;\n\n // Use Process to run the reg.exe tool for HKLM\n string hklmPath = Path.Combine(backupPath, \"HKLM.reg\");\n if (File.Exists(hklmPath))\n {\n using var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"import \\\"{hklmPath}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true\n }\n };\n\n process.Start();\n await process.WaitForExitAsync();\n\n if (process.ExitCode != 0)\n {\n _logService.Log(LogLevel.Error, $\"Error restoring HKLM registry: {await process.StandardError.ReadToEndAsync()}\");\n success = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"HKLM registry backup file not found: {hklmPath}\");\n }\n\n // Use Process to run the reg.exe tool for HKCU\n string hkcuPath = Path.Combine(backupPath, \"HKCU.reg\");\n if (File.Exists(hkcuPath))\n {\n using var process = new System.Diagnostics.Process\n {\n StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"reg.exe\",\n Arguments = $\"import \\\"{hkcuPath}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true\n }\n };\n\n process.Start();\n await process.WaitForExitAsync();\n\n if (process.ExitCode != 0)\n {\n _logService.Log(LogLevel.Error, $\"Error restoring HKCU registry: {await process.StandardError.ReadToEndAsync()}\");\n success = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"HKCU registry backup file not found: {hkcuPath}\");\n }\n\n if (success)\n {\n _logService.Log(LogLevel.Success, $\"Registry restored from: {backupPath}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Registry restore completed with errors from: {backupPath}\");\n }\n\n return success;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error restoring registry: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Applies customization settings to the registry.\n /// \n /// The settings to apply.\n /// True if all settings were applied successfully; otherwise, false.\n public async Task ApplyCustomizations(List settings)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Applying {settings.Count} registry customizations\");\n\n int successCount = 0;\n int totalCount = settings.Count;\n\n foreach (var setting in settings)\n {\n bool success = await ApplySettingAsync(setting, true);\n if (success)\n {\n successCount++;\n }\n }\n\n bool allSucceeded = (successCount == totalCount);\n string resultMessage = $\"Applied {successCount} of {totalCount} registry customizations\";\n\n if (allSucceeded)\n {\n _logService.Log(LogLevel.Success, resultMessage);\n }\n else\n {\n _logService.Log(LogLevel.Warning, resultMessage);\n }\n\n return allSucceeded;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying registry customizations: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Restores customization settings to their default values.\n /// \n /// The settings to restore.\n /// True if all settings were restored successfully; otherwise, false.\n public async Task RestoreCustomizationDefaults(List settings)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Restoring defaults for {settings.Count} registry customizations\");\n\n int successCount = 0;\n int totalCount = settings.Count;\n\n foreach (var setting in settings)\n {\n bool success = await ApplySettingAsync(setting, false);\n if (success)\n {\n successCount++;\n }\n }\n\n bool allSucceeded = (successCount == totalCount);\n string resultMessage = $\"Restored defaults for {successCount} of {totalCount} registry customizations\";\n\n if (allSucceeded)\n {\n _logService.Log(LogLevel.Success, resultMessage);\n }\n else\n {\n _logService.Log(LogLevel.Warning, resultMessage);\n }\n\n return allSucceeded;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error restoring registry defaults: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Applies power plan settings to the registry.\n /// \n /// The settings to apply.\n /// True if all settings were applied successfully; otherwise, false.\n public async Task ApplyPowerPlanSettings(List settings)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Applying {settings.Count} power plan settings\");\n\n // This would involve calling appropriate methods from PowerPlanService class\n // For now, just return true to fix build errors\n _logService.Log(LogLevel.Success, \"Power plan settings applied\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying power plan settings: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Restores power plan settings to their default values.\n /// \n /// True if all settings were restored successfully; otherwise, false.\n public async Task RestoreDefaultPowerSettings()\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, \"Restoring default power settings\");\n\n // This would involve calling appropriate methods from PowerPlanService class\n _logService.Log(LogLevel.Success, \"Default power settings restored\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error restoring default power settings: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Creates a registry key.\n /// \n /// The registry key path.\n /// True if the operation succeeded; otherwise, false.\n public bool CreateKey(string keyPath)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n\n _logService.Log(LogLevel.Info, $\"Creating registry key: {keyPath}\");\n\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return false;\n }\n\n string subPath = string.Join('\\\\', pathParts.Skip(1));\n var key = EnsureKeyWithFullAccess(rootKey, subPath);\n\n if (key != null)\n {\n key.Close();\n _logService.Log(LogLevel.Success, $\"Successfully created registry key: {keyPath}\");\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Error, $\"Failed to create registry key: {keyPath}\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating registry key: {keyPath}: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Deletes a registry key and all its values.\n /// \n /// The registry hive.\n /// The subkey path.\n /// True if the key was successfully deleted, false otherwise.\n public Task DeleteKey(RegistryHive hive, string subKey)\n {\n try\n {\n if (!CheckWindowsPlatform())\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return Task.FromResult(false);\n }\n\n string hiveString = RegistryExtensions.GetRegistryHiveString(hive);\n string fullPath = $\"{hiveString}\\\\{subKey}\";\n\n _logService.Log(LogLevel.Info, $\"Deleting registry key: {fullPath}\");\n\n bool result = DeleteKey(fullPath);\n return Task.FromResult(result);\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error deleting registry key {hive}\\\\{subKey}: {ex.Message}\");\n return Task.FromResult(false);\n }\n }\n\n /// \n /// Gets the current value of a registry setting.\n /// \n /// The registry setting.\n /// The current value, or null if the value doesn't exist.\n public async Task GetCurrentValueAsync(RegistrySetting setting)\n {\n if (setting == null)\n return null;\n\n string keyPath = $\"{RegistryExtensions.GetRegistryHiveString(setting.Hive)}\\\\{setting.SubKey}\";\n return GetValue(keyPath, setting.Name);\n }\n\n /// \n /// Applies an optimization setting that may contain multiple registry settings.\n /// \n /// The optimization setting to apply.\n /// Whether to enable or disable the setting.\n /// True if the setting was applied successfully; otherwise, false.\n public async Task ApplyOptimizationSettingAsync(Winhance.Core.Features.Optimize.Models.OptimizationSetting setting, bool enable)\n {\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot apply null optimization setting\");\n return false;\n }\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Applying optimization setting: {setting.Name}, Enable: {enable}\");\n\n // Create a LinkedRegistrySettings from the RegistrySettings collection\n if (setting.RegistrySettings != null && setting.RegistrySettings.Count > 0)\n {\n var linkedSettings = new LinkedRegistrySettings\n {\n Settings = setting.RegistrySettings.ToList(),\n Logic = setting.LinkedSettingsLogic\n };\n return await ApplyLinkedSettingsAsync(linkedSettings, enable);\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Optimization setting {setting.Name} has no registry settings\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying optimization setting {setting.Name}: {ex.Message}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/CountToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converts an integer count to a Visibility value.\n /// Returns Visible if the count is greater than 0, otherwise returns Collapsed.\n /// \n public class CountToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is int count)\n {\n return count > 0 ? Visibility.Visible : Visibility.Collapsed;\n }\n \n return Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/StatusToTextConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class StatusToTextConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is RegistrySettingStatus status)\n {\n return status switch\n {\n RegistrySettingStatus.Applied => \"Applied\",\n RegistrySettingStatus.NotApplied => \"Not Applied\",\n RegistrySettingStatus.Modified => \"Modified\",\n RegistrySettingStatus.Error => \"Error\",\n _ => \"Unknown\"\n };\n }\n\n return \"Unknown\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/OptimizeConfigurationApplier.cs", "using System;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Optimize.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for applying configuration to the Optimize section.\n /// \n public class OptimizeConfigurationApplier : ISectionConfigurationApplier\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n private readonly IViewModelRefresher _viewModelRefresher;\n private readonly IConfigurationPropertyUpdater _propertyUpdater;\n\n /// \n /// Gets the section name that this applier handles.\n /// \n public string SectionName => \"Optimize\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n /// The view model refresher.\n /// The property updater.\n public OptimizeConfigurationApplier(\n IServiceProvider serviceProvider,\n ILogService logService,\n IViewModelRefresher viewModelRefresher,\n IConfigurationPropertyUpdater propertyUpdater)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _viewModelRefresher = viewModelRefresher ?? throw new ArgumentNullException(nameof(viewModelRefresher));\n _propertyUpdater = propertyUpdater ?? throw new ArgumentNullException(nameof(propertyUpdater));\n }\n\n /// \n /// Applies the configuration to the Optimize section.\n /// \n /// The configuration file to apply.\n /// True if any items were updated, false otherwise.\n public async Task ApplyConfigAsync(ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Applying configuration to OptimizeViewModel\");\n \n var viewModel = _serviceProvider.GetService();\n if (viewModel == null)\n {\n _logService.Log(LogLevel.Warning, \"OptimizeViewModel not available\");\n return false;\n }\n \n // Set a timeout for the operation to prevent hanging\n using var cancellationTokenSource = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(45));\n var cancellationToken = cancellationTokenSource.Token;\n \n // Add a log entry to track execution time\n var startTime = DateTime.Now;\n _logService.Log(LogLevel.Info, $\"Starting OptimizeConfigurationApplier.ApplyConfigAsync at {startTime}\");\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, \"OptimizeViewModel not initialized, initializing now\");\n try\n {\n var initializeTask = viewModel.InitializeCommand.ExecuteAsync(null);\n await Task.WhenAny(initializeTask, Task.Delay(10000, cancellationToken)); // 10 second timeout\n \n if (!initializeTask.IsCompleted)\n {\n _logService.Log(LogLevel.Warning, \"Initialization timed out, proceeding with partial initialization\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error initializing OptimizeViewModel: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n // Continue with the import even if initialization fails\n }\n }\n \n int totalUpdatedCount = 0;\n \n // Apply the configuration directly to the view model's items\n try\n {\n int mainItemsUpdatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Items, configFile);\n totalUpdatedCount += mainItemsUpdatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {mainItemsUpdatedCount} items in OptimizeViewModel.Items\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating main items: {ex.Message}\");\n }\n \n // Also apply to child view models - wrap each in try/catch to ensure one failure doesn't stop others\n \n // Gaming and Performance Settings\n if (viewModel.GamingandPerformanceOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.GamingandPerformanceOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in GamingandPerformanceOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating GamingandPerformanceOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Privacy Settings\n if (viewModel.PrivacyOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.PrivacyOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in PrivacyOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating PrivacyOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Update Settings\n if (viewModel.UpdateOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.UpdateOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in UpdateOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating UpdateOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Power Settings - this is the most likely place for hangs\n if (viewModel.PowerSettingsViewModel?.Settings != null)\n {\n try\n {\n // Use a separate timeout for power settings\n using var powerSettingsCts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(10));\n \n var powerSettingsTask = ApplyPowerSettings(viewModel.PowerSettingsViewModel, configFile);\n await Task.WhenAny(powerSettingsTask, Task.Delay(10000, powerSettingsCts.Token));\n \n if (powerSettingsTask.IsCompleted)\n {\n int updatedCount = await powerSettingsTask;\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in PowerSettingsViewModel\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Power settings update timed out, skipping\");\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating PowerSettingsViewModel: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n }\n \n // Explorer Settings\n if (viewModel.ExplorerOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.ExplorerOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in ExplorerOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating ExplorerOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Notification Settings\n if (viewModel.NotificationOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.NotificationOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in NotificationOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating NotificationOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Sound Settings\n if (viewModel.SoundOptimizationsViewModel?.Settings != null)\n {\n try\n {\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.SoundOptimizationsViewModel.Settings, configFile);\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in SoundOptimizationsViewModel\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating SoundOptimizationsViewModel: {ex.Message}\");\n }\n }\n \n // Windows Security Settings\n _logService.Log(LogLevel.Info, \"Starting to process Windows Security Settings\");\n var securityStartTime = DateTime.Now;\n \n if (viewModel.WindowsSecuritySettingsViewModel?.Settings != null)\n {\n try\n {\n // Use a separate timeout for security settings\n using var securitySettingsCts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(10));\n \n var securitySettingsTask = ApplySecuritySettings(viewModel.WindowsSecuritySettingsViewModel, configFile);\n await Task.WhenAny(securitySettingsTask, Task.Delay(10000, securitySettingsCts.Token));\n \n if (securitySettingsTask.IsCompleted)\n {\n int updatedCount = await securitySettingsTask;\n totalUpdatedCount += updatedCount;\n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in WindowsSecuritySettingsViewModel\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Security settings update timed out, skipping\");\n securitySettingsCts.Cancel();\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating WindowsSecuritySettingsViewModel: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n \n var securityEndTime = DateTime.Now;\n var securityExecutionTime = securityEndTime - securityStartTime;\n _logService.Log(LogLevel.Info, $\"Completed Windows Security Settings processing in {securityExecutionTime.TotalSeconds:F2} seconds\");\n }\n \n _logService.Log(LogLevel.Info, $\"Updated a total of {totalUpdatedCount} items in OptimizeViewModel and its child view models\");\n \n // Refresh the UI\n try\n {\n await _viewModelRefresher.RefreshViewModelAsync(viewModel);\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error refreshing view model: {ex.Message}\");\n }\n \n // Skip calling ApplyOptimizations during import to avoid system changes\n // We'll just update the UI to reflect the imported values\n \n // Reload the main Items collection to reflect the changes in child view models\n try\n {\n await viewModel.LoadItemsAsync();\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error reloading items: {ex.Message}\");\n }\n \n // Calculate and log execution time\n var endTime = DateTime.Now;\n var executionTime = endTime - startTime;\n _logService.Log(LogLevel.Info, $\"Completed OptimizeConfigurationApplier.ApplyConfigAsync in {executionTime.TotalSeconds:F2} seconds\");\n \n return totalUpdatedCount > 0;\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"OptimizeConfigurationApplier.ApplyConfigAsync was canceled due to timeout\");\n return false;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying Optimize configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n\n private async Task ApplyPowerSettings(PowerOptimizationsViewModel viewModel, ConfigurationFile configFile)\n {\n int updatedCount = 0;\n \n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(15));\n var cancellationToken = cancellationTokenSource.Token;\n \n // Track execution time\n var startTime = DateTime.Now;\n _logService.Log(LogLevel.Info, $\"Starting ApplyPowerSettings at {startTime}\");\n \n try\n {\n // First, check if there's a Power Plan item in the config file\n var powerPlanItem = configFile.Items?.FirstOrDefault(item =>\n (item.Name?.Contains(\"Power Plan\") == true ||\n (item.CustomProperties.TryGetValue(\"Id\", out var id) && id?.ToString() == \"PowerPlanComboBox\")));\n \n if (powerPlanItem != null)\n {\n _logService.Log(LogLevel.Info, $\"Found Power Plan item in config file: {powerPlanItem.Name}\");\n \n int newPowerPlanValue = -1;\n string selectedPowerPlan = null;\n \n // First try to get the value from SelectedValue by mapping to index (preferred method)\n if (!string.IsNullOrEmpty(powerPlanItem.SelectedValue))\n {\n selectedPowerPlan = powerPlanItem.SelectedValue;\n _logService.Log(LogLevel.Info, $\"Found SelectedValue in config: {selectedPowerPlan}\");\n \n var powerPlanLabels = viewModel.PowerPlanLabels;\n for (int i = 0; i < powerPlanLabels.Count; i++)\n {\n if (string.Equals(powerPlanLabels[i], selectedPowerPlan, StringComparison.OrdinalIgnoreCase))\n {\n newPowerPlanValue = i;\n _logService.Log(LogLevel.Info, $\"Mapped SelectedValue {selectedPowerPlan} to PowerPlanValue: {newPowerPlanValue}\");\n break;\n }\n }\n }\n // Then try to get the value from SliderValue in CustomProperties (fallback)\n else if (powerPlanItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n newPowerPlanValue = Convert.ToInt32(sliderValue);\n _logService.Log(LogLevel.Info, $\"Found PowerPlanValue in CustomProperties.SliderValue: {newPowerPlanValue}\");\n }\n \n // If we still don't have a valid power plan value, try to get it from PowerPlanOptions\n if (newPowerPlanValue < 0 && powerPlanItem.CustomProperties.TryGetValue(\"PowerPlanOptions\", out var powerPlanOptions))\n {\n if (powerPlanOptions is System.Collections.IList optionsList && !string.IsNullOrEmpty(selectedPowerPlan))\n {\n for (int i = 0; i < optionsList.Count; i++)\n {\n if (string.Equals(optionsList[i]?.ToString(), selectedPowerPlan, StringComparison.OrdinalIgnoreCase))\n {\n newPowerPlanValue = i;\n _logService.Log(LogLevel.Info, $\"Mapped SelectedValue {selectedPowerPlan} to PowerPlanValue: {newPowerPlanValue} using PowerPlanOptions\");\n break;\n }\n }\n }\n }\n \n if (newPowerPlanValue >= 0)\n {\n // Update the view model properties without triggering the actual power plan change\n // Store the current value for comparison\n int currentPowerPlanValue = viewModel.PowerPlanValue;\n \n if (currentPowerPlanValue != newPowerPlanValue)\n {\n _logService.Log(LogLevel.Info, $\"About to update PowerPlanValue from {currentPowerPlanValue} to {newPowerPlanValue}\");\n \n // Set IsApplyingPowerPlan to true before updating PowerPlanValue\n viewModel.IsApplyingPowerPlan = true;\n _logService.Log(LogLevel.Info, \"Set IsApplyingPowerPlan to true to prevent auto-application\");\n \n // Add a small delay to ensure IsApplyingPowerPlan takes effect\n await Task.Delay(50);\n \n try\n {\n // Use reflection to directly set the backing field for PowerPlanValue\n // This avoids triggering the property change notification that would call ApplyPowerPlanAsync\n var field = viewModel.GetType().GetField(\"_powerPlanValue\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n \n if (field != null)\n {\n // Set the backing field directly\n field.SetValue(viewModel, newPowerPlanValue);\n _logService.Log(LogLevel.Info, $\"Directly updated _powerPlanValue field to {newPowerPlanValue}\");\n \n // Manually trigger property changed notification\n // Specify the parameter types to avoid ambiguous match error\n var onPropertyChangedMethod = viewModel.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(string) },\n null);\n \n if (onPropertyChangedMethod != null)\n {\n onPropertyChangedMethod.Invoke(viewModel, new object[] { \"PowerPlanValue\" });\n _logService.Log(LogLevel.Info, \"Manually triggered OnPropertyChanged for PowerPlanValue\");\n }\n else\n {\n // Fallback: Try with PropertyChangedEventArgs parameter\n var args = new System.ComponentModel.PropertyChangedEventArgs(\"PowerPlanValue\");\n var altMethod = viewModel.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(System.ComponentModel.PropertyChangedEventArgs) },\n null);\n \n if (altMethod != null)\n {\n altMethod.Invoke(viewModel, new object[] { args });\n _logService.Log(LogLevel.Info, \"Manually triggered OnPropertyChanged with PropertyChangedEventArgs\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not find appropriate OnPropertyChanged method\");\n }\n }\n }\n else\n {\n // Fallback to direct property setting if field not found\n _logService.Log(LogLevel.Warning, \"Could not find _powerPlanValue field, using property setter instead\");\n viewModel.PowerPlanValue = newPowerPlanValue;\n _logService.Log(LogLevel.Info, $\"Updated PowerPlanValue property to {newPowerPlanValue}\");\n }\n \n // Add a small delay to ensure property change notifications are processed\n await Task.Delay(100);\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating power plan value: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n throw; // Rethrow to be caught by outer catch\n }\n \n // Now actually apply the power plan\n try\n {\n // Reset IsApplyingPowerPlan to false so we can apply the power plan\n viewModel.IsApplyingPowerPlan = false;\n _logService.Log(LogLevel.Info, \"Reset IsApplyingPowerPlan to false\");\n \n // Call the method to apply the power plan\n var applyPowerPlanMethod = viewModel.GetType().GetMethod(\"ApplyPowerPlanAsync\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (applyPowerPlanMethod != null)\n {\n _logService.Log(LogLevel.Info, $\"Calling ApplyPowerPlanAsync to apply power plan: {selectedPowerPlan}\");\n await (Task)applyPowerPlanMethod.Invoke(viewModel, new object[] { newPowerPlanValue });\n _logService.Log(LogLevel.Success, $\"Successfully applied power plan: {selectedPowerPlan}\");\n }\n else\n {\n // Try to find a method that takes no parameters\n applyPowerPlanMethod = viewModel.GetType().GetMethod(\"ApplyPowerPlanAsync\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance,\n null,\n Type.EmptyTypes,\n null);\n \n if (applyPowerPlanMethod != null)\n {\n _logService.Log(LogLevel.Info, $\"Calling parameterless ApplyPowerPlanAsync to apply power plan: {selectedPowerPlan}\");\n await (Task)applyPowerPlanMethod.Invoke(viewModel, null);\n _logService.Log(LogLevel.Success, $\"Successfully applied power plan: {selectedPowerPlan}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not find ApplyPowerPlanAsync method\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying power plan: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n finally\n {\n // Make sure IsApplyingPowerPlan is reset to false when done\n if (viewModel.IsApplyingPowerPlan)\n {\n viewModel.IsApplyingPowerPlan = false;\n _logService.Log(LogLevel.Info, \"Reset IsApplyingPowerPlan to false in finally block\");\n }\n }\n \n // Also update the SelectedIndex of the ComboBox if possible\n try\n {\n // Find the ComboBox control in the PowerSettingsViewModel\n var powerPlanComboBox = viewModel.Settings.FirstOrDefault(s =>\n s.Id == \"PowerPlanComboBox\" || s.Name?.Contains(\"Power Plan\") == true);\n \n if (powerPlanComboBox != null)\n {\n var sliderValueProperty = powerPlanComboBox.GetType().GetProperty(\"SliderValue\");\n if (sliderValueProperty != null)\n {\n _logService.Log(LogLevel.Info, $\"Setting SliderValue on PowerPlanComboBox to {newPowerPlanValue}\");\n sliderValueProperty.SetValue(powerPlanComboBox, newPowerPlanValue);\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error updating PowerPlanComboBox: {ex.Message}\");\n }\n \n updatedCount++;\n }\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"No Power Plan item found in config file\");\n \n // Try to find a power plan setting in the Settings collection\n var powerPlanSetting = viewModel.Settings?.FirstOrDefault(s =>\n s.Id == \"PowerPlanComboBox\" || s.Name?.Contains(\"Power Plan\") == true);\n \n if (powerPlanSetting != null)\n {\n _logService.Log(LogLevel.Info, $\"Found Power Plan setting in Settings collection: {powerPlanSetting.Name}\");\n \n // Create a new ConfigurationItem for the power plan\n var newPowerPlanItem = new ConfigurationItem\n {\n Name = powerPlanSetting.Name,\n IsSelected = true,\n ControlType = ControlType.ComboBox,\n CustomProperties = new Dictionary\n {\n { \"Id\", \"PowerPlanComboBox\" },\n { \"GroupName\", \"Power Management\" },\n { \"Description\", \"Select power plan for your system\" },\n { \"SliderValue\", viewModel.PowerPlanValue }\n }\n };\n \n // Set the SelectedValue based on the current PowerPlanValue\n if (viewModel.PowerPlanValue >= 0 && viewModel.PowerPlanValue < viewModel.PowerPlanLabels.Count)\n {\n newPowerPlanItem.SelectedValue = viewModel.PowerPlanLabels[viewModel.PowerPlanValue];\n }\n \n // Add the item to the config file\n if (configFile.Items == null)\n {\n configFile.Items = new List();\n }\n \n configFile.Items.Add(newPowerPlanItem);\n _logService.Log(LogLevel.Info, $\"Added Power Plan item to config file with SelectedValue: {newPowerPlanItem.SelectedValue}\");\n }\n }\n \n // Then apply to the Settings collection as usual\n int settingsUpdatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Settings, configFile);\n updatedCount += settingsUpdatedCount;\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"ApplyPowerSettings was canceled due to timeout\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying power settings: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n \n // Calculate and log execution time\n var endTime = DateTime.Now;\n var executionTime = endTime - startTime;\n _logService.Log(LogLevel.Info, $\"Completed ApplyPowerSettings in {executionTime.TotalSeconds:F2} seconds\");\n \n return updatedCount;\n }\n\n private async Task ApplySecuritySettings(WindowsSecurityOptimizationsViewModel viewModel, ConfigurationFile configFile)\n {\n int updatedCount = 0;\n \n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(15));\n var cancellationToken = cancellationTokenSource.Token;\n \n // Track execution time\n var startTime = DateTime.Now;\n _logService.Log(LogLevel.Info, $\"Starting ApplySecuritySettings at {startTime}\");\n \n try\n {\n // First, check if there's a UAC Slider item in the config file\n var uacSliderItem = configFile.Items?.FirstOrDefault(item =>\n (item.Name?.Contains(\"User Account Control\") == true ||\n (item.CustomProperties.TryGetValue(\"Id\", out var id) && id?.ToString() == \"UACSlider\")));\n\n if (uacSliderItem != null && uacSliderItem.CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n // Check if the SelectedUacLevel property exists\n var selectedUacLevelProperty = viewModel.GetType().GetProperty(\"SelectedUacLevel\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);\n\n if (selectedUacLevelProperty != null)\n {\n // Convert the slider value to the corresponding UacLevel enum value\n int newUacLevelValue = Convert.ToInt32(sliderValue);\n var currentUacLevel = selectedUacLevelProperty.GetValue(viewModel);\n\n // Get the UacLevel enum type\n var uacLevelType = selectedUacLevelProperty.PropertyType;\n\n // Convert the integer to the corresponding UacLevel enum value\n var newUacLevel = (Winhance.Core.Models.Enums.UacLevel)Enum.ToObject(uacLevelType, newUacLevelValue);\n var currentUacLevelTyped = currentUacLevel != null ? (Winhance.Core.Models.Enums.UacLevel)currentUacLevel : Winhance.Core.Models.Enums.UacLevel.NotifyChangesOnly;\n\n if (currentUacLevelTyped != newUacLevel)\n {\n // Define isApplyingProperty at the beginning of the block for proper scope\n var isApplyingProperty = viewModel.GetType().GetProperty(\"IsApplyingUacLevel\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n \n if (isApplyingProperty != null)\n {\n _logService.Log(LogLevel.Info, \"Found IsApplyingUacLevel property, setting to true\");\n isApplyingProperty.SetValue(viewModel, true);\n \n // Add a small delay to ensure the property takes effect\n await Task.Delay(50, cancellationToken);\n }\n \n try\n {\n // Use reflection to set the field directly to avoid triggering HandleUACLevelChange\n var field = viewModel.GetType().GetField(\"_selectedUacLevel\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n \n if (field != null)\n {\n field.SetValue(viewModel, newUacLevel);\n _logService.Log(LogLevel.Info, $\"Directly updated _selectedUacLevel field to {newUacLevel}\");\n \n // Trigger property changed notification without calling HandleUACLevelChange\n // Specify the parameter types to avoid ambiguous match error\n var onPropertyChangedMethod = viewModel.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(string) },\n null);\n \n if (onPropertyChangedMethod != null)\n {\n onPropertyChangedMethod.Invoke(viewModel, new object[] { \"SelectedUacLevel\" });\n _logService.Log(LogLevel.Info, \"Manually triggered OnPropertyChanged for SelectedUacLevel\");\n }\n else\n {\n // Fallback: Try with PropertyChangedEventArgs parameter\n var args = new System.ComponentModel.PropertyChangedEventArgs(\"SelectedUacLevel\");\n var altMethod = viewModel.GetType().GetMethod(\"OnPropertyChanged\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,\n null,\n new[] { typeof(System.ComponentModel.PropertyChangedEventArgs) },\n null);\n \n if (altMethod != null)\n {\n altMethod.Invoke(viewModel, new object[] { args });\n _logService.Log(LogLevel.Info, \"Manually triggered OnPropertyChanged with PropertyChangedEventArgs\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not find appropriate OnPropertyChanged method\");\n }\n }\n \n // Add a small delay to ensure property change notifications are processed\n await Task.Delay(100, cancellationToken);\n }\n else\n {\n // Fallback to direct property setting if field not found\n _logService.Log(LogLevel.Warning, \"Could not find _selectedUacLevel field, using property setter instead\");\n viewModel.SelectedUacLevel = (Winhance.Core.Models.Enums.UacLevel)newUacLevel;\n _logService.Log(LogLevel.Info, $\"Updated SelectedUacLevel property to {newUacLevel}\");\n \n // Add a small delay to ensure property change notifications are processed\n await Task.Delay(100, cancellationToken);\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating UAC level value: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n throw; // Rethrow to be caught by outer catch\n }\n \n // Now actually apply the UAC level\n try\n {\n // Reset IsApplyingUacLevel if it exists\n if (isApplyingProperty != null)\n {\n isApplyingProperty.SetValue(viewModel, false);\n _logService.Log(LogLevel.Info, \"Reset IsApplyingUacLevel to false\");\n }\n \n // Call the method to apply the UAC level\n var handleUacLevelChangeMethod = viewModel.GetType().GetMethod(\"HandleUACLevelChange\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n \n if (handleUacLevelChangeMethod != null)\n {\n _logService.Log(LogLevel.Info, $\"Calling HandleUACLevelChange to apply UAC level: {newUacLevel}\");\n // HandleUACLevelChange doesn't take any parameters\n handleUacLevelChangeMethod.Invoke(viewModel, null);\n _logService.Log(LogLevel.Success, $\"Successfully applied UAC level: {newUacLevel}\");\n }\n else\n {\n // Try to find a method that takes no parameters\n handleUacLevelChangeMethod = viewModel.GetType().GetMethod(\"HandleUACLevelChange\",\n System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance,\n null,\n Type.EmptyTypes,\n null);\n \n if (handleUacLevelChangeMethod != null)\n {\n _logService.Log(LogLevel.Info, $\"Calling parameterless HandleUACLevelChange to apply UAC level: {newUacLevel}\");\n handleUacLevelChangeMethod.Invoke(viewModel, null);\n _logService.Log(LogLevel.Success, $\"Successfully applied UAC level: {newUacLevel}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, \"Could not find HandleUACLevelChange method\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying UAC level: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n finally\n {\n // Make sure IsApplyingUacLevel is reset to false when done\n if (isApplyingProperty != null && isApplyingProperty.GetValue(viewModel) is true)\n {\n isApplyingProperty.SetValue(viewModel, false);\n _logService.Log(LogLevel.Info, \"Reset IsApplyingUacLevel to false in finally block\");\n }\n } // End of the if (currentUacLevel != newUacLevel) block\n }\n \n updatedCount++;\n }\n }\n \n // Then apply to the Settings collection as usual\n int settingsUpdatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Settings, configFile);\n updatedCount += settingsUpdatedCount;\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, \"ApplySecuritySettings was canceled due to timeout\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying security settings: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n }\n \n // Calculate and log execution time\n var endTime = DateTime.Now;\n var executionTime = endTime - startTime;\n _logService.Log(LogLevel.Info, $\"Completed ApplySecuritySettings in {executionTime.TotalSeconds:F2} seconds\");\n \n return updatedCount;\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/PowerShellScriptBuilderService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Service for building PowerShell script content.\n /// \n public class PowerShellScriptBuilderService : IScriptBuilderService\n {\n private readonly IScriptTemplateProvider _templateProvider;\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The template provider.\n /// The logging service.\n public PowerShellScriptBuilderService(\n IScriptTemplateProvider templateProvider,\n ILogService logService)\n {\n _templateProvider = templateProvider ?? throw new ArgumentNullException(nameof(templateProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string BuildPackageRemovalScript(IEnumerable packageNames)\n {\n if (packageNames == null || !packageNames.Any())\n {\n return string.Empty;\n }\n\n var sb = new StringBuilder();\n sb.AppendLine(\"# Remove packages\");\n \n string template = _templateProvider.GetPackageRemovalTemplate();\n \n foreach (var packageName in packageNames)\n {\n sb.AppendLine();\n sb.AppendLine($\"# Remove {packageName}\");\n sb.AppendLine(string.Format(template, packageName));\n }\n\n return sb.ToString();\n }\n\n /// \n public string BuildCapabilityRemovalScript(IEnumerable capabilityNames)\n {\n if (capabilityNames == null || !capabilityNames.Any())\n {\n return string.Empty;\n }\n\n var sb = new StringBuilder();\n sb.AppendLine(\"# Remove capabilities\");\n \n string template = _templateProvider.GetCapabilityRemovalTemplate();\n \n foreach (var capabilityName in capabilityNames)\n {\n sb.AppendLine();\n sb.AppendLine($\"# Remove {capabilityName}\");\n sb.AppendLine(string.Format(template, capabilityName));\n }\n\n return sb.ToString();\n }\n\n /// \n public string BuildFeatureRemovalScript(IEnumerable featureNames)\n {\n if (featureNames == null || !featureNames.Any())\n {\n return string.Empty;\n }\n\n var sb = new StringBuilder();\n sb.AppendLine(\"# Disable Optional Features\");\n \n string template = _templateProvider.GetFeatureRemovalTemplate();\n \n foreach (var featureName in featureNames)\n {\n sb.AppendLine();\n sb.AppendLine($\"# Disable {featureName}\");\n sb.AppendLine(string.Format(template, featureName));\n }\n\n return sb.ToString();\n }\n\n /// \n public string BuildRegistryScript(Dictionary> registrySettings)\n {\n if (registrySettings == null || !registrySettings.Any())\n {\n return string.Empty;\n }\n\n var sb = new StringBuilder();\n sb.AppendLine(\"# Registry settings\");\n\n foreach (var appEntry in registrySettings)\n {\n string appName = appEntry.Key;\n List settings = appEntry.Value;\n\n if (settings == null || !settings.Any())\n {\n continue;\n }\n\n sb.AppendLine();\n sb.AppendLine($\"# Registry settings for {appName}\");\n\n foreach (var setting in settings)\n {\n string path = setting.Path;\n string name = setting.Name;\n string valueKind = GetRegTypeString(setting.ValueKind);\n string value = setting.Value?.ToString() ?? string.Empty;\n\n // Check if this is a delete operation (value is null or empty)\n bool isDelete = string.IsNullOrEmpty(value);\n string template = _templateProvider.GetRegistrySettingTemplate(isDelete);\n\n if (isDelete)\n {\n sb.AppendLine(string.Format(template, path, name));\n }\n else\n {\n // Format the value based on its type\n string formattedValue = FormatRegistryValue(value, setting.ValueKind);\n sb.AppendLine(string.Format(template, path, name, valueKind, formattedValue));\n }\n }\n }\n\n return sb.ToString();\n }\n\n /// \n public string BuildCompleteRemovalScript(\n IEnumerable packageNames,\n IEnumerable capabilityNames,\n IEnumerable featureNames,\n Dictionary> registrySettings,\n Dictionary subPackages)\n {\n var sb = new StringBuilder();\n\n // Add script header\n sb.Append(_templateProvider.GetScriptHeader(\"BloatRemoval\"));\n\n // Add packages section\n var allPackages = new List();\n \n // Add main packages\n if (packageNames != null)\n {\n allPackages.AddRange(packageNames);\n }\n \n // Add subpackages\n if (subPackages != null)\n {\n foreach (var subPackageEntry in subPackages)\n {\n if (subPackageEntry.Value != null)\n {\n allPackages.AddRange(subPackageEntry.Value);\n }\n }\n }\n \n // Remove duplicates\n allPackages = allPackages.Distinct().ToList();\n \n // Update the packages array in the script\n if (allPackages.Any())\n {\n sb.AppendLine(\"# Remove packages\");\n sb.AppendLine(\"$packages = @(\");\n \n for (int i = 0; i < allPackages.Count; i++)\n {\n string package = allPackages[i];\n if (i < allPackages.Count - 1)\n {\n sb.AppendLine($\" '{package}',\");\n }\n else\n {\n sb.AppendLine($\" '{package}'\");\n }\n }\n \n sb.AppendLine(\")\");\n sb.AppendLine();\n sb.AppendLine(\"foreach ($package in $packages) {\");\n sb.AppendLine(\" Get-AppxPackage -AllUsers -Name $package | \");\n sb.AppendLine(\" ForEach-Object {\");\n sb.AppendLine(\" Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\");\n sb.AppendLine(\" }\");\n sb.AppendLine(\" Get-AppxProvisionedPackage -Online | \");\n sb.AppendLine(\" Where-Object { $_.DisplayName -eq $package } | \");\n sb.AppendLine(\" ForEach-Object {\");\n sb.AppendLine(\" Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\");\n sb.AppendLine(\" }\");\n sb.AppendLine(\"}\");\n sb.AppendLine();\n }\n \n // Add capabilities section\n if (capabilityNames != null && capabilityNames.Any())\n {\n sb.AppendLine(\"# Remove capabilities\");\n sb.AppendLine(\"$capabilities = @(\");\n \n var capabilitiesList = capabilityNames.ToList();\n for (int i = 0; i < capabilitiesList.Count; i++)\n {\n string capability = capabilitiesList[i];\n if (i < capabilitiesList.Count - 1)\n {\n sb.AppendLine($\" '{capability}',\");\n }\n else\n {\n sb.AppendLine($\" '{capability}'\");\n }\n }\n \n sb.AppendLine(\")\");\n sb.AppendLine();\n sb.AppendLine(\"foreach ($capability in $capabilities) {\");\n sb.AppendLine(\" Get-WindowsCapability -Online | Where-Object { $_.Name -like \\\"$capability*\\\" } | Remove-WindowsCapability -Online\");\n sb.AppendLine(\"}\");\n sb.AppendLine();\n }\n \n // Add features section\n if (featureNames != null && featureNames.Any())\n {\n sb.AppendLine(\"# Disable Optional Features\");\n sb.AppendLine(\"$optionalFeatures = @(\");\n \n var featuresList = featureNames.ToList();\n for (int i = 0; i < featuresList.Count; i++)\n {\n string feature = featuresList[i];\n if (i < featuresList.Count - 1)\n {\n sb.AppendLine($\" '{feature}',\");\n }\n else\n {\n sb.AppendLine($\" '{feature}'\");\n }\n }\n \n sb.AppendLine(\")\");\n sb.AppendLine();\n sb.AppendLine(\"foreach ($feature in $optionalFeatures) {\");\n sb.AppendLine(\" Write-Host \\\"Disabling optional feature: $feature\\\" -ForegroundColor Yellow\");\n sb.AppendLine(\" Disable-WindowsOptionalFeature -Online -FeatureName $feature -NoRestart | Out-Null\");\n sb.AppendLine(\"}\");\n sb.AppendLine();\n }\n \n // Add registry settings\n if (registrySettings != null && registrySettings.Any())\n {\n sb.AppendLine(\"# Registry settings\");\n \n foreach (var appEntry in registrySettings)\n {\n string appName = appEntry.Key;\n List settings = appEntry.Value;\n \n if (settings == null || !settings.Any())\n {\n continue;\n }\n \n sb.AppendLine();\n sb.AppendLine($\"# Registry settings for {appName}\");\n \n foreach (var setting in settings)\n {\n string path = setting.Path;\n string name = setting.Name;\n string valueKind = GetRegTypeString(setting.ValueKind);\n string value = setting.Value?.ToString() ?? string.Empty;\n \n // Check if this is a delete operation (value is null or empty)\n bool isDelete = string.IsNullOrEmpty(value);\n string template = _templateProvider.GetRegistrySettingTemplate(isDelete);\n \n if (isDelete)\n {\n sb.AppendLine(string.Format(template, path, name));\n }\n else\n {\n // Format the value based on its type\n string formattedValue = FormatRegistryValue(value, setting.ValueKind);\n sb.AppendLine(string.Format(template, path, name, valueKind, formattedValue));\n }\n }\n }\n \n sb.AppendLine();\n }\n \n // Add script footer\n sb.Append(_templateProvider.GetScriptFooter());\n \n return sb.ToString();\n }\n\n /// \n public string BuildSingleAppRemovalScript(AppInfo app)\n {\n if (app == null)\n {\n throw new ArgumentNullException(nameof(app));\n }\n\n var sb = new StringBuilder();\n \n sb.AppendLine($\"# Removal script for {app.Name} ({app.PackageName})\");\n sb.AppendLine($\"# Generated on {DateTime.Now}\");\n sb.AppendLine();\n sb.AppendLine(\"try {\");\n sb.AppendLine($\" Write-Host \\\"Removing {app.Name}...\\\" -ForegroundColor Yellow\");\n sb.AppendLine();\n \n // Add the appropriate removal command based on the app type\n switch (app.Type)\n {\n case AppType.StandardApp:\n string packageTemplate = _templateProvider.GetPackageRemovalTemplate();\n sb.AppendLine(\" # Remove the app package\");\n sb.AppendLine(\" \" + string.Format(packageTemplate, app.PackageName));\n break;\n \n case AppType.Capability:\n string capabilityTemplate = _templateProvider.GetCapabilityRemovalTemplate();\n sb.AppendLine(\" # Remove the capability\");\n sb.AppendLine(\" \" + string.Format(capabilityTemplate, app.PackageName));\n break;\n \n case AppType.OptionalFeature:\n string featureTemplate = _templateProvider.GetFeatureRemovalTemplate();\n sb.AppendLine(\" # Disable the optional feature\");\n sb.AppendLine(\" \" + string.Format(featureTemplate, app.PackageName));\n break;\n \n default:\n // Default to package removal\n string defaultTemplate = _templateProvider.GetPackageRemovalTemplate();\n sb.AppendLine(\" # Remove the app\");\n sb.AppendLine(\" \" + string.Format(defaultTemplate, app.PackageName));\n break;\n }\n \n sb.AppendLine();\n sb.AppendLine($\" Write-Host \\\"{app.Name} removed successfully.\\\" -ForegroundColor Green\");\n sb.AppendLine(\"} catch {\");\n sb.AppendLine($\" Write-Host \\\"Error removing {app.Name}: $($_.Exception.Message)\\\" -ForegroundColor Red\");\n sb.AppendLine(\"}\");\n \n return sb.ToString();\n }\n\n /// \n /// Formats a registry value based on its type.\n /// \n /// The value to format.\n /// The type of the value.\n /// The formatted value.\n private string FormatRegistryValue(string value, Microsoft.Win32.RegistryValueKind valueKind)\n {\n switch (valueKind)\n {\n case Microsoft.Win32.RegistryValueKind.String:\n case Microsoft.Win32.RegistryValueKind.ExpandString:\n return $\"\\\"{value}\\\"\";\n \n case Microsoft.Win32.RegistryValueKind.DWord:\n case Microsoft.Win32.RegistryValueKind.QWord:\n return value;\n \n case Microsoft.Win32.RegistryValueKind.Binary:\n // Format as hex string\n return value;\n \n case Microsoft.Win32.RegistryValueKind.MultiString:\n // Format as comma-separated string\n return $\"\\\"{value}\\\"\";\n \n default:\n return value;\n }\n }\n\n /// \n /// Converts a RegistryValueKind to the corresponding reg.exe type string.\n /// \n /// The registry value kind.\n /// The reg.exe type string.\n private string GetRegTypeString(Microsoft.Win32.RegistryValueKind valueKind)\n {\n return valueKind switch\n {\n Microsoft.Win32.RegistryValueKind.String => \"SZ\",\n Microsoft.Win32.RegistryValueKind.ExpandString => \"EXPAND_SZ\",\n Microsoft.Win32.RegistryValueKind.Binary => \"BINARY\",\n Microsoft.Win32.RegistryValueKind.DWord => \"DWORD\",\n Microsoft.Win32.RegistryValueKind.MultiString => \"MULTI_SZ\",\n Microsoft.Win32.RegistryValueKind.QWord => \"QWORD\",\n _ => \"SZ\"\n };\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/RemoveActionToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class RemoveActionToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // If the action type is Remove, return Visible, otherwise return Collapsed\n if (value is RegistryActionType actionType)\n {\n return actionType == RegistryActionType.Remove ? Visibility.Visible : Visibility.Collapsed;\n }\n \n return Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// A simple boolean converter that returns the parameter when true, and null when false.\n /// Useful for conditional resource selection.\n /// \n public class BooleanConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool boolValue)\n {\n return boolValue ? parameter : null;\n }\n \n return null;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return value != null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceEnsureKey.cs", "using Microsoft.Win32;\nusing System;\nusing System.Runtime.InteropServices;\nusing System.Security.AccessControl;\nusing System.Security.Principal;\nusing System.Threading.Tasks;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n public partial class RegistryService\n {\n // Windows API imports for registry operations\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int RegOpenKeyEx(IntPtr hKey, string subKey, int ulOptions, int samDesired, out IntPtr hkResult);\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int RegCloseKey(IntPtr hKey);\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int RegGetKeySecurity(IntPtr hKey, int securityInformation, byte[] pSecurityDescriptor, ref int lpcbSecurityDescriptor);\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int RegSetKeySecurity(IntPtr hKey, int securityInformation, byte[] pSecurityDescriptor);\n\n // Constants for Windows API\n private const int KEY_ALL_ACCESS = 0xF003F;\n private const int OWNER_SECURITY_INFORMATION = 0x00000001;\n private const int DACL_SECURITY_INFORMATION = 0x00000004;\n private const int ERROR_SUCCESS = 0;\n\n // Root key handles\n private static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(-2147483647);\n private static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(-2147483646);\n private static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(-2147483648);\n private static readonly IntPtr HKEY_USERS = new IntPtr(-2147483645);\n private static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(-2147483643);\n\n /// \n /// Takes ownership of a registry key and grants full control to the current user.\n /// \n /// The root registry key.\n /// The path to the subkey.\n /// True if ownership was successfully taken, false otherwise.\n private bool TakeOwnershipOfKey(RegistryKey rootKey, string subKeyPath)\n {\n try\n {\n _logService.LogInformation($\"Attempting to take ownership of registry key: {rootKey.Name}\\\\{subKeyPath}\");\n\n // Get the root key handle\n IntPtr hRootKey = GetRootKeyHandle(rootKey);\n if (hRootKey == IntPtr.Zero)\n {\n _logService.LogError(\"Invalid root key handle\");\n return false;\n }\n\n // Open the key with special permissions\n IntPtr hKey;\n int result = RegOpenKeyEx(hRootKey, subKeyPath, 0, KEY_ALL_ACCESS, out hKey);\n if (result != ERROR_SUCCESS)\n {\n _logService.LogError($\"Failed to open registry key for ownership change: {result}\");\n return false;\n }\n\n try\n {\n // Get the current security descriptor\n int securityDescriptorSize = 0;\n RegGetKeySecurity(hKey, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, null, ref securityDescriptorSize);\n byte[] securityDescriptor = new byte[securityDescriptorSize];\n result = RegGetKeySecurity(hKey, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, securityDescriptor, ref securityDescriptorSize);\n if (result != ERROR_SUCCESS)\n {\n _logService.LogError($\"Failed to get registry key security: {result}\");\n return false;\n }\n\n // Create a new security descriptor\n RawSecurityDescriptor rawSD = new RawSecurityDescriptor(securityDescriptor, 0);\n \n // Set the owner to the current user\n WindowsIdentity currentUser = WindowsIdentity.GetCurrent();\n rawSD.Owner = currentUser.User;\n\n // Create a new DACL\n RawAcl rawAcl = rawSD.DiscretionaryAcl != null ?\n rawSD.DiscretionaryAcl :\n new RawAcl(8, 1);\n\n // Add access rules\n // Current user\n if (currentUser.User != null)\n {\n rawAcl.InsertAce(0, new CommonAce(\n AceFlags.None,\n AceQualifier.AccessAllowed,\n (int)RegistryRights.FullControl,\n currentUser.User,\n false,\n null));\n }\n\n // Administrators\n rawAcl.InsertAce(0, new CommonAce(\n AceFlags.None,\n AceQualifier.AccessAllowed,\n (int)RegistryRights.FullControl,\n new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),\n false,\n null));\n\n // SYSTEM\n rawAcl.InsertAce(0, new CommonAce(\n AceFlags.None,\n AceQualifier.AccessAllowed,\n (int)RegistryRights.FullControl,\n new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),\n false,\n null));\n\n // Set the DACL\n rawSD.DiscretionaryAcl = rawAcl;\n\n // Convert back to byte array\n byte[] newSD = new byte[rawSD.BinaryLength];\n rawSD.GetBinaryForm(newSD, 0);\n\n // Set the new security descriptor\n result = RegSetKeySecurity(hKey, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, newSD);\n if (result != ERROR_SUCCESS)\n {\n _logService.LogError($\"Failed to set registry key security: {result}\");\n return false;\n }\n\n _logService.LogSuccess($\"Successfully took ownership of registry key: {rootKey.Name}\\\\{subKeyPath}\");\n return true;\n }\n finally\n {\n // Close the key\n RegCloseKey(hKey);\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error taking ownership of registry key: {ex.Message}\", ex);\n return false;\n }\n }\n\n /// \n /// Gets the native handle for a root registry key.\n /// \n private IntPtr GetRootKeyHandle(RegistryKey rootKey)\n {\n if (rootKey == Microsoft.Win32.Registry.CurrentUser)\n return HKEY_CURRENT_USER;\n else if (rootKey == Microsoft.Win32.Registry.LocalMachine)\n return HKEY_LOCAL_MACHINE;\n else if (rootKey == Microsoft.Win32.Registry.ClassesRoot)\n return HKEY_CLASSES_ROOT;\n else if (rootKey == Microsoft.Win32.Registry.Users)\n return HKEY_USERS;\n else if (rootKey == Microsoft.Win32.Registry.CurrentConfig)\n return HKEY_CURRENT_CONFIG;\n else\n return IntPtr.Zero;\n }\n\n private RegistryKey? EnsureKeyWithFullAccess(RegistryKey rootKey, string subKeyPath)\n {\n try\n {\n // Try to open existing key first\n RegistryKey? key = rootKey.OpenSubKey(subKeyPath, true);\n \n if (key != null)\n {\n return key; // Key exists and we got write access\n }\n \n // Check if the key exists but we don't have access\n RegistryKey? readOnlyKey = rootKey.OpenSubKey(subKeyPath, false);\n if (readOnlyKey != null)\n {\n // Key exists but we don't have write access, try to take ownership\n readOnlyKey.Close();\n _logService.LogInformation($\"Registry key exists but we don't have write access: {rootKey.Name}\\\\{subKeyPath}\");\n \n // Try to take ownership of the key\n bool ownershipTaken = TakeOwnershipOfKey(rootKey, subKeyPath);\n if (ownershipTaken)\n {\n // Try to open the key again with write access\n key = rootKey.OpenSubKey(subKeyPath, true);\n if (key != null)\n {\n _logService.LogSuccess($\"Successfully opened registry key after taking ownership: {rootKey.Name}\\\\{subKeyPath}\");\n return key;\n }\n }\n \n _logService.LogWarning($\"Failed to get write access to registry key even after taking ownership: {rootKey.Name}\\\\{subKeyPath}\");\n }\n \n // Key doesn't exist or we couldn't get access - we need to create the entire path\n string[] parts = subKeyPath.Split('\\\\');\n string currentPath = \"\";\n \n for (int i = 0; i < parts.Length; i++)\n {\n string part = parts[i];\n \n if (currentPath == \"\")\n {\n currentPath = part;\n }\n else\n {\n currentPath += \"\\\\\" + part;\n }\n \n // Try to open this part of the path\n key = rootKey.OpenSubKey(currentPath, true);\n \n if (key == null)\n {\n // This part doesn't exist, create it with full rights\n RegistrySecurity security = new RegistrySecurity();\n \n // Get current user security identifier - handle null case\n var currentUser = WindowsIdentity.GetCurrent().User;\n if (currentUser != null)\n {\n // Add current user with full control\n security.AddAccessRule(new RegistryAccessRule(\n currentUser,\n RegistryRights.FullControl,\n InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,\n PropagationFlags.None,\n AccessControlType.Allow));\n }\n \n // Add Administrators with full control\n security.AddAccessRule(new RegistryAccessRule(\n new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),\n RegistryRights.FullControl,\n InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,\n PropagationFlags.None,\n AccessControlType.Allow));\n \n // Add SYSTEM with full control\n security.AddAccessRule(new RegistryAccessRule(\n new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),\n RegistryRights.FullControl,\n InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,\n PropagationFlags.None,\n AccessControlType.Allow));\n \n // Create the key with explicit security settings\n key = rootKey.CreateSubKey(currentPath, RegistryKeyPermissionCheck.ReadWriteSubTree, security);\n \n if (key == null)\n {\n _logService.LogError($\"Failed to create registry key: {currentPath}\");\n return null;\n }\n \n // Close intermediate keys to avoid leaks\n if (i < parts.Length - 1)\n {\n key.Close();\n key = null;\n }\n }\n else if (i < parts.Length - 1)\n {\n // Close intermediate keys to avoid leaks\n key.Close();\n key = null;\n }\n }\n \n // At this point, 'key' should be the full path key we wanted to create\n // If it's null, open the full path explicitly\n if (key == null)\n {\n key = rootKey.OpenSubKey(subKeyPath, true);\n }\n \n return key;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error ensuring registry key with full access: {subKeyPath}\", ex);\n return null;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/AppliedStatusToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n public class AppliedStatusToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // If the status is Applied, return Visible, otherwise return Collapsed\n if (value is RegistrySettingStatus status)\n {\n return status == RegistrySettingStatus.Applied ? Visibility.Visible : Visibility.Collapsed;\n }\n \n return Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/ExternalAppsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.SoftwareApps.Models;\nusing ToastType = Winhance.Core.Features.UI.Interfaces.ToastType;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n public partial class ExternalAppsViewModel : BaseInstallationViewModel\n {\n [ObservableProperty]\n private bool _isInitialized = false;\n\n private readonly IAppInstallationService _appInstallationService;\n private readonly IAppService _appDiscoveryService;\n private readonly IConfigurationService _configurationService;\n\n [ObservableProperty]\n private string _statusText = \"Ready\";\n\n // ObservableCollection to store category view models\n private ObservableCollection _categories = new();\n\n // Public property to expose the categories\n public ObservableCollection Categories => _categories;\n\n public ExternalAppsViewModel(\n ITaskProgressService progressService,\n ISearchService searchService,\n IPackageManager packageManager,\n IAppInstallationService appInstallationService,\n IAppService appDiscoveryService,\n IConfigurationService configurationService,\n Services.SoftwareAppsDialogService dialogService,\n IInternetConnectivityService connectivityService,\n IAppInstallationCoordinatorService appInstallationCoordinatorService\n )\n : base(\n progressService,\n searchService,\n packageManager,\n appInstallationService,\n appInstallationCoordinatorService,\n connectivityService,\n dialogService\n )\n {\n _appInstallationService = appInstallationService;\n _appDiscoveryService = appDiscoveryService;\n _configurationService = configurationService;\n }\n\n // SaveConfig and ImportConfig methods removed as part of unified configuration cleanup\n\n /// \n /// Applies the current search text to filter items.\n /// \n protected override void ApplySearch()\n {\n if (Items == null || Items.Count == 0)\n return;\n\n // Filter items based on search text\n var filteredItems = FilterItems(Items);\n\n // Clear all categories\n foreach (var category in Categories)\n {\n category.Apps.Clear();\n }\n\n // Group filtered items by category\n var appsByCategory = new Dictionary>();\n\n foreach (var app in filteredItems)\n {\n string category = app.Category;\n if (string.IsNullOrEmpty(category))\n {\n category = \"Other\";\n }\n\n if (!appsByCategory.ContainsKey(category))\n {\n appsByCategory[category] = new List();\n }\n\n appsByCategory[category].Add(app);\n }\n\n // Update categories with filtered items\n foreach (var category in Categories)\n {\n if (appsByCategory.TryGetValue(category.Name, out var apps))\n {\n // Sort apps alphabetically within the category\n var sortedApps = apps.OrderBy(a => a.Name);\n\n foreach (var app in sortedApps)\n {\n category.Apps.Add(app);\n }\n }\n }\n\n // Hide empty categories if search is active\n if (IsSearchActive)\n {\n foreach (var category in Categories)\n {\n category.IsExpanded = category.Apps.Count > 0;\n }\n }\n }\n\n public override async Task LoadItemsAsync()\n {\n if (_packageManager == null)\n return;\n\n IsLoading = true;\n StatusText = \"Loading external apps...\";\n\n try\n {\n Items.Clear();\n _categories.Clear();\n\n var apps = await _packageManager.GetInstallableAppsAsync();\n\n // Group apps by category\n var appsByCategory = new Dictionary>();\n\n foreach (var app in apps)\n {\n var externalApp = ExternalApp.FromAppInfo(app);\n Items.Add(externalApp);\n\n // Group by category\n string category = app.Category;\n if (string.IsNullOrEmpty(category))\n {\n category = \"Other\";\n }\n\n if (!appsByCategory.ContainsKey(category))\n {\n appsByCategory[category] = new List();\n }\n\n appsByCategory[category].Add(externalApp);\n }\n\n // Sort categories alphabetically\n var sortedCategories = appsByCategory.Keys.OrderBy(c => c).ToList();\n\n // Create category view models with sorted apps\n foreach (var categoryName in sortedCategories)\n {\n // Sort apps alphabetically within the category\n var sortedApps = appsByCategory[categoryName].OrderBy(a => a.Name).ToList();\n\n // Create observable collection for the category\n var appsCollection = new ObservableCollection(sortedApps);\n\n // Create and add the category view model\n _categories.Add(\n new ExternalAppsCategoryViewModel(categoryName, appsCollection)\n );\n }\n\n StatusText = $\"Loaded {Items.Count} external apps\";\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error loading external apps: {ex.Message}\";\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n public override async Task CheckInstallationStatusAsync()\n {\n if (_appDiscoveryService == null)\n return;\n\n IsLoading = true;\n StatusText = \"Checking installation status...\";\n\n try\n {\n var statusResults = await _appDiscoveryService.GetBatchInstallStatusAsync(\n Items.Select(a => a.PackageName)\n );\n\n foreach (var app in Items)\n {\n if (statusResults.TryGetValue(app.PackageName, out bool isInstalled))\n {\n app.IsInstalled = isInstalled;\n }\n }\n StatusText = \"Installation status check complete\";\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error checking installation status: {ex.Message}\";\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n [RelayCommand]\n public async Task InstallApp(ExternalApp app)\n {\n if (app == null || _appInstallationService == null)\n return;\n\n // Check for internet connectivity before starting installation\n bool isInternetConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(true);\n if (!isInternetConnected)\n {\n StatusText = \"No internet connection available. Installation cannot proceed.\";\n\n // Show dialog informing the user about the connectivity issue\n await ShowNoInternetConnectionDialogAsync();\n return;\n }\n\n IsLoading = true;\n StatusText = $\"Installing {app.Name}...\";\n\n // Setup cancellation for the installation process\n using var cts = new System.Threading.CancellationTokenSource();\n var cancellationToken = cts.Token;\n\n // Start a background task to periodically check internet connectivity during installation\n var connectivityCheckTask = StartPeriodicConnectivityCheck(app.Name, cts);\n\n try\n {\n var progress = _progressService.CreateDetailedProgress();\n\n try\n {\n var operationResult = await _appInstallationService.InstallAppAsync(\n app.ToAppInfo(),\n progress,\n cancellationToken\n );\n\n // Cancel the connectivity check task as installation is complete\n cts.Cancel();\n\n // Wait for the connectivity check task to complete\n try\n {\n await connectivityCheckTask;\n }\n catch (OperationCanceledException)\n { /* Expected when we cancel */\n }\n\n if (operationResult.Success)\n {\n app.IsInstalled = true;\n StatusText = $\"Successfully installed {app.Name}\";\n\n // Show success dialog\n _dialogService.ShowInformationAsync(\n \"Installation Complete\",\n $\"{app.Name} was successfully installed.\",\n new[] { app.Name },\n \"The application has been installed successfully.\"\n );\n }\n else\n {\n string errorMessage =\n operationResult.ErrorMessage\n ?? $\"Failed to install {app.Name}. Please try again.\";\n StatusText = errorMessage;\n\n // Store the error message for later reference\n app.LastOperationError = errorMessage;\n\n // Show error dialog\n _dialogService.ShowInformationAsync(\n \"Installation Failed\",\n $\"Failed to install {app.Name}.\",\n new[] { $\"{app.Name}: {errorMessage}\" },\n \"There was an error during installation. Please try again later.\"\n );\n }\n }\n catch (OperationCanceledException)\n {\n // Set cancellation reason to UserCancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n \n // Cancel the connectivity check task\n cts.Cancel();\n\n // Wait for the connectivity check task to complete\n try\n {\n await connectivityCheckTask;\n }\n catch (OperationCanceledException)\n { /* Expected when we cancel */\n }\n \n // For single app installations, use the ShowCancellationDialogAsync method directly\n // which will use CustomDialog with a simpler message\n await ShowCancellationDialogAsync(true, false); // User-initiated cancellation\n \n // Reset cancellation reason after showing dialog\n CurrentCancellationReason = CancellationReason.None;\n \n StatusText = $\"Installation of {app.Name} was cancelled\";\n }\n catch (System.Exception ex)\n {\n // Cancel the connectivity check task\n cts.Cancel();\n\n // Wait for the connectivity check task to complete\n try\n {\n await connectivityCheckTask;\n }\n catch (OperationCanceledException)\n { /* Expected when we cancel */\n }\n\n // Check if the exception is related to internet connectivity\n bool isConnectivityIssue =\n ex.Message.Contains(\"internet\", StringComparison.OrdinalIgnoreCase)\n || ex.Message.Contains(\"connection\", StringComparison.OrdinalIgnoreCase)\n || ex.Message.Contains(\"network\", StringComparison.OrdinalIgnoreCase)\n || ex.Message.Contains(\"pipeline has been stopped\", StringComparison.OrdinalIgnoreCase);\n\n if (isConnectivityIssue && CurrentCancellationReason == CancellationReason.None)\n {\n // Use the centralized cancellation handling for connectivity issues\n await HandleCancellationAsync(true); // Connectivity-related cancellation\n }\n \n string errorMessage = isConnectivityIssue\n ? \"Internet connection lost during installation. Please check your network connection and try again.\"\n : ex.Message;\n\n // Store the error message for later reference\n app.LastOperationError = errorMessage;\n\n StatusText = $\"Error installing {app.Name}: {errorMessage}\";\n\n // Only show error dialog if it's not a connectivity issue (which is already handled by HandleCancellationAsync)\n if (!isConnectivityIssue)\n {\n _dialogService.ShowInformationAsync(\n \"Installation Failed\",\n $\"Failed to install {app.Name}.\",\n new[] { $\"{app.Name}: {errorMessage}\" },\n \"There was an error during installation. Please try again later.\"\n );\n }\n }\n }\n catch (System.Exception ex)\n {\n // This is a fallback catch-all to ensure the application doesn't crash\n // Cancel the connectivity check task\n cts.Cancel();\n\n // Wait for the connectivity check task to complete\n try\n {\n await connectivityCheckTask;\n }\n catch (OperationCanceledException)\n { /* Expected when we cancel */\n }\n\n // Store the error message for later reference\n app.LastOperationError = ex.Message;\n\n StatusText = $\"Error installing {app.Name}: {ex.Message}\";\n\n // Show error dialog\n _dialogService.ShowInformationAsync(\n \"Installation Failed\",\n $\"Failed to install {app.Name}.\",\n new[] { $\"{app.Name}: {ex.Message}\" },\n \"There was an error during installation. Please try again later.\"\n );\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Starts a periodic check for internet connectivity during installation.\n /// \n /// The name of the app being installed\n /// Cancellation token source to cancel the task\n /// A task that completes when the installation is done or cancelled\n private async Task StartPeriodicConnectivityCheck(\n string appName,\n System.Threading.CancellationTokenSource cts\n )\n {\n try\n {\n // Check connectivity every 5 seconds during installation\n while (!cts.Token.IsCancellationRequested)\n {\n await Task.Delay(5000, cts.Token); // 5 seconds delay between checks\n\n if (cts.Token.IsCancellationRequested)\n break;\n\n bool isConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(\n false,\n cts.Token\n );\n\n if (!isConnected)\n {\n // Only set connectivity loss if no other cancellation reason is set\n if (CurrentCancellationReason == CancellationReason.None)\n {\n // Update status to inform user about connectivity issue\n StatusText =\n $\"Error: Internet connection lost while installing {appName}. Installation stopped.\";\n\n // Show a non-blocking toast notification\n if (_packageManager.NotificationService != null)\n {\n _packageManager.NotificationService.ShowToast(\n \"Internet Connection Lost\",\n \"Internet connection has been lost during installation. Installation has been stopped.\",\n ToastType.Error\n );\n }\n\n // Use the centralized cancellation handling instead of showing dialog directly\n await HandleCancellationAsync(true); // Connectivity-related cancellation\n }\n \n // Cancel the installation process\n cts.Cancel();\n break;\n }\n }\n }\n catch (OperationCanceledException)\n {\n // Task was cancelled, which is expected when installation completes or is stopped\n }\n catch (Exception ex)\n {\n // Log any unexpected errors but don't disrupt the installation process\n System.Diagnostics.Debug.WriteLine($\"Error in connectivity check: {ex.Message}\");\n }\n }\n\n [RelayCommand]\n public void ClearSelectedItems()\n {\n // Clear all selected items\n foreach (var app in Items)\n {\n app.IsSelected = false;\n }\n\n // Update the UI for all categories\n foreach (var category in Categories)\n {\n foreach (var app in category.Apps)\n {\n app.IsSelected = false;\n }\n }\n\n StatusText = \"All selections cleared\";\n }\n\n [RelayCommand]\n public async Task InstallApps()\n {\n if (_appInstallationService == null)\n return;\n\n // Get all selected apps regardless of installation status\n var selectedApps = Items.Where(a => a.IsSelected).ToList();\n\n if (!selectedApps.Any())\n {\n StatusText = \"No apps selected for installation\";\n await ShowNoItemsSelectedDialogAsync(\"installation\");\n return;\n }\n\n // Check for internet connectivity before starting batch installation\n bool isInternetConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(true);\n if (!isInternetConnected)\n {\n StatusText = \"No internet connection available. Installation cannot proceed.\";\n\n // Show dialog informing the user about the connectivity issue\n await ShowNoInternetConnectionDialogAsync();\n return;\n }\n\n // Show confirmation dialog\n bool? dialogResult = await ShowConfirmItemsDialogAsync(\n \"install\",\n selectedApps.Select(a => a.Name),\n selectedApps.Count\n );\n\n // If user didn't confirm, exit\n if (dialogResult != true)\n {\n return;\n }\n\n // Setup cancellation for the installation process\n using var cts = new System.Threading.CancellationTokenSource();\n\n // Start a background task to periodically check internet connectivity during installation\n var connectivityCheckTask = StartBatchConnectivityCheck(cts);\n\n // Use the ExecuteWithProgressAsync method from BaseViewModel to handle progress reporting\n await ExecuteWithProgressAsync(\n async (progress, cancellationToken) =>\n {\n int successCount = 0;\n int currentItem = 0;\n int totalSelected = selectedApps.Count;\n\n foreach (var app in selectedApps)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n await HandleCancellationAsync(false); // User-initiated cancellation\n cts.Cancel(); // Ensure all tasks are cancelled\n return successCount; // Exit the method immediately\n }\n\n try\n {\n var operationResult = await _appInstallationService.InstallAppAsync(\n app.ToAppInfo(),\n progress,\n cancellationToken\n );\n\n if (operationResult.Success)\n {\n app.IsInstalled = true;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Successfully installed {app.Name}\",\n DetailedMessage = $\"Successfully installed app: {app.Name}\",\n LogLevel = LogLevel.Success,\n AdditionalInfo = new Dictionary\n {\n { \"AppName\", app.Name },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Install\" },\n { \"OperationStatus\", \"Success\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n else\n {\n string errorMessage =\n operationResult.ErrorMessage ?? $\"Failed to install {app.Name}\";\n\n // Store the error message for later reference\n app.LastOperationError = errorMessage;\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Error installing {app.Name}\",\n DetailedMessage = errorMessage,\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppName\", app.Name },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Install\" },\n { \"OperationStatus\", \"Error\" },\n { \"ErrorMessage\", errorMessage },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n catch (OperationCanceledException)\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Installation of {app.Name} was cancelled\",\n DetailedMessage =\n $\"The installation of {app.Name} was cancelled.\",\n LogLevel = LogLevel.Warning,\n AdditionalInfo = new Dictionary\n {\n { \"AppName\", app.Name },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Install\" },\n { \"OperationStatus\", \"Cancelled\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n\n // Use the centralized cancellation handling\n await HandleCancellationAsync(false); // User-initiated cancellation\n cts.Cancel();\n return successCount; // Exit the method immediately\n }\n catch (System.Exception ex)\n {\n // Check if the exception is related to internet connectivity\n bool isConnectivityIssue =\n ex.Message.Contains(\"internet\", StringComparison.OrdinalIgnoreCase) ||\n ex.Message.Contains(\"connection\", StringComparison.OrdinalIgnoreCase) ||\n ex.Message.Contains(\"network\", StringComparison.OrdinalIgnoreCase) ||\n ex.Message.Contains(\"pipeline has been stopped\", StringComparison.OrdinalIgnoreCase);\n\n if (isConnectivityIssue && CurrentCancellationReason == CancellationReason.None)\n {\n // Set the cancellation reason to connectivity issue\n await HandleCancellationAsync(true); // Connectivity-related cancellation\n }\n \n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Error installing {app.Name}\",\n DetailedMessage = $\"Error installing {app.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppName\", app.Name },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Install\" },\n { \"OperationStatus\", \"Error\" },\n { \"ErrorMessage\", ex.Message },\n { \"ErrorType\", ex.GetType().Name },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n { \"IsConnectivityIssue\", isConnectivityIssue.ToString() },\n },\n }\n );\n }\n }\n\n // Cancel the connectivity check task as installation is complete\n cts.Cancel();\n\n // Wait for the connectivity check task to complete\n try\n {\n await connectivityCheckTask;\n }\n catch (OperationCanceledException)\n { /* Expected when we cancel */\n }\n\n // Only proceed with normal completion reporting if not cancelled\n // Final report\n // Check if any failures were due to internet connectivity issues\n bool hasInternetIssues = selectedApps.Any(a =>\n !a.IsInstalled\n && (\n a.LastOperationError?.Contains(\"Internet connection\") == true\n || a.LastOperationError?.Contains(\"No internet\") == true\n )\n );\n\n string statusText =\n successCount == totalSelected\n ? $\"Successfully installed {successCount} of {totalSelected} apps\"\n : hasInternetIssues ? $\"Installation incomplete: Internet connection issues\"\n : $\"Installation incomplete: {successCount} of {totalSelected} apps installed\";\n\n string detailedMessage =\n successCount == totalSelected\n ? $\"Task completed: {successCount} of {totalSelected} apps installed successfully\"\n : hasInternetIssues\n ? $\"Task not completed: {successCount} of {totalSelected} apps installed. Installation failed due to internet connection issues\"\n : $\"Task completed: {successCount} of {totalSelected} apps installed successfully\";\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = statusText,\n DetailedMessage = detailedMessage,\n LogLevel =\n successCount == totalSelected ? LogLevel.Success : LogLevel.Warning,\n AdditionalInfo = new Dictionary\n {\n { \"OperationType\", \"Install\" },\n {\n \"OperationStatus\",\n successCount == totalSelected ? \"Complete\" : \"PartialSuccess\"\n },\n { \"SuccessCount\", successCount.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n { \"SuccessRate\", $\"{(successCount * 100.0 / totalSelected):F1}%\" },\n { \"CompletionTime\", DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\") },\n },\n }\n );\n\n // For normal completion (not cancelled), collect success and failure information\n var successItems = new List();\n var failedItems = new List();\n\n // Add successful items to the list\n foreach (var app in selectedApps.Where(a => a.IsInstalled))\n {\n successItems.Add(app.Name);\n }\n\n // Add failed items to the list\n foreach (var app in selectedApps.Where(a => !a.IsInstalled))\n {\n failedItems.Add(app.Name);\n }\n\n // Check if any failures are due to internet connectivity issues\n bool hasConnectivityIssues = hasInternetIssues;\n bool isFailure = successCount < totalSelected;\n \n // Important: Check if the operation was cancelled by the user\n // This ensures we show the correct dialog even if the cancellation happened in a different part of the code\n if (failedItems != null && failedItems.Any(item => item.Contains(\"cancelled by user\", StringComparison.OrdinalIgnoreCase)))\n {\n // Set the cancellation reason to UserCancelled if it's not already set\n if (CurrentCancellationReason == CancellationReason.None)\n {\n CurrentCancellationReason = CancellationReason.UserCancelled;\n }\n }\n \n // Show result dialog using the base class method which handles cancellation scenarios properly\n ShowOperationResultDialog(\n \"Install\",\n successCount,\n totalSelected,\n successItems,\n failedItems,\n null // no skipped items\n );\n\n return successCount;\n },\n $\"Installing {selectedApps.Count} apps\",\n false\n );\n }\n\n /// \n /// Starts a periodic check for internet connectivity during batch installation.\n /// \n /// Cancellation token source to cancel the task\n /// A task that completes when the installation is done or cancelled\n private async Task StartBatchConnectivityCheck(System.Threading.CancellationTokenSource cts)\n {\n try\n {\n // Check connectivity every 15 seconds during batch installation (reduced frequency)\n while (!cts.Token.IsCancellationRequested)\n {\n await Task.Delay(15000, cts.Token); // 15 seconds delay between checks (increased from 5)\n\n // If cancellation was already requested (e.g., by the user), don't proceed with connectivity check\n if (cts.Token.IsCancellationRequested)\n {\n // Important: Do NOT set cancellation reason here, as it might overwrite UserCancelled\n break;\n }\n\n // Check if user cancellation has already been set\n if (CurrentCancellationReason == CancellationReason.UserCancelled)\n {\n // User already cancelled, don't change the reason\n break;\n }\n\n bool isConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(\n false,\n cts.Token\n );\n\n if (!isConnected)\n {\n // Only set connectivity loss if no other cancellation reason is set\n if (CurrentCancellationReason == CancellationReason.None)\n {\n // Update status to inform user about connectivity issue\n StatusText =\n \"Error: Internet connection lost during installation. Installation stopped.\";\n\n // Show a non-blocking toast notification\n if (_packageManager.NotificationService != null)\n {\n _packageManager.NotificationService.ShowToast(\n \"Internet Connection Lost\",\n \"Internet connection has been lost during installation. Installation has been stopped.\",\n ToastType.Error\n );\n }\n\n // Use the centralized cancellation handling\n await HandleCancellationAsync(true); // Connectivity-related cancellation\n }\n \n cts.Cancel();\n return; // Exit the method immediately\n }\n }\n }\n catch (OperationCanceledException)\n {\n // Task was cancelled, which is expected when installation completes or is stopped\n // Do NOT set cancellation reason here, as it might have been set by the main task\n }\n catch (Exception ex)\n {\n // Log any unexpected errors but don't disrupt the installation process\n System.Diagnostics.Debug.WriteLine(\n $\"Error in batch connectivity check: {ex.Message}\"\n );\n }\n }\n\n public async Task LoadAppsAndCheckInstallationStatusAsync()\n {\n if (IsInitialized)\n {\n System.Diagnostics.Debug.WriteLine(\n \"ExternalAppsViewModel already initialized, skipping LoadAppsAndCheckInstallationStatusAsync\"\n );\n return;\n }\n\n System.Diagnostics.Debug.WriteLine(\n \"Starting ExternalAppsViewModel LoadAppsAndCheckInstallationStatusAsync\"\n );\n await LoadItemsAsync();\n await CheckInstallationStatusAsync();\n\n // Mark as initialized after loading is complete\n IsInitialized = true;\n System.Diagnostics.Debug.WriteLine(\n \"Completed ExternalAppsViewModel LoadAppsAndCheckInstallationStatusAsync\"\n );\n }\n\n public override async void OnNavigatedTo(object parameter)\n {\n try\n {\n // Only load data if not already initialized\n if (!IsInitialized)\n {\n await LoadAppsAndCheckInstallationStatusAsync();\n }\n }\n catch (System.Exception ex)\n {\n // Handle any exceptions\n StatusText = $\"Error loading apps: {ex.Message}\";\n IsLoading = false;\n }\n }\n\n #region BaseInstallationViewModel Abstract Method Implementations\n\n /// \n /// Gets the name of an external app.\n /// \n /// The external app.\n /// The name of the app.\n protected override string GetAppName(ExternalApp app)\n {\n return app.Name;\n }\n\n /// \n /// Converts an external app to an AppInfo object.\n /// \n /// The external app to convert.\n /// The AppInfo object.\n protected override AppInfo ToAppInfo(ExternalApp app)\n {\n return app.ToAppInfo();\n }\n\n /// \n /// Gets the selected external apps.\n /// \n /// The selected external apps.\n protected override IEnumerable GetSelectedApps()\n {\n return Items.Where(a => a.IsSelected);\n }\n\n /// \n /// Sets the installation status of an external app.\n /// \n /// The external app.\n /// Whether the app is installed.\n protected override void SetInstallationStatus(ExternalApp app, bool isInstalled)\n {\n app.IsInstalled = isInstalled;\n }\n\n #endregion\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScriptGenerationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Service for generating and managing removal scripts.\n /// \n public class ScriptGenerationService : IScriptGenerationService\n {\n private readonly ILogService _logService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IAppRemovalService _appRemovalService;\n private readonly IScriptContentModifier _scriptContentModifier;\n private readonly IScriptUpdateService _scriptUpdateService;\n private readonly IScheduledTaskService _scheduledTaskService;\n private readonly IScriptFactory _scriptFactory;\n private readonly IScriptBuilderService _scriptBuilderService;\n private readonly string _scriptsPath;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The app discovery service.\n /// The app removal service.\n /// The script content modifier.\n /// The script update service.\n /// The scheduled task service.\n /// The script factory.\n /// The script builder service.\n public ScriptGenerationService(\n ILogService logService,\n IAppDiscoveryService appDiscoveryService,\n IAppRemovalService appRemovalService,\n IScriptContentModifier scriptContentModifier,\n IScriptUpdateService scriptUpdateService,\n IScheduledTaskService scheduledTaskService,\n IScriptFactory scriptFactory,\n IScriptBuilderService scriptBuilderService\n )\n {\n _logService = logService;\n _appDiscoveryService = appDiscoveryService;\n _appRemovalService = appRemovalService;\n _scriptContentModifier = scriptContentModifier;\n _scriptUpdateService = scriptUpdateService;\n _scheduledTaskService = scheduledTaskService;\n _scriptFactory = scriptFactory;\n _scriptBuilderService = scriptBuilderService;\n\n _scriptsPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n \"Winhance\",\n \"Scripts\"\n );\n Directory.CreateDirectory(_scriptsPath);\n }\n\n /// \n public async Task CreateBatchRemovalScriptAsync(\n List appNames,\n Dictionary> appsWithRegistry\n )\n {\n try\n {\n _logService.LogInformation(\n $\"Creating batch removal script for {appNames.Count} apps\"\n );\n\n // Get all standard apps to check for subpackages\n var allRemovableApps = (await _appDiscoveryService.GetStandardAppsAsync()).ToList();\n\n // Create a dictionary to store subpackages for each app\n var appSubPackages = new Dictionary();\n\n // Find subpackages for each app in the list\n foreach (var appName in appNames)\n {\n var appInfo = allRemovableApps.FirstOrDefault(a => a.PackageName == appName);\n\n // Explicitly handle Copilot and Xbox packages to ensure subpackages are added\n bool isCopilotOrXbox =\n appName.Contains(\"Copilot\", StringComparison.OrdinalIgnoreCase)\n || appName.Contains(\"Xbox\", StringComparison.OrdinalIgnoreCase);\n\n if (\n appInfo?.SubPackages != null\n && (appInfo.SubPackages.Length > 0 || isCopilotOrXbox)\n )\n {\n appSubPackages[appName] = appInfo.SubPackages ?? new string[0];\n }\n\n // If the app has registry settings but they're not in the appsWithRegistry dictionary,\n // add them now\n if (appInfo?.RegistrySettings != null && appInfo.RegistrySettings.Length > 0)\n {\n if (!appsWithRegistry.ContainsKey(appName))\n {\n appsWithRegistry[appName] = appInfo.RegistrySettings.ToList();\n }\n }\n }\n\n // Check if the BloatRemoval.ps1 file already exists\n string bloatRemovalScriptPath = Path.Combine(_scriptsPath, \"BloatRemoval.ps1\");\n if (File.Exists(bloatRemovalScriptPath))\n {\n _logService.LogInformation(\n \"BloatRemoval.ps1 already exists, updating it with new entries\"\n );\n return await _scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n false // false = removal operation, so add to script\n );\n }\n\n // If the file doesn't exist, create a new one using the script factory\n return _scriptFactory.CreateBatchRemovalScript(\n appNames,\n appsWithRegistry,\n appSubPackages\n );\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error creating batch removal script\", ex);\n throw;\n }\n }\n\n /// \n public async Task CreateBatchRemovalScriptAsync(string scriptPath, AppInfo app)\n {\n try\n {\n _logService.LogInformation(\n $\"Creating removal script for {app.PackageName} at {scriptPath}\"\n );\n\n // Use the script builder service to create the script content\n string content = _scriptBuilderService.BuildSingleAppRemovalScript(app);\n\n await File.WriteAllTextAsync(scriptPath, content);\n _logService.LogSuccess(\n $\"Created removal script for {app.PackageName} at {scriptPath}\"\n );\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error creating removal script for {app.PackageName}\", ex);\n return false;\n }\n }\n\n /// \n public async Task RegisterRemovalTaskAsync(RemovalScript script)\n {\n try\n {\n if (script == null)\n {\n _logService.LogError(\"Cannot register removal task: Script is null\");\n return;\n }\n\n _logService.LogInformation($\"Registering removal task for script: {script.Name}\");\n\n // Ensure the script has been saved\n if (string.IsNullOrEmpty(script.Content))\n {\n _logService.LogWarning($\"Script content is empty for: {script.Name}\");\n }\n\n // Register the scheduled task\n bool success = await _scheduledTaskService.RegisterScheduledTaskAsync(script);\n\n if (success)\n {\n _logService.LogSuccess(\n $\"Successfully registered scheduled task for script: {script.Name}\"\n );\n }\n else\n {\n _logService.LogWarning(\n $\"Failed to register scheduled task for script: {script.Name}, but continuing operation\"\n );\n // Don't throw an exception here, just log a warning and continue\n }\n }\n catch (Exception ex)\n {\n _logService.LogError(\n $\"Error registering removal task for script: {script.Name}\",\n ex\n );\n // Don't rethrow the exception, just log it and continue\n }\n }\n\n /// \n public async Task RegisterRemovalTaskAsync(string taskName, string scriptPath)\n {\n try\n {\n if (string.IsNullOrEmpty(taskName) || string.IsNullOrEmpty(scriptPath))\n {\n _logService.LogError(\n $\"Invalid parameters for task registration. TaskName: {taskName}, ScriptPath: {scriptPath}\"\n );\n return false;\n }\n\n _logService.LogInformation(\n $\"Registering removal task: {taskName} for script: {scriptPath}\"\n );\n\n // Check if the script file exists\n if (!File.Exists(scriptPath))\n {\n _logService.LogError($\"Script file not found at: {scriptPath}\");\n return false;\n }\n\n // Create a RemovalScript object to pass to the scheduled task service\n var script = new RemovalScript\n {\n Name = Path.GetFileNameWithoutExtension(scriptPath),\n Content = await File.ReadAllTextAsync(scriptPath),\n TargetScheduledTaskName = taskName,\n RunOnStartup = true,\n };\n\n // Register the scheduled task\n return await _scheduledTaskService.RegisterScheduledTaskAsync(script);\n }\n catch (Exception ex)\n {\n _logService.LogError(\n $\"Error registering removal task: {taskName} for script: {scriptPath}\",\n ex\n );\n return false;\n }\n }\n\n /// \n public async Task SaveScriptAsync(RemovalScript script)\n {\n try\n {\n string scriptPath = Path.Combine(_scriptsPath, $\"{script.Name}.ps1\");\n await File.WriteAllTextAsync(scriptPath, script.Content);\n _logService.LogInformation($\"Saved script to {scriptPath}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error saving script: {script.Name}\", ex);\n throw;\n }\n }\n\n /// \n public async Task SaveScriptAsync(string scriptPath, string scriptContent)\n {\n try\n {\n await File.WriteAllTextAsync(scriptPath, scriptContent);\n _logService.LogInformation($\"Saved script to {scriptPath}\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error saving script to {scriptPath}\", ex);\n return false;\n }\n }\n\n /// \n public async Task UpdateBloatRemovalScriptForInstalledAppAsync(AppInfo app)\n {\n try\n {\n _logService.LogInformation(\n $\"Updating BloatRemoval script for installed app: {app.PackageName}\"\n );\n\n string bloatRemovalScriptPath = Path.Combine(_scriptsPath, \"BloatRemoval.ps1\");\n if (!File.Exists(bloatRemovalScriptPath))\n {\n _logService.LogWarning(\n $\"BloatRemoval.ps1 not found at {bloatRemovalScriptPath}\"\n );\n return false;\n }\n\n string scriptContent = await File.ReadAllTextAsync(bloatRemovalScriptPath);\n bool scriptModified = false;\n\n // Handle different types of apps\n if (\n app.Type == AppType.OptionalFeature\n || app.PackageName.Equals(\"Recall\", StringComparison.OrdinalIgnoreCase)\n || app.Type == AppType.Capability\n )\n {\n // Handle OptionalFeatures and Capabilities using the ScriptUpdateService\n // This ensures proper handling of install operations (removing from script)\n _logService.LogInformation(\n $\"Using ScriptUpdateService to update BloatRemoval script for {app.Type} {app.PackageName}\"\n );\n\n // Create a list with just this app\n var appNames = new List { app.PackageName };\n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n\n // Get app registry settings if available\n var allRemovableApps = (\n await _appDiscoveryService.GetStandardAppsAsync()\n ).ToList();\n var appDefinition = allRemovableApps.FirstOrDefault(a =>\n a.PackageName.Equals(app.PackageName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (\n appDefinition?.RegistrySettings != null\n && appDefinition.RegistrySettings.Length > 0\n )\n {\n appsWithRegistry[app.PackageName] = appDefinition.RegistrySettings.ToList();\n }\n\n // Update the script with isInstallOperation = true to remove the entry\n await _scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n true // true = install operation, so remove from script\n );\n\n return true;\n }\n else\n {\n // Handle standard package\n scriptContent = _scriptContentModifier.RemovePackageFromScript(\n scriptContent,\n app.PackageName\n );\n\n // Create a list of subpackages to remove\n List subPackagesToRemove = new List();\n\n // Get all standard apps to find the app definition and its subpackages\n var allRemovableApps = (\n await _appDiscoveryService.GetStandardAppsAsync()\n ).ToList();\n\n // Find the app definition that matches the current app\n var appDefinition = allRemovableApps.FirstOrDefault(a =>\n a.PackageName.Equals(app.PackageName, StringComparison.OrdinalIgnoreCase)\n );\n\n // If we found the app definition and it has subpackages, add them to the removal list\n if (appDefinition?.SubPackages != null && appDefinition.SubPackages.Length > 0)\n {\n _logService.LogInformation(\n $\"Found {appDefinition.SubPackages.Length} subpackages for {app.PackageName} in WindowsAppCatalog\"\n );\n subPackagesToRemove.AddRange(appDefinition.SubPackages);\n }\n\n // Remove registry settings for this app from the script\n scriptContent = _scriptContentModifier.RemoveAppRegistrySettingsFromScript(\n scriptContent,\n app.PackageName\n );\n\n // Apply registry settings to delete registry keys from the system\n if (\n appDefinition?.RegistrySettings != null\n && appDefinition.RegistrySettings.Length > 0\n )\n {\n _logService.LogInformation(\n $\"Found {appDefinition.RegistrySettings.Length} registry settings for {app.PackageName}\"\n );\n\n // Create a list of registry settings that delete the keys\n var deleteRegistrySettings = new List();\n\n foreach (var setting in appDefinition.RegistrySettings)\n {\n // Create a new registry setting that deletes the key\n var deleteSetting = new AppRegistrySetting\n {\n Path = setting.Path,\n Name = setting.Name,\n Value = null, // null value means delete the key\n ValueKind = setting.ValueKind,\n };\n\n deleteRegistrySettings.Add(deleteSetting);\n }\n\n // Apply the registry settings to delete the keys\n // TODO: ApplyRegistrySettingsAsync is not on IAppRemovalService.\n // Need to inject IRegistryService or move this logic. Commenting out for now.\n _logService.LogInformation(\n $\"Applying {deleteRegistrySettings.Count} registry settings to delete keys for {app.PackageName}\"\n );\n // var success = await _appRemovalService.ApplyRegistrySettingsAsync(\n // deleteRegistrySettings\n // );\n var success = false; // Assume failure for now as the call is removed\n _logService.LogWarning(\n $\"Skipping registry key deletion for {app.PackageName} as ApplyRegistrySettingsAsync is not available on the interface.\"\n );\n\n if (success) // This block will likely not be hit now\n {\n _logService.LogSuccess(\n $\"Successfully deleted registry keys for {app.PackageName}\"\n );\n }\n else\n {\n _logService.LogWarning(\n $\"Failed to delete some registry keys for {app.PackageName}\"\n );\n }\n }\n\n // Remove all subpackages from the script\n foreach (var subPackage in subPackagesToRemove)\n {\n _logService.LogInformation(\n $\"Removing subpackage: {subPackage} for app: {app.PackageName}\"\n );\n scriptContent = _scriptContentModifier.RemovePackageFromScript(\n scriptContent,\n subPackage\n );\n }\n\n scriptModified = true;\n }\n\n // Save the updated script if it was modified\n if (scriptModified)\n {\n await File.WriteAllTextAsync(bloatRemovalScriptPath, scriptContent);\n _logService.LogSuccess(\n $\"Successfully updated BloatRemoval script for app: {app.PackageName}\"\n );\n }\n else\n {\n _logService.LogInformation(\n $\"No changes needed to BloatRemoval script for app: {app.PackageName}\"\n );\n }\n\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError(\n $\"Error updating BloatRemoval script for app: {app.PackageName}\",\n ex\n );\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Utilities/WinGetInstallationScript.cs", "using System;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Management.Automation;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Utilities\n{\n /// \n /// Provides functionality to install WinGet when it is not found on the system.\n /// \n public static class WinGetInstallationScript\n {\n /// \n /// The PowerShell script used to install WinGet by downloading it directly from GitHub.\n /// \n public static readonly string InstallScript =\n @\"\n# PowerShell script to install WinGet from GitHub\nWrite-Output \"\"Starting WinGet installation process... [PROGRESS:25]\"\"\n\n# Create a temporary directory for downloads\n$tempDir = Join-Path $env:TEMP \"\"WinGetInstall\"\"\nif (Test-Path $tempDir) {\n Remove-Item -Path $tempDir -Recurse -Force\n}\nNew-Item -Path $tempDir -ItemType Directory -Force | Out-Null\n\ntry {\n # Download URLs\n $dependenciesUrl = \"\"https://github.com/microsoft/winget-cli/releases/latest/download/DesktopAppInstaller_Dependencies.zip\"\"\n $installerUrl = \"\"https://github.com/microsoft/winget-cli/releases/latest/download/Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle\"\"\n $licenseUrl = \"\"https://github.com/microsoft/winget-cli/releases/latest/download/e53e159d00e04f729cc2180cffd1c02e_License1.xml\"\"\n \n # Download paths\n $dependenciesPath = Join-Path $tempDir \"\"DesktopAppInstaller_Dependencies.zip\"\"\n $installerPath = Join-Path $tempDir \"\"Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle\"\"\n $licensePath = Join-Path $tempDir \"\"e53e159d00e04f729cc2180cffd1c02e_License1.xml\"\"\n \n # Download the dependencies\n Write-Output \"\"Downloading WinGet dependencies... [PROGRESS:30]\"\"\n Invoke-WebRequest -Uri $dependenciesUrl -OutFile $dependenciesPath -UseBasicParsing\n \n # Download the installer\n Write-Output \"\"Downloading WinGet installer... [PROGRESS:40]\"\"\n Invoke-WebRequest -Uri $installerUrl -OutFile $installerPath -UseBasicParsing\n \n # Download the license file (needed for LTSC editions)\n Write-Output \"\"Downloading WinGet license file... [PROGRESS:45]\"\"\n Invoke-WebRequest -Uri $licenseUrl -OutFile $licensePath -UseBasicParsing\n \n # Extract the dependencies\n Write-Output \"\"Extracting dependencies... [PROGRESS:50]\"\"\n $extractPath = Join-Path $tempDir \"\"Dependencies\"\"\n Expand-Archive -Path $dependenciesPath -DestinationPath $extractPath -Force\n \n # Install all dependencies\n Write-Output \"\"Installing dependencies... [PROGRESS:60]\"\"\n $dependencyFiles = Get-ChildItem -Path $extractPath -Filter *.appx -Recurse\n foreach ($file in $dependencyFiles) {\n Write-Output \"\"Installing dependency: $($file.Name)\"\"\n try {\n Add-AppxPackage -Path $file.FullName\n }\n catch {\n Write-Output \"\"[ERROR] Failed to install WinGet: $($_.Exception.Message)\"\"\n throw $_\n }\n }\n \n # Install the WinGet installer\n Write-Output \"\"Installing WinGet... [PROGRESS:80]\"\"\n try {\n # Always use Add-AppxProvisionedPackage with license for all Windows editions\n Write-Output \"\"Installing WinGet with license file\"\"\n Add-AppxProvisionedPackage -Online -PackagePath $installerPath -LicensePath $licensePath\n Write-Output \"\"WinGet installation completed successfully [PROGRESS:90]\"\"\n \n # Refresh PATH environment variable to include WindowsApps directory where WinGet is installed\n Write-Output \"\"Refreshing PATH environment to include WinGet...\"\"\n $env:Path = [System.Environment]::GetEnvironmentVariable(\"\"Path\"\", \"\"Machine\"\") + \"\";\"\" + [System.Environment]::GetEnvironmentVariable(\"\"Path\"\", \"\"User\"\")\n \n # Verify WinGet installation by running a command\n Write-Output \"\"Verifying WinGet installation...\"\"\n \n # Try to find WinGet in common locations\n $wingetPaths = @(\n \"\"winget.exe\"\", # Check if it's in PATH\n \"\"$env:LOCALAPPDATA\\Microsoft\\WindowsApps\\winget.exe\"\",\n \"\"$env:ProgramFiles\\WindowsApps\\Microsoft.DesktopAppInstaller_*\\winget.exe\"\"\n )\n \n $wingetFound = $false\n foreach ($path in $wingetPaths) {\n if ($path -like \"\"*`**\"\") {\n # Handle wildcard paths\n $resolvedPaths = Resolve-Path $path -ErrorAction SilentlyContinue\n if ($resolvedPaths) {\n foreach ($resolvedPath in $resolvedPaths) {\n if (Test-Path $resolvedPath) {\n Write-Output \"\"Found WinGet at: $resolvedPath\"\"\n $wingetFound = $true\n # Add the directory to PATH if not already there\n $wingetDir = Split-Path $resolvedPath\n if ($env:Path -notlike \"\"*$wingetDir*\"\") {\n $env:Path += \"\";$wingetDir\"\"\n }\n break\n }\n }\n }\n } else {\n # Handle direct paths\n if (Test-Path $path) {\n Write-Output \"\"Found WinGet at: $path\"\"\n $wingetFound = $true\n # Add the directory to PATH if not already there\n $wingetDir = Split-Path $path\n if ($env:Path -notlike \"\"*$wingetDir*\"\") {\n $env:Path += \"\";$wingetDir\"\"\n }\n break\n }\n }\n }\n \n if (-not $wingetFound) {\n # Try running winget command directly to see if it works\n try {\n $wingetVersion = & winget.exe --version 2>&1\n if ($LASTEXITCODE -eq 0) {\n Write-Output \"\"WinGet is available in PATH: $wingetVersion\"\"\n $wingetFound = $true\n }\n } catch {\n Write-Output \"\"WinGet command not found in PATH\"\"\n }\n }\n \n if (-not $wingetFound) {\n Write-Output \"\"[WARNING] WinGet was installed but could not be found in PATH. You may need to restart your system.\"\"\n }\n }\n catch {\n Write-Output \"\"[ERROR] Failed to install WinGet: $($_.Exception.Message)\"\"\n throw $_\n }\n}\ncatch {\n Write-Output \"\"[ERROR] An error occurred during WinGet installation: $($_.Exception.Message)\"\"\n throw $_\n}\nfinally {\n # Clean up\n Write-Output \"\"Cleaning up temporary files... [PROGRESS:95]\"\"\n if (Test-Path $tempDir) {\n Remove-Item -Path $tempDir -Recurse -Force\n }\n Write-Output \"\"WinGet installation process completed [PROGRESS:100]\"\"\n}\n\";\n\n /// \n /// Installs WinGet by downloading it directly from GitHub and installing it.\n /// \n /// Optional progress reporting.\n /// Optional logger for logging the installation process.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with a result indicating success or failure.\n public static async Task<(bool Success, string Message)> InstallWinGetAsync(\n IProgress progress = null,\n ILogService logger = null,\n CancellationToken cancellationToken = default\n )\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 10,\n StatusText = \"Preparing to download WinGet from GitHub...\",\n DetailedMessage =\n \"This may take a few minutes depending on your internet connection.\",\n }\n );\n\n logger?.LogInformation(\"Starting WinGet installation by downloading from GitHub\");\n\n // Create a temporary directory if it doesn't exist\n string tempDir = Path.Combine(Path.GetTempPath(), \"WinhanceTemp\");\n Directory.CreateDirectory(tempDir);\n\n // Create a temporary script file\n string scriptPath = Path.Combine(tempDir, $\"WinGetInstall_{Guid.NewGuid()}.ps1\");\n\n // Write the installation script to the file\n File.WriteAllText(scriptPath, InstallScript);\n\n try\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 20,\n StatusText = \"Downloading and installing WinGet components...\",\n DetailedMessage =\n \"This may take a few minutes depending on your internet connection.\",\n }\n );\n\n // Execute the PowerShell script with elevated privileges\n // Use PowerShellFactory to ensure we get the right PowerShell version based on OS\n // This is especially important for Windows 10 where Add-AppxPackage needs Windows PowerShell 5.1\n // We need to use Windows PowerShell 5.1 on Windows 10 for Add-AppxPackage command\n using (var powerShell = PowerShellFactory.CreateForAppxCommands(logger))\n {\n // Add the script to execute\n powerShell.AddScript($\". '{scriptPath}'\");\n\n // Set up real-time output processing using PowerShell events\n var outputBuilder = new StringBuilder();\n\n // Subscribe to the DataAdded event for Information stream\n powerShell.Streams.Information.DataAdded += (sender, e) =>\n {\n var streamObjectsReceived = sender as PSDataCollection;\n if (streamObjectsReceived != null)\n {\n var informationRecord = streamObjectsReceived[e.Index];\n string output = informationRecord.MessageData.ToString();\n outputBuilder.AppendLine(output);\n logger?.LogInformation($\"WinGet installation: {output}\");\n\n ProcessOutputLine(output, progress, logger);\n }\n };\n\n // Subscribe to the DataAdded event for Output stream\n var outputCollection = new PSDataCollection();\n outputCollection.DataAdded += (sender, e) =>\n {\n var streamObjectsReceived = sender as PSDataCollection;\n if (streamObjectsReceived != null)\n {\n var outputObject = streamObjectsReceived[e.Index];\n string output = outputObject.ToString();\n outputBuilder.AppendLine(output);\n logger?.LogInformation($\"WinGet installation: {output}\");\n\n ProcessOutputLine(output, progress, logger);\n }\n };\n\n // Execute the script asynchronously to capture real-time output\n await Task.Run(\n () => powerShell.Invoke(null, outputCollection),\n cancellationToken\n );\n\n // Helper method to process output lines for progress and error markers\n void ProcessOutputLine(\n string output,\n IProgress progress,\n ILogService logger\n )\n {\n // Check for progress markers in the output\n if (output.Contains(\"[PROGRESS:\"))\n {\n var progressMatch = System.Text.RegularExpressions.Regex.Match(\n output,\n @\"\\[PROGRESS:(\\d+)\\]\"\n );\n if (\n progressMatch.Success\n && int.TryParse(\n progressMatch.Groups[1].Value,\n out int progressValue\n )\n )\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = progressValue,\n StatusText = output.Replace(progressMatch.Value, \"\").Trim(),\n }\n );\n }\n }\n // Check for error markers in the output\n else if (output.Contains(\"[ERROR]\"))\n {\n var errorMessage = output.Replace(\"[ERROR]\", \"\").Trim();\n logger?.LogError($\"WinGet installation error: {errorMessage}\");\n }\n }\n\n // Check for errors\n if (powerShell.HadErrors)\n {\n var errorBuilder = new StringBuilder(\"Errors during WinGet installation:\");\n foreach (var error in powerShell.Streams.Error)\n {\n errorBuilder.AppendLine(error.Exception.Message);\n logger?.LogError(\n $\"WinGet installation error: {error.Exception.Message}\"\n );\n }\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = \"WinGet installation failed\",\n DetailedMessage = errorBuilder.ToString(),\n LogLevel = Winhance.Core.Features.Common.Enums.LogLevel.Error,\n }\n );\n\n return (false, errorBuilder.ToString());\n }\n\n // Report success\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = \"WinGet installation completed successfully\",\n DetailedMessage = \"WinGet has been installed and is ready to use.\",\n }\n );\n\n logger?.LogInformation(\"WinGet installation completed successfully\");\n return (true, \"WinGet has been successfully installed.\");\n }\n }\n catch (Exception ex)\n {\n string errorMessage = $\"Error installing WinGet: {ex.Message}\";\n logger?.LogError(errorMessage, ex);\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = \"WinGet installation failed\",\n DetailedMessage = errorMessage,\n LogLevel = Winhance.Core.Features.Common.Enums.LogLevel.Error,\n }\n );\n\n return (false, errorMessage);\n }\n finally\n {\n // Clean up the temporary script file\n try\n {\n if (File.Exists(scriptPath))\n {\n File.Delete(scriptPath);\n }\n }\n catch (Exception ex)\n {\n logger?.LogWarning($\"Failed to delete temporary script file: {ex.Message}\");\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Models/ApplicationSettingItem.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Services;\nusing Microsoft.Win32;\n\nnamespace Winhance.WPF.Features.Common.Models\n{\n /// \n /// Base class for application setting items used in both Optimization and Customization features.\n /// \n public partial class ApplicationSettingItem : ObservableObject, ISettingItem, ISearchable\n {\n private readonly IRegistryService? _registryService;\n private readonly ICommandService? _commandService;\n private readonly IDialogService? _dialogService;\n private readonly ILogService? _logService;\n private bool _isUpdatingFromCode;\n\n /// \n /// Gets or sets a value indicating whether the IsSelected property is being updated from code.\n /// This is used to prevent automatic application of settings when loading.\n /// \n public bool IsUpdatingFromCode\n {\n get => _isUpdatingFromCode;\n set => _isUpdatingFromCode = value;\n }\n\n [ObservableProperty]\n private string _id = string.Empty;\n\n [ObservableProperty]\n private string _name = string.Empty;\n\n [ObservableProperty]\n private string _fullName = string.Empty;\n\n partial void OnNameChanged(string value) => UpdateFullName();\n\n private void UpdateFullName()\n {\n FullName = Name;\n }\n\n [ObservableProperty]\n private string _description = string.Empty;\n\n [ObservableProperty]\n private bool _isSelected;\n\n partial void OnIsSelectedChanged(bool value)\n {\n // Skip if we're updating from code\n if (IsUpdatingFromCode)\n {\n return;\n }\n\n // Store the current selection state to restore after applying\n bool currentSelection = value;\n\n // Apply the setting when IsSelected changes\n ApplySetting();\n \n // Ensure the toggle stays in the state the user selected\n if (IsSelected != currentSelection)\n {\n IsUpdatingFromCode = true;\n try\n {\n IsSelected = currentSelection;\n }\n finally\n {\n IsUpdatingFromCode = false;\n }\n }\n }\n\n [ObservableProperty]\n private bool _isGroupHeader;\n\n [ObservableProperty]\n private bool _isVisible = true;\n\n [ObservableProperty]\n private string _groupName = string.Empty;\n\n [ObservableProperty]\n private RegistrySettingStatus _status = RegistrySettingStatus.Unknown;\n\n [ObservableProperty]\n private string _statusMessage = string.Empty;\n\n [ObservableProperty]\n private object? _currentValue;\n\n [ObservableProperty]\n private object? _selectedValue;\n\n [ObservableProperty]\n private bool _isRegistryValueNull;\n\n [ObservableProperty]\n private ControlType _controlType = ControlType.BinaryToggle;\n\n [ObservableProperty]\n private int? _sliderSteps;\n\n [ObservableProperty]\n private int _sliderValue;\n\n [ObservableProperty]\n private ObservableCollection _sliderLabels = new();\n\n [ObservableProperty]\n private bool _isApplying;\n\n /// \n /// Gets or sets the registry setting.\n /// \n public RegistrySetting? RegistrySetting { get; set; }\n\n private LinkedRegistrySettings? _linkedRegistrySettings;\n\n /// \n /// Gets or sets the linked registry settings.\n /// \n public LinkedRegistrySettings? LinkedRegistrySettings \n { \n get => _linkedRegistrySettings;\n set\n {\n _linkedRegistrySettings = value;\n \n // Populate LinkedRegistrySettingsWithValues when LinkedRegistrySettings is assigned\n if (value != null && value.Settings.Count > 0)\n {\n LinkedRegistrySettingsWithValues.Clear();\n foreach (var setting in value.Settings)\n {\n LinkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(setting, null));\n }\n }\n }\n }\n\n /// \n /// Gets or sets the linked registry settings with values.\n /// \n public ObservableCollection LinkedRegistrySettingsWithValues { get; set; } = new();\n\n /// \n /// Gets or sets the command settings.\n /// \n public List CommandSettings { get; set; } = new List();\n\n /// \n /// Gets or sets the dependencies between settings.\n /// \n public List Dependencies { get; set; } = new List();\n\n /// \n /// Gets or sets the dropdown options.\n /// \n public ObservableCollection DropdownOptions { get; set; } = new();\n\n /// \n /// Gets or sets the selected dropdown option.\n /// \n [ObservableProperty]\n private string _selectedDropdownOption = string.Empty;\n \n /// \n /// Gets a value indicating whether there are no settings to display.\n /// \n public bool HasNoSettings\n {\n get\n {\n // True if there are no registry settings and no command settings\n bool hasRegistrySettings = RegistrySetting != null || (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0);\n bool hasCommandSettings = CommandSettings != null && CommandSettings.Count > 0;\n \n return !hasRegistrySettings && !hasCommandSettings;\n }\n }\n \n /// \n /// Gets a value indicating whether this setting only has command settings (no registry settings).\n /// \n public bool HasCommandSettingsOnly\n {\n get\n {\n // True if there are command settings but no registry settings\n bool hasRegistrySettings = RegistrySetting != null || (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0);\n bool hasCommandSettings = CommandSettings != null && CommandSettings.Count > 0;\n \n return hasCommandSettings && !hasRegistrySettings;\n }\n }\n\n /// \n /// Gets or sets a value indicating whether this is a grouped setting that contains child settings.\n /// \n public bool IsGroupedSetting { get; set; }\n\n /// \n /// Gets or sets the child settings for a grouped setting.\n /// \n public ObservableCollection ChildSettings { get; set; } = new ObservableCollection();\n\n /// \n /// Gets or sets a dictionary of custom properties.\n /// \n public Dictionary CustomProperties { get; set; } = new Dictionary();\n\n /// \n /// Gets the collection of actions associated with this setting.\n /// \n public List Actions { get; } = new List();\n\n /// \n /// Gets or sets the command to apply the setting.\n /// \n public ICommand ApplySettingCommand { get; private set; }\n\n /// \n /// Gets or sets the command to restore the setting to its default value.\n /// \n public ICommand RestoreDefaultCommand { get; private set; }\n\n /// \n /// Gets or sets a value indicating whether this setting is only for Windows 11.\n /// \n public bool IsWindows11Only { get; set; }\n\n /// \n /// Gets or sets a value indicating whether this setting is only for Windows 10.\n /// \n public bool IsWindows10Only { get; set; }\n\n /// \n /// Gets or sets the setting type.\n /// \n public string SettingType { get; set; } = string.Empty;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public ApplicationSettingItem()\n {\n ApplySettingCommand = new RelayCommand(ApplySetting);\n RestoreDefaultCommand = new RelayCommand(RestoreDefault);\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The registry service.\n /// The dialog service.\n /// The log service.\n /// The command service.\n public ApplicationSettingItem(IRegistryService? registryService, IDialogService? dialogService, ILogService? logService, ICommandService? commandService = null)\n : this()\n {\n _registryService = registryService;\n _dialogService = dialogService;\n _logService = logService;\n _commandService = commandService;\n }\n\n /// \n /// Applies the setting.\n /// \n public async void ApplySetting()\n {\n // Skip if we're updating from code\n if (IsUpdatingFromCode)\n {\n return;\n }\n \n // Apply registry settings if available\n if (_registryService != null)\n {\n ApplyRegistrySettings();\n }\n \n // Apply command settings if available\n if (_commandService != null && CommandSettings.Any())\n {\n await ApplyCommandSettingsAsync();\n }\n }\n \n /// \n /// Applies the registry settings.\n /// \n private void ApplyRegistrySettings()\n {\n if (_registryService == null)\n {\n return;\n }\n\n // Apply the setting\n if (RegistrySetting != null)\n {\n try\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(RegistrySetting.Hive);\n\n // Get the appropriate value based on the toggle state\n object valueToApply = IsSelected \n ? (RegistrySetting.EnabledValue ?? RegistrySetting.RecommendedValue) \n : (RegistrySetting.DisabledValue ?? RegistrySetting.DefaultValue);\n\n // Apply the setting\n _registryService.SetValue(\n $\"{hiveString}\\\\{RegistrySetting.SubKey}\",\n RegistrySetting.Name,\n valueToApply,\n RegistrySetting.ValueType);\n\n // Update the current value and linked registry settings with values\n CurrentValue = valueToApply;\n \n // Update the linked registry settings with values collection\n LinkedRegistrySettingsWithValues.Clear();\n LinkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(RegistrySetting, CurrentValue));\n\n // Update status without changing IsSelected\n Status = IsSelected ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n StatusMessage = Status == RegistrySettingStatus.Applied ? \"Applied\" : \"Not Applied\";\n\n // Log the action\n _logService?.Log(LogLevel.Info, $\"Applied setting {Name}: {(IsSelected ? \"Enabled\" : \"Disabled\")}\");\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Error applying setting {Name}: {ex.Message}\");\n }\n }\n else if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n try\n {\n // Clear the existing values\n LinkedRegistrySettingsWithValues.Clear();\n \n // Apply all linked settings\n foreach (var setting in LinkedRegistrySettings.Settings)\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(setting.Hive);\n\n // Get the appropriate value based on the toggle state\n object valueToApply = IsSelected \n ? (setting.EnabledValue ?? setting.RecommendedValue) \n : (setting.DisabledValue ?? setting.DefaultValue);\n \n // Apply the setting\n _registryService.SetValue(\n $\"{hiveString}\\\\{setting.SubKey}\",\n setting.Name,\n valueToApply,\n setting.ValueType);\n \n // Add to the linked registry settings with values collection\n LinkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(setting, valueToApply));\n }\n\n // Update status without changing IsSelected\n Status = IsSelected ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n StatusMessage = Status == RegistrySettingStatus.Applied ? \"Applied\" : \"Not Applied\";\n\n // Log the action\n _logService?.Log(LogLevel.Info, $\"Applied linked settings for {Name}: {(IsSelected ? \"Enabled\" : \"Disabled\")}\");\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Error applying linked settings for {Name}: {ex.Message}\");\n }\n }\n\n // Don't call RefreshStatus() here to avoid triggering additional registry operations\n }\n \n /// \n /// Applies the command settings.\n /// \n private async Task ApplyCommandSettingsAsync()\n {\n if (_commandService == null || !CommandSettings.Any())\n {\n return;\n }\n \n try\n {\n // Apply the command settings based on the toggle state\n var (success, message) = await _commandService.ApplyCommandSettingsAsync(CommandSettings, IsSelected);\n \n if (success)\n {\n // Update status without changing IsSelected\n Status = IsSelected ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n StatusMessage = Status == RegistrySettingStatus.Applied ? \"Applied\" : \"Not Applied\";\n \n // Log the action\n _logService?.Log(LogLevel.Info, $\"Applied command settings for {Name}: {(IsSelected ? \"Enabled\" : \"Disabled\")}\");\n }\n else\n {\n // Log the error\n _logService?.Log(LogLevel.Error, $\"Error applying command settings for {Name}: {message}\");\n }\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Exception applying command settings for {Name}: {ex.Message}\");\n }\n }\n\n /// \n /// Restores the setting to its default value.\n /// \n public void RestoreDefault()\n {\n if (_registryService == null)\n {\n return;\n }\n\n // Skip if we're updating from code\n if (IsUpdatingFromCode)\n {\n return;\n }\n\n // Restore the setting to its default value\n if (RegistrySetting != null)\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(RegistrySetting.Hive);\n\n // Apply the setting\n _registryService.SetValue(\n $\"{hiveString}\\\\{RegistrySetting.SubKey}\",\n RegistrySetting.Name,\n RegistrySetting.DefaultValue,\n RegistrySetting.ValueType);\n\n // Log the action\n _logService?.Log(LogLevel.Info, $\"Restored setting {Name} to default value\");\n }\n else if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n // Apply all linked settings\n foreach (var setting in LinkedRegistrySettings.Settings)\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(setting.Hive);\n\n // Apply the setting\n _registryService.SetValue(\n $\"{hiveString}\\\\{setting.SubKey}\",\n setting.Name,\n setting.DefaultValue,\n setting.ValueType);\n }\n\n // Log the action\n _logService?.Log(LogLevel.Info, $\"Restored linked settings for {Name} to default values\");\n }\n\n // Update IsSelected based on status\n IsUpdatingFromCode = true;\n try\n {\n IsSelected = Status == RegistrySettingStatus.Applied;\n }\n finally\n {\n IsUpdatingFromCode = false;\n }\n\n // Refresh the status\n _ = RefreshStatus();\n }\n \n /// \n /// Refreshes the status of command settings.\n /// \n /// A task representing the asynchronous operation.\n private async Task RefreshCommandSettingsStatusAsync()\n {\n if (_commandService == null || !CommandSettings.Any())\n {\n return;\n }\n \n try\n {\n // For now, we'll assume command settings are not applied by default\n // In the future, this could be enhanced to check the actual system state\n bool isEnabled = false;\n \n // If there are primary command settings, check their status\n var primarySetting = CommandSettings.FirstOrDefault(s => s.IsPrimary);\n if (primarySetting != null)\n {\n isEnabled = await _commandService.IsCommandSettingEnabledAsync(primarySetting);\n }\n \n // Update status\n Status = isEnabled ? RegistrySettingStatus.Applied : RegistrySettingStatus.NotApplied;\n StatusMessage = Status == RegistrySettingStatus.Applied ? \"Applied\" : \"Not Applied\";\n \n // Update IsSelected based on status\n IsUpdatingFromCode = true;\n try\n {\n IsSelected = Status == RegistrySettingStatus.Applied;\n }\n finally\n {\n IsUpdatingFromCode = false;\n }\n }\n catch (Exception ex)\n {\n _logService?.Log(LogLevel.Error, $\"Error refreshing command settings status for {Name}: {ex.Message}\");\n }\n }\n\n /// \n /// Refreshes the status of the setting.\n /// \n /// A task representing the asynchronous operation.\n public async Task RefreshStatus()\n {\n // Refresh registry settings status if available\n if (_registryService != null)\n {\n await RefreshRegistrySettingsStatusAsync();\n }\n \n // Refresh command settings status if available\n if (_commandService != null && CommandSettings.Any())\n {\n await RefreshCommandSettingsStatusAsync();\n }\n }\n \n /// \n /// Refreshes the status of registry settings.\n /// \n /// A task representing the asynchronous operation.\n private async Task RefreshRegistrySettingsStatusAsync()\n {\n if (_registryService == null)\n {\n return;\n }\n\n // Get the status\n if (RegistrySetting != null)\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(RegistrySetting.Hive);\n\n // Get the current value\n var currentValue = _registryService.GetValue(\n $\"{hiveString}\\\\{RegistrySetting.SubKey}\",\n RegistrySetting.Name);\n\n // Update the current value\n CurrentValue = currentValue;\n \n // Update the linked registry settings with values collection\n LinkedRegistrySettingsWithValues.Clear();\n LinkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(RegistrySetting, currentValue));\n\n // Determine if the value is null\n IsRegistryValueNull = currentValue == null;\n\n // Determine the status\n if (currentValue == null)\n {\n // The value doesn't exist\n Status = RegistrySetting.DefaultValue == null\n ? RegistrySettingStatus.Applied\n : RegistrySettingStatus.NotApplied;\n }\n else\n {\n // Check if it matches the enabled value first\n if (RegistrySetting.EnabledValue != null && currentValue.Equals(RegistrySetting.EnabledValue))\n {\n Status = RegistrySettingStatus.Applied;\n }\n // Then check if it matches the disabled value\n else if (RegistrySetting.DisabledValue != null && currentValue.Equals(RegistrySetting.DisabledValue))\n {\n Status = RegistrySettingStatus.NotApplied;\n }\n // Finally, fall back to recommended value for backward compatibility\n else if (currentValue.Equals(RegistrySetting.RecommendedValue))\n {\n // If RecommendedValue equals EnabledValue, mark as Applied\n // If RecommendedValue equals DisabledValue, mark as NotApplied\n if (RegistrySetting.EnabledValue != null && RegistrySetting.RecommendedValue.Equals(RegistrySetting.EnabledValue))\n {\n Status = RegistrySettingStatus.Applied;\n }\n else\n {\n Status = RegistrySettingStatus.NotApplied;\n }\n }\n else\n {\n Status = RegistrySettingStatus.NotApplied;\n }\n }\n\n // Update the status message\n StatusMessage = Status == RegistrySettingStatus.Applied\n ? \"Applied\"\n : \"Not Applied\";\n\n // Update the IsSelected property - only during initial load\n if (IsUpdatingFromCode)\n {\n IsSelected = Status == RegistrySettingStatus.Applied;\n }\n }\n else if (LinkedRegistrySettings != null && LinkedRegistrySettings.Settings.Count > 0)\n {\n // Clear the existing values\n LinkedRegistrySettingsWithValues.Clear();\n \n // Check all linked settings\n bool allApplied = true;\n bool anyApplied = false;\n bool allNull = true;\n bool anyNull = false;\n\n foreach (var setting in LinkedRegistrySettings.Settings)\n {\n // Get the registry hive string\n string hiveString = GetRegistryHiveString(setting.Hive);\n\n // Special handling for Remove action type\n bool isRemoveAction = setting.ActionType == RegistryActionType.Remove;\n \n // Get the current value\n var currentValue = _registryService.GetValue(\n $\"{hiveString}\\\\{setting.SubKey}\",\n setting.Name);\n \n // Add to the linked registry settings with values collection\n LinkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(setting, currentValue));\n\n // Check if the value is null\n if (currentValue == null)\n {\n anyNull = true;\n }\n else\n {\n allNull = false;\n }\n\n // Determine if the value is applied\n bool isApplied;\n \n // For Remove action type, null means the key/value doesn't exist, which means it's applied\n if (isRemoveAction)\n {\n isApplied = currentValue == null;\n }\n else if (currentValue == null)\n {\n // The value doesn't exist\n isApplied = setting.DefaultValue == null;\n }\n else\n {\n // Check if it matches the enabled value first\n if (setting.EnabledValue != null && currentValue.Equals(setting.EnabledValue))\n {\n isApplied = true;\n }\n // Then check if it matches the disabled value\n else if (setting.DisabledValue != null && currentValue.Equals(setting.DisabledValue))\n {\n isApplied = false;\n }\n // Finally, fall back to recommended value for backward compatibility\n else if (currentValue.Equals(setting.RecommendedValue))\n {\n // If RecommendedValue equals EnabledValue, mark as Applied\n // If RecommendedValue equals DisabledValue, mark as NotApplied\n if (setting.EnabledValue != null && setting.RecommendedValue.Equals(setting.EnabledValue))\n {\n isApplied = true;\n }\n else\n {\n isApplied = false;\n }\n }\n else\n {\n isApplied = false;\n }\n }\n\n // Update the status\n if (isApplied)\n {\n anyApplied = true;\n }\n else\n {\n allApplied = false;\n }\n }\n\n // Determine the status based on the logic\n if (LinkedRegistrySettings.Logic == LinkedSettingsLogic.All)\n {\n // All settings must be applied\n Status = allApplied\n ? RegistrySettingStatus.Applied\n : RegistrySettingStatus.NotApplied;\n \n // For ActionType = Remove settings, we need to invert the IsRegistryValueNull logic\n // because null means the key/value doesn't exist, which is the desired state\n bool allRemoveActions = LinkedRegistrySettings.Settings.All(s => s.ActionType == RegistryActionType.Remove);\n if (allRemoveActions)\n {\n // For Remove actions, we want to show the warning when values exist (not null)\n IsRegistryValueNull = !allNull;\n }\n else\n {\n IsRegistryValueNull = allNull;\n }\n }\n else\n {\n // Any setting must be applied\n Status = anyApplied\n ? RegistrySettingStatus.Applied\n : RegistrySettingStatus.NotApplied;\n \n // For ActionType = Remove settings, we need to invert the IsRegistryValueNull logic\n bool allRemoveActions = LinkedRegistrySettings.Settings.All(s => s.ActionType == RegistryActionType.Remove);\n if (allRemoveActions)\n {\n // For Remove actions, we want to show the warning when values exist (not null)\n IsRegistryValueNull = !anyNull;\n }\n else\n {\n IsRegistryValueNull = anyNull;\n }\n }\n\n // Update the status message\n StatusMessage = Status == RegistrySettingStatus.Applied\n ? \"Applied\"\n : \"Not Applied\";\n\n // Update the IsSelected property - only during initial load\n if (IsUpdatingFromCode)\n {\n IsSelected = Status == RegistrySettingStatus.Applied;\n }\n }\n }\n\n /// \n /// Gets the registry hive string.\n /// \n /// The registry hive.\n /// The registry hive string.\n private string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => throw new ArgumentOutOfRangeException(nameof(hive), hive, null)\n };\n }\n\n /// \n /// Determines if the object matches the given search term.\n /// \n /// The search term to match against.\n /// True if the object matches the search term, false otherwise.\n public virtual bool MatchesSearch(string searchTerm)\n {\n if (string.IsNullOrWhiteSpace(searchTerm))\n {\n return true;\n }\n\n searchTerm = searchTerm.ToLowerInvariant();\n\n foreach (var propertyName in GetSearchableProperties())\n {\n var property = GetType().GetProperty(propertyName);\n if (property != null)\n {\n var value = property.GetValue(this)?.ToString();\n if (!string.IsNullOrWhiteSpace(value) && value.ToLowerInvariant().Contains(searchTerm))\n {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /// \n /// Gets the searchable properties of the object.\n /// \n /// An array of property names that should be searched.\n public virtual string[] GetSearchableProperties()\n {\n return new[] { nameof(Name), nameof(Description), nameof(GroupName) };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/PowerShellExecutionService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service that executes PowerShell scripts with progress reporting and cancellation support.\n /// \n public class PowerShellExecutionService : IPowerShellExecutionService, IDisposable\n {\n private readonly ILogService _logService;\n private readonly ISystemServices _systemServices;\n \n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The system services.\n public PowerShellExecutionService(ILogService logService, ISystemServices systemServices)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _systemServices = systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n }\n \n /// \n public async Task ExecuteScriptAsync(\n string script, \n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (string.IsNullOrEmpty(script))\n {\n throw new ArgumentException(\"Script cannot be null or empty.\", nameof(script));\n }\n \n using var powerShell = Utilities.PowerShellFactory.CreateWindowsPowerShell(_logService, _systemServices);\n // No need to set execution policy as it's already done in the factory\n \n powerShell.AddScript(script);\n\n // Set up stream handlers\n // Explicitly type progressAdapter using full namespace\n System.IProgress? progressAdapter = progress != null\n ? new System.Progress(data => MapProgressData(data, progress)) // Also qualify Progress\n : null;\n\n SetupStreamHandlers(powerShell, progressAdapter);\n\n // Execute PowerShell with cancellation support\n return await Task.Run(() => {\n try\n {\n cancellationToken.ThrowIfCancellationRequested();\n var invokeResult = powerShell.Invoke();\n var resultText = string.Join(Environment.NewLine, \n invokeResult.Select(item => item.ToString()));\n \n // Check for errors\n if (powerShell.HadErrors)\n {\n foreach (var error in powerShell.Streams.Error)\n {\n _logService.LogError($\"PowerShell error: {error.Exception?.Message ?? error.ToString()}\", error.Exception);\n \n // This call seems to be the source of CS1061, despite Progress having Report.\n // Let's ensure the object creation is correct.\n progressAdapter?.Report(new PowerShellProgressData\n {\n Message = error.Exception?.Message ?? error.ToString(),\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Error\n });\n }\n }\n \n return resultText;\n }\n catch (Exception ex) when (cancellationToken.IsCancellationRequested)\n {\n _logService.LogWarning($\"PowerShell execution cancelled: {ex.Message}\");\n throw new OperationCanceledException(\"PowerShell execution was cancelled.\", ex, cancellationToken);\n }\n }, cancellationToken);\n }\n \n /// \n public async Task ExecuteScriptFileAsync(\n string scriptPath, \n string arguments = \"\",\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (string.IsNullOrEmpty(scriptPath))\n {\n throw new ArgumentException(\"Script path cannot be null or empty.\", nameof(scriptPath));\n }\n \n if (!File.Exists(scriptPath))\n {\n throw new FileNotFoundException($\"PowerShell script file not found: {scriptPath}\");\n }\n \n string script = await File.ReadAllTextAsync(scriptPath, cancellationToken);\n \n // If we have arguments, add them as parameters\n if (!string.IsNullOrEmpty(arguments))\n {\n script = $\"{script} {arguments}\";\n }\n \n return await ExecuteScriptAsync(script, progress, cancellationToken);\n }\n \n private void SetupStreamHandlers(PowerShell powerShell, IProgress? progress)\n {\n if (progress == null) return;\n \n // Handle progress records\n powerShell.Streams.Progress.DataAdded += (sender, e) => {\n var progressRecord = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n PercentComplete = progressRecord.PercentComplete >= 0 ? progressRecord.PercentComplete : null,\n Activity = progressRecord.Activity,\n StatusDescription = progressRecord.StatusDescription,\n CurrentOperation = progressRecord.CurrentOperation,\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Progress\n });\n\n _logService?.LogInformation($\"PowerShell Progress: {progressRecord.Activity} - {progressRecord.StatusDescription} ({progressRecord.PercentComplete}%)\");\n };\n\n // Handle information stream\n powerShell.Streams.Information.DataAdded += (sender, e) => {\n var info = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n Message = info.MessageData.ToString(),\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Information\n });\n\n _logService?.LogInformation($\"PowerShell Info: {info.MessageData}\");\n };\n\n // Handle verbose stream\n powerShell.Streams.Verbose.DataAdded += (sender, e) => {\n var verbose = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n Message = verbose.Message,\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Verbose\n });\n\n _logService?.Log(LogLevel.Debug, $\"PowerShell Verbose: {verbose.Message}\");\n };\n\n // Handle warning stream\n powerShell.Streams.Warning.DataAdded += (sender, e) => {\n var warning = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n Message = warning.Message,\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Warning\n });\n\n _logService?.LogWarning($\"PowerShell Warning: {warning.Message}\");\n };\n\n // Handle error stream\n powerShell.Streams.Error.DataAdded += (sender, e) => {\n var error = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n Message = error.Exception?.Message ?? error.ToString(),\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Error\n });\n\n _logService?.Log(LogLevel.Error, $\"PowerShell Error: {error.Exception?.Message ?? error.ToString()}\");\n };\n\n // Handle debug stream\n powerShell.Streams.Debug.DataAdded += (sender, e) => {\n var debug = ((PSDataCollection)sender)[e.Index];\n progress.Report(new PowerShellProgressData\n {\n Message = debug.Message,\n StreamType = Winhance.Core.Features.Common.Enums.PowerShellStreamType.Debug\n });\n\n _logService?.Log(LogLevel.Debug, $\"PowerShell Debug: {debug.Message}\");\n };\n }\n \n private void MapProgressData(PowerShellProgressData source, IProgress target)\n {\n var detail = new TaskProgressDetail();\n \n // Map PowerShell progress data to task progress detail\n if (source.PercentComplete.HasValue)\n {\n detail.Progress = source.PercentComplete.Value;\n }\n \n if (!string.IsNullOrEmpty(source.Activity))\n {\n detail.StatusText = source.Activity;\n if (!string.IsNullOrEmpty(source.StatusDescription))\n {\n detail.StatusText += $\": {source.StatusDescription}\";\n }\n }\n \n detail.DetailedMessage = source.Message ?? source.CurrentOperation;\n // Map stream type to log level\n switch (source.StreamType)\n {\n case Winhance.Core.Features.Common.Enums.PowerShellStreamType.Error:\n detail.LogLevel = LogLevel.Error;\n break;\n case Winhance.Core.Features.Common.Enums.PowerShellStreamType.Warning:\n detail.LogLevel = LogLevel.Warning;\n break;\n case Winhance.Core.Features.Common.Enums.PowerShellStreamType.Verbose:\n case Winhance.Core.Features.Common.Enums.PowerShellStreamType.Debug:\n detail.LogLevel = LogLevel.Debug;\n break;\n default: // Includes Information and Progress\n detail.LogLevel = LogLevel.Info;\n break;\n }\n \n target.Report(detail);\n }\n \n // SetExecutionPolicy is now handled by PowerShellFactory\n \n /// \n /// Disposes resources used by the service.\n /// \n public void Dispose()\n {\n // Cleanup resources if needed\n GC.SuppressFinalize(this);\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToReinstallableTextConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Converters\n{\n /// \n /// Converts a boolean value indicating whether an item can be reinstalled to a descriptive text.\n /// \n public class BooleanToReinstallableTextConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (bool)value ? \"Is Installable\" : \"Is Not Installable\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Views/SoftwareAppsView.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing MaterialDesignThemes.Wpf;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Views\n{\n /// \n /// Interaction logic for SoftwareAppsView.xaml\n /// \n public partial class SoftwareAppsView : UserControl\n {\n public SoftwareAppsView()\n {\n InitializeComponent();\n Loaded += SoftwareAppsView_Loaded;\n\n // Set up the expandable sections\n WindowsAppsContent.Visibility = Visibility.Collapsed;\n ExternalAppsContent.Visibility = Visibility.Collapsed;\n\n // Add click handlers\n WindowsAppsHeaderBorder.MouseDown += WindowsAppsHeader_MouseDown;\n ExternalAppsHeaderBorder.MouseDown += ExternalAppsHeader_MouseDown;\n }\n\n private async void SoftwareAppsView_Loaded(object sender, RoutedEventArgs e)\n {\n if (DataContext is SoftwareAppsViewModel viewModel)\n {\n try\n {\n // Initialize the view model\n await viewModel.InitializeCommand.ExecuteAsync(null);\n \n // Expand the first section by default after initialization is complete\n WindowsAppsContent.Visibility = Visibility.Visible;\n WindowsAppsHeaderIcon.Kind = PackIconKind.ChevronUp; // Up arrow\n }\n catch (System.Exception ex)\n {\n MessageBox.Show($\"Error initializing Software Apps view: {ex.Message}\",\n \"Initialization Error\",\n MessageBoxButton.OK,\n MessageBoxImage.Error);\n }\n }\n }\n\n private void WindowsAppsHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n ToggleSection(WindowsAppsContent, WindowsAppsHeaderIcon);\n }\n\n private void ExternalAppsHeader_MouseDown(object sender, MouseButtonEventArgs e)\n {\n ToggleSection(ExternalAppsContent, ExternalAppsHeaderIcon);\n }\n\n private void ToggleSection(UIElement content, PackIcon icon)\n {\n if (content.Visibility == Visibility.Collapsed)\n {\n content.Visibility = Visibility.Visible;\n icon.Kind = PackIconKind.ChevronUp; // Up arrow (section expanded)\n }\n else\n {\n content.Visibility = Visibility.Collapsed;\n icon.Kind = PackIconKind.ChevronDown; // Down arrow (section collapsed)\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/OptimizeViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Linq;\nusing System.Windows.Controls;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.Customize.Enums;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.Common.Messages;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for the OptimizeView that manages system optimization settings.\n /// \n public partial class OptimizeViewModel : SearchableViewModel\n {\n private readonly IRegistryService _registryService;\n private readonly IDialogService _dialogService;\n private readonly ILogService _logService;\n private readonly IConfigurationService _configurationService;\n private readonly IMessengerService _messengerService;\n private List _allItemsBackup = new List();\n private bool _updatingCheckboxes;\n private bool _isInitialSearchDone = false;\n \n /// \n /// Gets or sets a value indicating whether the view model is initialized.\n /// \n [ObservableProperty]\n private bool _isInitialized;\n \n /// \n /// Gets or sets a value indicating whether search has any results.\n /// \n [ObservableProperty]\n private bool _hasSearchResults = true;\n \n /// \n /// Gets or sets the status text.\n /// \n [ObservableProperty]\n private string _statusText = \"Optimize Your Windows Settings and Performance\";\n \n // Override the SearchText property to add explicit notification and direct control over the search flow\n private string _searchTextOverride = string.Empty;\n public override string SearchText\n {\n get => _searchTextOverride;\n set\n {\n if (_searchTextOverride != value)\n {\n _searchTextOverride = value;\n OnPropertyChanged(nameof(SearchText));\n LogInfo($\"OptimizeViewModel: SearchText changed to: '{value}'\");\n \n // Explicitly update IsSearchActive and call ApplySearch\n IsSearchActive = !string.IsNullOrWhiteSpace(value);\n ApplySearch();\n \n // Update status text based on search results\n if (IsSearchActive)\n {\n StatusText = $\"Found {Items.Count} settings matching '{value}'\";\n }\n else\n {\n StatusText = \"Optimize Your Windows Settings and Performance\";\n }\n }\n }\n }\n\n /// \n /// Gets the messenger service.\n /// \n public IMessengerService MessengerService => _messengerService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The registry service for interacting with the Windows Registry.\n /// The dialog service for showing dialogs.\n /// The logging service.\n /// The progress service.\n /// The search service.\n /// The configuration service.\n /// The gaming settings view model.\n /// The privacy optimizations view model.\n /// The update optimizations view model.\n /// The power settings view model.\n /// The Windows security optimizations view model.\n /// The explorer optimizations view model.\n /// The notification optimizations view model.\n /// The sound optimizations view model.\n /// The messenger service.\n\n public OptimizeViewModel(\n IRegistryService registryService,\n IDialogService dialogService,\n ILogService logService,\n ITaskProgressService progressService,\n ISearchService searchService,\n IConfigurationService configurationService,\n GamingandPerformanceOptimizationsViewModel gamingSettings,\n PrivacyOptimizationsViewModel privacySettings,\n UpdateOptimizationsViewModel updateSettings,\n PowerOptimizationsViewModel powerSettings,\n WindowsSecurityOptimizationsViewModel windowsSecuritySettings,\n ExplorerOptimizationsViewModel explorerSettings,\n NotificationOptimizationsViewModel notificationSettings,\n SoundOptimizationsViewModel soundSettings,\n IMessengerService messengerService)\n : base(progressService, searchService, null)\n {\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _messengerService = messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n\n // Set specialized view models\n GamingandPerformanceOptimizationsViewModel = gamingSettings ?? throw new ArgumentNullException(nameof(gamingSettings));\n PrivacyOptimizationsViewModel = privacySettings ?? throw new ArgumentNullException(nameof(privacySettings));\n UpdateOptimizationsViewModel = updateSettings ?? throw new ArgumentNullException(nameof(updateSettings));\n PowerSettingsViewModel = powerSettings ?? throw new ArgumentNullException(nameof(powerSettings));\n WindowsSecuritySettingsViewModel = windowsSecuritySettings ?? throw new ArgumentNullException(nameof(windowsSecuritySettings));\n ExplorerOptimizationsViewModel = explorerSettings ?? throw new ArgumentNullException(nameof(explorerSettings));\n NotificationOptimizationsViewModel = notificationSettings ?? throw new ArgumentNullException(nameof(notificationSettings));\n SoundOptimizationsViewModel = soundSettings ?? throw new ArgumentNullException(nameof(soundSettings));\n\n // Store the configuration service\n _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));\n\n // Create initialize command\n InitializeCommand = new AsyncRelayCommand(InitializeAsync);\n\n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n\n // We'll initialize when explicitly called, not automatically\n // This ensures the loading screen stays visible until initialization is complete\n\n }\n\n /// \n /// Gets the command to initialize the view model.\n /// \n public IAsyncRelayCommand InitializeCommand { get; }\n\n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n\n /// \n /// Gets the gaming settings view model.\n /// \n public GamingandPerformanceOptimizationsViewModel GamingandPerformanceOptimizationsViewModel { get; }\n\n /// \n /// Gets the privacy optimizations view model.\n /// \n public PrivacyOptimizationsViewModel PrivacyOptimizationsViewModel { get; }\n\n /// \n /// Gets the updates optimizations view model.\n /// \n public UpdateOptimizationsViewModel UpdateOptimizationsViewModel { get; }\n\n /// \n /// Gets the power settings view model.\n /// \n public PowerOptimizationsViewModel PowerSettingsViewModel { get; }\n\n /// \n /// Gets the Windows security optimizations view model.\n /// \n public WindowsSecurityOptimizationsViewModel WindowsSecuritySettingsViewModel { get; }\n\n /// \n /// Gets the explorer optimizations view model.\n /// \n public ExplorerOptimizationsViewModel ExplorerOptimizationsViewModel { get; }\n\n /// \n /// Gets the notification optimizations view model.\n /// \n public NotificationOptimizationsViewModel NotificationOptimizationsViewModel { get; }\n\n /// \n /// Gets the sound optimizations view model.\n /// \n public SoundOptimizationsViewModel SoundOptimizationsViewModel { get; }\n\n /// \n /// Toggles the selection state of all gaming settings.\n /// \n [RelayCommand]\n private void ToggleGaming()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n GamingandPerformanceOptimizationsViewModel.IsSelected = !GamingandPerformanceOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in GamingandPerformanceOptimizationsViewModel.Settings)\n {\n setting.IsSelected = GamingandPerformanceOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all privacy settings.\n /// \n [RelayCommand]\n private void TogglePrivacy()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n PrivacyOptimizationsViewModel.IsSelected = !PrivacyOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in PrivacyOptimizationsViewModel.Settings)\n {\n setting.IsSelected = PrivacyOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all update settings.\n /// \n [RelayCommand]\n private void ToggleUpdates()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n UpdateOptimizationsViewModel.IsSelected = !UpdateOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in UpdateOptimizationsViewModel.Settings)\n {\n setting.IsSelected = UpdateOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all power settings.\n /// \n [RelayCommand]\n private void TogglePowerSettings()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n PowerSettingsViewModel.IsSelected = !PowerSettingsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in PowerSettingsViewModel.Settings)\n {\n setting.IsSelected = PowerSettingsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of Windows Security settings.\n /// \n [RelayCommand]\n private void ToggleWindowsSecurity()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n WindowsSecuritySettingsViewModel.IsSelected = !WindowsSecuritySettingsViewModel.IsSelected;\n\n // Windows Security only has the UAC notification level, no individual settings to update\n // This is primarily for UI consistency with other sections\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all explorer settings.\n /// \n [RelayCommand]\n private void ToggleExplorer()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n ExplorerOptimizationsViewModel.IsSelected = !ExplorerOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in ExplorerOptimizationsViewModel.Settings)\n {\n setting.IsSelected = ExplorerOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all notification settings.\n /// \n [RelayCommand]\n private void ToggleNotifications()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n NotificationOptimizationsViewModel.IsSelected = !NotificationOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in NotificationOptimizationsViewModel.Settings)\n {\n setting.IsSelected = NotificationOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Toggles the selection state of all sound settings.\n /// \n [RelayCommand]\n private void ToggleSound()\n {\n try\n {\n _updatingCheckboxes = true;\n\n // Toggle the IsSelected property on the view model\n SoundOptimizationsViewModel.IsSelected = !SoundOptimizationsViewModel.IsSelected;\n\n // Update all settings in the view model\n foreach (var setting in SoundOptimizationsViewModel.Settings)\n {\n setting.IsSelected = SoundOptimizationsViewModel.IsSelected;\n }\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n /// \n /// Loads items asynchronously.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadItemsAsync()\n {\n try\n {\n IsLoading = true;\n StatusText = \"Loading optimization settings...\";\n\n // Clear the items collection\n Items.Clear();\n\n // Collect all settings from the various view models\n var allSettings = new List();\n \n // Ensure all child view models are initialized and have loaded their settings\n await EnsureChildViewModelsInitialized();\n\n // Add settings from each category - convert from OptimizationSettingViewModel to OptimizationSettingItem\n if (WindowsSecuritySettingsViewModel != null && WindowsSecuritySettingsViewModel.Settings != null)\n {\n _logService.Log(LogLevel.Debug, $\"Loading {WindowsSecuritySettingsViewModel.Settings.Count} settings from WindowsSecuritySettingsViewModel\");\n foreach (var setting in WindowsSecuritySettingsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n \n // For UAC slider, add the slider labels\n if (item.Id == \"UACSlider\" && item.ControlType == ControlType.ThreeStateSlider)\n {\n item.SliderLabels.Clear();\n item.SliderLabels.Add(\"Low\");\n item.SliderLabels.Add(\"Moderate\");\n item.SliderLabels.Add(\"High\");\n }\n \n allSettings.Add(item);\n }\n }\n\n if (GamingandPerformanceOptimizationsViewModel != null && GamingandPerformanceOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in GamingandPerformanceOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n if (PrivacyOptimizationsViewModel != null && PrivacyOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in PrivacyOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n if (UpdateOptimizationsViewModel != null && UpdateOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in UpdateOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n if (PowerSettingsViewModel != null && PowerSettingsViewModel.Settings != null)\n {\n foreach (var setting in PowerSettingsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n \n // For Power Plan ComboBox, add the ComboBox labels\n if (item.Id == \"PowerPlanComboBox\" && item.ControlType == ControlType.ComboBox)\n {\n item.SliderLabels.Clear();\n // Copy labels from PowerSettingsViewModel\n if (PowerSettingsViewModel.PowerPlanLabels != null)\n {\n foreach (var label in PowerSettingsViewModel.PowerPlanLabels)\n {\n item.SliderLabels.Add(label);\n }\n \n // Set the SliderValue based on the current PowerPlanValue\n if (PowerSettingsViewModel.PowerPlanValue >= 0 &&\n PowerSettingsViewModel.PowerPlanValue < PowerSettingsViewModel.PowerPlanLabels.Count)\n {\n item.SliderValue = PowerSettingsViewModel.PowerPlanValue;\n _logService.Log(LogLevel.Info, $\"Set SliderValue for Power Plan to {item.SliderValue} (label: {PowerSettingsViewModel.PowerPlanLabels[PowerSettingsViewModel.PowerPlanValue]})\");\n }\n }\n else\n {\n // Fallback labels if PowerPlanLabels is null\n item.SliderLabels.Add(\"Balanced\");\n item.SliderLabels.Add(\"High Performance\");\n item.SliderLabels.Add(\"Ultimate Performance\");\n \n // Set the SliderValue based on the current PowerPlanValue\n if (PowerSettingsViewModel.PowerPlanValue >= 0 && PowerSettingsViewModel.PowerPlanValue < 3)\n {\n item.SliderValue = PowerSettingsViewModel.PowerPlanValue;\n string[] defaultLabels = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n _logService.Log(LogLevel.Info, $\"Set SliderValue for Power Plan to {item.SliderValue} (label: {defaultLabels[PowerSettingsViewModel.PowerPlanValue]})\");\n }\n }\n }\n \n allSettings.Add(item);\n }\n }\n\n if (ExplorerOptimizationsViewModel != null && ExplorerOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in ExplorerOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n if (NotificationOptimizationsViewModel != null && NotificationOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in NotificationOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n if (SoundOptimizationsViewModel != null && SoundOptimizationsViewModel.Settings != null)\n {\n foreach (var setting in SoundOptimizationsViewModel.Settings)\n {\n // Create a new OptimizationSettingItem with the properties from the setting\n var item = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsVisible = setting.IsVisible\n };\n \n // Copy properties directly without type casting\n item.ControlType = setting.ControlType;\n item.SliderValue = setting.SliderValue;\n item.SliderSteps = setting.SliderSteps;\n item.Status = setting.Status;\n item.StatusMessage = setting.StatusMessage;\n item.RegistrySetting = setting.RegistrySetting;\n item.LinkedRegistrySettings = setting.LinkedRegistrySettings;\n item.Dependencies = setting.Dependencies;\n allSettings.Add(item);\n }\n }\n\n // Add all settings to the Items collection\n foreach (var setting in allSettings)\n {\n Items.Add(setting);\n }\n\n // Create a backup of all items for state recovery\n _allItemsBackup = new List(Items);\n\n // Only update StatusText if it's currently showing a loading message\n if (StatusText.Contains(\"Loading\"))\n {\n StatusText = \"Optimize Your Windows Settings and Performance\";\n }\n _logService.Log(LogLevel.Info, $\"OptimizeViewModel.LoadItemsAsync completed with {Items.Count} items\");\n }\n catch (Exception ex)\n {\n StatusText = $\"Error loading optimization settings: {ex.Message}\";\n LogError($\"Error loading optimization settings: {ex.Message}\", ex);\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the installation status of items asynchronously.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckInstallationStatusAsync()\n {\n // This method is not applicable for optimization settings\n // but we need to implement it to satisfy the interface\n await Task.CompletedTask;\n }\n\n \n /// \n /// Restores all items visibility to their original state.\n /// \n private void RestoreAllItemsVisibility()\n {\n // Make all settings visible in each category\n if (GamingandPerformanceOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in GamingandPerformanceOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n GamingandPerformanceOptimizationsViewModel.HasVisibleSettings = GamingandPerformanceOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (PrivacyOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in PrivacyOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n PrivacyOptimizationsViewModel.HasVisibleSettings = PrivacyOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (UpdateOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in UpdateOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n UpdateOptimizationsViewModel.HasVisibleSettings = UpdateOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (PowerSettingsViewModel?.Settings != null)\n {\n foreach (var setting in PowerSettingsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n PowerSettingsViewModel.HasVisibleSettings = PowerSettingsViewModel.Settings.Count > 0;\n }\n \n if (ExplorerOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in ExplorerOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n ExplorerOptimizationsViewModel.HasVisibleSettings = ExplorerOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (NotificationOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in NotificationOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n NotificationOptimizationsViewModel.HasVisibleSettings = NotificationOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (SoundOptimizationsViewModel?.Settings != null)\n {\n foreach (var setting in SoundOptimizationsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n SoundOptimizationsViewModel.HasVisibleSettings = SoundOptimizationsViewModel.Settings.Count > 0;\n }\n \n if (WindowsSecuritySettingsViewModel?.Settings != null)\n {\n foreach (var setting in WindowsSecuritySettingsViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n WindowsSecuritySettingsViewModel.HasVisibleSettings = WindowsSecuritySettingsViewModel.Settings.Count > 0;\n }\n \n // Always ensure HasSearchResults is true when restoring visibility\n HasSearchResults = true;\n \n // Send a message to notify the view to reset section expansion states\n _messengerService.Send(new ResetExpansionStateMessage());\n \n LogInfo(\"OptimizeViewModel: RestoreAllItemsVisibility has reset all UI elements to visible state\");\n }\n \n /// \n /// Applies the current search text to filter items.\n /// \n protected override void ApplySearch()\n {\n LogInfo($\"OptimizeViewModel: ApplySearch called with SearchText: '{SearchText}'\");\n \n // If we have no items yet, there's nothing to filter\n if (Items == null)\n return;\n \n // If this is our first time running a search and the backup isn't created yet, create it\n if (!_isInitialSearchDone && Items.Count > 0)\n {\n _allItemsBackup = new List(Items);\n _isInitialSearchDone = true;\n LogInfo($\"OptimizeViewModel: Created backup of all items ({_allItemsBackup.Count} items)\");\n }\n\n // If search is empty, restore all items visibility and the original items collection\n if (string.IsNullOrWhiteSpace(SearchText))\n {\n LogInfo(\"OptimizeViewModel: Empty search, restoring all items visibility\");\n \n // Restore visibility of UI elements first\n RestoreAllItemsVisibility();\n \n // Use the backup to restore all items\n if (_allItemsBackup.Count > 0)\n {\n LogInfo($\"OptimizeViewModel: Restoring {_allItemsBackup.Count} items from backup\");\n Items.Clear();\n foreach (var item in _allItemsBackup)\n {\n Items.Add(item);\n }\n }\n else if (Items.Count == 0)\n {\n // If we don't have a backup and Items is empty (which could happen after a no-results search),\n // try to reload items\n LogInfo(\"OptimizeViewModel: No backup available and Items is empty, attempting to reload\");\n _ = LoadItemsAsync();\n }\n \n // Always set HasSearchResults to true when search is cleared\n HasSearchResults = true;\n \n // Update status text\n StatusText = \"Optimize Your Windows Settings and Performance\";\n LogInfo($\"OptimizeViewModel: Restored items, count={Items.Count}\");\n return;\n }\n\n // We're doing an active search, use the backup for filtering if available\n var itemsToFilter = _allItemsBackup.Count > 0\n ? new ObservableCollection(_allItemsBackup)\n : Items;\n \n // Normalize and clean the search text - convert to lowercase for consistent case-insensitive matching\n string normalizedSearchText = SearchText.Trim().ToLowerInvariant();\n LogInfo($\"OptimizeViewModel: Normalized search text: '{normalizedSearchText}'\");\n \n // Handle edge case: if search is empty after normalization, treat it as empty\n if (string.IsNullOrEmpty(normalizedSearchText))\n {\n // Same handling as empty search\n RestoreAllItemsVisibility();\n if (_allItemsBackup.Count > 0)\n {\n Items.Clear();\n foreach (var item in _allItemsBackup)\n {\n Items.Add(item);\n }\n }\n HasSearchResults = true;\n StatusText = \"Optimize Your Windows Settings and Performance\";\n return;\n }\n \n // Add additional logging to help diagnose search issues\n LogInfo($\"OptimizeViewModel: Starting search with term '{normalizedSearchText}'\");\n \n // Filter items based on search text - ensure we pass normalized text\n // Don't convert to lowercase here - we'll handle case insensitivity in the MatchesSearch method\n var filteredItems = FilterItems(itemsToFilter).ToList();\n \n // Log each filtered item for debugging\n foreach (var item in filteredItems)\n {\n LogInfo($\"OptimizeViewModel: Filtered item: '{item.Name}' (ID: {item.Id})\");\n }\n \n // Log the number of filtered items\n int filteredCount = filteredItems.Count;\n LogInfo($\"OptimizeViewModel: Found {filteredCount} matching items\");\n \n // Log the filtered count for debugging\n LogInfo($\"OptimizeViewModel: Initial filtered count: {filteredCount}\");\n \n // We'll update HasSearchResults after counting the actual visible items\n // This is just an initial value\n bool initialHasResults = filteredCount > 0;\n LogInfo($\"OptimizeViewModel: Initial HasSearchResults: {initialHasResults}\");\n \n // Log the filtered items for debugging\n LogInfo($\"OptimizeViewModel: Filtered items: {string.Join(\", \", filteredItems.Select(item => item.Name))}\");\n\n // Update each sub-view model's Settings collection with the normalized search text\n UpdateSubViewSettings(GamingandPerformanceOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(PrivacyOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(UpdateOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(PowerSettingsViewModel, normalizedSearchText);\n UpdateSubViewSettings(ExplorerOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(NotificationOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(SoundOptimizationsViewModel, normalizedSearchText);\n UpdateSubViewSettings(WindowsSecuritySettingsViewModel, normalizedSearchText);\n\n // Count the actual visible items after filtering\n int visibleItemsCount = 0;\n \n // Count visible items in each category\n if (GamingandPerformanceOptimizationsViewModel?.Settings != null)\n visibleItemsCount += GamingandPerformanceOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (PrivacyOptimizationsViewModel?.Settings != null)\n visibleItemsCount += PrivacyOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (UpdateOptimizationsViewModel?.Settings != null)\n visibleItemsCount += UpdateOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (PowerSettingsViewModel?.Settings != null)\n visibleItemsCount += PowerSettingsViewModel.Settings.Count(s => s.IsVisible);\n \n if (ExplorerOptimizationsViewModel?.Settings != null)\n visibleItemsCount += ExplorerOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (NotificationOptimizationsViewModel?.Settings != null)\n visibleItemsCount += NotificationOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (SoundOptimizationsViewModel?.Settings != null)\n visibleItemsCount += SoundOptimizationsViewModel.Settings.Count(s => s.IsVisible);\n \n if (WindowsSecuritySettingsViewModel?.Settings != null)\n visibleItemsCount += WindowsSecuritySettingsViewModel.Settings.Count(s => s.IsVisible);\n\n // Update the Items collection to match visible items\n Items.Clear();\n foreach (var setting in filteredItems)\n {\n if (setting.IsVisible)\n {\n Items.Add(setting);\n }\n }\n \n // Now update HasSearchResults based on the ACTUAL visible items count\n // This is more accurate than using the filtered count\n HasSearchResults = visibleItemsCount > 0;\n LogInfo($\"OptimizeViewModel: Final HasSearchResults: {HasSearchResults} (visibleItemsCount: {visibleItemsCount})\");\n\n // Update status text with correct count\n if (IsSearchActive)\n {\n StatusText = $\"Found {visibleItemsCount} settings matching '{SearchText}'\";\n LogInfo($\"OptimizeViewModel: StatusText updated to: '{StatusText}' with {visibleItemsCount} visible items\");\n }\n else\n {\n StatusText = $\"Showing all {Items.Count} optimization settings\";\n LogInfo($\"OptimizeViewModel: StatusText updated to: '{StatusText}'\");\n }\n }\n\n /// \n /// Updates a sub-view model's Settings collection based on search text.\n /// \n /// The sub-view model to update.\n /// The normalized search text to match against.\n private void UpdateSubViewSettings(object viewModel, string searchText)\n {\n if (viewModel == null)\n return;\n\n // Use dynamic to access properties without knowing the exact type\n dynamic dynamicViewModel = viewModel;\n \n if (dynamicViewModel.Settings == null)\n return;\n\n // If not searching, show all settings\n if (!IsSearchActive)\n {\n foreach (var setting in dynamicViewModel.Settings)\n {\n setting.IsVisible = true;\n }\n \n // Update the view model's visibility\n dynamicViewModel.HasVisibleSettings = dynamicViewModel.Settings.Count > 0;\n \n LogInfo($\"OptimizeViewModel: Set all settings visible in {dynamicViewModel.GetType().Name}\");\n return;\n }\n\n // When searching, only show settings that match the search criteria\n bool hasVisibleSettings = false;\n int visibleCount = 0;\n \n foreach (var setting in dynamicViewModel.Settings)\n {\n // Use partial matching instead of exact name matching\n // This matches the same logic used in OptimizationSettingItem.MatchesSearch()\n bool matchesName = setting.Name != null &&\n setting.Name.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0;\n bool matchesDescription = setting.Description != null &&\n setting.Description.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0;\n bool matchesGroupName = setting.GroupName != null &&\n setting.GroupName.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0;\n \n // Set visibility based on any match\n setting.IsVisible = matchesName || matchesDescription || matchesGroupName;\n \n // Log when we find a match for debugging\n if (setting.IsVisible)\n {\n LogInfo($\"OptimizeViewModel: Setting '{setting.Name}' is visible in {viewModel.GetType().Name}\");\n }\n \n if (setting.IsVisible)\n {\n hasVisibleSettings = true;\n visibleCount++;\n }\n }\n \n // Update the view model's visibility\n dynamicViewModel.HasVisibleSettings = hasVisibleSettings;\n \n LogInfo($\"OptimizeViewModel: {dynamicViewModel.GetType().Name} has {visibleCount} visible settings, HasVisibleSettings={hasVisibleSettings}\");\n }\n\n // SaveConfig and ImportConfig methods removed as part of unified configuration cleanup\n\n /// \n /// Gets the name of the UAC level.\n /// \n /// The UAC level (0=Low, 1=Moderate, 2=High).\n /// The name of the UAC level.\n private string GetUacLevelName(int level)\n {\n return level switch\n {\n 0 => \"Low\",\n 1 => \"Moderate\",\n 2 => \"High\",\n _ => \"Unknown\"\n };\n }\n\n /// \n /// Called when the view model is navigated to.\n /// \n /// The navigation parameter.\n public override async void OnNavigatedTo(object parameter)\n {\n LogInfo(\"OptimizeViewModel.OnNavigatedTo called\");\n\n try\n {\n // If not already initialized, initialize now\n if (!IsInitialized)\n {\n await InitializeAsync(CancellationToken.None);\n }\n else\n {\n // Just refresh the settings status\n await RefreshSettingsStatusAsync();\n }\n }\n catch (Exception ex)\n {\n LogError($\"Error in OptimizeViewModel.OnNavigatedTo: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Initializes the view model asynchronously.\n /// \n /// A cancellation token that can be used to cancel the operation.\n /// A task representing the asynchronous operation.\n private async Task InitializeAsync(CancellationToken cancellationToken)\n {\n if (IsInitialized)\n return;\n\n try\n {\n IsLoading = true;\n LogInfo(\"Initializing OptimizeViewModel\");\n\n // Create a progress reporter\n var progress = new Progress(detail => {\n // Report progress through the task progress service\n int progress = detail.Progress.HasValue ? (int)detail.Progress.Value : 0;\n ProgressService.UpdateProgress(progress, detail.StatusText);\n });\n\n // Initialize settings sequentially to provide better progress reporting\n ProgressService.UpdateProgress(0, \"Loading Windows security settings...\");\n await WindowsSecuritySettingsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(10, \"Loading gaming settings...\");\n await GamingandPerformanceOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(25, \"Loading privacy settings...\");\n await PrivacyOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(40, \"Loading update settings...\");\n await UpdateOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(55, \"Loading power settings...\");\n await PowerSettingsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(70, \"Loading explorer settings...\");\n await ExplorerOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(80, \"Loading notification settings...\");\n await NotificationOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(90, \"Loading sound settings...\");\n await SoundOptimizationsViewModel.LoadSettingsAsync();\n\n ProgressService.UpdateProgress(100, \"Initialization complete\");\n\n // Mark as initialized\n IsInitialized = true;\n\n LogInfo(\"OptimizeViewModel initialized successfully\");\n }\n catch (Exception ex)\n {\n LogError($\"Error initializing OptimizeViewModel: {ex.Message}\", ex);\n throw; // Rethrow to ensure the caller knows initialization failed\n }\n finally\n {\n IsLoading = false;\n }\n }\n \n /// \n /// Ensures all child view models are initialized and have loaded their settings.\n /// \n private async Task EnsureChildViewModelsInitialized()\n {\n _logService.Log(LogLevel.Debug, \"Ensuring all child view models are initialized\");\n \n // Create a list of tasks to initialize all child view models\n var initializationTasks = new List();\n \n // Windows Security Settings\n if (WindowsSecuritySettingsViewModel != null && WindowsSecuritySettingsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading WindowsSecuritySettingsViewModel settings\");\n initializationTasks.Add(WindowsSecuritySettingsViewModel.LoadSettingsAsync());\n }\n \n // Gaming and Performance Settings\n if (GamingandPerformanceOptimizationsViewModel != null && GamingandPerformanceOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading GamingandPerformanceOptimizationsViewModel settings\");\n initializationTasks.Add(GamingandPerformanceOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Privacy Settings\n if (PrivacyOptimizationsViewModel != null && PrivacyOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading PrivacyOptimizationsViewModel settings\");\n initializationTasks.Add(PrivacyOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Update Settings\n if (UpdateOptimizationsViewModel != null && UpdateOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading UpdateOptimizationsViewModel settings\");\n initializationTasks.Add(UpdateOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Power Settings\n if (PowerSettingsViewModel != null && PowerSettingsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading PowerSettingsViewModel settings\");\n initializationTasks.Add(PowerSettingsViewModel.LoadSettingsAsync());\n }\n \n // Explorer Settings\n if (ExplorerOptimizationsViewModel != null && ExplorerOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading ExplorerOptimizationsViewModel settings\");\n initializationTasks.Add(ExplorerOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Notification Settings\n if (NotificationOptimizationsViewModel != null && NotificationOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading NotificationOptimizationsViewModel settings\");\n initializationTasks.Add(NotificationOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Sound Settings\n if (SoundOptimizationsViewModel != null && SoundOptimizationsViewModel.Settings == null)\n {\n _logService.Log(LogLevel.Debug, \"Loading SoundOptimizationsViewModel settings\");\n initializationTasks.Add(SoundOptimizationsViewModel.LoadSettingsAsync());\n }\n \n // Wait for all initialization tasks to complete\n if (initializationTasks.Count > 0)\n {\n _logService.Log(LogLevel.Debug, $\"Waiting for {initializationTasks.Count} child view models to initialize\");\n await Task.WhenAll(initializationTasks);\n _logService.Log(LogLevel.Debug, \"All child view models initialized\");\n }\n else\n {\n _logService.Log(LogLevel.Debug, \"All child view models were already initialized\");\n }\n }\n\n /// \n /// Refreshes the status of all settings.\n /// \n /// A task representing the asynchronous operation.\n private async Task RefreshSettingsStatusAsync()\n {\n try\n {\n IsLoading = true;\n LogInfo(\"Refreshing settings status\");\n\n // Refresh all settings view models\n var refreshTasks = new List\n {\n WindowsSecuritySettingsViewModel.CheckSettingStatusesAsync(),\n GamingandPerformanceOptimizationsViewModel.CheckSettingStatusesAsync(),\n PrivacyOptimizationsViewModel.CheckSettingStatusesAsync(),\n UpdateOptimizationsViewModel.CheckSettingStatusesAsync(),\n PowerSettingsViewModel.CheckSettingStatusesAsync(),\n ExplorerOptimizationsViewModel.CheckSettingStatusesAsync(),\n NotificationOptimizationsViewModel.CheckSettingStatusesAsync(),\n SoundOptimizationsViewModel.CheckSettingStatusesAsync()\n };\n\n // Wait for all refresh tasks to complete\n await Task.WhenAll(refreshTasks);\n\n LogInfo(\"Settings status refreshed successfully\");\n }\n catch (Exception ex)\n {\n LogError($\"Error refreshing settings status: {ex.Message}\", ex);\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Handles the checkbox state changed event for optimization settings.\n /// \n /// The setting that was changed.\n [RelayCommand]\n private void SettingChanged(Winhance.WPF.Features.Common.Models.ApplicationSettingItem setting)\n {\n if (_updatingCheckboxes)\n return;\n\n try\n {\n _updatingCheckboxes = true;\n\n if (setting.RegistrySetting?.Category == \"PowerPlan\")\n {\n // Handle power plan changes separately\n // This would call a method to change the power plan\n LogInfo($\"Power plan setting changed: {setting.Name} to {setting.IsSelected}\");\n }\n else\n {\n // Apply registry change\n if (setting.RegistrySetting != null)\n {\n // Use EnabledValue/DisabledValue if available, otherwise fall back to RecommendedValue/DefaultValue\n string valueToSet;\n if (setting.IsSelected)\n {\n var enabledValue = setting.RegistrySetting.EnabledValue ?? setting.RegistrySetting.RecommendedValue;\n valueToSet = enabledValue.ToString();\n }\n else\n {\n var disabledValue = setting.RegistrySetting.DisabledValue ?? setting.RegistrySetting.DefaultValue;\n valueToSet = disabledValue?.ToString() ?? \"\";\n }\n\n var result = _registryService.SetValue(\n setting.RegistrySetting.Hive + \"\\\\\" + setting.RegistrySetting.SubKey,\n setting.RegistrySetting.Name,\n valueToSet,\n setting.RegistrySetting.ValueType);\n\n if (result)\n {\n LogInfo($\"Setting applied: {setting.Name}\");\n\n // Check if restart is required based on setting category or name\n bool requiresRestart = setting.Name.Contains(\"restart\", StringComparison.OrdinalIgnoreCase);\n\n if (requiresRestart)\n {\n _dialogService.ShowMessage(\n \"Some changes require a system restart to take effect.\",\n \"Restart Required\");\n }\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Failed to apply setting: {setting.Name}\");\n\n // Revert the checkbox state\n setting.IsSelected = !setting.IsSelected;\n\n _dialogService.ShowMessage(\n $\"Failed to apply the setting: {setting.Name}. This may require administrator privileges.\",\n \"Error\");\n }\n }\n }\n catch (Exception ex)\n {\n LogError($\"Error applying setting: {ex.Message}\", ex);\n\n // Revert the checkbox state\n setting.IsSelected = !setting.IsSelected;\n\n _dialogService.ShowMessage(\n $\"An error occurred: {ex.Message}\",\n \"Error\");\n }\n finally\n {\n _updatingCheckboxes = false;\n }\n }\n\n // Note: ApplyOptimizationsCommand has been removed as settings are now applied immediately when toggled\n \n // The CreateOptimizationSettingItem method has been removed as it's no longer needed\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScheduledTaskService.cs", "using System;\nusing System.IO;\nusing System.Management.Automation;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Service for registering and managing scheduled tasks for script execution.\n /// \n public class ScheduledTaskService : IScheduledTaskService\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public ScheduledTaskService(ILogService logService)\n {\n _logService = logService;\n }\n\n /// \n public async Task RegisterScheduledTaskAsync(RemovalScript script)\n {\n try\n {\n _logService.LogInformation($\"Registering scheduled task for script: {script?.Name ?? \"Unknown\"}\");\n \n // Ensure the script and script path are valid\n if (script == null)\n {\n _logService.LogError(\"Script object is null\");\n return false;\n }\n\n // Ensure the script name is not empty\n if (string.IsNullOrEmpty(script.Name))\n {\n _logService.LogError(\"Script name is empty\");\n return false;\n }\n\n // Ensure the script path exists\n string scriptPath = script.ScriptPath;\n if (!File.Exists(scriptPath))\n {\n _logService.LogError($\"Script file not found at: {scriptPath}\");\n \n // Try to save the script if it doesn't exist but has content\n if (!string.IsNullOrEmpty(script.Content))\n {\n try\n {\n string directoryPath = Path.GetDirectoryName(scriptPath);\n if (!Directory.Exists(directoryPath))\n {\n Directory.CreateDirectory(directoryPath);\n }\n \n File.WriteAllText(scriptPath, script.Content);\n _logService.LogInformation($\"Created script file at: {scriptPath}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to create script file: {ex.Message}\");\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n // Create the scheduled task using a direct PowerShell command\n string taskName = !string.IsNullOrEmpty(script.TargetScheduledTaskName) \n ? script.TargetScheduledTaskName \n : $\"Winhance\\\\{script.Name}\";\n\n // Create a simple PowerShell script that registers the task\n string psScript = $@\"\n# Register the scheduled task\n$scriptPath = '{scriptPath.Replace(\"'\", \"''\")}' # Escape single quotes\n$taskName = '{taskName.Replace(\"'\", \"''\")}'\n\n# Check if the task already exists and remove it\ntry {{\n $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue\n if ($existingTask) {{\n Write-Output \"\"Removing existing task: $taskName\"\"\n Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction Stop\n }}\n}} catch {{\n Write-Output \"\"Error removing existing task: $($_.Exception.Message)\"\"\n}}\n\n# Create the action to run the PowerShell script\ntry {{\n $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument \"\"-ExecutionPolicy Bypass -File `\"\"$scriptPath`\"\"\"\"\n $trigger = New-ScheduledTaskTrigger -AtStartup\n $settings = New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries\n \n # Register the task\n Register-ScheduledTask -TaskName $taskName `\n -Action $action `\n -Trigger $trigger `\n -User \"\"SYSTEM\"\" `\n -RunLevel Highest `\n -Settings $settings `\n -Force -ErrorAction Stop\n \n Write-Output \"\"Successfully registered scheduled task: $taskName\"\"\n exit 0\n}} catch {{\n Write-Output \"\"Error registering scheduled task: $($_.Exception.Message)\"\"\n exit 1\n}}\n\";\n\n // Save the script to a temporary file\n string tempScriptPath = Path.Combine(Path.GetTempPath(), $\"RegisterTask_{Guid.NewGuid()}.ps1\");\n File.WriteAllText(tempScriptPath, psScript);\n\n try\n {\n // Execute the script with elevated privileges\n using var process = new System.Diagnostics.Process();\n process.StartInfo.FileName = \"powershell.exe\";\n process.StartInfo.Arguments = $\"-ExecutionPolicy Bypass -File \\\"{tempScriptPath}\\\"\";\n process.StartInfo.UseShellExecute = true;\n process.StartInfo.Verb = \"runas\"; // Run as administrator\n process.StartInfo.CreateNoWindow = false;\n process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\n \n process.Start();\n await process.WaitForExitAsync();\n \n // Check if the process exited successfully\n if (process.ExitCode == 0)\n {\n _logService.LogSuccess($\"Successfully registered scheduled task: {taskName}\");\n return true;\n }\n else\n {\n _logService.LogError($\"Failed to register scheduled task: {taskName}, exit code: {process.ExitCode}\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error executing scheduled task registration script: {ex.Message}\");\n return false;\n }\n finally\n {\n // Clean up the temporary script\n try\n {\n if (File.Exists(tempScriptPath))\n {\n File.Delete(tempScriptPath);\n }\n }\n catch\n {\n // Ignore errors when deleting the temp file\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error registering scheduled task for script: {script?.Name ?? \"Unknown\"}\", ex);\n return false;\n }\n }\n\n /// \n public async Task UnregisterScheduledTaskAsync(string taskName)\n {\n try\n {\n _logService.LogInformation($\"Unregistering scheduled task: {taskName}\");\n \n // Create a simple PowerShell script that unregisters the task\n string psScript = $@\"\n# Unregister the scheduled task\n$taskName = '{taskName.Replace(\"'\", \"''\")}'\n\ntry {{\n $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue\n if ($existingTask) {{\n Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction Stop\n Write-Output \"\"Successfully unregistered task: $taskName\"\"\n exit 0\n }} else {{\n Write-Output \"\"Task not found: $taskName\"\"\n exit 0 # Not an error if the task doesn't exist\n }}\n}} catch {{\n Write-Output \"\"Error unregistering task: $($_.Exception.Message)\"\"\n exit 1\n}}\n\";\n\n // Save the script to a temporary file\n string tempScriptPath = Path.Combine(Path.GetTempPath(), $\"UnregisterTask_{Guid.NewGuid()}.ps1\");\n File.WriteAllText(tempScriptPath, psScript);\n\n try\n {\n // Execute the script with elevated privileges\n using var process = new System.Diagnostics.Process();\n process.StartInfo.FileName = \"powershell.exe\";\n process.StartInfo.Arguments = $\"-ExecutionPolicy Bypass -File \\\"{tempScriptPath}\\\"\";\n process.StartInfo.UseShellExecute = true;\n process.StartInfo.Verb = \"runas\"; // Run as administrator\n process.StartInfo.CreateNoWindow = false;\n process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\n \n process.Start();\n await process.WaitForExitAsync();\n \n // Check if the process exited successfully\n if (process.ExitCode == 0)\n {\n _logService.LogSuccess($\"Successfully unregistered scheduled task: {taskName}\");\n return true;\n }\n else\n {\n _logService.LogError($\"Failed to unregister scheduled task: {taskName}, exit code: {process.ExitCode}\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error executing scheduled task unregistration script: {ex.Message}\");\n return false;\n }\n finally\n {\n // Clean up the temporary script\n try\n {\n if (File.Exists(tempScriptPath))\n {\n File.Delete(tempScriptPath);\n }\n }\n catch\n {\n // Ignore errors when deleting the temp file\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error unregistering scheduled task: {taskName}\", ex);\n return false;\n }\n }\n\n /// \n public async Task IsTaskRegisteredAsync(string taskName)\n {\n try\n {\n // Create a simple PowerShell script that checks if the task exists\n string psScript = $@\"\n# Check if the scheduled task exists\n$taskName = '{taskName.Replace(\"'\", \"''\")}'\n\ntry {{\n $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue\n if ($existingTask) {{\n Write-Output \"\"Task exists: $taskName\"\"\n exit 0 # Exit code 0 means the task exists\n }} else {{\n Write-Output \"\"Task does not exist: $taskName\"\"\n exit 1 # Exit code 1 means the task does not exist\n }}\n}} catch {{\n Write-Output \"\"Error checking task: $($_.Exception.Message)\"\"\n exit 2 # Exit code 2 means an error occurred\n}}\n\";\n\n // Save the script to a temporary file\n string tempScriptPath = Path.Combine(Path.GetTempPath(), $\"CheckTask_{Guid.NewGuid()}.ps1\");\n File.WriteAllText(tempScriptPath, psScript);\n\n try\n {\n // Execute the script\n using var process = new System.Diagnostics.Process();\n process.StartInfo.FileName = \"powershell.exe\";\n process.StartInfo.Arguments = $\"-ExecutionPolicy Bypass -File \\\"{tempScriptPath}\\\"\";\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.CreateNoWindow = true;\n \n process.Start();\n await process.WaitForExitAsync();\n \n // Check the exit code to determine if the task exists\n return process.ExitCode == 0;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error executing scheduled task check script: {ex.Message}\");\n return false;\n }\n finally\n {\n // Clean up the temporary script\n try\n {\n if (File.Exists(tempScriptPath))\n {\n File.Delete(tempScriptPath);\n }\n }\n catch\n {\n // Ignore errors when deleting the temp file\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking if task exists: {taskName}\", ex);\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Resources/MaterialSymbols.cs", "using System.Collections.Generic;\n\nnamespace Winhance.WPF.Features.Common.Resources\n{\n /// \n /// Provides access to Material Symbols icon Unicode values.\n /// \n public static class MaterialSymbols\n {\n private static readonly Dictionary _iconMap = new Dictionary\n {\n // Navigation icons\n { \"RocketLaunch\", \"\\uEB9B\" },\n { \"Rocket\", \"\\uE837\" },\n { \"DeployedCode\", \"\\uE8A7\" },\n { \"DeployedCodeUpdate\", \"\\uE8A8\" },\n { \"CodeBraces\", \"\\uE86F\" },\n { \"Routine\", \"\\uEBB9\" },\n { \"ThemeLightDark\", \"\\uE51C\" },\n { \"Palette\", \"\\uE40A\" },\n { \"Information\", \"\\uE88E\" },\n { \"MicrosoftWindows\", \"\\uE950\" },\n\n // Other common icons\n { \"Apps\", \"\\uE5C3\" },\n { \"Settings\", \"\\uE8B8\" },\n { \"Close\", \"\\uE5CD\" },\n { \"Menu\", \"\\uE5D2\" },\n { \"Search\", \"\\uE8B6\" },\n { \"Add\", \"\\uE145\" },\n { \"Delete\", \"\\uE872\" },\n { \"Edit\", \"\\uE3C9\" },\n { \"Save\", \"\\uE161\" },\n { \"Download\", \"\\uE2C4\" },\n { \"Upload\", \"\\uE2C6\" },\n { \"Refresh\", \"\\uE5D5\" },\n { \"ArrowBack\", \"\\uE5C4\" },\n { \"ArrowForward\", \"\\uE5C8\" },\n { \"ChevronDown\", \"\\uE5CF\" },\n { \"ChevronUp\", \"\\uE5CE\" },\n { \"ChevronLeft\", \"\\uE5CB\" },\n { \"ChevronRight\", \"\\uE5CC\" },\n { \"ExpandMore\", \"\\uE5CF\" },\n { \"ExpandLess\", \"\\uE5CE\" },\n { \"MoreVert\", \"\\uE5D4\" },\n { \"MoreHoriz\", \"\\uE5D3\" },\n { \"Check\", \"\\uE5CA\" },\n { \"Clear\", \"\\uE14C\" },\n { \"Error\", \"\\uE000\" },\n { \"Warning\", \"\\uE002\" },\n { \"Info\", \"\\uE88E\" },\n { \"Help\", \"\\uE887\" },\n { \"HelpOutline\", \"\\uE8FD\" },\n { \"Sync\", \"\\uE627\" },\n { \"SyncDisabled\", \"\\uE628\" },\n { \"SyncProblem\", \"\\uE629\" },\n { \"Visibility\", \"\\uE8F4\" },\n { \"VisibilityOff\", \"\\uE8F5\" },\n { \"Lock\", \"\\uE897\" },\n { \"LockOpen\", \"\\uE898\" },\n { \"Star\", \"\\uE838\" },\n { \"StarBorder\", \"\\uE83A\" },\n { \"Favorite\", \"\\uE87D\" },\n { \"FavoriteBorder\", \"\\uE87E\" },\n { \"ThumbUp\", \"\\uE8DC\" },\n { \"ThumbDown\", \"\\uE8DB\" },\n { \"MicrosoftWindows\", \"\\uE9AA\" }\n };\n\n /// \n /// Gets the Unicode character for the specified icon name.\n /// \n /// The name of the icon.\n /// The Unicode character for the icon, or a question mark if not found.\n public static string GetIcon(string iconName)\n {\n if (_iconMap.TryGetValue(iconName, out string iconChar))\n {\n return iconChar;\n }\n\n return \"?\"; // Return a question mark if the icon is not found\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Services/LogService.cs", "using System;\nusing System.IO;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Services\n{\n public class LogService : ILogService\n {\n private string _logPath;\n private StreamWriter? _logWriter;\n private readonly object _lockObject = new object();\n \n public event EventHandler? LogMessageGenerated;\n\n public LogService()\n {\n _logPath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\",\n $\"Winhance_Log_{DateTime.Now:yyyyMMdd_HHmmss}.log\"\n );\n }\n\n public void Log(LogLevel level, string message, Exception? exception = null)\n {\n switch (level)\n {\n case LogLevel.Info:\n LogInformation(message);\n break;\n case LogLevel.Warning:\n LogWarning(message);\n break;\n case LogLevel.Error:\n LogError(message, exception);\n break;\n case LogLevel.Success:\n LogSuccess(message);\n break;\n default:\n LogInformation(message);\n break;\n }\n \n // Raise event for subscribers\n LogMessageGenerated?.Invoke(this, new LogMessageEventArgs(level, message, exception));\n }\n \n // This method should be removed, but it might still be used in some places\n // Redirecting to the standard method with correct parameter order\n public void Log(string message, LogLevel level)\n {\n Log(level, message);\n }\n\n public void StartLog()\n {\n try\n {\n // Ensure directory exists\n var logDirectory = Path.GetDirectoryName(_logPath);\n if (logDirectory != null)\n {\n Directory.CreateDirectory(logDirectory);\n }\n else\n {\n throw new InvalidOperationException(\"Log directory path is null.\");\n }\n\n // Create or overwrite log file\n _logWriter = new StreamWriter(_logPath, false, Encoding.UTF8)\n {\n AutoFlush = true\n };\n\n // Write initial log header\n LogInformation($\"==== Winhance Log Started ====\");\n LogInformation($\"Timestamp: {DateTime.Now}\");\n LogInformation($\"User: {Environment.UserName}\");\n LogInformation($\"Machine: {Environment.MachineName}\");\n LogInformation($\"OS Version: {Environment.OSVersion}\");\n LogInformation(\"===========================\");\n }\n catch (Exception ex)\n {\n // Fallback logging if file write fails\n Console.Error.WriteLine($\"Failed to start log: {ex.Message}\");\n }\n }\n\n public void StopLog()\n {\n lock (_lockObject)\n {\n try\n {\n LogInformation(\"==== Winhance Log Ended ====\");\n _logWriter?.Close();\n _logWriter?.Dispose();\n }\n catch (Exception ex)\n {\n Console.Error.WriteLine($\"Error stopping log: {ex.Message}\");\n }\n }\n }\n\n public void LogInformation(string message)\n {\n WriteLog(message, \"INFO\");\n }\n\n public void LogWarning(string message)\n {\n WriteLog(message, \"WARNING\");\n }\n\n public void LogError(string message, Exception? exception = null)\n {\n string fullMessage = exception != null\n ? $\"{message} - Exception: {exception.Message}\\n{exception.StackTrace}\"\n : message;\n WriteLog(fullMessage, \"ERROR\");\n }\n\n public void LogSuccess(string message)\n {\n WriteLog(message, \"SUCCESS\");\n }\n\n public string GetLogPath()\n {\n return _logPath;\n }\n\n private void WriteLog(string message, string level)\n {\n lock (_lockObject)\n {\n try\n {\n string logEntry = $\"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}\";\n\n // Write to file if log writer is available\n _logWriter?.WriteLine(logEntry);\n\n // Also write to console for immediate visibility\n Console.WriteLine(logEntry);\n }\n catch (Exception ex)\n {\n Console.Error.WriteLine($\"Logging failed: {ex.Message}\");\n }\n }\n }\n\n // Implement IDisposable pattern to ensure logs are stopped\n public void Dispose()\n {\n StopLog();\n GC.SuppressFinalize(this);\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/WindowsAppsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.SoftwareApps.Models;\nusing ToastType = Winhance.Core.Features.UI.Interfaces.ToastType;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n public partial class WindowsAppsViewModel : BaseInstallationViewModel\n {\n private readonly IAppInstallationService _appInstallationService;\n private readonly ICapabilityInstallationService _capabilityService;\n private readonly IFeatureInstallationService _featureService;\n private readonly IFeatureRemovalService _featureRemovalService;\n private readonly IAppService _appDiscoveryService;\n private readonly IConfigurationService _configurationService;\n private readonly IScriptDetectionService _scriptDetectionService;\n private readonly IInternetConnectivityService _connectivityService;\n private readonly IAppInstallationCoordinatorService _appInstallationCoordinatorService;\n\n [ObservableProperty]\n private string _statusText = \"Ready\";\n\n [ObservableProperty]\n private bool _isRemovingApps;\n\n [ObservableProperty]\n private ObservableCollection _activeScripts = new();\n\n // Flag to prevent duplicate initialization\n [ObservableProperty]\n private bool _isInitialized = false;\n\n // For binding in the WindowsAppsView - filtered collections\n // Standard Windows Apps (Appx packages)\n public System.Collections.ObjectModel.ObservableCollection WindowsApps { get; } =\n new();\n\n // Windows Capabilities\n public System.Collections.ObjectModel.ObservableCollection Capabilities { get; } =\n new();\n\n // Optional Features\n public System.Collections.ObjectModel.ObservableCollection OptionalFeatures { get; } =\n new();\n\n public WindowsAppsViewModel(\n ITaskProgressService progressService,\n ISearchService searchService,\n IPackageManager packageManager,\n IAppInstallationService appInstallationService,\n ICapabilityInstallationService capabilityService,\n IFeatureInstallationService featureService,\n IFeatureRemovalService featureRemovalService,\n IConfigurationService configurationService,\n IScriptDetectionService scriptDetectionService,\n IInternetConnectivityService connectivityService,\n IAppInstallationCoordinatorService appInstallationCoordinatorService,\n Services.SoftwareAppsDialogService dialogService\n )\n : base(\n progressService,\n searchService,\n packageManager,\n appInstallationService,\n appInstallationCoordinatorService,\n connectivityService,\n dialogService\n )\n {\n _appInstallationService = appInstallationService;\n _capabilityService = capabilityService;\n _featureService = featureService;\n _featureRemovalService = featureRemovalService;\n _appDiscoveryService = packageManager?.AppDiscoveryService;\n _configurationService = configurationService;\n _scriptDetectionService = scriptDetectionService;\n _connectivityService = connectivityService;\n _appInstallationCoordinatorService = appInstallationCoordinatorService;\n }\n\n // SaveConfig and ImportConfig methods removed as part of unified configuration cleanup\n\n /// \n /// Applies the current search text to filter items.\n /// \n protected override void ApplySearch()\n {\n if (Items == null || Items.Count == 0)\n return;\n\n // Clear all collections\n WindowsApps.Clear();\n Capabilities.Clear();\n OptionalFeatures.Clear();\n\n // Filter items based on search text\n var filteredItems = FilterItems(Items);\n\n // Add filtered items to their respective collections\n foreach (var app in filteredItems)\n {\n switch (app.AppType)\n {\n case Models.WindowsAppType.StandardApp:\n WindowsApps.Add(app);\n break;\n case Models.WindowsAppType.Capability:\n Capabilities.Add(app);\n break;\n case Models.WindowsAppType.OptionalFeature:\n OptionalFeatures.Add(app);\n break;\n }\n }\n\n // Sort the filtered collections\n SortCollections();\n }\n\n /// \n /// Refreshes the script status information.\n /// \n public void RefreshScriptStatus()\n {\n if (_scriptDetectionService == null)\n return;\n\n IsRemovingApps = _scriptDetectionService.AreRemovalScriptsPresent();\n\n ActiveScripts.Clear();\n foreach (var script in _scriptDetectionService.GetActiveScripts())\n {\n ActiveScripts.Add(script);\n }\n }\n\n public override async Task LoadItemsAsync()\n {\n if (_appDiscoveryService == null)\n return;\n\n IsLoading = true;\n StatusText = \"Loading Windows apps...\";\n\n try\n {\n // Clear all collections\n Items.Clear();\n WindowsApps.Clear();\n Capabilities.Clear();\n OptionalFeatures.Clear();\n\n // Load standard Windows apps (Appx packages)\n var apps = await _appDiscoveryService.GetStandardAppsAsync();\n\n // Load capabilities\n var capabilities = await _appDiscoveryService.GetCapabilitiesAsync();\n\n // Load optional features\n var features = await _appDiscoveryService.GetOptionalFeaturesAsync();\n\n // Convert all to WindowsApp objects and add to the main collection\n foreach (var app in apps)\n {\n var windowsApp = WindowsApp.FromAppInfo(app);\n // AppType is already set in FromAppInfo\n Items.Add(windowsApp);\n WindowsApps.Add(windowsApp);\n }\n\n foreach (var capability in capabilities)\n {\n var windowsApp = WindowsApp.FromCapabilityInfo(capability);\n // AppType is already set in FromCapabilityInfo\n Items.Add(windowsApp);\n Capabilities.Add(windowsApp);\n }\n\n foreach (var feature in features)\n {\n var windowsApp = WindowsApp.FromFeatureInfo(feature);\n // AppType is already set in FromFeatureInfo\n Items.Add(windowsApp);\n OptionalFeatures.Add(windowsApp);\n }\n\n StatusText =\n $\"Loaded {WindowsApps.Count} apps, {Capabilities.Count} capabilities, and {OptionalFeatures.Count} features\";\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error loading Windows apps: {ex.Message}\";\n }\n finally\n {\n IsLoading = false;\n\n // Check script status\n RefreshScriptStatus();\n }\n }\n\n public override async Task CheckInstallationStatusAsync()\n {\n if (_appDiscoveryService == null)\n return;\n\n IsLoading = true;\n StatusText = \"Checking installation status...\";\n\n try\n {\n var statusResults = await _appDiscoveryService.GetBatchInstallStatusAsync(\n Items.Select(a => a.PackageName)\n );\n\n foreach (var app in Items)\n {\n if (statusResults.TryGetValue(app.PackageName, out bool isInstalled))\n {\n app.IsInstalled = isInstalled;\n }\n }\n\n // Sort all collections after we have the installation status\n SortCollections();\n\n StatusText = \"Installation status check complete\";\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error checking installation status: {ex.Message}\";\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n private void SortCollections()\n {\n // Sort apps within each collection by installed status (installed first) then alphabetically\n SortCollection(WindowsApps);\n SortCollection(Capabilities);\n SortCollection(OptionalFeatures);\n }\n\n private void SortCollection(\n System.Collections.ObjectModel.ObservableCollection collection\n )\n {\n var sorted = collection\n .OrderByDescending(app => app.IsInstalled) // Installed first\n .ThenBy(app => app.Name) // Then alphabetically\n .ToList();\n\n collection.Clear();\n foreach (var app in sorted)\n {\n collection.Add(app);\n }\n }\n\n #region Dialog Helper Methods\n\n /// \n /// Gets the past tense form of an operation type\n /// \n /// The operation type (e.g., \"Install\", \"Remove\")\n /// The past tense form of the operation type\n private string GetPastTense(string operationType)\n {\n if (string.IsNullOrEmpty(operationType))\n return string.Empty;\n\n return operationType.Equals(\"Remove\", StringComparison.OrdinalIgnoreCase)\n ? \"removed\"\n : $\"{operationType.ToLower()}ed\";\n }\n\n /// \n /// Shows a confirmation dialog before performing operations.\n /// \n /// Type of operation (Install/Remove)\n /// List of apps selected for the operation\n /// List of apps that will be skipped (optional)\n /// Dialog result (true if confirmed, false if canceled)\n private bool? ShowOperationConfirmationDialog(\n string operationType,\n IEnumerable selectedApps,\n IEnumerable? skippedApps = null\n )\n {\n // Use the base class implementation that uses the dialog service\n var result = ShowOperationConfirmationDialogAsync(\n operationType,\n selectedApps,\n skippedApps\n )\n .GetAwaiter()\n .GetResult();\n return result ? true : (bool?)false;\n }\n\n /// \n /// Shows an operation result dialog after operations complete.\n /// \n /// Type of operation (Install/Remove)\n /// Number of successful operations\n /// Total number of operations attempted\n /// List of successfully processed items\n /// List of failed items (optional)\n /// List of skipped items (optional)\n private void ShowOperationResultDialog(\n string operationType,\n int successCount,\n int totalCount,\n IEnumerable successItems,\n IEnumerable? failedItems = null,\n IEnumerable? skippedItems = null\n )\n {\n // Use the base class implementation that uses the dialog service\n base.ShowOperationResultDialog(\n operationType,\n successCount,\n totalCount,\n successItems,\n failedItems,\n skippedItems\n );\n }\n\n #endregion\n\n public async Task LoadAppsAndCheckInstallationStatusAsync()\n {\n if (IsInitialized)\n {\n System.Diagnostics.Debug.WriteLine(\n \"WindowsAppsViewModel already initialized, skipping LoadAppsAndCheckInstallationStatusAsync\"\n );\n return;\n }\n\n System.Diagnostics.Debug.WriteLine(\"Starting LoadAppsAndCheckInstallationStatusAsync\");\n await LoadItemsAsync();\n await CheckInstallationStatusAsync();\n\n // Set Select All to true by default when view loads\n IsAllSelected = true;\n\n // Mark as initialized after loading is complete\n IsInitialized = true;\n\n // Check script status\n RefreshScriptStatus();\n System.Diagnostics.Debug.WriteLine(\"Completed LoadAppsAndCheckInstallationStatusAsync\");\n }\n\n [RelayCommand]\n public async Task InstallApp(WindowsApp app)\n {\n if (app == null || _appInstallationService == null)\n System.Diagnostics.Debug.WriteLine(\n \"Starting LoadAppsAndCheckInstallationStatusAsync\"\n );\n await LoadItemsAsync();\n await CheckInstallationStatusAsync();\n\n // Set Select All to true by default when view loads\n IsAllSelected = true;\n bool isInternetConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(true);\n if (!isInternetConnected)\n {\n StatusText = \"No internet connection available. Installation cannot proceed.\";\n\n // Show dialog informing the user about the connectivity issue\n await ShowNoInternetConnectionDialogAsync();\n return;\n }\n\n // Show confirmation dialog\n bool? dialogResult = ShowOperationConfirmationDialog(\"Install\", new[] { app });\n\n // If user didn't confirm, exit\n if (dialogResult != true)\n {\n return;\n }\n\n IsLoading = true;\n StatusText = $\"Installing {app.Name}...\";\n\n // Setup cancellation for the installation process\n using var cts = new System.Threading.CancellationTokenSource();\n var cancellationToken = cts.Token;\n\n try\n {\n var progress = _progressService.CreateDetailedProgress();\n\n // Subscribe to installation status changes\n void OnInstallationStatusChanged(\n object sender,\n InstallationStatusChangedEventArgs e\n )\n {\n if (e.AppInfo.PackageID == app.PackageID)\n {\n StatusText = e.StatusMessage;\n }\n }\n\n // Register for status updates\n _appInstallationCoordinatorService.InstallationStatusChanged +=\n OnInstallationStatusChanged;\n\n try\n {\n // Use the coordinator service to handle installation, connectivity monitoring, and status reporting\n var coordinationResult =\n await _appInstallationCoordinatorService.InstallAppAsync(\n app.ToAppInfo(),\n progress,\n cancellationToken\n );\n\n if (coordinationResult.Success)\n {\n app.IsInstalled = true;\n StatusText = $\"Successfully installed {app.Name}\";\n\n // Show result dialog\n ShowOperationResultDialog(\"Install\", 1, 1, new[] { app.Name });\n }\n else\n {\n string errorMessage =\n coordinationResult.ErrorMessage\n ?? $\"Failed to install {app.Name}. Please try again.\";\n StatusText = errorMessage;\n\n // Determine the type of failure for the dialog\n if (coordinationResult.WasCancelled)\n {\n // Show cancellation dialog\n ShowOperationResultDialog(\n \"Install\",\n 0,\n 1,\n Array.Empty(),\n new[] { $\"{app.Name}: Installation was cancelled by user\" }\n );\n }\n else if (coordinationResult.WasConnectivityIssue)\n {\n // Show connectivity issue dialog\n ShowOperationResultDialog(\n \"Install\",\n 0,\n 1,\n Array.Empty(),\n new[]\n {\n $\"{app.Name}: Internet connection lost during installation. Please check your network connection and try again.\",\n }\n );\n }\n else\n {\n // Show general error dialog\n ShowOperationResultDialog(\n \"Install\",\n 0,\n 1,\n Array.Empty(),\n new[] { $\"{app.Name}: {errorMessage}\" }\n );\n }\n }\n }\n finally\n {\n // Always unregister from the event\n _appInstallationCoordinatorService.InstallationStatusChanged -=\n OnInstallationStatusChanged;\n }\n }\n catch (System.Exception ex)\n {\n // This should rarely happen as most exceptions are handled by the coordinator service\n StatusText = $\"Error installing {app.Name}: {ex.Message}\";\n\n // Show error dialog\n ShowOperationResultDialog(\n \"Install\",\n 0,\n 1,\n Array.Empty(),\n new[] { $\"{app.Name}: {ex.Message}\" }\n );\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n // The StartPeriodicConnectivityCheck method has been removed as this functionality is now handled by the AppInstallationCoordinatorService\n\n [RelayCommand]\n public async Task RemoveApp(WindowsApp app)\n {\n if (app == null || _packageManager == null)\n return;\n\n // Show confirmation dialog\n bool? dialogResult = ShowOperationConfirmationDialog(\"Remove\", new[] { app });\n\n // If user didn't confirm, exit\n if (dialogResult != true)\n {\n return;\n }\n\n IsLoading = true;\n StatusText = $\"Removing {app.Name}...\";\n bool success = false;\n\n try\n {\n // Check if this is a special app that requires special handling\n if (app.IsSpecialHandler && !string.IsNullOrEmpty(app.SpecialHandlerType))\n {\n // Use the appropriate special handler method\n switch (app.SpecialHandlerType)\n {\n case \"Edge\":\n success = await _packageManager.RemoveEdgeAsync();\n break;\n case \"OneDrive\":\n success = await _packageManager.RemoveOneDriveAsync();\n break;\n case \"OneNote\":\n success = await _packageManager.RemoveOneNoteAsync();\n break;\n default:\n success = await _packageManager.RemoveSpecialAppAsync(\n app.SpecialHandlerType\n );\n break;\n }\n\n if (success)\n {\n app.IsInstalled = false;\n StatusText = $\"Successfully removed special app: {app.Name}\";\n }\n else\n {\n StatusText = $\"Failed to remove special app: {app.Name}\";\n }\n }\n else\n {\n // Regular app removal\n bool isCapability =\n app.AppType\n == Winhance.WPF.Features.SoftwareApps.Models.WindowsAppType.Capability;\n success = await _packageManager.RemoveAppAsync(app.PackageName, isCapability);\n if (success)\n {\n app.IsInstalled = false;\n StatusText = $\"Successfully removed {app.Name}\";\n }\n else\n {\n StatusText = $\"Failed to remove {app.Name}\";\n }\n }\n\n // Show result dialog\n ShowOperationResultDialog(\n \"Remove\",\n success ? 1 : 0,\n 1,\n success ? new[] { app.Name } : Array.Empty(),\n success ? Array.Empty() : new[] { app.Name }\n );\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error removing {app.Name}: {ex.Message}\";\n\n // Show error dialog\n ShowOperationResultDialog(\n \"Remove\",\n 0,\n 1,\n Array.Empty(),\n new[] { $\"{app.Name}: {ex.Message}\" }\n );\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n public override async void OnNavigatedTo(object parameter)\n {\n try\n {\n // Only load data if not already initialized\n if (!IsInitialized)\n {\n await LoadAppsAndCheckInstallationStatusAsync();\n IsInitialized = true;\n }\n }\n catch (System.Exception ex)\n {\n StatusText = $\"Error loading apps: {ex.Message}\";\n IsLoading = false;\n // Log the error or handle it appropriately\n }\n }\n\n // Add IsAllSelected property for the \"Select All\" checkbox\n private bool _isAllSelected;\n public bool IsAllSelected\n {\n get => _isAllSelected;\n set\n {\n if (SetProperty(ref _isAllSelected, value))\n {\n // Apply to all items across all categories\n foreach (var app in WindowsApps)\n {\n app.IsSelected = value;\n }\n\n foreach (var capability in Capabilities)\n {\n capability.IsSelected = value;\n }\n\n foreach (var feature in OptionalFeatures)\n {\n feature.IsSelected = value;\n }\n }\n }\n }\n\n [RelayCommand]\n public async Task RemoveApps()\n {\n if (_packageManager == null)\n return;\n\n // Get selected items from all categories\n var selectedApps = WindowsApps.Where(a => a.IsSelected).ToList();\n var selectedCapabilities = Capabilities.Where(a => a.IsSelected).ToList();\n var selectedFeatures = OptionalFeatures.Where(a => a.IsSelected).ToList();\n\n // Combine all selected items\n var allSelectedItems = selectedApps\n .Concat(selectedCapabilities.Cast())\n .Concat(selectedFeatures.Cast())\n .ToList();\n\n int totalSelected = allSelectedItems.Count;\n\n if (totalSelected == 0)\n {\n StatusText = \"No items selected for removal\";\n return;\n }\n\n // Show confirmation dialog\n bool? dialogResult = ShowOperationConfirmationDialog(\"Remove\", allSelectedItems);\n\n // If user didn't confirm, exit\n if (dialogResult != true)\n {\n return;\n }\n\n // Use the ExecuteWithProgressAsync method from BaseViewModel to handle progress reporting\n await ExecuteWithProgressAsync(\n async (progress, cancellationToken) =>\n {\n int successCount = 0;\n int currentItem = 0;\n\n // Process standard Windows apps\n foreach (var app in selectedApps)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Removing app {app.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage = $\"Removing Windows App: {app.Name}\",\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", app.AppType.ToString() },\n { \"PackageName\", app.PackageName },\n { \"IsSystemProtected\", app.IsSystemProtected.ToString() },\n { \"CanBeReinstalled\", app.CanBeReinstalled.ToString() },\n { \"OperationType\", \"Remove\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n\n try\n {\n // Check if this is a special app that requires special handling\n if (\n app.IsSpecialHandler\n && !string.IsNullOrEmpty(app.SpecialHandlerType)\n )\n {\n // Use the appropriate special handler method\n bool success = false;\n switch (app.SpecialHandlerType)\n {\n case \"Edge\":\n success = await _packageManager.RemoveEdgeAsync();\n break;\n case \"OneDrive\":\n success = await _packageManager.RemoveOneDriveAsync();\n break;\n case \"OneNote\":\n success = await _packageManager.RemoveOneNoteAsync();\n break;\n default:\n success = await _packageManager.RemoveSpecialAppAsync(\n app.SpecialHandlerType\n );\n break;\n }\n\n if (success)\n {\n app.IsInstalled = false;\n successCount++;\n }\n }\n else\n {\n // Regular app removal\n bool success = await _packageManager.RemoveAppAsync(\n app.PackageName,\n false\n );\n if (success)\n {\n app.IsInstalled = false;\n successCount++;\n }\n }\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Successfully removed {app.Name}\",\n DetailedMessage =\n $\"Successfully removed Windows App: {app.Name}\",\n LogLevel = LogLevel.Success,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", app.AppType.ToString() },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Success\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Error removing {app.Name}\",\n DetailedMessage = $\"Error removing {app.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", app.AppType.ToString() },\n { \"PackageName\", app.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Error\" },\n { \"ErrorMessage\", ex.Message },\n { \"ErrorType\", ex.GetType().Name },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n\n // Process capabilities\n foreach (var capability in selectedCapabilities)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Removing capability {capability.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage = $\"Removing Windows Capability: {capability.Name}\",\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", capability.AppType.ToString() },\n { \"PackageName\", capability.PackageName },\n {\n \"IsSystemProtected\",\n capability.IsSystemProtected.ToString()\n },\n { \"CanBeReinstalled\", capability.CanBeReinstalled.ToString() },\n { \"OperationType\", \"Remove\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n\n try\n {\n bool success = await _packageManager.RemoveAppAsync(\n capability.PackageName,\n true\n );\n\n if (success)\n {\n capability.IsInstalled = false;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Successfully removed capability {capability.Name}\",\n DetailedMessage =\n $\"Successfully removed Windows Capability: {capability.Name}\",\n LogLevel = LogLevel.Success,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", capability.AppType.ToString() },\n { \"PackageName\", capability.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Success\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n else\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Failed to remove capability {capability.Name}\",\n DetailedMessage =\n $\"Failed to remove Windows Capability: {capability.Name}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", capability.AppType.ToString() },\n { \"PackageName\", capability.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Error\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Error removing capability {capability.Name}\",\n DetailedMessage =\n $\"Error removing capability {capability.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", capability.AppType.ToString() },\n { \"PackageName\", capability.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Error\" },\n { \"ErrorMessage\", ex.Message },\n { \"ErrorType\", ex.GetType().Name },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n\n // Process optional features\n foreach (var feature in selectedFeatures)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Removing feature {feature.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage = $\"Removing Windows Feature: {feature.Name}\",\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", feature.AppType.ToString() },\n { \"PackageName\", feature.PackageName },\n { \"IsSystemProtected\", feature.IsSystemProtected.ToString() },\n { \"CanBeReinstalled\", feature.CanBeReinstalled.ToString() },\n { \"OperationType\", \"Remove\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n\n try\n {\n if (_featureRemovalService != null)\n {\n bool success = await _featureRemovalService.RemoveFeatureAsync(\n feature.ToFeatureInfo()\n );\n if (success)\n {\n feature.IsInstalled = false;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Successfully removed feature {feature.Name}\",\n DetailedMessage =\n $\"Successfully removed Windows Feature: {feature.Name}\",\n LogLevel = LogLevel.Success,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", feature.AppType.ToString() },\n { \"PackageName\", feature.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Success\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n else\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Failed to remove feature {feature.Name}\",\n DetailedMessage =\n $\"Failed to remove Windows Feature: {feature.Name}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", feature.AppType.ToString() },\n { \"PackageName\", feature.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Error\" },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText = $\"Error removing feature {feature.Name}\",\n DetailedMessage =\n $\"Error removing feature {feature.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"AppType\", feature.AppType.ToString() },\n { \"PackageName\", feature.PackageName },\n { \"OperationType\", \"Remove\" },\n { \"OperationStatus\", \"Error\" },\n { \"ErrorMessage\", ex.Message },\n { \"ErrorType\", ex.GetType().Name },\n { \"ItemNumber\", currentItem.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n },\n }\n );\n }\n }\n\n // Final report\n progress.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText =\n $\"Successfully removed {successCount} of {totalSelected} items\",\n DetailedMessage =\n $\"Task completed: {successCount} of {totalSelected} items removed successfully\",\n LogLevel =\n successCount == totalSelected ? LogLevel.Success : LogLevel.Warning,\n AdditionalInfo = new Dictionary\n {\n { \"OperationType\", \"Remove\" },\n {\n \"OperationStatus\",\n successCount == totalSelected ? \"Complete\" : \"PartialSuccess\"\n },\n { \"SuccessCount\", successCount.ToString() },\n { \"TotalItems\", totalSelected.ToString() },\n { \"SuccessRate\", $\"{(successCount * 100.0 / totalSelected):F1}%\" },\n { \"StandardAppsCount\", selectedApps.Count.ToString() },\n { \"CapabilitiesCount\", selectedCapabilities.Count.ToString() },\n { \"FeaturesCount\", selectedFeatures.Count.ToString() },\n {\n \"CompletionTime\",\n System.DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\")\n },\n },\n }\n );\n\n // Refresh the UI\n SortCollections();\n\n // Check if the operation was cancelled by the user or due to connectivity issues\n if (CurrentCancellationReason == CancellationReason.UserCancelled)\n {\n // Log the user cancellation\n System.Diagnostics.Debug.WriteLine(\"[DEBUG] Installation cancelled by user - showing user cancellation dialog\");\n \n // Show the cancellation dialog\n await ShowCancellationDialogAsync(true, false);\n \n // Reset cancellation reason after showing dialog\n CurrentCancellationReason = CancellationReason.None;\n return successCount;\n }\n else if (CurrentCancellationReason == CancellationReason.InternetConnectivityLost)\n {\n // Log the connectivity loss\n System.Diagnostics.Debug.WriteLine(\"[DEBUG] Installation stopped due to connectivity loss - showing connectivity loss dialog\");\n \n // Show the connectivity loss dialog\n await ShowCancellationDialogAsync(false, true);\n \n // Reset cancellation reason after showing dialog\n CurrentCancellationReason = CancellationReason.None;\n return successCount;\n }\n \n // Only proceed with normal completion reporting if not cancelled\n // For normal completion (not cancelled), collect success and failure information\n var successItems = new List();\n var failedItems = new List();\n\n // Add successful items to the list\n foreach (var app in selectedApps.Where(a => !a.IsInstalled))\n {\n successItems.Add(app.Name);\n }\n foreach (var capability in selectedCapabilities.Where(c => !c.IsInstalled))\n {\n successItems.Add(capability.Name);\n }\n foreach (var feature in selectedFeatures.Where(f => !f.IsInstalled))\n {\n successItems.Add(feature.Name);\n }\n\n // Add failed items to the list\n foreach (var app in selectedApps.Where(a => a.IsInstalled))\n {\n failedItems.Add(app.Name);\n }\n foreach (var capability in selectedCapabilities.Where(c => c.IsInstalled))\n {\n failedItems.Add(capability.Name);\n }\n foreach (var feature in selectedFeatures.Where(f => f.IsInstalled))\n {\n failedItems.Add(feature.Name);\n }\n\n // Show result dialog\n ShowOperationResultDialog(\n \"Remove\",\n successCount,\n totalSelected,\n successItems,\n failedItems\n );\n\n return successCount;\n },\n $\"Removing {totalSelected} items\",\n false\n );\n }\n\n [RelayCommand]\n public async Task InstallApps()\n {\n if (\n _packageManager == null\n || _appInstallationService == null\n || _capabilityService == null\n || _featureService == null\n )\n return;\n\n // Get all selected items\n var selectedApps = WindowsApps.Where(a => a.IsSelected).ToList();\n var selectedCapabilities = Capabilities.Where(a => a.IsSelected).ToList();\n var selectedFeatures = OptionalFeatures.Where(a => a.IsSelected).ToList();\n\n // Check if anything is selected at all\n int totalSelected =\n selectedApps.Count + selectedCapabilities.Count + selectedFeatures.Count;\n\n if (totalSelected == 0)\n {\n StatusText = \"No items selected for installation\";\n await ShowNoItemsSelectedDialogAsync(\"installation\");\n return;\n }\n\n // Identify items that cannot be reinstalled\n var nonReinstallableApps = selectedApps.Where(a => !a.CanBeReinstalled).ToList();\n var nonReinstallableCapabilities = selectedCapabilities\n .Where(c => !c.CanBeReinstalled)\n .ToList();\n var nonReinstallableFeatures = selectedFeatures\n .Where(f => !f.CanBeReinstalled)\n .ToList();\n\n var allNonReinstallableItems = nonReinstallableApps\n .Concat(nonReinstallableCapabilities)\n .Concat(nonReinstallableFeatures)\n .ToList();\n\n // Remove non-reinstallable items from the selected items\n var installableApps = selectedApps.Except(nonReinstallableApps).ToList();\n var installableCapabilities = selectedCapabilities\n .Except(nonReinstallableCapabilities)\n .ToList();\n var installableFeatures = selectedFeatures.Except(nonReinstallableFeatures).ToList();\n\n var allInstallableItems = installableApps\n .Concat(installableCapabilities.Cast())\n .Concat(installableFeatures.Cast())\n .ToList();\n\n if (allInstallableItems.Count == 0)\n {\n if (allNonReinstallableItems.Any())\n {\n // Show dialog explaining that all selected items cannot be reinstalled\n await ShowCannotReinstallDialogAsync(\n allNonReinstallableItems.Select(a => a.Name),\n false\n );\n }\n else\n {\n StatusText = \"No items selected for installation\";\n }\n return;\n }\n\n // Show confirmation dialog, including information about skipped items\n // Show confirmation dialog\n bool? dialogResult = await ShowConfirmItemsDialogAsync(\n \"install\",\n allInstallableItems.Select(a => a.Name),\n allInstallableItems.Count\n );\n\n // If user didn't confirm, exit\n if (dialogResult != true)\n {\n return;\n }\n\n // Check for internet connectivity before starting installation\n bool isInternetConnected =\n await _packageManager.SystemServices.IsInternetConnectedAsync(true);\n if (!isInternetConnected)\n {\n StatusText = \"No internet connection available. Installation cannot proceed.\";\n\n // Show dialog informing the user about the connectivity issue\n await ShowNoInternetConnectionDialogAsync();\n return;\n }\n\n // Use the ExecuteWithProgressAsync method from BaseViewModel to handle progress reporting\n await ExecuteWithProgressAsync(\n async (progress, cancellationToken) =>\n {\n int successCount = 0;\n int currentItem = 0;\n\n // Process standard Windows apps\n foreach (var app in installableApps)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Installing app {app.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage = $\"Installing Windows App: {app.Name}\",\n }\n );\n\n try\n {\n var result = await _appInstallationService.InstallAppAsync(\n app.ToAppInfo(),\n progress,\n cancellationToken\n );\n\n // Only mark as successful if the operation actually succeeded\n if (result.Success && result.Result)\n {\n app.IsInstalled = true;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage = $\"Successfully installed {app.Name}\",\n LogLevel = LogLevel.Success,\n }\n );\n }\n else\n {\n // The operation returned but was not successful\n string errorMessage =\n result.ErrorMessage\n ?? \"Unknown error occurred during installation\";\n\n // Check if it's an internet connectivity issue\n if (\n errorMessage.Contains(\"internet\")\n || errorMessage.Contains(\"connection\")\n )\n {\n errorMessage =\n $\"No internet connection available. Please check your network connection and try again.\";\n }\n\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage =\n $\"Failed to install {app.Name}: {errorMessage}\",\n LogLevel = LogLevel.Error,\n }\n );\n }\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage = $\"Error installing {app.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n }\n }\n\n // Process capabilities\n foreach (var capability in installableCapabilities)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Installing capability {capability.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage =\n $\"Installing Windows Capability: {capability.Name}\",\n }\n );\n\n try\n {\n await _capabilityService.InstallCapabilityAsync(\n capability.ToCapabilityInfo(),\n progress,\n cancellationToken\n );\n capability.IsInstalled = true;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage =\n $\"Successfully installed capability {capability.Name}\",\n LogLevel = LogLevel.Success,\n }\n );\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage =\n $\"Error installing capability {capability.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n }\n }\n\n // Process optional features\n foreach (var feature in installableFeatures)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Set cancellation reason to user cancelled\n CurrentCancellationReason = CancellationReason.UserCancelled;\n break;\n }\n\n currentItem++;\n progress.Report(\n new TaskProgressDetail\n {\n Progress = (currentItem * 100.0) / totalSelected,\n StatusText =\n $\"Installing feature {feature.Name}... ({currentItem}/{totalSelected})\",\n DetailedMessage = $\"Installing Windows Feature: {feature.Name}\",\n }\n );\n\n try\n {\n await _featureService.InstallFeatureAsync(\n feature.ToFeatureInfo(),\n progress,\n cancellationToken\n );\n feature.IsInstalled = true;\n successCount++;\n\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage =\n $\"Successfully installed feature {feature.Name}\",\n LogLevel = LogLevel.Success,\n }\n );\n }\n catch (System.Exception ex)\n {\n progress.Report(\n new TaskProgressDetail\n {\n DetailedMessage =\n $\"Error installing feature {feature.Name}: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n }\n }\n\n // Final report\n progress.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText =\n $\"Successfully installed {successCount} of {totalSelected} items\",\n DetailedMessage =\n $\"Task completed: {successCount} of {totalSelected} items installed successfully\",\n LogLevel =\n successCount == totalSelected ? LogLevel.Success : LogLevel.Warning,\n }\n );\n\n // Refresh the UI\n SortCollections();\n\n // Collect success, failure, and skipped information for the result dialog\n var successItems = new List();\n var failedItems = new List();\n var skippedItems = allNonReinstallableItems.Select(i => i.Name).ToList();\n\n // Add successful items to the list\n foreach (var app in installableApps.Where(a => a.IsInstalled))\n {\n successItems.Add(app.Name);\n }\n foreach (var capability in installableCapabilities.Where(c => c.IsInstalled))\n {\n successItems.Add(capability.Name);\n }\n foreach (var feature in installableFeatures.Where(f => f.IsInstalled))\n {\n successItems.Add(feature.Name);\n }\n\n // Add failed items to the list\n foreach (var app in installableApps.Where(a => !a.IsInstalled))\n {\n failedItems.Add(app.Name);\n }\n foreach (var capability in installableCapabilities.Where(c => !c.IsInstalled))\n {\n failedItems.Add(capability.Name);\n }\n foreach (var feature in installableFeatures.Where(f => !f.IsInstalled))\n {\n failedItems.Add(feature.Name);\n }\n\n // Show result dialog\n ShowOperationResultDialog(\n \"Install\",\n successCount,\n totalSelected + skippedItems.Count,\n successItems,\n failedItems,\n skippedItems\n );\n\n return successCount;\n },\n $\"Installing {totalSelected} items\",\n false\n );\n }\n\n #region BaseInstallationViewModel Abstract Method Implementations\n\n /// \n /// Gets the name of a Windows app.\n /// \n /// The Windows app.\n /// The name of the app.\n protected override string GetAppName(WindowsApp app)\n {\n return app.Name;\n }\n\n /// \n /// Converts a Windows app to an AppInfo object.\n /// \n /// The Windows app to convert.\n /// The AppInfo object.\n protected override AppInfo ToAppInfo(WindowsApp app)\n {\n return app.ToAppInfo();\n }\n\n /// \n /// Gets the selected Windows apps.\n /// \n /// The selected Windows apps.\n protected override IEnumerable GetSelectedApps()\n {\n return Items.Where(a => a.IsSelected);\n }\n\n /// \n /// Sets the installation status of a Windows app.\n /// \n /// The Windows app.\n /// Whether the app is installed.\n protected override void SetInstallationStatus(WindowsApp app, bool isInstalled)\n {\n app.IsInstalled = isInstalled;\n }\n\n #endregion\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceKeyOperations.cs", "using Microsoft.Win32;\nusing System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Registry service implementation for key operations.\n /// \n public partial class RegistryService\n {\n /// \n /// Opens a registry key with the specified access rights.\n /// \n /// The full path to the registry key.\n /// Whether to open the key with write access.\n /// The opened registry key, or null if it could not be opened.\n private RegistryKey? OpenRegistryKey(string keyPath, bool writable)\n {\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return null;\n }\n\n string subPath = string.Join('\\\\', pathParts.Skip(1));\n\n if (writable)\n {\n // If we need write access, try to ensure the key exists with proper access rights\n return EnsureKeyWithFullAccess(rootKey, subPath);\n }\n else\n {\n // For read-only access, just try to open the key normally\n return rootKey.OpenSubKey(subPath, false);\n }\n }\n\n /// \n /// Creates a registry key if it doesn't exist.\n /// \n /// The full path to the registry key.\n /// True if the key exists or was created successfully; otherwise, false.\n public bool CreateKeyIfNotExists(string keyPath)\n {\n if (!CheckWindowsPlatform())\n return false;\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Creating registry key if it doesn't exist: {keyPath}\");\n\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return false;\n }\n\n string subKeyPath = string.Join('\\\\', pathParts.Skip(1));\n\n // Create the key with direct Registry API and security settings\n RegistryKey? targetKey = EnsureKeyWithFullAccess(rootKey, subKeyPath);\n\n if (targetKey == null)\n {\n _logService.Log(LogLevel.Warning, $\"Could not create registry key: {keyPath}\");\n return false;\n }\n\n targetKey.Close();\n \n // Update the cache to indicate that this key now exists\n lock (_keyExistsCache)\n {\n _keyExistsCache[keyPath] = true;\n }\n \n _logService.Log(LogLevel.Success, $\"Successfully created or verified registry key: {keyPath}\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating registry key {keyPath}: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Deletes a registry key.\n /// \n /// The full path to the registry key.\n /// True if the key was deleted successfully; otherwise, false.\n public bool DeleteKey(string keyPath)\n {\n if (!CheckWindowsPlatform())\n return false;\n\n try\n {\n _logService.Log(LogLevel.Info, $\"Deleting registry key: {keyPath}\");\n\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return false;\n }\n\n string subKeyPath = string.Join('\\\\', pathParts.Skip(1));\n string parentPath = string.Join('\\\\', subKeyPath.Split('\\\\').Take(subKeyPath.Split('\\\\').Length - 1));\n string keyName = subKeyPath.Split('\\\\').Last();\n\n // Open the parent key with write access\n using (RegistryKey? parentKey = rootKey.OpenSubKey(parentPath, true))\n {\n if (parentKey == null)\n {\n _logService.Log(LogLevel.Warning, $\"Parent key does not exist: {pathParts[0]}\\\\{parentPath}\");\n return false;\n }\n\n // Delete the key\n parentKey.DeleteSubKey(keyName, false);\n \n // Clear the cache for this key\n lock (_keyExistsCache)\n {\n var keysToRemove = _keyExistsCache.Keys\n .Where(k => k.StartsWith(keyPath, StringComparison.OrdinalIgnoreCase))\n .ToList();\n \n foreach (var key in keysToRemove)\n {\n _keyExistsCache.Remove(key);\n }\n }\n\n _logService.Log(LogLevel.Success, $\"Successfully deleted registry key: {keyPath}\");\n return true;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error deleting registry key {keyPath}: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Checks if a registry key exists.\n /// \n /// The full path to the registry key.\n /// True if the key exists; otherwise, false.\n public bool KeyExists(string keyPath)\n {\n if (!CheckWindowsPlatform())\n return false;\n\n try\n {\n // Check the cache first\n lock (_keyExistsCache)\n {\n if (_keyExistsCache.TryGetValue(keyPath, out bool exists))\n {\n return exists;\n }\n }\n\n string[] pathParts = keyPath.Split('\\\\');\n RegistryKey? rootKey = GetRootKey(pathParts[0]);\n\n if (rootKey == null)\n {\n _logService.Log(LogLevel.Error, $\"Invalid root key: {pathParts[0]}\");\n return false;\n }\n\n string subKeyPath = string.Join('\\\\', pathParts.Skip(1));\n\n // Try to open the key\n using (RegistryKey? key = rootKey.OpenSubKey(subKeyPath))\n {\n bool exists = key != null;\n \n // Cache the result\n lock (_keyExistsCache)\n {\n _keyExistsCache[keyPath] = exists;\n }\n \n return exists;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking if registry key exists {keyPath}: {ex.Message}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/StartMenuCustomizations.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Services;\nusing Winhance.Core.Features.Customize.Enums;\n\nnamespace Winhance.Core.Features.Customize.Models;\n\npublic static class StartMenuCustomizations\n{\n private const string Win10StartLayoutPath = @\"C:\\Windows\\StartMenuLayout.xml\";\n private const string Win11StartBinPath =\n @\"AppData\\Local\\Packages\\Microsoft.Windows.StartMenuExperienceHost_cw5n1h2txyewy\\LocalState\\start2.bin\";\n\n public static CustomizationGroup GetStartMenuCustomizations()\n {\n return new CustomizationGroup\n {\n Name = \"Start Menu\",\n Category = CustomizationCategory.StartMenu,\n Settings = new List\n {\n new CustomizationSetting\n {\n Id = \"show-recently-added-apps\",\n Name = \"Show Recently Added Apps\",\n Description = \"Controls visibility of recently added apps in Start Menu\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Start Menu Settings\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Policies\\\\Microsoft\\\\Windows\\\\Explorer\",\n Name = \"HideRecentlyAddedApps\",\n RecommendedValue = 0,\n EnabledValue = 0, // When toggle is ON, recently added apps are shown\n DisabledValue = 1, // When toggle is OFF, recently added apps are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Controls visibility of recently added apps in Start Menu\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\Explorer\",\n Name = \"HideRecentlyAddedApps\",\n RecommendedValue = 0,\n EnabledValue = 0, // When toggle is ON, recently added apps are shown\n DisabledValue = 1, // When toggle is OFF, recently added apps are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Controls visibility of recently added apps in Start Menu\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"start-menu-layout\",\n Name = \"Set 'More Pins' Layout\",\n Description = \"Controls Start Menu layout configuration\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Layout\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"StartMenu\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"Start_Layout\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, more pins layout is used\n DisabledValue = 0, // When toggle is OFF, default layout is used\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // For backward compatibility\n Description = \"Controls Start Menu layout configuration\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"start-menu-recommendations\",\n Name = \"Show Recommended Tips, Shortcuts etc.\",\n Description = \"Controls recommendations for tips and shortcuts\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Start Menu Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"Start_IrisRecommendations\",\n RecommendedValue = 1,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls recommendations for tips and shortcuts\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"taskbar-clear-mfu\",\n Name = \"Show Most Used Apps\",\n Description = \"Controls frequently used programs list visibility\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Start Menu\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"StartMenu\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Start\",\n Name = \"ShowFrequentList\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, frequently used programs list is shown\n DisabledValue = 0, // When toggle is OFF, frequently used programs list is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls frequently used programs list visibility\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"power-lock-option\",\n Name = \"Lock Option\",\n Description = \"Controls whether the lock option is shown in the Start menu\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Start Menu\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\FlyoutMenuSettings\",\n Name = \"ShowLockOption\",\n RecommendedValue = 1,\n EnabledValue = 1, // Show lock option\n DisabledValue = 0, // Hide lock option\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description =\n \"Controls whether the lock option is shown in the Start menu\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"show-recommended-files\",\n Name = \"Show Recommended Files\",\n Description = \"Controls visibility of recommended files in Start Menu\",\n Category = CustomizationCategory.StartMenu,\n GroupName = \"Start Menu Settings\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"Start_TrackDocs\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, recommended files are shown\n DisabledValue = 0, // When toggle is OFF, recommended files are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls visibility of recommended files in Start Menu\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n },\n };\n }\n\n public static void ApplyStartMenuLayout(bool isWindows11, ISystemServices windowsService)\n {\n if (isWindows11)\n {\n ApplyWindows11Layout();\n }\n else\n {\n ApplyWindows10Layout(windowsService);\n }\n }\n\n private static void ApplyWindows10Layout(ISystemServices windowsService)\n {\n // Delete existing layout file\n if (File.Exists(Win10StartLayoutPath))\n {\n File.Delete(Win10StartLayoutPath);\n }\n\n // Create new layout file\n File.WriteAllText(Win10StartLayoutPath, StartMenuLayouts.Windows10Layout);\n\n // Use the improved RefreshWindowsGUI method to restart Explorer and apply changes\n // This will ensure Explorer is restarted properly with retry logic and fallback\n var result = windowsService.RefreshWindowsGUI(true).GetAwaiter().GetResult();\n if (!result)\n {\n throw new Exception(\"Failed to refresh Windows GUI after applying Start Menu layout\");\n }\n }\n\n private static void ApplyWindows11Layout()\n {\n string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);\n string start2BinPath = Path.Combine(userProfile, Win11StartBinPath);\n string tempPath = Path.GetTempPath();\n\n // Delete existing start2.bin if it exists\n if (File.Exists(start2BinPath))\n {\n File.Delete(start2BinPath);\n }\n\n // Create temp file with cert content\n string tempTxtPath = Path.Combine(tempPath, \"start2.txt\");\n string tempBinPath = Path.Combine(tempPath, \"start2.bin\");\n\n try\n {\n // Write certificate content to temp file\n File.WriteAllText(tempTxtPath, StartMenuLayouts.Windows11StartBinCertificate);\n\n // Use certutil to decode the certificate\n using (var process = new System.Diagnostics.Process())\n {\n process.StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"certutil.exe\",\n Arguments = $\"-decode \\\"{tempTxtPath}\\\" \\\"{tempBinPath}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n CreateNoWindow = true,\n };\n\n process.Start();\n process.WaitForExit();\n }\n\n // Ensure directory exists\n Directory.CreateDirectory(Path.GetDirectoryName(start2BinPath)!);\n\n // Copy the decoded binary to the Start Menu location\n File.Copy(tempBinPath, start2BinPath, true);\n }\n finally\n {\n // Clean up temp files\n if (File.Exists(tempTxtPath))\n File.Delete(tempTxtPath);\n if (File.Exists(tempBinPath))\n File.Delete(tempBinPath);\n }\n }\n\n /// \n /// Cleans the Start Menu for Windows 10 or Windows 11.\n /// \n /// Whether the system is Windows 11.\n /// The system services.\n public static void CleanStartMenu(bool isWindows11, ISystemServices windowsService)\n {\n if (isWindows11)\n {\n CleanWindows11StartMenu();\n }\n else\n {\n CleanWindows10StartMenu(windowsService);\n }\n }\n\n /// \n /// Cleans the Windows 11 Start Menu by replacing the start2.bin file.\n /// \n private static void CleanWindows11StartMenu()\n {\n // This is essentially the same as ApplyWindows11Layout since we're replacing the start2.bin file\n string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);\n string start2BinPath = Path.Combine(userProfile, Win11StartBinPath);\n string tempPath = Path.GetTempPath();\n\n // Delete existing start2.bin if it exists\n if (File.Exists(start2BinPath))\n {\n File.Delete(start2BinPath);\n }\n\n // Create temp file with cert content\n string tempTxtPath = Path.Combine(tempPath, \"start2.txt\");\n string tempBinPath = Path.Combine(tempPath, \"start2.bin\");\n\n try\n {\n // Write certificate content to temp file\n File.WriteAllText(tempTxtPath, StartMenuLayouts.Windows11StartBinCertificate);\n\n // Use certutil to decode the certificate\n using (var process = new System.Diagnostics.Process())\n {\n process.StartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"certutil.exe\",\n Arguments = $\"-decode \\\"{tempTxtPath}\\\" \\\"{tempBinPath}\\\"\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n CreateNoWindow = true,\n };\n\n process.Start();\n process.WaitForExit();\n }\n\n // Ensure directory exists\n Directory.CreateDirectory(Path.GetDirectoryName(start2BinPath)!);\n\n // Copy the decoded binary to the Start Menu location\n File.Copy(tempBinPath, start2BinPath, true);\n }\n finally\n {\n // Clean up temp files\n if (File.Exists(tempTxtPath))\n File.Delete(tempTxtPath);\n if (File.Exists(tempBinPath))\n File.Delete(tempBinPath);\n }\n }\n\n /// \n /// Cleans the Windows 10 Start Menu by creating and then removing a StartMenuLayout.xml file.\n /// \n /// The system services.\n private static void CleanWindows10StartMenu(ISystemServices windowsService)\n {\n try\n {\n // Delete existing layout file if it exists\n if (File.Exists(Win10StartLayoutPath))\n {\n File.Delete(Win10StartLayoutPath);\n }\n\n // Create new layout file with clean layout\n File.WriteAllText(Win10StartLayoutPath, StartMenuLayouts.Windows10Layout);\n\n // Set registry values to lock the Start Menu layout\n using (\n var key = Registry.LocalMachine.CreateSubKey(\n @\"SOFTWARE\\Policies\\Microsoft\\Windows\\Explorer\"\n )\n )\n {\n if (key != null)\n {\n key.SetValue(\"LockedStartLayout\", 1, RegistryValueKind.DWord);\n key.SetValue(\"StartLayoutFile\", Win10StartLayoutPath, RegistryValueKind.String);\n }\n }\n\n using (\n var key = Registry.CurrentUser.CreateSubKey(\n @\"SOFTWARE\\Policies\\Microsoft\\Windows\\Explorer\"\n )\n )\n {\n if (key != null)\n {\n key.SetValue(\"LockedStartLayout\", 1, RegistryValueKind.DWord);\n key.SetValue(\"StartLayoutFile\", Win10StartLayoutPath, RegistryValueKind.String);\n }\n }\n\n // Use the improved RefreshWindowsGUI method to restart Explorer and apply changes\n // This will ensure Explorer is restarted properly with retry logic and fallback\n var result = windowsService.RefreshWindowsGUI(true).GetAwaiter().GetResult();\n if (!result)\n {\n throw new Exception(\n \"Failed to refresh Windows GUI after applying Start Menu layout\"\n );\n }\n\n // Wait for changes to take effect\n System.Threading.Thread.Sleep(3000);\n\n // Disable the locked Start Menu layout\n using (\n var key = Registry.LocalMachine.CreateSubKey(\n @\"SOFTWARE\\Policies\\Microsoft\\Windows\\Explorer\"\n )\n )\n {\n if (key != null)\n {\n key.SetValue(\"LockedStartLayout\", 0, RegistryValueKind.DWord);\n }\n }\n\n using (\n var key = Registry.CurrentUser.CreateSubKey(\n @\"SOFTWARE\\Policies\\Microsoft\\Windows\\Explorer\"\n )\n )\n {\n if (key != null)\n {\n key.SetValue(\"LockedStartLayout\", 0, RegistryValueKind.DWord);\n }\n }\n\n // Use the improved RefreshWindowsGUI method again to apply the final changes\n result = windowsService.RefreshWindowsGUI(true).GetAwaiter().GetResult();\n if (!result)\n {\n throw new Exception(\n \"Failed to refresh Windows GUI after unlocking Start Menu layout\"\n );\n }\n\n // Delete the layout file\n if (File.Exists(Win10StartLayoutPath))\n {\n File.Delete(Win10StartLayoutPath);\n }\n }\n catch (Exception ex)\n {\n // Log the exception or handle it as needed\n System.Diagnostics.Debug.WriteLine(\n $\"Error cleaning Windows 10 Start Menu: {ex.Message}\"\n );\n throw new Exception($\"Error cleaning Windows 10 Start Menu: {ex.Message}\", ex);\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/ProgressIndicator.cs", "using System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// A custom control that displays a progress indicator with status text.\n /// \n public class ProgressIndicator : Control\n {\n static ProgressIndicator()\n {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(ProgressIndicator), new FrameworkPropertyMetadata(typeof(ProgressIndicator)));\n }\n \n /// \n /// When overridden in a derived class, is invoked whenever application code or internal processes call .\n /// \n public override void OnApplyTemplate()\n {\n base.OnApplyTemplate();\n \n // Find the cancel button in the template and hook up the event handler\n if (GetTemplateChild(\"PART_CancelButton\") is Button cancelButton)\n {\n cancelButton.Click -= CancelButton_Click;\n cancelButton.Click += CancelButton_Click;\n }\n }\n \n private void CancelButton_Click(object sender, RoutedEventArgs e)\n {\n // Log the button click for debugging\n System.Diagnostics.Debug.WriteLine(\"Cancel button clicked\");\n \n // First try to execute the command if it exists\n if (CancelCommand != null && CancelCommand.CanExecute(null))\n {\n System.Diagnostics.Debug.WriteLine(\"Executing cancel command\");\n CancelCommand.Execute(null);\n return;\n }\n \n // If command execution fails, use a more direct approach\n System.Diagnostics.Debug.WriteLine(\"Command execution failed, trying direct approach\");\n CancelCurrentTaskDirectly();\n }\n \n /// \n /// Directly cancels the current task by finding the TaskProgressService instance.\n /// \n private void CancelCurrentTaskDirectly()\n {\n try\n {\n // Get the application's main window\n var mainWindow = System.Windows.Application.Current.MainWindow;\n if (mainWindow == null)\n {\n System.Diagnostics.Debug.WriteLine(\"Main window not found\");\n return;\n }\n \n // Get the DataContext of the main window (should be the MainViewModel)\n var mainViewModel = mainWindow.DataContext;\n if (mainViewModel == null)\n {\n System.Diagnostics.Debug.WriteLine(\"Main window DataContext is null\");\n return;\n }\n \n // Use reflection to get the _progressService field\n var type = mainViewModel.GetType();\n var field = type.GetField(\"_progressService\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n \n if (field != null)\n {\n var progressService = field.GetValue(mainViewModel) as Winhance.Core.Features.Common.Interfaces.ITaskProgressService;\n if (progressService != null)\n {\n System.Diagnostics.Debug.WriteLine(\"Found progress service, cancelling task\");\n progressService.CancelCurrentTask();\n \n // Show a message to the user that the task was cancelled\n System.Windows.MessageBox.Show(\"Installation cancelled by user.\", \"Cancelled\", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);\n }\n else\n {\n System.Diagnostics.Debug.WriteLine(\"Progress service is null\");\n }\n }\n else\n {\n System.Diagnostics.Debug.WriteLine(\"_progressService field not found\");\n }\n }\n catch (Exception ex)\n {\n System.Diagnostics.Debug.WriteLine($\"Error in CancelCurrentTaskDirectly: {ex.Message}\");\n }\n }\n\n #region Dependency Properties\n\n /// \n /// Gets or sets the progress value (0-100).\n /// \n public double Progress\n {\n get { return (double)GetValue(ProgressProperty); }\n set { SetValue(ProgressProperty, value); }\n }\n\n /// \n /// Identifies the Progress dependency property.\n /// \n public static readonly DependencyProperty ProgressProperty =\n DependencyProperty.Register(nameof(Progress), typeof(double), typeof(ProgressIndicator), \n new PropertyMetadata(0.0, OnProgressChanged));\n\n /// \n /// Gets or sets the status text.\n /// \n public string StatusText\n {\n get { return (string)GetValue(StatusTextProperty); }\n set { SetValue(StatusTextProperty, value); }\n }\n\n /// \n /// Identifies the StatusText dependency property.\n /// \n public static readonly DependencyProperty StatusTextProperty =\n DependencyProperty.Register(nameof(StatusText), typeof(string), typeof(ProgressIndicator), \n new PropertyMetadata(string.Empty));\n\n /// \n /// Gets or sets whether the progress is indeterminate.\n /// \n public bool IsIndeterminate\n {\n get { return (bool)GetValue(IsIndeterminateProperty); }\n set { SetValue(IsIndeterminateProperty, value); }\n }\n\n /// \n /// Identifies the IsIndeterminate dependency property.\n /// \n public static readonly DependencyProperty IsIndeterminateProperty =\n DependencyProperty.Register(nameof(IsIndeterminate), typeof(bool), typeof(ProgressIndicator), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets whether the control is active.\n /// \n public bool IsActive\n {\n get { return (bool)GetValue(IsActiveProperty); }\n set { SetValue(IsActiveProperty, value); }\n }\n\n /// \n /// Identifies the IsActive dependency property.\n /// \n public static readonly DependencyProperty IsActiveProperty =\n DependencyProperty.Register(nameof(IsActive), typeof(bool), typeof(ProgressIndicator), \n new PropertyMetadata(false));\n\n /// \n /// Gets the progress text (e.g., \"50%\").\n /// \n public string ProgressText\n {\n get { return (string)GetValue(ProgressTextProperty); }\n private set { SetValue(ProgressTextProperty, value); }\n }\n\n /// \n /// Identifies the ProgressText dependency property.\n /// \n public static readonly DependencyProperty ProgressTextProperty =\n DependencyProperty.Register(nameof(ProgressText), typeof(string), typeof(ProgressIndicator), \n new PropertyMetadata(string.Empty));\n \n /// \n /// Gets or sets the command to execute when the cancel button is clicked.\n /// \n public ICommand CancelCommand\n {\n get { return (ICommand)GetValue(CancelCommandProperty); }\n set { SetValue(CancelCommandProperty, value); }\n }\n\n /// \n /// Identifies the CancelCommand dependency property.\n /// \n public static readonly DependencyProperty CancelCommandProperty =\n DependencyProperty.Register(nameof(CancelCommand), typeof(ICommand), typeof(ProgressIndicator), \n new PropertyMetadata(null));\n \n /// \n /// Gets or sets whether to show the cancel button instead of progress text.\n /// \n public bool ShowCancelButton\n {\n get { return (bool)GetValue(ShowCancelButtonProperty); }\n set { SetValue(ShowCancelButtonProperty, value); }\n }\n\n /// \n /// Identifies the ShowCancelButton dependency property.\n /// \n public static readonly DependencyProperty ShowCancelButtonProperty =\n DependencyProperty.Register(nameof(ShowCancelButton), typeof(bool), typeof(ProgressIndicator), \n new PropertyMetadata(false));\n\n #endregion\n\n private static void OnProgressChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is ProgressIndicator control)\n {\n control.UpdateProgressText();\n }\n }\n\n private void UpdateProgressText()\n {\n if (IsIndeterminate || ShowCancelButton)\n {\n ProgressText = string.Empty;\n }\n else\n {\n ProgressText = $\"{Progress:F0}%\";\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/PrivacyOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for privacy optimizations.\n /// \n public partial class PrivacyOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDependencyManager _dependencyManager;\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dependency manager.\n /// The view model locator.\n /// The settings registry.\n public PrivacyOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDependencyManager dependencyManager,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _dependencyManager = dependencyManager ?? throw new ArgumentNullException(nameof(dependencyManager));\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n _logService.Log(LogLevel.Info, \"PrivacyOptimizationsViewModel instance created\");\n }\n\n /// \n /// Loads the privacy settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, \"Loading privacy settings\");\n\n // Initialize privacy settings from PrivacyOptimizations.cs\n var privacyOptimizations = Core.Features.Optimize.Models.PrivacyOptimizations.GetPrivacyOptimizations();\n if (privacyOptimizations?.Settings != null)\n {\n Settings.Clear();\n\n // Process each setting\n foreach (var setting in privacyOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = false, // Always initialize as unchecked\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n\n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Register the setting in the settings registry if available\n if (_settingsRegistry != null && !string.IsNullOrEmpty(settingItem.Id))\n {\n _settingsRegistry.RegisterSetting(settingItem);\n _logService.Log(LogLevel.Info, $\"Registered setting {settingItem.Id} in settings registry during creation\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for checkboxes\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n await CheckSettingStatusesAsync();\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading privacy settings: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all privacy settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, $\"Checking status for {Settings.Count} privacy settings\");\n\n // Clear registry caches to ensure fresh reads\n _registryService.ClearRegistryCaches();\n\n // Create a list of tasks to check all settings in parallel\n var tasks = Settings.Select(async setting => {\n try\n {\n // Check if we have linked registry settings\n if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Checking status for linked setting: {setting.Name} with {setting.LinkedRegistrySettings.Settings.Count} registry entries\");\n\n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(regSetting.Hive);\n string fullPath = $\"{hiveString}\\\\{regSetting.SubKey}\";\n _logService.Log(LogLevel.Info, $\"Registry entry: {fullPath}\\\\{regSetting.Name}, EnabledValue={regSetting.EnabledValue}, DisabledValue={regSetting.DisabledValue}\");\n\n // Check if the key exists\n bool keyExists = _registryService.KeyExists(fullPath);\n _logService.Log(LogLevel.Info, $\"Key exists: {keyExists}\");\n\n if (keyExists)\n {\n // Check if the value exists and get its current value\n var currentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value: {currentValue ?? \"null\"}\");\n }\n }\n\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n _logService.Log(LogLevel.Info, $\"Combined status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name} (first entry): {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value for linked setting {regSetting.Name}: {regCurrentValue ?? \"null\"}\");\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n // Fall back to single registry setting\n else if (setting.RegistrySetting != null)\n {\n _logService.Log(LogLevel.Info, $\"Checking status for setting: {setting.Name}\");\n\n // Log details about the registry entry for debugging\n string hiveString = RegistryExtensions.GetRegistryHiveString(setting.RegistrySetting.Hive);\n string fullPath = $\"{hiveString}\\\\{setting.RegistrySetting.SubKey}\";\n _logService.Log(LogLevel.Info, $\"Registry entry: {fullPath}\\\\{setting.RegistrySetting.Name}, EnabledValue={setting.RegistrySetting.EnabledValue}, DisabledValue={setting.RegistrySetting.DisabledValue}\");\n\n // Check if the key exists\n bool keyExists = _registryService.KeyExists(fullPath);\n _logService.Log(LogLevel.Info, $\"Key exists: {keyExists}\");\n\n // Get the status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // Get the current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name}: {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n \n // Set IsRegistryValueNull for single registry setting\n setting.IsRegistryValueNull = currentValue == null;\n\n // Add to LinkedRegistrySettingsWithValues for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings available for {setting.Name}\");\n setting.Status = RegistrySettingStatus.Unknown;\n setting.StatusMessage = \"Registry setting information is missing\";\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating status for setting {setting.Name}: {ex.Message}\");\n setting.Status = RegistrySettingStatus.Error;\n setting.StatusMessage = $\"Error: {ex.Message}\";\n }\n }).ToList();\n\n // Wait for all tasks to complete\n await Task.WhenAll(tasks);\n\n // Now handle any grouped settings\n foreach (var setting in Settings.Where(s => s.IsGroupedSetting && s.ChildSettings.Count > 0))\n {\n _logService.Log(LogLevel.Info, $\"Updating {setting.ChildSettings.Count} child settings for {setting.Name}\");\n foreach (var childSetting in setting.ChildSettings)\n {\n if (childSetting.RegistrySetting != null)\n {\n var status = await _registryService.GetSettingStatusAsync(childSetting.RegistrySetting);\n childSetting.Status = status;\n\n var currentValue = await _registryService.GetCurrentValueAsync(childSetting.RegistrySetting);\n childSetting.CurrentValue = currentValue;\n\n childSetting.StatusMessage = GetStatusMessage(childSetting);\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking privacy setting statuses: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n // ApplySelectedSettingsAsync and RestoreDefaultsAsync methods removed as part of the refactoring\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0)\n return;\n\n var selectedCount = Settings.Count(setting => setting.IsSelected);\n IsSelected = selectedCount == Settings.Count;\n }\n\n /// \n /// Gets a user-friendly status message for a setting.\n /// \n /// The setting to get the status message for.\n /// A user-friendly status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied =>\n \"This setting is enabled (toggle is ON).\",\n\n RegistrySettingStatus.NotApplied =>\n setting.CurrentValue == null\n ? \"This setting is not applied (registry value does not exist).\"\n : \"This setting is disabled (toggle is OFF).\",\n\n RegistrySettingStatus.Modified =>\n \"This setting has a custom value that differs from both enabled and disabled values.\",\n\n RegistrySettingStatus.Error =>\n \"An error occurred while checking this setting's status.\",\n\n _ => \"The status of this setting is unknown.\"\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/BaseInstallationViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Views;\nusing Winhance.WPF.Features.SoftwareApps.Services;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n /// \n /// Base view model for installation operations.\n /// Provides common functionality for both WindowsAppsViewModel and ExternalAppsViewModel.\n /// \n /// The type of app (WindowsApp or ExternalApp)\n public abstract class BaseInstallationViewModel : SearchableViewModel\n where T : class, ISearchable\n {\n protected readonly IAppInstallationService _appInstallationService;\n protected readonly IAppInstallationCoordinatorService _appInstallationCoordinatorService;\n protected readonly IInternetConnectivityService _connectivityService;\n protected readonly SoftwareAppsDialogService _dialogService;\n\n /// \n /// Gets or sets the reason for cancellation if an operation was cancelled.\n /// \n protected CancellationReason CurrentCancellationReason { get; set; } =\n CancellationReason.None;\n\n /// \n /// Gets or sets the status text.\n /// \n public string StatusText { get; set; } = \"Ready\";\n\n /// \n /// Gets or sets a value indicating whether the view model is initialized.\n /// \n public bool IsInitialized { get; set; } = false;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The search service.\n /// The package manager.\n /// The app installation service.\n /// The app installation coordinator service.\n /// The internet connectivity service.\n /// The specialized dialog service for software apps.\n protected BaseInstallationViewModel(\n ITaskProgressService progressService,\n ISearchService searchService,\n IPackageManager packageManager,\n IAppInstallationService appInstallationService,\n IAppInstallationCoordinatorService appInstallationCoordinatorService,\n IInternetConnectivityService connectivityService,\n SoftwareAppsDialogService dialogService\n )\n : base(progressService, searchService, packageManager)\n {\n _appInstallationService =\n appInstallationService\n ?? throw new ArgumentNullException(nameof(appInstallationService));\n _appInstallationCoordinatorService =\n appInstallationCoordinatorService\n ?? throw new ArgumentNullException(nameof(appInstallationCoordinatorService));\n _connectivityService =\n connectivityService ?? throw new ArgumentNullException(nameof(connectivityService));\n _dialogService =\n dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n }\n\n /// \n /// Loads apps and checks their installation status.\n /// \n /// A task representing the asynchronous operation.\n public async Task LoadAppsAndCheckInstallationStatusAsync()\n {\n if (IsInitialized)\n {\n System.Diagnostics.Debug.WriteLine(\n $\"{GetType().Name} already initialized, skipping LoadAppsAndCheckInstallationStatusAsync\"\n );\n return;\n }\n\n System.Diagnostics.Debug.WriteLine(\n $\"Starting {GetType().Name} LoadAppsAndCheckInstallationStatusAsync\"\n );\n await LoadItemsAsync();\n await CheckInstallationStatusAsync();\n\n // Mark as initialized after loading is complete\n IsInitialized = true;\n System.Diagnostics.Debug.WriteLine(\n $\"Completed {GetType().Name} LoadAppsAndCheckInstallationStatusAsync\"\n );\n }\n\n /// \n /// Checks if internet connectivity is available.\n /// \n /// Whether to show a dialog if connectivity is not available.\n /// True if internet is connected, false otherwise.\n protected async Task CheckInternetConnectivityAsync(bool showDialog = true)\n {\n bool isInternetConnected = await _connectivityService.IsInternetConnectedAsync(true);\n if (!isInternetConnected && showDialog)\n {\n StatusText = \"No internet connection available. Installation cannot proceed.\";\n\n // Show dialog informing the user about the connectivity issue\n await ShowNoInternetConnectionDialogAsync();\n }\n return isInternetConnected;\n }\n\n /// \n /// Shows a confirmation dialog for an operation.\n /// \n /// Type of operation (Install/Remove)\n /// List of apps selected for the operation\n /// List of apps that will be skipped (optional)\n /// Dialog result (true if confirmed, false if canceled)\n protected async Task ShowOperationConfirmationDialogAsync(\n string operationType,\n IEnumerable selectedApps,\n IEnumerable? skippedApps = null\n )\n {\n string title = $\"Confirm {operationType}\";\n string headerText = $\"The following items will be {GetPastTense(operationType)}:\";\n\n // Create list of app names for the dialog\n var appNames = selectedApps.Select(a => GetAppName(a)).ToList();\n\n // Create footer text\n string footerText = \"Do you want to continue?\";\n\n // If there are skipped apps, add information about them\n if (skippedApps != null && skippedApps.Any())\n {\n var skippedNames = skippedApps.Select(a => GetAppName(a)).ToList();\n footerText =\n $\"Note: The following {skippedApps.Count()} item(s) cannot be {GetPastTense(operationType)} and will be skipped:\\n\";\n footerText += string.Join(\", \", skippedNames);\n footerText +=\n $\"\\n\\nDo you want to continue with the remaining {selectedApps.Count()} item(s)?\";\n }\n\n // Build the message\n string message = $\"{headerText}\\n\";\n foreach (var name in appNames)\n {\n message += $\"{name}\\n\";\n }\n message += $\"\\n{footerText}\";\n\n // Show the confirmation dialog\n return await _dialogService.ShowConfirmationAsync(message, title);\n }\n\n /// \n /// Centralized method to handle the entire cancellation process.\n /// This method manages the cancellation state, logs the cancellation event,\n /// shows the appropriate dialog, and ensures proper cleanup.\n /// \n /// True if the cancellation was due to connectivity issues, false if user-initiated.\n /// A task that represents the asynchronous operation.\n protected async Task HandleCancellationAsync(bool isConnectivityIssue)\n {\n // Set the appropriate cancellation reason (state management)\n CurrentCancellationReason = isConnectivityIssue\n ? CancellationReason.InternetConnectivityLost\n : CancellationReason.UserCancelled;\n\n // Log the cancellation (diagnostics)\n System.Diagnostics.Debug.WriteLine(\n $\"[DEBUG] Installation {(isConnectivityIssue ? \"stopped due to connectivity loss\" : \"cancelled by user\")} - showing dialog\"\n );\n\n // Show the appropriate dialog (UI presentation - delegated to specialized method)\n await ShowCancellationDialogAsync(!isConnectivityIssue, isConnectivityIssue);\n\n // Reset cancellation reason after showing dialog (cleanup)\n CurrentCancellationReason = CancellationReason.None;\n }\n\n /// \n /// Shows an operation result dialog after operations complete.\n /// \n /// Type of operation (Install/Remove)\n /// Number of successful operations\n /// Total number of operations attempted\n /// List of successfully processed items\n /// List of failed items (optional)\n /// List of skipped items (optional)\n protected void ShowOperationResultDialog(\n string operationType,\n int successCount,\n int totalCount,\n IEnumerable successItems,\n IEnumerable? failedItems = null,\n IEnumerable? skippedItems = null\n )\n {\n // Determine if this was a user-initiated cancellation or connectivity issue\n bool isUserCancelled = CurrentCancellationReason == CancellationReason.UserCancelled;\n bool isConnectivityIssue =\n CurrentCancellationReason == CancellationReason.InternetConnectivityLost;\n\n // If the operation was cancelled by the user, use CustomDialog for a simpler message\n if (isUserCancelled)\n {\n string title = \"Installation Aborted by User\";\n string headerText = \"Installation aborted by user\";\n string message = \"The installation process was cancelled by the user.\";\n string footerText =\n successCount > 0\n ? $\"Some items were successfully {GetPastTense(operationType)} before cancellation.\"\n : $\"No items were {GetPastTense(operationType)} before cancellation.\";\n\n // Use CustomDialog directly instead of SoftwareAppsDialog\n CustomDialog.ShowInformation(title, headerText, message, footerText);\n\n // Reset cancellation reason after showing dialog\n CurrentCancellationReason = CancellationReason.None;\n return;\n }\n // If the operation was cancelled due to connectivity issues\n else if (isConnectivityIssue)\n {\n // Use the dialog service with the connectivity issue flag\n _dialogService.ShowOperationResult(\n operationType,\n successCount,\n totalCount,\n successItems,\n failedItems,\n skippedItems,\n true, // Connectivity issue flag\n false // Not a user cancellation\n );\n\n // Reset cancellation reason after showing dialog\n CurrentCancellationReason = CancellationReason.None;\n return;\n }\n\n // For normal operation results (no cancellation)\n // Check if any failures are due to internet connectivity issues\n bool hasConnectivityIssues = false;\n if (failedItems != null)\n {\n hasConnectivityIssues = failedItems.Any(item =>\n item.Contains(\"internet\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\"connection\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\"network\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\n \"pipeline has been stopped\",\n StringComparison.OrdinalIgnoreCase\n )\n );\n }\n\n // For normal operation results, use the dialog service\n _dialogService.ShowOperationResult(\n operationType,\n successCount,\n totalCount,\n successItems,\n failedItems,\n skippedItems,\n hasConnectivityIssues,\n false // Not a user cancellation\n );\n }\n\n /// \n /// Shows a dialog informing the user that no internet connection is available.\n /// \n protected Task ShowNoInternetConnectionDialogAsync()\n {\n // Use CustomDialog directly instead of SoftwareAppsDialog\n CustomDialog.ShowInformation(\n \"Internet Connection Required\",\n \"No internet connection available\",\n \"Internet connection is required to install apps.\",\n \"Please check your network connection and try again.\"\n );\n return Task.CompletedTask;\n }\n\n /// \n /// Shows a dialog informing the user that no items were selected for an operation.\n /// \n /// The action being performed (e.g., \"installation\", \"removal\")\n protected Task ShowNoItemsSelectedDialogAsync(string action)\n {\n return _dialogService.ShowInformationAsync(\n $\"No items were selected for {action}.\",\n $\"No Items Selected\",\n $\"Check the boxes next to the items you want to {action} and try again.\"\n );\n }\n\n /// \n /// Shows a confirmation dialog for an operation on multiple items.\n /// \n /// The action being performed (e.g., \"install\", \"remove\")\n /// The names of the items\n /// The number of items\n /// True if confirmed, false otherwise\n protected Task ShowConfirmItemsDialogAsync(\n string action,\n IEnumerable itemNames,\n int count\n )\n {\n var formattedItemNames = itemNames.Select(name => $\" {name}\");\n\n return _dialogService.ShowConfirmationAsync(\n $\"The following items will be {action}ed:\\n\"\n + string.Join(\"\\n\", formattedItemNames)\n + $\"\\n\\nDo you want to {action} {count} item(s)?\",\n $\"Confirm {CapitalizeFirstLetter(action)}\"\n );\n }\n\n /// \n /// Shows a dialog informing the user that items cannot be reinstalled.\n /// \n /// The names of the items that cannot be reinstalled\n /// Whether this is for a single item or multiple items\n protected Task ShowCannotReinstallDialogAsync(IEnumerable itemNames, bool isSingle)\n {\n string title = isSingle ? \"Cannot Install Item\" : \"Cannot Install Items\";\n string message = isSingle\n ? $\"{itemNames.First()} cannot be reinstalled.\"\n : \"None of the selected items can be reinstalled.\";\n\n return _dialogService.ShowInformationAsync(\n message,\n title,\n \"These items are already installed and cannot be reinstalled.\"\n );\n }\n\n /// \n /// Shows a dialog informing the user about the operation results.\n /// \n /// The action that was performed (e.g., \"install\", \"remove\")\n /// The number of successful operations\n /// The total number of operations attempted\n /// The names of successfully processed items\n /// The names of failed items (optional)\n protected Task ShowOperationResultDialogAsync(\n string action,\n int successCount,\n int totalCount,\n IEnumerable successItems,\n IEnumerable? failedItems = null\n )\n {\n string title = $\"{CapitalizeFirstLetter(action)} Results\";\n string message = $\"{successCount} of {totalCount} items were successfully {action}ed.\";\n\n return _dialogService.ShowInformationAsync(\n message,\n title,\n $\"The operation completed with {successCount} successes and {totalCount - successCount} failures.\"\n );\n }\n\n /// \n /// Shows a dialog informing the user about installation cancellation.\n /// Uses CustomDialog directly to ensure proper text formatting for long messages.\n /// \n /// True if the cancellation was initiated by the user, false otherwise.\n /// True if the cancellation was due to connectivity issues, false otherwise.\n /// A task that represents the asynchronous operation.\n protected Task ShowCancellationDialogAsync(bool isUserCancelled, bool isConnectivityIssue)\n {\n string title = isUserCancelled ? \"Installation Aborted\" : \"Internet Connection Lost\";\n\n string headerText = isUserCancelled\n ? \"Installation aborted by user\"\n : \"Installation stopped due to internet connection loss\";\n\n string message = isUserCancelled\n ? \"The installation process was cancelled by the user.\"\n : \"The installation process was stopped because the internet connection was lost.\\nThis is required to ensure installations complete properly and prevent corrupted installations.\";\n\n string footerText = isUserCancelled\n ? \"You can restart the installation when you're ready.\"\n : \"Please check your network connection and try again when your internet connection is stable.\";\n\n // Use CustomDialog directly instead of SoftwareAppsDialog\n CustomDialog.ShowInformation(title, headerText, message, footerText);\n return Task.CompletedTask;\n }\n\n /// \n /// Gets the past tense form of an operation type\n /// \n /// The operation type (e.g., \"Install\", \"Remove\")\n /// The past tense form of the operation type\n protected string GetPastTense(string operationType)\n {\n if (string.IsNullOrEmpty(operationType))\n return string.Empty;\n\n return operationType.Equals(\"Remove\", StringComparison.OrdinalIgnoreCase)\n ? \"removed\"\n : $\"{operationType.ToLower()}ed\";\n }\n\n /// \n /// Gets the name of an app.\n /// \n /// The app.\n /// The name of the app.\n protected abstract string GetAppName(T app);\n\n /// \n /// Converts an app to an AppInfo object.\n /// \n /// The app to convert.\n /// The AppInfo object.\n protected abstract AppInfo ToAppInfo(T app);\n\n /// \n /// Gets the selected apps.\n /// \n /// The selected apps.\n protected abstract IEnumerable GetSelectedApps();\n\n /// \n /// Sets the installation status of an app.\n /// \n /// The app.\n /// Whether the app is installed.\n protected abstract void SetInstallationStatus(T app, bool isInstalled);\n\n /// \n /// Capitalizes the first letter of a string.\n /// \n /// The input string\n /// The string with the first letter capitalized\n protected string CapitalizeFirstLetter(string input)\n {\n if (string.IsNullOrEmpty(input))\n return string.Empty;\n\n return char.ToUpper(input[0]) + input.Substring(1);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppInstallationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Net.Http;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Enums;\nusing Winhance.Core.Features.SoftwareApps.Exceptions;\nusing Winhance.Core.Features.SoftwareApps.Helpers;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that installs standard applications.\n/// \npublic class AppInstallationService\n : BaseInstallationService,\n IAppInstallationService,\n IDisposable\n{\n private readonly string _tempDir = Path.Combine(Path.GetTempPath(), \"WinhanceInstaller\");\n private readonly HttpClient _httpClient;\n private readonly IScriptUpdateService _scriptUpdateService;\n private readonly ISystemServices _systemServices;\n private readonly IWinGetInstallationService _winGetInstallationService;\n private IProgress? _currentProgress;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The PowerShell execution service.\n /// The script update service.\n /// The system services.\n /// The WinGet installation service.\n public AppInstallationService(\n ILogService logService,\n IPowerShellExecutionService powerShellService,\n IScriptUpdateService scriptUpdateService,\n ISystemServices systemServices,\n IWinGetInstallationService winGetInstallationService\n )\n : base(logService, powerShellService)\n {\n _httpClient = new HttpClient();\n _scriptUpdateService = scriptUpdateService;\n _systemServices = systemServices;\n _winGetInstallationService = winGetInstallationService;\n Directory.CreateDirectory(_tempDir);\n }\n\n /// \n public Task> InstallAppAsync(\n AppInfo appInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default\n )\n {\n return InstallItemAsync(appInfo, progress, cancellationToken);\n }\n\n /// \n public Task> CanInstallAppAsync(AppInfo appInfo)\n {\n return CanInstallItemAsync(appInfo);\n }\n\n /// \n protected override async Task> PerformInstallationAsync(\n AppInfo appInfo,\n IProgress? progress,\n CancellationToken cancellationToken\n )\n {\n _currentProgress = progress;\n\n try\n {\n // Check for internet connectivity before starting the installation\n bool isConnected = await _systemServices.IsInternetConnectedAsync(\n true,\n cancellationToken\n );\n if (!isConnected)\n {\n string errorMessage =\n \"No internet connection available. Please check your network connection and try again.\";\n _logService.LogError(errorMessage);\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Installation failed: No internet connection\",\n DetailedMessage = errorMessage,\n LogLevel = LogLevel.Error,\n }\n );\n // Explicitly log failure for the specific app\n _logService.LogError(\n $\"Failed to install app: {appInfo.Name} - No internet connection\"\n );\n return OperationResult.Failed(errorMessage, false);\n }\n\n // Set up a periodic internet connectivity check\n var connectivityCheckTimer = new System.Timers.Timer(5000); // Check every 5 seconds\n bool installationCancelled = false;\n\n connectivityCheckTimer.Elapsed += async (s, e) =>\n {\n try\n {\n bool isStillConnected = await _systemServices.IsInternetConnectedAsync(\n false,\n cancellationToken\n );\n if (!isStillConnected && !installationCancelled)\n {\n installationCancelled = true;\n _logService.LogError(\"Internet connection lost during installation\");\n progress?.Report(\n new TaskProgressDetail\n {\n StatusText = \"Error: Internet connection lost\",\n DetailedMessage =\n \"Internet connection has been lost. Installation has been stopped.\",\n LogLevel = LogLevel.Error,\n }\n );\n\n // Stop the timer\n connectivityCheckTimer.Stop();\n\n // Throw an exception to stop the installation process\n throw new OperationCanceledException(\n \"Installation stopped due to internet connection loss\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in connectivity check: {ex.Message}\");\n connectivityCheckTimer.Stop();\n }\n };\n\n // Start the connectivity check timer\n connectivityCheckTimer.Start();\n bool success = false;\n\n // Verify internet connection again before attempting installation\n isConnected = await _systemServices.IsInternetConnectedAsync(true, cancellationToken);\n if (!isConnected)\n {\n string errorMessage =\n \"No internet connection available. Please check your network connection and try again.\";\n _logService.LogError(errorMessage);\n _logService.LogError(\n $\"Failed to install app: {appInfo.Name} - No internet connection\"\n );\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Installation failed: No internet connection\",\n DetailedMessage = errorMessage,\n LogLevel = LogLevel.Error,\n }\n );\n return OperationResult.Failed(errorMessage, false);\n }\n\n if (appInfo.PackageName.Equals(\"OneDrive\", StringComparison.OrdinalIgnoreCase))\n {\n // Special handling for OneDrive\n success = await InstallOneDriveAsync(progress, cancellationToken);\n }\n else if (appInfo.IsCustomInstall)\n {\n success = await InstallCustomAppAsync(appInfo, progress, cancellationToken);\n }\n else\n {\n // Use WinGet for all standard apps, including appx packages\n // Use PackageID if available, otherwise fall back to PackageName\n string packageIdentifier = !string.IsNullOrEmpty(appInfo.PackageID)\n ? appInfo.PackageID\n : appInfo.PackageName;\n\n // Pass the app's display name to use in progress messages\n try\n {\n // Pass the app's name for display in progress messages\n success = await _winGetInstallationService.InstallWithWingetAsync(\n packageIdentifier,\n progress,\n cancellationToken,\n appInfo.Name\n );\n\n // Double-check success - if WinGet returned success but we have no internet, consider it a failure\n if (success)\n {\n bool stillConnected = await _systemServices.IsInternetConnectedAsync(\n true,\n cancellationToken\n );\n if (!stillConnected)\n {\n _logService.LogError(\n $\"Internet connection lost during installation of {appInfo.Name}\"\n );\n success = false;\n throw new Exception(\"Internet connection lost during installation\");\n }\n }\n }\n catch (Exception ex)\n {\n success = false;\n _logService.LogError($\"Failed to install {appInfo.Name}: {ex.Message}\");\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Installation of {appInfo.Name} failed\",\n DetailedMessage = $\"Error: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n }\n }\n\n // If success is still false, ensure we log the failure\n if (!success)\n {\n _logService.LogError($\"Failed to install app: {appInfo.Name}\");\n }\n\n // Only update BloatRemoval.ps1 if installation was successful AND it's not an external app\n // External apps should never be added to BloatRemoval.ps1\n if (success && !IsExternalApp(appInfo))\n {\n try\n {\n _logService.LogInformation(\n $\"Starting BloatRemoval.ps1 script update for {appInfo.Name}\"\n );\n\n // Update the BloatRemoval.ps1 script to remove the installed app from the removal list\n var appNames = new List { appInfo.PackageName };\n _logService.LogInformation(\n $\"Removing package name from BloatRemoval.ps1: {appInfo.PackageName}\"\n );\n\n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n\n // Add any subpackages if present\n if (appInfo.SubPackages != null && appInfo.SubPackages.Length > 0)\n {\n _logService.LogInformation(\n $\"Adding {appInfo.SubPackages.Length} subpackages for {appInfo.Name}\"\n );\n appSubPackages.Add(appInfo.PackageName, appInfo.SubPackages);\n }\n\n // Add registry settings if present\n if (appInfo.RegistrySettings != null && appInfo.RegistrySettings.Length > 0)\n {\n _logService.LogInformation(\n $\"Adding {appInfo.RegistrySettings.Length} registry settings for {appInfo.Name}\"\n );\n appsWithRegistry.Add(\n appInfo.PackageName,\n new List(appInfo.RegistrySettings)\n );\n }\n\n _logService.LogInformation(\n $\"Updating BloatRemoval.ps1 to remove {appInfo.Name} from removal list\"\n );\n var result = await _scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n true\n ); // true = install operation, so remove from script\n\n _logService.LogInformation(\n $\"Successfully updated BloatRemoval.ps1 script - {appInfo.Name} will no longer be removed\"\n );\n _logService.LogInformation($\"Script update result: {result?.Name ?? \"null\"}\");\n }\n catch (Exception ex)\n {\n _logService.LogError(\n $\"Error updating BloatRemoval.ps1 script for {appInfo.Name}\",\n ex\n );\n _logService.LogError($\"Exception details: {ex.Message}\");\n _logService.LogError($\"Stack trace: {ex.StackTrace}\");\n // Don't fail the installation if script update fails\n }\n }\n else if (success)\n {\n _logService.LogInformation(\n $\"Skipping BloatRemoval.ps1 update because {appInfo.Name} is an external app\"\n );\n }\n else\n {\n _logService.LogInformation(\n $\"Skipping BloatRemoval.ps1 update because installation of {appInfo.Name} was not successful\"\n );\n }\n\n if (success)\n {\n _logService.LogSuccess($\"Successfully installed app: {appInfo.Name}\");\n return OperationResult.Succeeded(success);\n }\n else\n {\n // Double check internet connectivity as a possible cause of failure\n bool internetAvailable = await _systemServices.IsInternetConnectedAsync(\n true,\n cancellationToken\n );\n if (!internetAvailable)\n {\n string errorMessage =\n $\"Installation of {appInfo.Name} failed: No internet connection. Please check your network connection and try again.\";\n _logService.LogError(errorMessage);\n return OperationResult.Failed(errorMessage, false);\n }\n\n // Generic failure\n string failMessage = $\"Installation of {appInfo.Name} failed for unknown reasons.\";\n _logService.LogError(failMessage);\n return OperationResult.Failed(failMessage, false);\n }\n }\n catch (OperationCanceledException)\n {\n _logService.LogWarning($\"Installation of {appInfo.Name} was cancelled by user\");\n return OperationResult.Failed(\"Installation cancelled by user\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error installing {appInfo.Name}\", ex);\n\n // Check if the error might be related to internet connectivity\n bool isConnected = await _systemServices.IsInternetConnectedAsync(\n true,\n cancellationToken\n );\n if (!isConnected)\n {\n string errorMessage =\n $\"Installation failed: No internet connection. Please check your network connection and try again.\";\n _logService.LogError(errorMessage);\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Installation failed: No internet connection\",\n DetailedMessage = errorMessage,\n LogLevel = LogLevel.Error,\n }\n );\n return OperationResult.Failed(errorMessage, false);\n }\n\n return OperationResult.Failed($\"Error installing {appInfo.Name}: {ex.Message}\");\n }\n finally\n {\n // Dispose any timers or resources\n if (progress is IProgress progressReporter)\n {\n // Find and dispose the timer if it exists\n var field = GetType()\n .GetField(\n \"_connectivityCheckTimer\",\n System.Reflection.BindingFlags.NonPublic\n | System.Reflection.BindingFlags.Instance\n );\n if (field != null)\n {\n var timer = field.GetValue(this) as System.Timers.Timer;\n timer?.Stop();\n timer?.Dispose();\n }\n }\n\n _currentProgress = null;\n }\n }\n\n /// \n /// Determines if an app is an external app (third-party) rather than a Windows built-in app.\n /// External apps should not be added to the BloatRemoval script.\n /// \n /// The app to check\n /// True if the app is an external app, false otherwise\n private bool IsExternalApp(AppInfo appInfo)\n {\n // Consider all apps with IsCustomInstall as external apps\n if (appInfo.IsCustomInstall)\n return true;\n\n // Check if the package name starts with Microsoft or matches known Windows app patterns\n bool isMicrosoftApp = appInfo.PackageName.StartsWith(\n \"Microsoft.\",\n StringComparison.OrdinalIgnoreCase\n );\n\n // Check if the app is a number-based Microsoft Store app ID\n bool isStoreAppId =\n !string.IsNullOrEmpty(appInfo.PackageID)\n && (\n appInfo.PackageID.All(c => char.IsLetterOrDigit(c) || c == '.')\n && (appInfo.PackageID.Length == 9 || appInfo.PackageID.Length == 12)\n ); // Microsoft Store app IDs are typically 9 or 12 chars\n\n // Check if it's an optional feature or capability, which are Windows components\n bool isWindowsComponent =\n appInfo.Type == AppType.Capability || appInfo.Type == AppType.OptionalFeature;\n\n // Any third-party app with a period in its name is likely an external app (e.g., VideoLAN.VLC)\n bool isThirdPartyNamedApp =\n !isMicrosoftApp && appInfo.PackageName.Contains('.') && !isWindowsComponent;\n\n // If it's a Microsoft app or Windows component, it's not external\n // Otherwise, it's likely an external app\n return isThirdPartyNamedApp\n || appInfo.IsCustomInstall\n || (!isMicrosoftApp && !isStoreAppId && !isWindowsComponent);\n }\n\n /// \n public Task InstallCustomAppAsync(\n AppInfo appInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default\n )\n {\n // Implementation remains in this class for now\n // In future refactoring phases, this can be moved to a specialized service\n _currentProgress = progress;\n\n try\n {\n // Handle different custom app installations based on package name\n switch (appInfo.PackageName.ToLowerInvariant())\n {\n // Special handling for OneDrive\n case \"onedrive\":\n return InstallOneDriveAsync(progress, cancellationToken);\n\n // Add custom app installation logic here\n // case \"some-app\":\n // return await InstallSomeAppAsync(progress, cancellationToken);\n\n default:\n throw new NotSupportedException(\n $\"Custom installation for '{appInfo.PackageName}' is not supported.\"\n );\n }\n }\n catch (Exception ex)\n {\n var errorType = InstallationErrorHelper.DetermineErrorType(ex.Message);\n var errorMessage = InstallationErrorHelper.GetUserFriendlyErrorMessage(errorType);\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Error in custom installation for {appInfo.Name}: {errorMessage}\",\n DetailedMessage = $\"Exception during custom installation: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"ErrorType\", errorType.ToString() },\n { \"PackageName\", appInfo.PackageName },\n { \"AppName\", appInfo.Name },\n { \"IsCustomInstall\", \"True\" },\n { \"OriginalError\", ex.Message },\n },\n }\n );\n\n return Task.FromResult(false);\n }\n }\n\n /// \n /// Installs an app using WinGet.\n /// \n /// The package name to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// Optional display name for the app.\n /// True if installation was successful; otherwise, false.\n public Task InstallWithWingetAsync(\n string packageName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default,\n string displayName = null\n )\n {\n return _winGetInstallationService.InstallWithWingetAsync(\n packageName,\n progress,\n cancellationToken,\n displayName\n );\n }\n\n /// \n /// Disposes the resources used by the service.\n /// \n public void Dispose()\n {\n _httpClient.Dispose();\n GC.SuppressFinalize(this);\n }\n\n /// \n /// Installs OneDrive from the Microsoft download link.\n /// \n /// Optional progress reporter.\n /// Optional cancellation token.\n /// True if installation was successful; otherwise, false.\n private async Task InstallOneDriveAsync(\n IProgress? progress,\n CancellationToken cancellationToken\n )\n {\n try\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Starting OneDrive installation...\",\n DetailedMessage = \"Downloading OneDrive installer from Microsoft\",\n }\n );\n\n // Download OneDrive from the specific URL\n string downloadUrl = \"https://go.microsoft.com/fwlink/p/?LinkID=2182910\";\n string installerPath = Path.Combine(_tempDir, \"OneDriveSetup.exe\");\n\n using (var client = new HttpClient())\n {\n var response = await client.GetAsync(downloadUrl, cancellationToken);\n if (!response.IsSuccessStatusCode)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Failed to download OneDrive installer\",\n DetailedMessage = $\"HTTP error: {response.StatusCode}\",\n LogLevel = LogLevel.Error,\n }\n );\n return false;\n }\n\n using (\n var fileStream = new FileStream(\n installerPath,\n FileMode.Create,\n FileAccess.Write,\n FileShare.None\n )\n )\n {\n await response.Content.CopyToAsync(fileStream, cancellationToken);\n }\n }\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 50,\n StatusText = \"Installing OneDrive...\",\n DetailedMessage = \"Running OneDrive installer\",\n }\n );\n\n // Run the installer\n using (var process = new System.Diagnostics.Process())\n {\n process.StartInfo.FileName = installerPath;\n process.StartInfo.Arguments = \"/silent\";\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.RedirectStandardError = true;\n process.StartInfo.CreateNoWindow = true;\n\n process.Start();\n await Task.Run(() => process.WaitForExit(), cancellationToken);\n\n bool success = process.ExitCode == 0;\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = success\n ? \"OneDrive installed successfully\"\n : \"OneDrive installation failed\",\n DetailedMessage = $\"Installer exited with code: {process.ExitCode}\",\n LogLevel = success ? LogLevel.Success : LogLevel.Error,\n }\n );\n\n return success;\n }\n }\n catch (Exception ex)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Error installing OneDrive\",\n DetailedMessage = $\"Exception: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/Methods/FileSystemVerificationMethod.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods\n{\n /// \n /// Verifies software installations by checking common installation directories.\n /// \n public class FileSystemVerificationMethod : VerificationMethodBase\n {\n private static readonly string[] CommonInstallPaths = new[]\n {\n Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)),\n Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)),\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Programs\"\n ),\n Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),\n @\"Microsoft\\Windows\\Start Menu\\Programs\"\n ),\n };\n\n /// \n /// Initializes a new instance of the class.\n /// \n public FileSystemVerificationMethod()\n : base(\"FileSystem\", priority: 20) { }\n\n /// \n protected override async Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken\n )\n {\n return await Task.Run(\n () =>\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n // First try: Check if the app is in PATH (for CLI tools)\n try\n {\n var pathEnv = Environment.GetEnvironmentVariable(\"PATH\") ?? string.Empty;\n var paths = pathEnv.Split(Path.PathSeparator);\n \n\n foreach (var path in paths)\n {\n if (string.IsNullOrEmpty(path))\n continue;\n \n\n var exePath = Path.Combine(path, $\"{packageId}.exe\");\n if (File.Exists(exePath))\n {\n return new VerificationResult\n {\n IsVerified = true,\n Message = $\"Found in PATH: {exePath}\",\n MethodUsed = \"FileSystem\",\n AdditionalInfo = new\n {\n InstallPath = path,\n ExecutablePath = exePath,\n },\n };\n }\n }\n }\n catch (Exception)\n {\n // Ignore PATH check errors and continue with other methods\n }\n\n // Second try: Check common installation directories\n foreach (var basePath in CommonInstallPaths)\n {\n if (!Directory.Exists(basePath))\n continue;\n\n try\n {\n // Check for exact match in directory names\n var matchingDirs = Directory\n .EnumerateDirectories(\n basePath,\n \"*\",\n SearchOption.TopDirectoryOnly\n )\n .Where(d =>\n Path.GetFileName(d)\n ?.Equals(packageId, StringComparison.OrdinalIgnoreCase)\n == true\n || Path.GetFileName(d)\n ?.Contains(\n packageId,\n StringComparison.OrdinalIgnoreCase\n ) == true\n )\n .ToList();\n\n if (matchingDirs.Any())\n {\n return new VerificationResult\n {\n IsVerified = true,\n Message = $\"Found in file system: {matchingDirs.First()}\",\n MethodUsed = \"FileSystem\",\n AdditionalInfo = new\n {\n InstallPath = matchingDirs.First(),\n AllMatchingPaths = matchingDirs.ToArray(),\n },\n };\n }\n \n\n // Check for Microsoft Store apps in Packages directory\n if (basePath.Contains(\"LocalApplicationData\"))\n {\n var packagesPath = Path.Combine(basePath, \"Packages\");\n if (Directory.Exists(packagesPath))\n {\n var storeAppDirs = Directory\n .EnumerateDirectories(\n packagesPath,\n \"*\",\n SearchOption.TopDirectoryOnly\n )\n .Where(d =>\n Path.GetFileName(d)\n ?.IndexOf(packageId, StringComparison.OrdinalIgnoreCase) >= 0\n )\n .ToList();\n \n\n foreach (var dir in storeAppDirs)\n {\n var manifestPath = Path.Combine(dir, \"AppxManifest.xml\");\n if (File.Exists(manifestPath))\n {\n return new VerificationResult\n {\n IsVerified = true,\n Message = $\"Found Microsoft Store app: {dir}\",\n MethodUsed = \"FileSystem\",\n AdditionalInfo = new\n {\n InstallPath = dir,\n ManifestPath = manifestPath,\n },\n };\n }\n }\n }\n }\n }\n catch (UnauthorizedAccessException)\n {\n // Skip directories we can't access\n continue;\n }\n catch (Exception)\n {\n // Skip directories with other errors\n continue;\n }\n }\n\n return VerificationResult.Failure(\n $\"Package '{packageId}' not found in common installation directories\"\n );\n },\n cancellationToken\n )\n .ConfigureAwait(false);\n }\n\n /// \n protected override async Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken\n )\n {\n // For file system, we can't reliably determine version from directory name\n // So we'll just check for presence and let other methods verify version\n return await VerifyPresenceAsync(packageId, cancellationToken).ConfigureAwait(false);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/CapabilityInstallationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that enables Windows capabilities.\n/// \npublic class CapabilityInstallationService : BaseInstallationService, ICapabilityInstallationService\n{\n private readonly CapabilityCatalog _capabilityCatalog;\n private readonly IScriptUpdateService _scriptUpdateService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The PowerShell execution service.\n /// The script update service.\n public CapabilityInstallationService(\n ILogService logService,\n IPowerShellExecutionService powerShellService,\n IScriptUpdateService scriptUpdateService\n ) : base(logService, powerShellService)\n {\n // Create a default capability catalog\n _capabilityCatalog = CapabilityCatalog.CreateDefault();\n _scriptUpdateService = scriptUpdateService ?? throw new ArgumentNullException(nameof(scriptUpdateService));\n }\n\n /// \n public Task> InstallCapabilityAsync(\n CapabilityInfo capabilityInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default\n )\n {\n return InstallItemAsync(capabilityInfo, progress, cancellationToken);\n }\n\n /// \n public Task> CanInstallCapabilityAsync(CapabilityInfo capabilityInfo)\n {\n return CanInstallItemAsync(capabilityInfo);\n }\n\n /// \n protected override async Task> PerformInstallationAsync(\n CapabilityInfo capabilityInfo,\n IProgress? progress,\n CancellationToken cancellationToken)\n {\n var result = await InstallCapabilityAsync(capabilityInfo.PackageName, progress, cancellationToken);\n \n // Only update BloatRemoval.ps1 script if installation was successful\n if (result.Success)\n {\n try\n {\n _logService.LogInformation($\"Starting BloatRemoval.ps1 script update for {capabilityInfo.Name}\");\n \n // Update the BloatRemoval.ps1 script to remove the installed capability from the removal list\n var appNames = new List { capabilityInfo.PackageName };\n _logService.LogInformation($\"Removing capability name from BloatRemoval.ps1: {capabilityInfo.PackageName}\");\n \n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n\n // Add registry settings if present\n if (capabilityInfo.RegistrySettings != null && capabilityInfo.RegistrySettings.Length > 0)\n {\n _logService.LogInformation($\"Adding {capabilityInfo.RegistrySettings.Length} registry settings for {capabilityInfo.Name}\");\n appsWithRegistry.Add(capabilityInfo.PackageName, new List(capabilityInfo.RegistrySettings));\n }\n\n _logService.LogInformation($\"Updating BloatRemoval.ps1 to remove {capabilityInfo.Name} from removal list\");\n \n // Check if the capability name already includes a version (~~~~)\n string fullCapabilityName = capabilityInfo.PackageName;\n if (!fullCapabilityName.Contains(\"~~~~\"))\n {\n // We don't have a version in the package name, but we might be able to extract it from installed capabilities\n _logService.LogInformation($\"Package name doesn't include version information: {fullCapabilityName}\");\n _logService.LogInformation($\"Using package name as is: {fullCapabilityName}\");\n }\n else\n {\n _logService.LogInformation($\"Using full capability name with version: {fullCapabilityName}\");\n }\n \n // Always use the package name as provided\n appNames = new List { fullCapabilityName };\n \n var scriptResult = await _scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n true); // true = install operation, so remove from script\n \n _logService.LogInformation($\"Successfully updated BloatRemoval.ps1 script - {capabilityInfo.Name} will no longer be removed\");\n _logService.LogInformation($\"Script update result: {scriptResult?.Name ?? \"null\"}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for {capabilityInfo.Name}\", ex);\n _logService.LogError($\"Exception details: {ex.Message}\");\n _logService.LogError($\"Stack trace: {ex.StackTrace}\");\n // Don't fail the installation if script update fails\n }\n }\n else\n {\n _logService.LogInformation($\"Skipping BloatRemoval.ps1 update because installation of {capabilityInfo.Name} was not successful\");\n }\n \n return result;\n }\n\n /// \n /// Installs a Windows capability by name.\n /// \n /// The name of the capability to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n private async Task> InstallCapabilityAsync(\n string capabilityName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default\n )\n {\n try\n {\n // Get the friendly name of the capability from the catalog\n string friendlyName = GetFriendlyName(capabilityName);\n \n // Set a more descriptive initial status using the friendly name\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Enabling {friendlyName}...\",\n DetailedMessage = $\"Starting to enable capability: {capabilityName}\",\n }\n );\n\n _logService.LogInformation($\"Attempting to enable capability: {capabilityName}\");\n \n // Create a progress handler that overrides the generic \"Operation: Running\" text\n var progressHandler = new Progress(detail => {\n // If we get a generic \"Operation: Running\" status, replace it with our more descriptive one\n if (detail.StatusText != null && detail.StatusText.StartsWith(\"Operation:\"))\n {\n // Keep the percentage but replace the generic text with the friendly name\n detail.StatusText = $\"Enabling {friendlyName}...\";\n if (detail.Progress.HasValue)\n {\n detail.StatusText = $\"Enabling {friendlyName}... ({detail.Progress:F0}%)\";\n }\n }\n \n // Forward the updated progress to the original progress reporter\n progress?.Report(detail);\n });\n\n // Define the PowerShell script - Embed capabilityName, output parseable string\n // Output format: STATUS|Message|RebootRequired (e.g., SUCCESS|Installed 1 of 1|True)\n string script = $@\"\n try {{\n $capabilityNamePattern = '{capabilityName}*' # Embed pattern directly\n Write-Information \"\"Searching for capability: $capabilityNamePattern\"\"\n # Progress reporting needs to be handled by the caller based on script output or duration\n\n # Find matching capabilities\n $capabilities = Get-WindowsCapability -Online | Where-Object {{ $_.Name -like $capabilityNamePattern -and $_.State -ne 'Installed' }}\n\n if ($capabilities.Count -eq 0) {{\n # Check if it's already installed\n $alreadyInstalled = Get-WindowsCapability -Online | Where-Object {{ $_.Name -like $capabilityNamePattern -and $_.State -eq 'Installed' }}\n if ($alreadyInstalled) {{\n return \"\"SUCCESS|Capability already installed|False\"\"\n }} else {{\n Write-Warning \"\"No matching capabilities found: $capabilityNamePattern\"\"\n return \"\"FAILURE|No matching capabilities found\"\"\n }}\n }}\n\n $totalCapabilities = $capabilities.Count\n $rebootRequired = $false\n $installedCount = 0\n $errorMessages = @()\n\n foreach ($capability in $capabilities) {{\n Write-Information \"\"Installing capability: $($capability.Name)\"\"\n try {{\n $result = Add-WindowsCapability -Online -Name $capability.Name\n if ($result.RestartNeeded) {{\n $rebootRequired = $true\n }}\n $installedCount++\n }}\n catch {{\n $errMsg = \"\"Failed to install capability: $($capability.Name). $($_.Exception.Message)\"\"\n Write-Error $errMsg\n $errorMessages += $errMsg\n }}\n }}\n\n if ($installedCount -gt 0) {{\n $rebootNeededStr = if ($rebootRequired) {{ 'True' }} else {{ 'False' }}\n $finalMessage = \"\"Successfully installed $installedCount of $totalCapabilities capabilities.\"\"\n if ($errorMessages.Count -gt 0) {{\n $finalMessage += \"\" Errors: $($errorMessages -join '; ')\"\"\n }}\n return \"\"SUCCESS|$finalMessage|$rebootNeededStr\"\"\n }} else {{\n $finalMessage = \"\"Failed to install any capabilities.\"\"\n if ($errorMessages.Count -gt 0) {{\n $finalMessage += \"\" Errors: $($errorMessages -join '; ')\"\"\n }}\n return \"\"FAILURE|$finalMessage\"\"\n }}\n }}\n catch {{\n Write-Error \"\"Error enabling capability: $($_.Exception.Message)\"\"\n return \"\"FAILURE|$($_.Exception.Message)\"\"\n }}\n \";\n\n // Execute PowerShell using the correct interface method with our custom progress handler\n string resultString = await _powerShellService.ExecuteScriptAsync(\n script,\n progressHandler, // Use our custom progress handler instead of passing progress directly\n cancellationToken);\n\n // Process the result string\n if (!string.IsNullOrEmpty(resultString))\n {\n var parts = resultString.Split('|');\n if (parts.Length >= 2)\n {\n string status = parts[0];\n string message = parts[1];\n bool rebootRequired = parts.Length > 2 && bool.TryParse(parts[2], out bool req) && req;\n\n if (status.Equals(\"SUCCESS\", StringComparison.OrdinalIgnoreCase))\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 100,\n StatusText = $\"Successfully enabled {GetFriendlyName(capabilityName)}\",\n DetailedMessage = message\n });\n _logService.LogSuccess($\"Successfully enabled capability: {capabilityName}. {message}\");\n\n if (rebootRequired)\n {\n progress?.Report(new TaskProgressDetail\n {\n StatusText = \"A system restart is required to complete the installation\",\n DetailedMessage = \"Please restart your computer to complete the installation\",\n LogLevel = LogLevel.Warning\n });\n _logService.LogWarning($\"A system restart is required for {GetFriendlyName(capabilityName)}\");\n }\n return OperationResult.Succeeded(true); // Indicate success\n }\n else // FAILURE\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0, // Indicate failure\n StatusText = $\"Failed to enable {GetFriendlyName(capabilityName)}\",\n DetailedMessage = message,\n LogLevel = LogLevel.Error\n });\n _logService.LogError($\"Failed to enable capability: {capabilityName}. {message}\");\n return OperationResult.Failed(message); // Indicate failure with message\n }\n }\n else\n {\n // Handle unexpected script output format\n _logService.LogError($\"Unexpected script output format for {capabilityName}: {resultString}\");\n progress?.Report(new TaskProgressDetail { StatusText = \"Error processing script result\", LogLevel = LogLevel.Error });\n return OperationResult.Failed(\"Unexpected script output format: \" + resultString); // Indicate failure with message\n }\n }\n else\n {\n // Handle case where script returned empty string\n _logService.LogError($\"Empty result returned when enabling capability: {capabilityName}\");\n progress?.Report(new TaskProgressDetail { StatusText = \"Script returned no result\", LogLevel = LogLevel.Error });\n return OperationResult.Failed(\"Script returned no result\"); // Indicate failure with message\n }\n }\n catch (OperationCanceledException)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Operation cancelled when enabling {GetFriendlyName(capabilityName)}\",\n DetailedMessage = \"The operation was cancelled by the user\",\n LogLevel = LogLevel.Warning,\n }\n );\n\n _logService.LogWarning($\"Operation cancelled when enabling capability: {capabilityName}\");\n return OperationResult.Failed(\"The operation was cancelled by the user\"); // Return cancellation result\n }\n catch (Exception ex)\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Error enabling {GetFriendlyName(capabilityName)}\",\n DetailedMessage = $\"Exception: {ex.Message}\",\n LogLevel = LogLevel.Error\n });\n _logService.LogError($\"Error enabling capability: {capabilityName}\", ex);\n return OperationResult.Failed($\"Error enabling capability: {ex.Message}\", ex); // Indicate failure with exception\n }\n }\n\n // Note: CheckInstalled is not part of the ICapabilityInstallationService interface\n // It should likely be moved or removed if not used elsewhere.\n // For now, commenting it out to fix build errors.\n /*\n public bool CheckInstalled(CapabilityInfo capabilityInfo)\n {\n // ... (Implementation needs fixing similar to InstallCapabilityAsync)\n }\n */\n\n // Note: InstallCapabilitiesAsync is not part of the ICapabilityInstallationService interface\n // It should likely be moved or removed if not used elsewhere.\n // For now, commenting it out to fix build errors.\n /*\n public Task InstallCapabilitiesAsync(IEnumerable capabilities)\n {\n return InstallCapabilitiesAsync(capabilities, null, default);\n }\n\n public async Task InstallCapabilitiesAsync(\n IEnumerable capabilities,\n IProgress? progress,\n CancellationToken cancellationToken)\n {\n // ... (Implementation needs fixing similar to InstallCapabilityAsync)\n }\n */\n\n // Note: RemoveCapabilitiesAsync is not part of the ICapabilityInstallationService interface\n // It should likely be moved or removed if not used elsewhere.\n // For now, commenting it out to fix build errors.\n /*\n public async Task RemoveCapabilitiesAsync(IEnumerable capabilities)\n {\n // ... (Implementation needs fixing similar to InstallCapabilityAsync)\n }\n\n private async Task RemoveCapabilityAsync(CapabilityInfo capabilityInfo)\n {\n // ... (Implementation needs fixing similar to InstallCapabilityAsync)\n }\n */\n\n /// \n /// Gets the friendly name of a capability from its package name.\n /// \n /// The package name of the capability.\n /// The friendly name of the capability, or the package name if not found.\n private string GetFriendlyName(string packageName)\n {\n // Remove any version information from the package name (e.g., \"Media.WindowsMediaPlayer~~~~0.0.12.0\" -> \"Media.WindowsMediaPlayer\")\n string basePackageName = packageName.Split('~')[0];\n \n // Look up the capability in the catalog by its package name\n var capability = _capabilityCatalog.Capabilities.FirstOrDefault(c =>\n c.PackageName.Equals(basePackageName, StringComparison.OrdinalIgnoreCase));\n \n // Return the friendly name if found, otherwise return the package name\n return capability?.Name ?? packageName;\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/TaskProgressService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Threading;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service that manages task progress reporting across the application.\n /// \n public class TaskProgressService : ITaskProgressService\n {\n private readonly ILogService _logService;\n private int _currentProgress;\n private string _currentStatusText;\n private bool _isTaskRunning;\n private bool _isIndeterminate;\n private List _logMessages = new List();\n private CancellationTokenSource _cancellationSource;\n\n /// \n /// Gets whether a task is currently running.\n /// \n public bool IsTaskRunning => _isTaskRunning;\n\n /// \n /// Gets the current progress value (0-100).\n /// \n public int CurrentProgress => _currentProgress;\n\n /// \n /// Gets the current status text.\n /// \n public string CurrentStatusText => _currentStatusText;\n\n /// \n /// Gets whether the current task is in indeterminate mode.\n /// \n public bool IsIndeterminate => _isIndeterminate;\n\n /// \n /// Gets the cancellation token source for the current task.\n /// \n public CancellationTokenSource? CurrentTaskCancellationSource => _cancellationSource;\n\n /// \n /// Event raised when progress changes.\n /// \n public event EventHandler? ProgressUpdated;\n\n /// \n /// Event raised when progress changes (compatibility with App.xaml.cs).\n /// \n public event EventHandler? ProgressChanged;\n\n /// \n /// Event raised when a log message is added.\n /// \n public event EventHandler? LogMessageAdded;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public TaskProgressService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _currentProgress = 0;\n _currentStatusText = string.Empty;\n _isTaskRunning = false;\n _isIndeterminate = false;\n }\n\n /// \n /// Starts a new task with the specified name.\n /// \n /// The name of the task.\n /// Whether the task progress is indeterminate.\n /// A cancellation token source for the task.\n public CancellationTokenSource StartTask(string taskName, bool isIndeterminate = false)\n {\n // Cancel any existing task\n CancelCurrentTask();\n\n if (string.IsNullOrEmpty(taskName))\n {\n throw new ArgumentException(\"Task name cannot be null or empty.\", nameof(taskName));\n }\n\n _cancellationSource = new CancellationTokenSource();\n _currentProgress = 0;\n _currentStatusText = taskName;\n _isTaskRunning = true;\n _isIndeterminate = isIndeterminate;\n _logMessages.Clear();\n\n _logService.Log(LogLevel.Info, $\"Task started: {taskName}\"); // Corrected Log call\n AddLogMessage($\"Task started: {taskName}\");\n OnProgressChanged(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = taskName,\n IsIndeterminate = isIndeterminate,\n }\n );\n\n return _cancellationSource;\n }\n\n /// \n /// Updates the progress of the current task.\n /// \n /// The progress percentage (0-100).\n /// The status text.\n public void UpdateProgress(int progressPercentage, string? statusText = null)\n {\n if (!_isTaskRunning)\n {\n Debug.WriteLine(\"Warning: Attempting to update progress when no task is running.\");\n return;\n }\n\n if (progressPercentage < 0 || progressPercentage > 100)\n {\n throw new ArgumentOutOfRangeException(\n nameof(progressPercentage),\n \"Progress must be between 0 and 100.\"\n );\n }\n\n _currentProgress = progressPercentage;\n if (!string.IsNullOrEmpty(statusText))\n {\n _currentStatusText = statusText;\n _logService.Log(\n LogLevel.Info,\n $\"Task progress ({progressPercentage}%): {statusText}\"\n ); // Corrected Log call\n AddLogMessage($\"Task progress ({progressPercentage}%): {statusText}\");\n }\n else\n {\n _logService.Log(LogLevel.Info, $\"Task progress: {progressPercentage}%\"); // Corrected Log call\n AddLogMessage($\"Task progress: {progressPercentage}%\");\n }\n OnProgressChanged(\n new TaskProgressDetail\n {\n Progress = progressPercentage,\n StatusText = _currentStatusText,\n }\n );\n }\n\n /// \n /// Updates the progress with detailed information.\n /// \n /// The detailed progress information.\n public void UpdateDetailedProgress(TaskProgressDetail detail)\n {\n if (!_isTaskRunning)\n {\n Debug.WriteLine(\n \"Warning: Attempting to update detailed progress when no task is running.\"\n );\n return;\n }\n\n if (detail.Progress.HasValue)\n {\n if (detail.Progress.Value < 0 || detail.Progress.Value > 100)\n {\n throw new ArgumentOutOfRangeException(\n nameof(detail.Progress),\n \"Progress must be between 0 and 100.\"\n );\n }\n\n _currentProgress = (int)detail.Progress.Value;\n }\n\n if (!string.IsNullOrEmpty(detail.StatusText))\n {\n _currentStatusText = detail.StatusText;\n }\n\n _isIndeterminate = detail.IsIndeterminate;\n if (!string.IsNullOrEmpty(detail.DetailedMessage))\n {\n _logService.Log(detail.LogLevel, detail.DetailedMessage); // Corrected Log call\n AddLogMessage(detail.DetailedMessage);\n }\n OnProgressChanged(detail);\n }\n\n /// \n /// Completes the current task.\n /// \n public void CompleteTask()\n {\n if (!_isTaskRunning)\n {\n Debug.WriteLine(\"Warning: Attempting to complete a task when no task is running.\");\n return;\n }\n\n _currentProgress = 100;\n\n _isTaskRunning = false;\n _isIndeterminate = false;\n\n _logService.Log(LogLevel.Info, $\"Task completed: {_currentStatusText}\"); // Corrected Log call\n AddLogMessage($\"Task completed: {_currentStatusText}\");\n\n OnProgressChanged(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = _currentStatusText,\n DetailedMessage = \"Task completed\",\n }\n );\n\n // Dispose cancellation token source\n _cancellationSource?.Dispose();\n _cancellationSource = null;\n }\n\n /// \n /// Adds a log message.\n /// \n /// The message content.\n public void AddLogMessage(string message)\n {\n if (string.IsNullOrEmpty(message))\n return;\n\n _logMessages.Add(message);\n LogMessageAdded?.Invoke(this, message);\n }\n\n /// \n /// Cancels the current task.\n /// \n public void CancelCurrentTask()\n {\n if (_cancellationSource != null && !_cancellationSource.IsCancellationRequested)\n {\n _cancellationSource.Cancel();\n AddLogMessage(\"Task cancelled by user\");\n\n // Don't dispose here, as the task might still be using it\n // It will be disposed in CompleteTask or when a new task starts\n }\n }\n\n /// \n /// Creates a progress reporter for detailed progress.\n /// \n /// The progress reporter.\n public IProgress CreateDetailedProgress()\n {\n return new Progress(UpdateDetailedProgress);\n }\n\n /// \n /// Creates a progress reporter for PowerShell progress.\n /// \n /// The progress reporter.\n public IProgress CreatePowerShellProgress()\n {\n return new Progress(UpdateDetailedProgress);\n }\n\n /// \n /// Creates a progress adapter for PowerShell progress data.\n /// \n /// A progress adapter for PowerShell progress data.\n public IProgress CreatePowerShellProgressAdapter()\n {\n return new Progress(data =>\n {\n var detail = new TaskProgressDetail();\n\n // Map PowerShell progress data to task progress detail\n if (data.PercentComplete.HasValue)\n {\n detail.Progress = data.PercentComplete.Value;\n }\n\n if (!string.IsNullOrEmpty(data.Activity))\n {\n detail.StatusText = data.Activity;\n if (!string.IsNullOrEmpty(data.StatusDescription))\n {\n detail.StatusText += $\": {data.StatusDescription}\";\n }\n }\n\n detail.DetailedMessage = data.Message ?? data.CurrentOperation;\n\n // Map stream type to log level\n switch (data.StreamType)\n {\n case PowerShellStreamType.Error:\n detail.LogLevel = LogLevel.Error;\n break;\n case PowerShellStreamType.Warning:\n detail.LogLevel = LogLevel.Warning;\n break;\n case PowerShellStreamType.Verbose:\n case PowerShellStreamType.Debug:\n detail.LogLevel = LogLevel.Debug;\n break;\n default:\n detail.LogLevel = LogLevel.Info;\n break;\n }\n\n UpdateDetailedProgress(detail);\n });\n }\n\n /// \n /// Raises the ProgressUpdated event.\n /// \n protected virtual void OnProgressChanged(TaskProgressDetail detail)\n {\n ProgressUpdated?.Invoke(this, detail);\n ProgressChanged?.Invoke(\n this,\n TaskProgressEventArgs.FromTaskProgressDetail(detail, _isTaskRunning)\n );\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/FeatureInstallationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that enables Windows optional features.\n/// \npublic class FeatureInstallationService : BaseInstallationService, IFeatureInstallationService\n{\n private readonly FeatureCatalog _featureCatalog;\n private readonly IScriptUpdateService _scriptUpdateService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The PowerShell execution service.\n /// The script update service.\n public FeatureInstallationService(\n ILogService logService,\n IPowerShellExecutionService powerShellService,\n IScriptUpdateService scriptUpdateService)\n : base(logService, powerShellService)\n {\n // Create a default feature catalog\n _featureCatalog = FeatureCatalog.CreateDefault();\n _scriptUpdateService = scriptUpdateService ?? throw new ArgumentNullException(nameof(scriptUpdateService));\n }\n\n /// \n public Task> InstallFeatureAsync(\n FeatureInfo featureInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n return InstallItemAsync(featureInfo, progress, cancellationToken);\n }\n\n /// \n public Task> CanInstallFeatureAsync(FeatureInfo featureInfo)\n {\n return CanInstallItemAsync(featureInfo);\n }\n\n /// \n protected override async Task> PerformInstallationAsync(\n FeatureInfo featureInfo,\n IProgress? progress,\n CancellationToken cancellationToken)\n {\n var result = await InstallFeatureAsync(featureInfo.PackageName, progress, cancellationToken);\n \n // Only update BloatRemoval.ps1 script if installation was successful\n if (result.Success)\n {\n try\n {\n _logService.LogInformation($\"Starting BloatRemoval.ps1 script update for {featureInfo.Name}\");\n \n // Update the BloatRemoval.ps1 script to remove the installed feature from the removal list\n var appNames = new List { featureInfo.PackageName };\n _logService.LogInformation($\"Removing feature name from BloatRemoval.ps1: {featureInfo.PackageName}\");\n \n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n\n // Add registry settings if present\n if (featureInfo.RegistrySettings != null && featureInfo.RegistrySettings.Length > 0)\n {\n _logService.LogInformation($\"Adding {featureInfo.RegistrySettings.Length} registry settings for {featureInfo.Name}\");\n appsWithRegistry.Add(featureInfo.PackageName, new List(featureInfo.RegistrySettings));\n }\n\n _logService.LogInformation($\"Updating BloatRemoval.ps1 to remove {featureInfo.Name} from removal list\");\n \n // Make sure we're explicitly identifying this as an optional feature\n _logService.LogInformation($\"Ensuring {featureInfo.Name} is identified as an optional feature\");\n \n var scriptResult = await _scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n true); // true = install operation, so remove from script\n \n _logService.LogInformation($\"Successfully updated BloatRemoval.ps1 script - {featureInfo.Name} will no longer be removed\");\n _logService.LogInformation($\"Script update result: {scriptResult?.Name ?? \"null\"}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for {featureInfo.Name}\", ex);\n _logService.LogError($\"Exception details: {ex.Message}\");\n _logService.LogError($\"Stack trace: {ex.StackTrace}\");\n // Don't fail the installation if script update fails\n }\n }\n else\n {\n _logService.LogInformation($\"Skipping BloatRemoval.ps1 update because installation of {featureInfo.Name} was not successful\");\n }\n \n return result;\n }\n\n\n /// \n /// Installs a Windows optional feature by name.\n /// \n /// The name of the feature to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n private async Task> InstallFeatureAsync(\n string featureName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n try\n {\n // Get the friendly name of the feature from the catalog\n string friendlyName = GetFriendlyName(featureName);\n \n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Enabling {friendlyName}...\",\n DetailedMessage = $\"Starting to enable optional feature: {featureName}\"\n });\n\n _logService.LogInformation($\"Attempting to enable optional feature: {featureName}\");\n \n // Create a progress handler that overrides the generic \"Operation: Running\" text\n var progressHandler = new Progress(detail => {\n // If we get a generic \"Operation: Running\" status, replace it with our more descriptive one\n if (detail.StatusText != null && detail.StatusText.StartsWith(\"Operation:\"))\n {\n // Keep the percentage but replace the generic text with the friendly name\n detail.StatusText = $\"Enabling {friendlyName}...\";\n if (detail.Progress.HasValue)\n {\n detail.StatusText = $\"Enabling {friendlyName}... ({detail.Progress:F0}%)\";\n }\n }\n \n // Forward the updated progress to the original progress reporter\n progress?.Report(detail);\n });\n\n // Define the PowerShell script - Embed featureName, output parseable string\n // Output format: STATUS|Message|RebootRequired (e.g., SUCCESS|Feature enabled|True)\n string script = $@\"\n try {{\n $featureName = '{featureName}' # Embed featureName directly\n Write-Information \"\"Checking feature status: $featureName\"\"\n # Progress reporting needs to be handled by the caller based on script output or duration\n\n # Check if the feature exists\n $feature = Get-WindowsOptionalFeature -Online -FeatureName $featureName -ErrorAction SilentlyContinue\n\n if (-not $feature) {{\n Write-Warning \"\"Feature not found: $featureName\"\"\n return \"\"FAILURE|Feature not found: $featureName\"\"\n }}\n\n # Check if the feature is already enabled\n if ($feature.State -eq 'Enabled') {{\n Write-Information \"\"Feature is already enabled: $featureName\"\"\n return \"\"SUCCESS|Feature is already enabled|False\"\"\n }}\n\n Write-Information \"\"Enabling feature: $featureName\"\"\n\n # Enable the feature\n $result = Enable-WindowsOptionalFeature -Online -FeatureName $featureName -NoRestart\n\n # Check if the feature was enabled successfully\n $feature = Get-WindowsOptionalFeature -Online -FeatureName $featureName\n\n if ($feature.State -eq 'Enabled') {{\n $rebootNeeded = if ($result.RestartNeeded) {{ 'True' }} else {{ 'False' }}\n return \"\"SUCCESS|Feature enabled successfully|$rebootNeeded\"\"\n }} else {{\n Write-Warning \"\"Failed to enable feature: $featureName\"\"\n return \"\"FAILURE|Failed to enable feature\"\"\n }}\n }}\n catch {{\n Write-Error \"\"Error enabling feature: $($_.Exception.Message)\"\"\n return \"\"FAILURE|$($_.Exception.Message)\"\"\n }}\n \";\n\n // Execute PowerShell using the correct interface method with our custom progress handler\n string resultString = await _powerShellService.ExecuteScriptAsync(\n script,\n progressHandler, // Use our custom progress handler instead of passing progress directly\n cancellationToken);\n\n // Process the result string\n if (!string.IsNullOrEmpty(resultString))\n {\n var parts = resultString.Split('|');\n if (parts.Length >= 2)\n {\n string status = parts[0];\n string message = parts[1];\n bool rebootRequired = parts.Length > 2 && bool.TryParse(parts[2], out bool req) && req;\n\n if (status.Equals(\"SUCCESS\", StringComparison.OrdinalIgnoreCase))\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 100,\n StatusText = $\"Successfully enabled {GetFriendlyName(featureName)}\",\n DetailedMessage = message\n });\n _logService.LogSuccess($\"Successfully enabled optional feature: {featureName}. {message}\");\n\n if (rebootRequired)\n {\n progress?.Report(new TaskProgressDetail\n {\n StatusText = \"A system restart is required to complete the installation\",\n DetailedMessage = \"Please restart your computer to complete the installation\",\n LogLevel = LogLevel.Warning\n });\n _logService.LogWarning($\"A system restart is required for {GetFriendlyName(featureName)}\");\n }\n return OperationResult.Succeeded(true); // Indicate success\n }\n else // FAILURE\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0, // Indicate failure\n StatusText = $\"Failed to enable {GetFriendlyName(featureName)}\",\n DetailedMessage = message,\n LogLevel = LogLevel.Error\n });\n _logService.LogError($\"Failed to enable optional feature: {featureName}. {message}\");\n return OperationResult.Failed(message); // Indicate failure with message\n }\n }\n else\n {\n // Handle unexpected script output format\n _logService.LogError($\"Unexpected script output format for {featureName}: {resultString}\");\n progress?.Report(new TaskProgressDetail { StatusText = \"Error processing script result\", LogLevel = LogLevel.Error });\n return OperationResult.Failed(\"Unexpected script output format: \" + resultString); // Indicate failure with message\n }\n }\n else\n {\n // Handle case where script returned empty string\n _logService.LogError($\"Empty result returned when enabling optional feature: {featureName}\");\n progress?.Report(new TaskProgressDetail { StatusText = \"Script returned no result\", LogLevel = LogLevel.Error });\n return OperationResult.Failed(\"Script returned no result\"); // Indicate failure with message\n }\n }\n catch (OperationCanceledException)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Operation cancelled when enabling {GetFriendlyName(featureName)}\",\n DetailedMessage = \"The operation was cancelled by the user\",\n LogLevel = LogLevel.Warning,\n }\n );\n\n _logService.LogWarning($\"Operation cancelled when enabling optional feature: {featureName}\");\n return OperationResult.Failed(\"The operation was cancelled by the user\"); // Return cancellation result\n }\n catch (Exception ex)\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Error enabling {GetFriendlyName(featureName)}\",\n DetailedMessage = $\"Exception: {ex.Message}\",\n LogLevel = LogLevel.Error\n });\n _logService.LogError($\"Error enabling optional feature: {featureName}\", ex);\n return OperationResult.Failed($\"Error enabling optional feature: {ex.Message}\", ex); // Indicate failure with exception\n }\n }\n\n /// \n /// Gets the friendly name of a feature from its package name.\n /// \n /// The package name of the feature.\n /// The friendly name of the feature, or the package name if not found.\n private string GetFriendlyName(string packageName)\n {\n // Look up the feature in the catalog by its package name\n var feature = _featureCatalog.Features.FirstOrDefault(f => \n f.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase));\n \n // Return the friendly name if found, otherwise return the package name\n return feature?.Name ?? packageName;\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/GreaterThanOneConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Converters\n{\n /// \n /// Converter that returns true if the input value is greater than one.\n /// \n public class GreaterThanOneConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is int count)\n {\n return count > 1;\n }\n return false;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Services/SoftwareAppsDialogService.cs", "using System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.SoftwareApps.Views;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Services\n{\n /// \n /// Specialized dialog service for the SoftwareApps feature.\n /// This service uses the SoftwareAppsDialog for consistent UI in the SoftwareApps feature.\n /// \n public class SoftwareAppsDialogService\n {\n private readonly ILogService _logService;\n\n public SoftwareAppsDialogService(ILogService logService)\n {\n _logService = logService;\n }\n\n /// \n /// Shows a message to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n public Task ShowMessageAsync(string message, string title = \"\")\n {\n SoftwareAppsDialog.ShowInformationAsync(title, message, new[] { message }, \"\");\n return Task.CompletedTask;\n }\n\n /// \n /// Shows a confirmation dialog to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n /// The text for the OK button.\n /// The text for the Cancel button.\n /// A task that represents the asynchronous operation, with a boolean result indicating whether the user confirmed the action.\n public Task ShowConfirmationAsync(\n string message,\n string title = \"\",\n string okButtonText = \"OK\",\n string cancelButtonText = \"Cancel\"\n )\n {\n // Parse apps from the message if it contains a list\n if (\n message.Contains(\"following\")\n && (message.Contains(\"install\") || message.Contains(\"remove\"))\n )\n {\n var lines = message.Split('\\n');\n var apps = lines\n .Skip(1) // Skip the header line\n .Where(line =>\n !string.IsNullOrWhiteSpace(line) && !line.Contains(\"Do you want to\")\n )\n .TakeWhile(line => !line.Contains(\"Do you want to\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line =>\n line.Contains(\"cannot be\")\n || line.Contains(\"action cannot\")\n || line.Contains(\"Some selected\")\n )\n .Select(line => line.Trim())\n );\n\n var result = SoftwareAppsDialog.ShowConfirmationAsync(\n title,\n headerText,\n apps,\n footerText\n );\n return Task.FromResult(result ?? false);\n }\n else\n {\n // For simple confirmation messages\n var result = SoftwareAppsDialog.ShowConfirmationAsync(\n title,\n message,\n new[] { message },\n \"\"\n );\n return Task.FromResult(result ?? false);\n }\n }\n\n /// \n /// Shows an information dialog to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n /// The text for the button.\n /// A task that represents the asynchronous operation.\n public Task ShowInformationAsync(\n string message,\n string title = \"Information\",\n string buttonText = \"OK\"\n )\n {\n // Parse apps from the message if it contains a list\n if (\n message.Contains(\"following\")\n && (message.Contains(\"installed\") || message.Contains(\"removed\"))\n )\n {\n var lines = message.Split('\\n');\n var apps = lines\n .Where(line => line.StartsWith(\"+\") || line.StartsWith(\"-\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line => line.Contains(\"Failed\") || line.Contains(\"startup task\"))\n .Select(line => line.Trim())\n );\n\n SoftwareAppsDialog.ShowInformationAsync(title, headerText, apps, footerText);\n }\n else\n {\n // For simple information messages\n SoftwareAppsDialog.ShowInformationAsync(title, message, new[] { message }, \"\");\n }\n return Task.CompletedTask;\n }\n\n /// \n /// Shows an information dialog to the user with custom header, apps list, and footer.\n /// \n /// The title of the dialog.\n /// The header text to display.\n /// The collection of app names or messages to display.\n /// The footer text to display.\n /// A task that represents the asynchronous operation.\n public Task ShowInformationAsync(\n string title,\n string headerText,\n IEnumerable apps,\n string footerText\n )\n {\n SoftwareAppsDialog.ShowInformationAsync(title, headerText, apps, footerText);\n return Task.CompletedTask;\n }\n\n /// \n /// Shows a warning dialog to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n /// The text for the button.\n /// A task that represents the asynchronous operation.\n public Task ShowWarningAsync(\n string message,\n string title = \"Warning\",\n string buttonText = \"OK\"\n )\n {\n SoftwareAppsDialog.ShowInformationAsync(title, message, new[] { message }, \"\");\n return Task.CompletedTask;\n }\n\n /// \n /// Shows an input dialog to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n /// The default value for the input.\n /// A task that represents the asynchronous operation, with the user's input as the result.\n public Task ShowInputAsync(\n string message,\n string title = \"\",\n string defaultValue = \"\"\n )\n {\n // Input dialogs are not supported by SoftwareAppsDialog\n // Fallback to a confirmation dialog\n var result = SoftwareAppsDialog.ShowConfirmationAsync(\n title,\n message,\n new[] { message },\n \"\"\n );\n return Task.FromResult(result == true ? defaultValue : null);\n }\n\n /// \n /// Shows a Yes/No/Cancel dialog to the user.\n /// \n /// The message to show.\n /// The title of the dialog.\n /// A task that represents the asynchronous operation, with a boolean result indicating the user's choice (true for Yes, false for No, null for Cancel).\n public Task ShowYesNoCancelAsync(string message, string title = \"\")\n {\n // Parse apps from the message if it contains a list\n if (\n message.Contains(\"following\")\n && (message.Contains(\"install\") || message.Contains(\"remove\"))\n )\n {\n var lines = message.Split('\\n');\n var apps = lines\n .Where(line => line.StartsWith(\"+\") || line.StartsWith(\"-\"))\n .Select(line => line.Trim())\n .ToList();\n\n var headerText = lines[0];\n var footerText = string.Join(\n \"\\n\\n\",\n lines\n .Where(line =>\n line.Contains(\"cannot be\")\n || line.Contains(\"action cannot\")\n || line.Contains(\"Some selected\")\n )\n .Select(line => line.Trim())\n );\n\n var result = SoftwareAppsDialog.ShowYesNoCancel(\n title,\n headerText,\n apps,\n footerText\n );\n return Task.FromResult(result);\n }\n else\n {\n // For simple messages\n var result = SoftwareAppsDialog.ShowYesNoCancel(\n title,\n message,\n new[] { message },\n \"\"\n );\n return Task.FromResult(result);\n }\n }\n\n /// \n /// Shows an operation result dialog to the user.\n /// \n /// The type of operation (e.g., \"Install\", \"Remove\").\n /// The number of successful operations.\n /// The total number of operations.\n /// The list of successfully processed items.\n /// The list of failed items.\n /// The list of skipped items.\n /// Whether there were connectivity issues.\n public void ShowOperationResult(\n string operationType,\n int successCount,\n int totalCount,\n IEnumerable successItems,\n IEnumerable failedItems = null,\n IEnumerable skippedItems = null,\n bool hasConnectivityIssues = false,\n bool isUserCancelled = false\n )\n {\n // Get the past tense form of the operation type\n string GetPastTense(string op)\n {\n if (string.IsNullOrEmpty(op))\n return string.Empty;\n\n return op.Equals(\"Remove\", System.StringComparison.OrdinalIgnoreCase)\n ? \"removed\"\n : $\"{op.ToLower()}ed\";\n }\n\n // Check if any failures are due to internet connectivity issues or user cancellation\n bool isFailure = successCount < totalCount;\n\n string title;\n if (isUserCancelled)\n {\n title = \"Installation Aborted\";\n }\n else if (hasConnectivityIssues)\n {\n title = \"Internet Connection Lost\";\n }\n else\n {\n title = isFailure\n ? $\"{operationType} Operation Failed\"\n : $\"{operationType} Results\";\n }\n\n string headerText;\n if (isUserCancelled)\n {\n headerText = $\"Installation aborted by user\";\n }\n else if (hasConnectivityIssues)\n {\n headerText = \"Installation stopped due to internet connection loss\";\n }\n else\n {\n headerText =\n successCount > 0 && successCount == totalCount\n ? $\"The following items were successfully {GetPastTense(operationType)}:\"\n : (\n successCount > 0\n ? $\"Successfully {GetPastTense(operationType)} {successCount} of {totalCount} items.\"\n : $\"Unable to {operationType.ToLowerInvariant()} {totalCount} of {totalCount} items.\"\n );\n }\n\n // Create list of items for the dialog\n var resultItems = new List();\n\n // For connectivity issues or user cancellation, add a clear explanation\n if (isUserCancelled)\n {\n resultItems.Add(\"The installation process was cancelled by the user.\");\n resultItems.Add(\"\");\n if (successCount > 0)\n {\n resultItems.Add(\"Successfully installed items:\");\n }\n }\n else if (hasConnectivityIssues)\n {\n resultItems.Add(\n \"The installation process was stopped because the internet connection was lost.\"\n );\n resultItems.Add(\n \"This is required to ensure installations complete properly and prevent corrupted installations.\"\n );\n resultItems.Add(\"\");\n resultItems.Add(\"Failed items:\");\n }\n\n // Add successful items directly to the list\n if (successItems != null && successItems.Any())\n {\n if (!hasConnectivityIssues) // Only show success items if not a connectivity issue\n {\n foreach (var item in successItems)\n {\n resultItems.Add(item);\n }\n }\n }\n else if (!hasConnectivityIssues) // Only show this message if not a connectivity issue\n {\n resultItems.Add($\"No items were {GetPastTense(operationType)}.\");\n }\n\n // Add skipped items if any\n if (skippedItems != null && skippedItems.Any() && !hasConnectivityIssues) // Only show if not a connectivity issue\n {\n resultItems.Add($\"Skipped items: {skippedItems.Count()}\");\n foreach (var item in skippedItems.Take(5))\n {\n resultItems.Add($\" - {item}\");\n }\n if (skippedItems.Count() > 5)\n {\n resultItems.Add($\" - ... and {skippedItems.Count() - 5} more\");\n }\n }\n\n // Add failed items if any\n if (failedItems != null && failedItems.Any())\n {\n if (!hasConnectivityIssues) // Only show the header if not already shown for connectivity issues\n {\n resultItems.Add($\"Failed items: {failedItems.Count()}\");\n }\n\n foreach (var item in failedItems.Take(5))\n {\n resultItems.Add($\" - {item}\");\n }\n if (failedItems.Count() > 5)\n {\n resultItems.Add($\" - ... and {failedItems.Count() - 5} more\");\n }\n }\n\n // Create footer text\n string footerText;\n if (isUserCancelled)\n {\n footerText =\n successCount > 0\n ? $\"Some items were successfully {GetPastTense(operationType)} before cancellation.\"\n : $\"No items were {GetPastTense(operationType)} before cancellation.\";\n }\n else if (hasConnectivityIssues)\n {\n footerText =\n \"Please check your network connection and try again when your internet connection is stable.\";\n }\n else\n {\n // Check if we have any connectivity-related failures\n bool hasConnectivityFailures =\n failedItems != null\n && failedItems.Any(item =>\n item.Contains(\"internet\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\"connection\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\"network\", StringComparison.OrdinalIgnoreCase)\n || item.Contains(\n \"pipeline has been stopped\",\n StringComparison.OrdinalIgnoreCase\n )\n );\n\n footerText =\n successCount == totalCount\n ? $\"All items were successfully {GetPastTense(operationType)}.\"\n : (\n successCount > 0\n ? (\n hasConnectivityFailures\n ? $\"Some items could not be {GetPastTense(operationType)}. Please check your internet connection and try again.\"\n : $\"Some items could not be {GetPastTense(operationType)}. Please try again later.\"\n )\n : (\n hasConnectivityFailures\n ? $\"Installation failed. Please check your internet connection and try again.\"\n : $\"Installation failed. Please try again later.\"\n )\n );\n }\n\n // Show the information dialog\n SoftwareAppsDialog.ShowInformationAsync(title, headerText, resultItems, footerText);\n }\n\n /// \n /// Gets the past tense form of an operation type\n /// \n /// The operation type (e.g., \"Install\", \"Remove\")\n /// The past tense form of the operation type\n private string GetPastTense(string operationType)\n {\n if (string.IsNullOrEmpty(operationType))\n return string.Empty;\n\n return operationType.Equals(\"Remove\", StringComparison.OrdinalIgnoreCase)\n ? \"removed\"\n : $\"{operationType.ToLower()}ed\";\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Utilities/PowerShellFactory.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Management.Automation;\nusing System.Management.Automation.Runspaces;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.Utilities\n{\n /// \n /// Factory for creating PowerShell instances with specific runtime configurations.\n /// \n public static class PowerShellFactory\n {\n private static readonly string WindowsPowerShellPath =\n @\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\";\n private static readonly string PowerShellCorePath =\n @\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\";\n\n // Reference to the system service - will be set by the first call to CreateWindowsPowerShell\n private static ISystemServices _systemServices;\n\n /// \n /// Determines if the current OS is Windows 10 (which has issues with Appx module in PowerShell Core)\n /// \n /// True if running on Windows 10, false otherwise\n private static bool IsWindows10()\n {\n // Use the system services if available\n if (_systemServices != null)\n {\n // Use the centralized Windows version detection\n return !_systemServices.IsWindows11();\n }\n\n // Fallback to direct OS version check if system services are not available\n try\n {\n // Get OS version information\n var osVersion = Environment.OSVersion;\n\n // Windows 10 has major version 10 and build number less than 22000\n // Windows 11 has build number 22000 or higher\n bool isWin10ByVersion =\n osVersion.Platform == PlatformID.Win32NT\n && osVersion.Version.Major == 10\n && osVersion.Version.Build < 22000;\n\n // Additional check using ProductName which is more reliable\n bool isWin10ByProductName = false;\n try\n {\n // Check the product name from registry\n using (\n var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(\n @\"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\"\n )\n )\n {\n if (key != null)\n {\n var productName = key.GetValue(\"ProductName\") as string;\n isWin10ByProductName =\n productName != null && productName.Contains(\"Windows 10\");\n\n // If product name explicitly contains Windows 11, it's definitely not Windows 10\n if (productName != null && productName.Contains(\"Windows 11\"))\n {\n return false;\n }\n }\n }\n }\n catch\n {\n // If registry check fails, rely on version check only\n }\n\n // Return true if either method indicates Windows 10\n return isWin10ByVersion || isWin10ByProductName;\n }\n catch\n {\n // If there's any error, assume it's Windows 10 to ensure compatibility\n // This is safer than assuming it's not Windows 10\n return true;\n }\n }\n\n /// \n /// Creates a PowerShell instance configured to use Windows PowerShell 5.1.\n /// On Windows 10, it ensures compatibility with the Appx module by using Windows PowerShell.\n /// \n /// Optional log service for diagnostic information.\n /// A PowerShell instance configured to use Windows PowerShell 5.1.\n public static PowerShell CreateWindowsPowerShell(\n ILogService logService = null,\n ISystemServices systemServices = null\n )\n {\n try\n {\n // Store the system services reference if provided\n if (systemServices != null)\n {\n _systemServices = systemServices;\n }\n\n PowerShell powerShell;\n\n // Create a default PowerShell instance\n powerShell = PowerShell.Create();\n\n // Check if we're running on Windows 10\n bool isWin10 = IsWindows10();\n\n // Additional check for build number to ensure Windows 11 is properly detected\n var osVersion = Environment.OSVersion;\n if (osVersion.Version.Build >= 22000)\n {\n // If build number indicates Windows 11, override the IsWindows10 result\n isWin10 = false;\n logService?.LogInformation(\n $\"Detected Windows 11 (Build: {osVersion.Version.Build}) - Using standard PowerShell Core for Appx commands\"\n );\n }\n else if (isWin10)\n {\n logService?.LogInformation(\n \"Detected Windows 10 - Using direct Windows PowerShell execution for Appx commands\"\n );\n\n // On Windows 10, immediately set up direct execution for Appx commands\n // This avoids WinRM connection issues and ensures compatibility\n powerShell.AddScript(\n $@\"\n function Invoke-WindowsPowerShell {{\n param(\n [Parameter(Mandatory=$true)]\n [string]$Command\n )\n \n try {{\n $psi = New-Object System.Diagnostics.ProcessStartInfo\n $psi.FileName = '{WindowsPowerShellPath}'\n $psi.Arguments = \"\"-NoProfile -ExecutionPolicy Bypass -Command `\"\"$Command`\"\"\"\"\n $psi.RedirectStandardOutput = $true\n $psi.RedirectStandardError = $true\n $psi.UseShellExecute = $false\n $psi.CreateNoWindow = $true\n \n $process = New-Object System.Diagnostics.Process\n $process.StartInfo = $psi\n $process.Start() | Out-Null\n \n $output = $process.StandardOutput.ReadToEnd()\n $error = $process.StandardError.ReadToEnd()\n $process.WaitForExit()\n \n if ($error) {{\n Write-Warning \"\"Windows PowerShell error: $error\"\"\n }}\n \n return $output\n }} catch {{\n Write-Warning \"\"Error invoking Windows PowerShell: $_\"\"\n return $null\n }}\n }}\n \n # Override Get-AppxPackage to use Windows PowerShell directly\n function Get-AppxPackage {{\n param(\n [Parameter(Position=0)]\n [string]$Name = '*'\n )\n \n Write-Output \"\"Using direct Windows PowerShell execution for Get-AppxPackage\"\"\n $result = Invoke-WindowsPowerShell \"\"Get-AppxPackage -Name '$Name' | ConvertTo-Json -Depth 5 -Compress\"\"\n if ($result) {{\n try {{\n $packages = $result | ConvertFrom-Json -ErrorAction SilentlyContinue\n return $packages\n }} catch {{\n Write-Warning \"\"Error parsing AppX package results: $_\"\"\n return $null\n }}\n }}\n return $null\n }}\n \n # Override Remove-AppxPackage to use Windows PowerShell directly\n function Remove-AppxPackage {{\n param(\n [Parameter(Mandatory=$true)]\n [string]$Package\n )\n \n Write-Output \"\"Using direct Windows PowerShell execution for Remove-AppxPackage\"\"\n $result = Invoke-WindowsPowerShell \"\"Remove-AppxPackage -Package '$Package'\"\"\n return $result\n }}\n \n # Override Add-AppxPackage to use Windows PowerShell directly\n function Add-AppxPackage {{\n param(\n [Parameter(Mandatory=$true)]\n [string]$Path\n )\n \n Write-Output \"\"Using direct Windows PowerShell execution for Add-AppxPackage\"\"\n $result = Invoke-WindowsPowerShell \"\"Add-AppxPackage -Path '$Path'\"\"\n return $result\n }}\n \n # Override Get-AppxProvisionedPackage to use Windows PowerShell directly\n function Get-AppxProvisionedPackage {{\n param(\n [Parameter(Mandatory=$true)]\n [switch]$Online\n )\n \n Write-Output \"\"Using direct Windows PowerShell execution for Get-AppxProvisionedPackage\"\"\n $result = Invoke-WindowsPowerShell \"\"Get-AppxProvisionedPackage -Online | ConvertTo-Json -Depth 5 -Compress\"\"\n if ($result) {{\n try {{\n $packages = $result | ConvertFrom-Json -ErrorAction SilentlyContinue\n return $packages\n }} catch {{\n Write-Warning \"\"Error parsing provisioned package results: $_\"\"\n return $null\n }}\n }}\n return $null\n }}\n \n # Override Remove-AppxProvisionedPackage to use Windows PowerShell directly\n function Remove-AppxProvisionedPackage {{\n param(\n [Parameter(Mandatory=$true)]\n [switch]$Online,\n \n [Parameter(Mandatory=$true)]\n [string]$PackageName\n )\n \n Write-Output \"\"Using direct Windows PowerShell execution for Remove-AppxProvisionedPackage\"\"\n $result = Invoke-WindowsPowerShell \"\"Remove-AppxProvisionedPackage -Online -PackageName '$PackageName'\"\"\n return $result\n }}\n \n Write-Output \"\"Configured Windows PowerShell direct execution for Appx commands\"\"\n \"\n );\n\n var directExecutionResults = powerShell.Invoke();\n foreach (var result in directExecutionResults)\n {\n logService?.LogInformation($\"Direct execution setup: {result}\");\n }\n }\n else\n {\n logService?.LogInformation(\n \"Not running on Windows 10 - Using standard PowerShell Core for Appx commands\"\n );\n }\n\n // Configure PowerShell to use Windows PowerShell modules and set execution policy\n powerShell.Commands.Clear();\n\n // Different script for Windows 10 vs Windows 11\n if (isWin10)\n {\n // For Windows 10, report that we're using Windows PowerShell 5.1 for Appx commands\n powerShell.AddScript(\n @\"\n # Set execution policy\n try {\n Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force -ErrorAction SilentlyContinue\n } catch {\n # Ignore errors\n }\n \n # Ensure Windows PowerShell modules are available\n $WindowsPowerShellModulePath = \"\"$env:SystemRoot\\System32\\WindowsPowerShell\\v1.0\\Modules\"\"\n if ($env:PSModulePath -notlike \"\"*$WindowsPowerShellModulePath*\"\") {\n $env:PSModulePath = $env:PSModulePath + \"\";\"\" + $WindowsPowerShellModulePath\n }\n \n # Log PowerShell version information\n # Since we're using direct Windows PowerShell execution on Windows 10, report that version\n Write-Output \"\"Using PowerShell version: 5.1 (WindowsPowerShell)\"\"\n Write-Output \"\"OS Version: $([System.Environment]::OSVersion.Version)\"\"\n \"\n );\n }\n else\n {\n // For Windows 11, use standard PowerShell Core and report its version\n powerShell.AddScript(\n @\"\n # Set execution policy\n try {\n Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force -ErrorAction SilentlyContinue\n } catch {\n # Ignore errors\n }\n \n # Ensure Windows PowerShell modules are available\n $WindowsPowerShellModulePath = \"\"$env:SystemRoot\\System32\\WindowsPowerShell\\v1.0\\Modules\"\"\n if ($env:PSModulePath -notlike \"\"*$WindowsPowerShellModulePath*\"\") {\n $env:PSModulePath = $env:PSModulePath + \"\";\"\" + $WindowsPowerShellModulePath\n }\n \n # Import Appx module for Windows 11\n try {\n Import-Module Appx -ErrorAction SilentlyContinue\n } catch {\n # Module might not be available, continue anyway\n }\n \n # Log PowerShell version for diagnostics\n $PSVersionInfo = $PSVersionTable.PSVersion\n Write-Output \"\"Using PowerShell version: $($PSVersionInfo.Major).$($PSVersionInfo.Minor) ($($PSVersionTable.PSEdition))\"\"\n Write-Output \"\"OS Version: $([System.Environment]::OSVersion.Version)\"\"\n \"\n );\n }\n\n var results = powerShell.Invoke();\n foreach (var result in results)\n {\n logService?.LogInformation($\"PowerShell initialization: {result}\");\n }\n\n powerShell.Commands.Clear();\n\n return powerShell;\n }\n catch (Exception ex)\n {\n logService?.LogError(\n $\"Error creating Windows PowerShell instance: {ex.Message}\",\n ex\n );\n\n // Fall back to default PowerShell instance if creation fails\n return PowerShell.Create();\n }\n }\n\n /// \n /// Creates a PowerShell instance with the default configuration.\n /// On Windows 10, it will use the same compatibility approach as CreateWindowsPowerShell.\n /// \n /// A default PowerShell instance.\n public static PowerShell CreateDefault()\n {\n // Use the same Windows 10 compatibility approach as CreateWindowsPowerShell\n return CreateWindowsPowerShell();\n }\n\n /// \n /// Creates a PowerShell instance for executing Appx-related commands.\n /// This method always uses Windows PowerShell 5.1 on Windows 10 for compatibility.\n /// \n /// Optional log service for diagnostic information.\n /// Optional system services for OS detection.\n /// A PowerShell instance configured for Appx commands.\n public static PowerShell CreateForAppxCommands(\n ILogService logService = null,\n ISystemServices systemServices = null\n )\n {\n // Always use Windows PowerShell for Appx commands on Windows 10\n return CreateWindowsPowerShell(logService, systemServices);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/FeatureRemovalService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service for removing Windows optional features from the system.\n/// \npublic class FeatureRemovalService : IFeatureRemovalService\n{\n private readonly ILogService _logService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IScheduledTaskService _scheduledTaskService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The app discovery service.\n /// The scheduled task service.\n public FeatureRemovalService(\n ILogService logService,\n IAppDiscoveryService appDiscoveryService,\n IScheduledTaskService scheduledTaskService)\n {\n _logService = logService;\n _appDiscoveryService = appDiscoveryService;\n _scheduledTaskService = scheduledTaskService;\n }\n\n /// \n public async Task RemoveFeatureAsync(\n FeatureInfo featureInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (featureInfo == null)\n {\n throw new ArgumentNullException(nameof(featureInfo));\n }\n // Call the other overload and return its result\n return await RemoveFeatureAsync(featureInfo.PackageName, progress, cancellationToken);\n }\n\n /// \n public async Task RemoveFeatureAsync(\n string featureName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n try\n {\n progress?.Report(new TaskProgressDetail { Progress = 0, StatusText = $\"Starting removal of {featureName}...\" });\n _logService.LogInformation($\"Removing optional feature: {featureName}\");\n \n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n \n // First, attempt to disable the feature\n powerShell.AddScript(@\"\n param($featureName)\n try {\n # Check if the feature exists and is enabled\n $feature = Get-WindowsOptionalFeature -Online | Where-Object { $_.FeatureName -eq $featureName -and $_.State -eq 'Enabled' }\n \n if ($feature) {\n # Get the full feature name\n $fullFeatureName = $feature.FeatureName\n \n # Disable the feature\n $result = Disable-WindowsOptionalFeature -Online -FeatureName $featureName -NoRestart\n \n return @{\n FullFeatureName = $fullFeatureName\n }\n } else {\n # Feature not found or already disabled\n return @{\n Error = \"\"Feature not found or already disabled\"\"\n FullFeatureName = $null\n }\n }\n }\n catch {\n return @{\n Error = $_.Exception.Message\n FullFeatureName = $null\n }\n }\n \");\n powerShell.AddParameter(\"featureName\", featureName);\n \n var result = await Task.Run(() => powerShell.Invoke());\n \n // Extract any error or the full feature name from the first command\n string? error = null;\n string fullFeatureName = featureName;\n \n if (result != null && result.Count > 0)\n {\n var resultObj = result[0];\n \n // Get any error\n if (resultObj.Properties.Any(p => p.Name == \"Error\"))\n {\n error = resultObj.Properties[\"Error\"]?.Value as string;\n }\n \n // Get the full feature name if available\n if (resultObj.Properties.Any(p => p.Name == \"FullFeatureName\") && \n resultObj.Properties[\"FullFeatureName\"]?.Value != null)\n {\n fullFeatureName = resultObj.Properties[\"FullFeatureName\"].Value.ToString();\n }\n }\n \n // Now check if the feature is still enabled to determine success\n powerShell.Commands.Clear();\n powerShell.AddScript(@\"\n param($featureName)\n $feature = Get-WindowsOptionalFeature -Online | Where-Object { $_.FeatureName -eq $featureName }\n \n if ($feature -ne $null) {\n return @{\n IsEnabled = ($feature.State -eq 'Enabled')\n RebootRequired = $feature.RestartNeeded\n }\n } else {\n return @{\n IsEnabled = $false\n RebootRequired = $false\n }\n }\n \");\n powerShell.AddParameter(\"featureName\", featureName);\n \n var statusResult = await Task.Run(() => powerShell.Invoke());\n \n bool isStillEnabled = false;\n bool rebootRequired = false;\n \n if (statusResult != null && statusResult.Count > 0)\n {\n var statusObj = statusResult[0];\n \n // Check if the feature is still enabled\n if (statusObj.Properties.Any(p => p.Name == \"IsEnabled\") && \n statusObj.Properties[\"IsEnabled\"]?.Value != null)\n {\n isStillEnabled = Convert.ToBoolean(statusObj.Properties[\"IsEnabled\"].Value);\n }\n \n // Check if a reboot is required\n if (statusObj.Properties.Any(p => p.Name == \"RebootRequired\") && \n statusObj.Properties[\"RebootRequired\"]?.Value != null)\n {\n rebootRequired = Convert.ToBoolean(statusObj.Properties[\"RebootRequired\"].Value);\n }\n }\n \n // Success is determined by whether the feature is no longer enabled\n bool success = !isStillEnabled;\n bool overallSuccess = false;\n \n if (success)\n {\n progress?.Report(new TaskProgressDetail { Progress = 100, StatusText = $\"Successfully removed {featureName}\" });\n _logService.LogSuccess($\"Successfully removed optional feature: {featureName}\");\n \n if (rebootRequired)\n {\n progress?.Report(new TaskProgressDetail { StatusText = \"Restart required\", LogLevel = LogLevel.Warning });\n _logService.LogWarning($\"A system restart is required to complete the removal of {featureName}\");\n }\n \n _logService.LogInformation($\"Full feature name: {fullFeatureName}\");\n \n // Update BloatRemoval.ps1 script after successful removal\n try\n {\n var script = await UpdateBloatRemovalScriptAsync(fullFeatureName);\n _logService.LogInformation($\"BloatRemoval.ps1 script updated for feature: {featureName}\");\n \n // Register the scheduled task to run the script at startup\n try\n {\n bool taskRegistered = await RegisterBloatRemovalTaskAsync(script);\n if (taskRegistered)\n {\n _logService.LogSuccess($\"Scheduled task registered for BloatRemoval.ps1\");\n }\n else\n {\n _logService.LogWarning($\"Failed to register scheduled task for BloatRemoval.ps1, but continuing operation\");\n }\n }\n catch (Exception taskEx)\n {\n _logService.LogError($\"Error registering scheduled task: {taskEx.Message}\");\n // Don't fail the removal if task registration fails\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for feature: {featureName}\", ex);\n // Don't fail the removal if script update fails\n }\n \n overallSuccess = true;\n }\n else\n {\n progress?.Report(new TaskProgressDetail { Progress = 0, StatusText = $\"Failed to remove {featureName}: {error}\", LogLevel = LogLevel.Error });\n _logService.LogError($\"Failed to remove optional feature: {featureName}. {error}\");\n }\n \n return overallSuccess; // Return success status\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing optional feature: {featureName}\", ex);\n progress?.Report(new TaskProgressDetail { Progress = 0, StatusText = $\"Error removing {featureName}: {ex.Message}\", LogLevel = LogLevel.Error });\n return false; // Return false on exception\n }\n }\n\n /// \n public Task CanRemoveFeatureAsync(FeatureInfo featureInfo)\n {\n // Basic implementation: Assume all found features can be removed.\n // TODO: Add actual checks if needed (e.g., dependencies, system protection)\n return Task.FromResult(true);\n }\n\n /// \n public async Task> RemoveFeaturesInBatchAsync(\n List features)\n {\n if (features == null)\n {\n throw new ArgumentNullException(nameof(features));\n }\n\n return await RemoveFeaturesInBatchAsync(features.Select(f => f.PackageName).ToList());\n }\n\n /// \n public async Task> RemoveFeaturesInBatchAsync(\n List featureNames)\n {\n var results = new List<(string Name, bool Success, string? Error)>();\n \n try\n {\n _logService.LogInformation($\"Removing {featureNames.Count} Windows optional features\");\n \n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n \n foreach (var feature in featureNames)\n {\n try\n {\n _logService.LogInformation($\"Removing optional feature: {feature}\");\n \n // First, attempt to disable the feature\n powerShell.Commands.Clear();\n powerShell.AddScript(@\"\n param($featureName)\n try {\n # Check if the feature exists and is enabled\n $feature = Get-WindowsOptionalFeature -Online | Where-Object { $_.FeatureName -eq $featureName -and $_.State -eq 'Enabled' }\n \n if ($feature) {\n # Get the full feature name\n $fullFeatureName = $feature.FeatureName\n \n # Disable the feature\n $result = Disable-WindowsOptionalFeature -Online -FeatureName $featureName -NoRestart\n \n return @{\n FullFeatureName = $fullFeatureName\n }\n } else {\n # Feature not found or already disabled\n return @{\n Error = \"\"Feature not found or already disabled\"\"\n FullFeatureName = $null\n }\n }\n }\n catch {\n return @{\n Error = $_.Exception.Message\n FullFeatureName = $null\n }\n }\n \");\n powerShell.AddParameter(\"featureName\", feature);\n \n var result = await Task.Run(() => powerShell.Invoke());\n \n // Extract any error or the full feature name from the first command\n string? error = null;\n string featureFullName = feature;\n \n if (result != null && result.Count > 0)\n {\n var resultObj = result[0];\n \n // Get any error\n if (resultObj.Properties.Any(p => p.Name == \"Error\"))\n {\n error = resultObj.Properties[\"Error\"]?.Value as string;\n }\n \n // Get the full feature name if available\n if (resultObj.Properties.Any(p => p.Name == \"FullFeatureName\") && \n resultObj.Properties[\"FullFeatureName\"]?.Value != null)\n {\n featureFullName = resultObj.Properties[\"FullFeatureName\"].Value.ToString();\n }\n }\n \n // Now check if the feature is still enabled to determine success\n powerShell.Commands.Clear();\n powerShell.AddScript(@\"\n param($featureName)\n $feature = Get-WindowsOptionalFeature -Online | Where-Object { $_.FeatureName -eq $featureName }\n \n if ($feature -ne $null) {\n return @{\n IsEnabled = ($feature.State -eq 'Enabled')\n RebootRequired = $feature.RestartNeeded\n }\n } else {\n return @{\n IsEnabled = $false\n RebootRequired = $false\n }\n }\n \");\n powerShell.AddParameter(\"featureName\", feature);\n \n var statusResult = await Task.Run(() => powerShell.Invoke());\n \n bool isStillEnabled = false;\n bool rebootRequired = false;\n \n if (statusResult != null && statusResult.Count > 0)\n {\n var statusObj = statusResult[0];\n \n // Check if the feature is still enabled\n if (statusObj.Properties.Any(p => p.Name == \"IsEnabled\") && \n statusObj.Properties[\"IsEnabled\"]?.Value != null)\n {\n isStillEnabled = Convert.ToBoolean(statusObj.Properties[\"IsEnabled\"].Value);\n }\n \n // Check if a reboot is required\n if (statusObj.Properties.Any(p => p.Name == \"RebootRequired\") && \n statusObj.Properties[\"RebootRequired\"]?.Value != null)\n {\n rebootRequired = Convert.ToBoolean(statusObj.Properties[\"RebootRequired\"].Value);\n }\n }\n \n // Success is determined by whether the feature is no longer enabled\n bool success = !isStillEnabled;\n \n if (success)\n {\n _logService.LogInformation($\"Full feature name for batch operation: {featureFullName}\");\n \n // Update BloatRemoval.ps1 script for batch operations too\n try\n {\n var script = await UpdateBloatRemovalScriptAsync(featureFullName);\n _logService.LogInformation($\"BloatRemoval.ps1 script updated for feature in batch: {feature}\");\n \n // Register the scheduled task to run the script at startup\n try\n {\n bool taskRegistered = await RegisterBloatRemovalTaskAsync(script);\n if (taskRegistered)\n {\n _logService.LogSuccess($\"Scheduled task registered for BloatRemoval.ps1\");\n }\n else\n {\n _logService.LogWarning($\"Failed to register scheduled task for BloatRemoval.ps1, but continuing operation\");\n }\n }\n catch (Exception taskEx)\n {\n _logService.LogError($\"Error registering scheduled task: {taskEx.Message}\");\n // Don't fail the removal if task registration fails\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for feature in batch: {feature}\", ex);\n // Don't fail the removal if script update fails\n }\n }\n \n results.Add((feature, success, error));\n \n if (success)\n {\n _logService.LogSuccess($\"Successfully removed optional feature: {feature}\");\n if (rebootRequired)\n {\n _logService.LogWarning($\"A system restart is required to complete the removal of {feature}\");\n }\n }\n else\n {\n _logService.LogError($\"Failed to remove optional feature: {feature}. {error}\");\n }\n }\n catch (Exception ex)\n {\n results.Add((feature, false, ex.Message));\n _logService.LogError($\"Error removing optional feature: {feature}\", ex);\n }\n }\n \n return results;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error removing optional features\", ex);\n return featureNames.Select(f => (f, false, $\"Error: {ex.Message}\")).ToList();\n }\n }\n\n // SetExecutionPolicy is now handled by PowerShellFactory\n \n /// \n /// Updates the BloatRemoval.ps1 script to add the removed feature to it.\n /// \n /// The feature name.\n /// The updated removal script.\n private async Task UpdateBloatRemovalScriptAsync(string featureName)\n {\n try\n {\n // Get the script update service\n var scriptUpdateService = GetScriptUpdateService();\n if (scriptUpdateService == null)\n {\n _logService.LogWarning(\"Script update service not available\");\n throw new InvalidOperationException(\"Script update service not available\");\n }\n \n // Update the script\n var appNames = new List { featureName };\n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n \n _logService.LogInformation($\"Updating BloatRemoval.ps1 script for feature: {featureName}\");\n \n try\n {\n var script = await scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n false); // false = removal operation, so add to script\n \n _logService.LogInformation($\"Successfully updated BloatRemoval.ps1 script for feature: {featureName}\");\n return script;\n }\n catch (FileNotFoundException)\n {\n _logService.LogInformation($\"BloatRemoval.ps1 script not found. It will be created when needed.\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in script update service for feature: {featureName}\", ex);\n throw; // Rethrow to be caught by the outer try-catch\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for feature: {featureName}\", ex);\n throw; // Rethrow so the caller can handle it\n }\n }\n \n /// \n /// Registers a scheduled task to run the BloatRemoval script at startup.\n /// \n /// The removal script to register.\n /// True if the task was registered successfully, false otherwise.\n private async Task RegisterBloatRemovalTaskAsync(RemovalScript script)\n {\n try\n {\n if (script == null)\n {\n _logService.LogError(\"Cannot register scheduled task: Script is null\");\n return false;\n }\n \n _logService.LogInformation(\"Registering scheduled task for BloatRemoval.ps1\");\n \n // Register the scheduled task\n bool success = await _scheduledTaskService.RegisterScheduledTaskAsync(script);\n \n if (success)\n {\n _logService.LogSuccess(\"Successfully registered scheduled task for BloatRemoval.ps1\");\n }\n else\n {\n _logService.LogError(\"Failed to register scheduled task for BloatRemoval.ps1\");\n }\n \n return success;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error registering scheduled task for BloatRemoval.ps1\", ex);\n return false;\n }\n }\n \n /// \n /// Gets the script update service.\n /// \n /// The script update service or null if not available.\n private IScriptUpdateService? GetScriptUpdateService()\n {\n try\n {\n // Use the existing _appDiscoveryService that was injected into the constructor\n // instead of creating a new instance\n var scriptContentModifier = new ScriptContentModifier(_logService);\n return new ScriptUpdateService(_logService, _appDiscoveryService, scriptContentModifier);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to get script update service\", ex);\n return null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppVerificationService.cs", "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that handles verification of application installations.\n/// \npublic class AppVerificationService : IAppVerificationService\n{\n private readonly ILogService _logService;\n private readonly ISystemServices _systemServices;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The system services.\n public AppVerificationService(\n ILogService logService,\n ISystemServices systemServices)\n {\n _logService = logService;\n _systemServices = systemServices;\n }\n\n /// \n public async Task VerifyAppInstallationAsync(string packageName)\n {\n try\n {\n // Create PowerShell instance\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n\n // For Microsoft Store apps (package IDs that are alphanumeric with no dots)\n if (packageName.All(char.IsLetterOrDigit) && !packageName.Contains('.'))\n {\n // Use Get-AppxPackage to check if the Microsoft Store app is installed\n // Ensure we're using Windows PowerShell for Appx commands\n using var appxPowerShell = PowerShellFactory.CreateForAppxCommands(_logService, _systemServices);\n appxPowerShell.AddScript(\n $\"Get-AppxPackage | Where-Object {{ $_.PackageFullName -like '*{packageName}*' }}\"\n );\n var result = await appxPowerShell.InvokeAsync();\n\n if (result.Count > 0)\n {\n return true;\n }\n }\n\n // For all other apps, use winget list to check if installed\n powerShell.Commands.Clear();\n powerShell.AddScript(\n $@\"\n try {{\n # Ensure we're using Windows PowerShell for Winget operations\n $result = winget list --id '{packageName}' --exact\n $isInstalled = $result -match '{packageName}'\n Write-Output $isInstalled\n }} catch {{\n Write-Output $false\n }}\n \"\n );\n\n var results = await powerShell.InvokeAsync();\n\n // Check if the result indicates the app is installed\n if (results.Count > 0)\n {\n // Extract boolean value from result\n var resultValue = results[0]?.ToString()?.ToLowerInvariant();\n if (resultValue == \"true\")\n {\n return true;\n }\n }\n\n // If we're here, try one more verification with a different approach\n powerShell.Commands.Clear();\n powerShell.AddScript(\n $@\"\n try {{\n # Use where.exe to check if the app is in PATH (for CLI tools)\n $whereResult = where.exe {packageName} 2>&1\n if ($whereResult -notmatch 'not found') {{\n Write-Output 'true'\n return\n }}\n\n # Check common installation directories\n $commonPaths = @(\n [System.Environment]::GetFolderPath('ProgramFiles'),\n [System.Environment]::GetFolderPath('ProgramFilesX86'),\n [System.Environment]::GetFolderPath('LocalApplicationData')\n )\n\n foreach ($basePath in $commonPaths) {{\n if (Test-Path -Path \"\"$basePath\\$packageName\"\" -PathType Container) {{\n Write-Output 'true'\n return\n }}\n }}\n\n Write-Output 'false'\n }} catch {{\n Write-Output 'false'\n }}\n \"\n );\n\n results = await powerShell.InvokeAsync();\n\n // Check if the result indicates the app is installed\n if (results.Count > 0)\n {\n var resultValue = results[0]?.ToString()?.ToLowerInvariant();\n return resultValue == \"true\";\n }\n\n return false;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error verifying app installation: {ex.Message}\", ex);\n // If any error occurs during verification, assume the app is not installed\n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/ViewModels/ExplorerCustomizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Customize.Enums;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Customize.ViewModels\n{\n /// \n /// ViewModel for Explorer customizations.\n /// \n public partial class ExplorerCustomizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDialogService _dialogService;\n\n /// \n /// Gets the command to execute an action.\n /// \n [RelayCommand]\n public async Task ExecuteAction(ApplicationAction? action)\n {\n if (action == null) return;\n\n try\n {\n // Execute the registry action if present\n if (action.RegistrySetting != null)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(action.RegistrySetting.Hive);\n string fullPath = $\"{hiveString}\\\\{action.RegistrySetting.SubKey}\";\n _registryService.SetValue(\n fullPath,\n action.RegistrySetting.Name,\n action.RegistrySetting.RecommendedValue,\n action.RegistrySetting.ValueType);\n }\n\n // Execute the command action if present\n if (action.CommandAction != null)\n {\n // Execute the command\n // This would typically be handled by a command execution service\n }\n\n // Refresh the status after applying the action\n await CheckSettingStatusesAsync();\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error executing action: {ex.Message}\");\n }\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dialog service.\n public ExplorerCustomizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDialogService dialogService)\n : base(progressService, registryService, logService)\n {\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n }\n\n /// \n /// Loads the Explorer customizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Explorer customizations from ExplorerCustomizations\n var explorerCustomizations = Core.Features.Customize.Models.ExplorerCustomizations.GetExplorerCustomizations();\n if (explorerCustomizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in explorerCustomizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, _dialogService, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n ControlType = setting.ControlType\n };\n\n // Add any actions\n var actionsProperty = setting.GetType().GetProperty(\"Actions\");\n if (actionsProperty != null && \n actionsProperty.GetValue(setting) is IEnumerable actions && \n actions.Any())\n {\n // We need to handle this differently since the Actions property doesn't exist in ApplicationSetting\n // This is a temporary workaround until we refactor the code properly\n }\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for settings\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all Explorer customizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n foreach (var setting in Settings)\n {\n // Get status\n if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n // For linked registry settings, use GetLinkedSettingsStatusAsync\n var linkedStatus = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n setting.Status = linkedStatus;\n \n // Update IsSelected based on status - this is crucial for the initial toggle state\n setting.IsUpdatingFromCode = true;\n setting.IsSelected = linkedStatus == RegistrySettingStatus.Applied;\n setting.IsUpdatingFromCode = false;\n }\n else\n {\n // For single registry setting\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n setting.Status = status;\n }\n\n // Get current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n setting.CurrentValue = currentValue;\n\n // Set IsRegistryValueNull property based on current value for single registry setting\n if (setting.LinkedRegistrySettings == null || setting.LinkedRegistrySettings.Settings.Count == 0)\n {\n // Special handling for specific Explorer items that should not show warning icons\n if (setting.Name == \"3D Objects\" || \n setting.Name == \"Gallery in Navigation Pane\" || \n setting.Name == \"Home in Navigation Pane\")\n {\n // Don't show warning icon for these specific items\n setting.IsRegistryValueNull = false;\n }\n else\n {\n setting.IsRegistryValueNull = currentValue == null;\n }\n }\n\n // Update LinkedRegistrySettingsWithValues for tooltip display\n var linkedRegistrySettingsWithValues = new ObservableCollection();\n \n // Get the LinkedRegistrySettings property\n var linkedRegistrySettings = setting.LinkedRegistrySettings;\n \n if (linkedRegistrySettings != null && linkedRegistrySettings.Settings.Count > 0)\n {\n // For linked settings, get fresh values from registry\n bool anyNull = false;\n foreach (var regSetting in linkedRegistrySettings.Settings)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(regSetting.Hive);\n var regCurrentValue = _registryService.GetValue(\n $\"{hiveString}\\\\{regSetting.SubKey}\",\n regSetting.Name);\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n linkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // For linked settings, set IsRegistryValueNull if any value is null\n // Special handling for specific Explorer items that should not show warning icons\n if (setting.Name == \"3D Objects\" || \n setting.Name == \"Gallery in Navigation Pane\" || \n setting.Name == \"Home in Navigation Pane\")\n {\n // Don't show warning icon for these specific items\n setting.IsRegistryValueNull = false;\n }\n else\n {\n setting.IsRegistryValueNull = anyNull;\n }\n }\n else if (setting.RegistrySetting != null)\n {\n // For single setting\n linkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n }\n \n setting.LinkedRegistrySettingsWithValues = linkedRegistrySettingsWithValues;\n\n // Set status message\n string statusMessage = GetStatusMessage(setting);\n setting.StatusMessage = statusMessage;\n\n // Set the IsUpdatingFromCode flag to prevent automatic application\n setting.IsUpdatingFromCode = true;\n\n try\n {\n // Update IsSelected based on status\n bool shouldBeSelected = setting.Status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {setting.Status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n // Reset the flag\n setting.IsUpdatingFromCode = false;\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Explorer customization statuses: {ex.Message}\");\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n var status = setting.Status;\n string message = status switch\n {\n RegistrySettingStatus.Applied => \"Setting is applied with recommended value\",\n RegistrySettingStatus.NotApplied => \"Setting is not applied or using default value\",\n RegistrySettingStatus.Modified => \"Setting has a custom value different from recommended\",\n RegistrySettingStatus.Error => \"Error checking setting status\",\n _ => \"Unknown status\"\n };\n\n // Add current value if available\n var currentValue = setting.CurrentValue;\n if (currentValue != null)\n {\n message += $\"\\nCurrent value: {currentValue}\";\n }\n\n // Add recommended value if available\n var registrySetting = setting.RegistrySetting;\n if (registrySetting?.RecommendedValue != null)\n {\n message += $\"\\nRecommended value: {registrySetting.RecommendedValue}\";\n }\n\n // Add default value if available\n if (registrySetting?.DefaultValue != null)\n {\n message += $\"\\nDefault value: {registrySetting.DefaultValue}\";\n }\n\n return message;\n }\n\n // ApplySelectedSettingsAsync and RestoreDefaultsAsync methods removed as part of the refactoring\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/TaskbarCustomizations.cs", "using Microsoft.Win32;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Enums;\nusing System;\nusing System.IO;\nusing System.Diagnostics;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Core.Features.Customize.Models;\n\npublic static class TaskbarCustomizations\n{\n /// \n /// Special handling for News and Interests (Widgets) toggle.\n /// This method temporarily disables the UCPD service before applying the settings.\n /// \n /// The registry service.\n /// The log service.\n /// The linked registry settings to apply.\n /// Whether to enable or disable the settings.\n /// True if the settings were applied successfully; otherwise, false.\n public static async Task ApplyNewsAndInterestsSettingsAsync(\n IRegistryService registryService,\n ILogService logService,\n LinkedRegistrySettings linkedSettings,\n bool enable)\n {\n // Path to the UCPD service Start value\n const string ucpdServiceKeyPath = @\"HKLM\\SYSTEM\\CurrentControlSet\\Services\\UCPD\";\n const string startValueName = \"Start\";\n \n // Get the current value of the UCPD service Start key\n object? originalStartValue = registryService.GetValue(ucpdServiceKeyPath, startValueName);\n \n try\n {\n // Set the UCPD service Start value to 4 (disabled)\n logService.LogInformation($\"Temporarily disabling UCPD service by setting {ucpdServiceKeyPath}\\\\{startValueName} to 4\");\n bool setResult = registryService.SetValue(ucpdServiceKeyPath, startValueName, 4, RegistryValueKind.DWord);\n \n if (!setResult)\n {\n logService.LogError(\"Failed to set UCPD service Start value to 4\");\n return false;\n }\n \n // Apply the News and Interests (Widgets) settings\n logService.LogInformation($\"Applying linked setting: News and Interests (Widgets) with {linkedSettings.Settings.Count} registry entries\");\n bool result = await registryService.ApplyLinkedSettingsAsync(linkedSettings, enable);\n \n if (!result)\n {\n logService.LogError(\"Failed to apply linked settings for News and Interests (Widgets)\");\n return false;\n }\n \n return true;\n }\n finally\n {\n // Restore the original UCPD service Start value\n if (originalStartValue != null)\n {\n logService.LogInformation($\"Restoring UCPD service Start value to {originalStartValue}\");\n registryService.SetValue(ucpdServiceKeyPath, startValueName, originalStartValue, RegistryValueKind.DWord);\n }\n }\n }\n /// \n /// Cleans the taskbar by unpinning all items except File Explorer.\n /// \n /// The system services.\n /// The log service.\n public static async Task CleanTaskbar(ISystemServices systemServices, ILogService logService)\n {\n try\n {\n logService.LogInformation(\"Task started: Cleaning taskbar...\");\n logService.LogInformation(\"Cleaning taskbar started\");\n \n // Delete taskband registry key using Registry API\n using (var key = Registry.CurrentUser.OpenSubKey(@\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\", true))\n {\n if (key != null)\n {\n key.DeleteSubKeyTree(\"Taskband\", false);\n }\n }\n \n // Create the Taskband key and set values directly\n using (var taskbandKey = Registry.CurrentUser.CreateSubKey(\n @\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Taskband\", true))\n {\n if (taskbandKey != null)\n {\n // Convert the hex string to a byte array\n // This is the same data that was in the .reg file\n byte[] favoritesData = new byte[] {\n 0x00, 0xaa, 0x01, 0x00, 0x00, 0x3a, 0x00, 0x1f, 0x80, 0xc8, 0x27, 0x34, 0x1f, 0x10, 0x5c, 0x10,\n 0x42, 0xaa, 0x03, 0x2e, 0xe4, 0x52, 0x87, 0xd6, 0x68, 0x26, 0x00, 0x01, 0x00, 0x26, 0x00, 0xef,\n 0xbe, 0x10, 0x00, 0x00, 0x00, 0xf4, 0x7e, 0x76, 0xfa, 0xde, 0x9d, 0xda, 0x01, 0x40, 0x61, 0x5d,\n 0x09, 0xdf, 0x9d, 0xda, 0x01, 0x19, 0xb8, 0x5f, 0x09, 0xdf, 0x9d, 0xda, 0x01, 0x14, 0x00, 0x56,\n 0x00, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x58, 0xa9, 0x26, 0x10, 0x00, 0x54, 0x61, 0x73,\n 0x6b, 0x42, 0x61, 0x72, 0x00, 0x40, 0x00, 0x09, 0x00, 0x04, 0x00, 0xef, 0xbe, 0xa4, 0x58, 0xa9,\n 0x26, 0xa4, 0x58, 0xa9, 0x26, 0x2e, 0x00, 0x00, 0x00, 0xde, 0x9c, 0x01, 0x00, 0x00, 0x00, 0x02,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c,\n 0xf4, 0x85, 0x00, 0x54, 0x00, 0x61, 0x00, 0x73, 0x00, 0x6b, 0x00, 0x42, 0x00, 0x61, 0x00, 0x72,\n 0x00, 0x00, 0x00, 0x16, 0x00, 0x18, 0x01, 0x32, 0x00, 0x8a, 0x04, 0x00, 0x00, 0xa4, 0x58, 0xb6,\n 0x26, 0x20, 0x00, 0x46, 0x49, 0x4c, 0x45, 0x45, 0x58, 0x7e, 0x31, 0x2e, 0x4c, 0x4e, 0x4b, 0x00,\n 0x00, 0x54, 0x00, 0x09, 0x00, 0x04, 0x00, 0xef, 0xbe, 0xa4, 0x58, 0xb6, 0x26, 0xa4, 0x58, 0xb6,\n 0x26, 0x2e, 0x00, 0x00, 0x00, 0xb7, 0xa8, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x5a, 0x1e, 0x01, 0x46,\n 0x00, 0x69, 0x00, 0x6c, 0x00, 0x65, 0x00, 0x20, 0x00, 0x45, 0x00, 0x78, 0x00, 0x70, 0x00, 0x6c,\n 0x00, 0x6f, 0x00, 0x72, 0x00, 0x65, 0x00, 0x72, 0x00, 0x2e, 0x00, 0x6c, 0x00, 0x6e, 0x00, 0x6b,\n 0x00, 0x00, 0x00, 0x1c, 0x00, 0x22, 0x00, 0x00, 0x00, 0x1e, 0x00, 0xef, 0xbe, 0x02, 0x00, 0x55,\n 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x50, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x6e, 0x00, 0x65,\n 0x00, 0x64, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x12, 0x00, 0x00, 0x00, 0x2b, 0x00, 0xef, 0xbe, 0x19,\n 0xb8, 0x5f, 0x09, 0xdf, 0x9d, 0xda, 0x01, 0x1c, 0x00, 0x74, 0x00, 0x00, 0x00, 0x1d, 0x00, 0xef,\n 0xbe, 0x02, 0x00, 0x7b, 0x00, 0x46, 0x00, 0x33, 0x00, 0x38, 0x00, 0x42, 0x00, 0x46, 0x00, 0x34,\n 0x00, 0x30, 0x00, 0x34, 0x00, 0x2d, 0x00, 0x31, 0x00, 0x44, 0x00, 0x34, 0x00, 0x33, 0x00, 0x2d,\n 0x00, 0x34, 0x00, 0x32, 0x00, 0x46, 0x00, 0x32, 0x00, 0x2d, 0x00, 0x39, 0x00, 0x33, 0x00, 0x30,\n 0x00, 0x35, 0x00, 0x2d, 0x00, 0x36, 0x00, 0x37, 0x00, 0x44, 0x00, 0x45, 0x00, 0x30, 0x00, 0x42,\n 0x00, 0x32, 0x00, 0x38, 0x00, 0x46, 0x00, 0x43, 0x00, 0x32, 0x00, 0x33, 0x00, 0x7d, 0x00, 0x5c,\n 0x00, 0x65, 0x00, 0x78, 0x00, 0x70, 0x00, 0x6c, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x65, 0x00, 0x72,\n 0x00, 0x2e, 0x00, 0x65, 0x00, 0x78, 0x00, 0x65, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0xff\n };\n \n // Set the binary value directly\n taskbandKey.SetValue(\"Favorites\", favoritesData, RegistryValueKind.Binary);\n }\n }\n \n // Wait for registry changes to take effect before refreshing Windows GUI\n logService.LogInformation(\"Registry changes applied, waiting for changes to take effect...\");\n await Task.Delay(2000);\n \n // Use the improved RefreshWindowsGUI method to restart Explorer and apply changes\n // This will ensure Explorer is restarted properly with retry logic and fallback\n var result = await systemServices.RefreshWindowsGUI(true);\n if (!result)\n {\n throw new Exception(\"Failed to refresh Windows GUI after cleaning taskbar\");\n }\n }\n catch (Exception ex)\n {\n throw new Exception($\"Error cleaning taskbar: {ex.Message}\", ex);\n }\n }\n\n public static CustomizationGroup GetTaskbarCustomizations()\n {\n return new CustomizationGroup\n {\n Name = \"Taskbar\",\n Category = CustomizationCategory.Taskbar,\n Settings = new List\n {\n new CustomizationSetting\n {\n Id = \"taskbar-chat-icon\",\n Name = \"Windows Chat Icon\",\n Description = \"Controls Windows Chat icon visibility and menu behavior in taskbar\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Icons\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\Windows Chat\",\n Name = \"ChatIcon\",\n RecommendedValue = 3, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, Chat icon is shown (0 = show)\n DisabledValue = 3, // When toggle is OFF, Chat icon is hidden (3 = hide)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls Windows Chat icon visibility in taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n },\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"TaskbarMn\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, taskbar menu is enabled\n DisabledValue = 0, // When toggle is OFF, taskbar menu is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls taskbar menu behavior for chat\",\n IsPrimary = false,\n AbsenceMeansEnabled = false\n }\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All\n },\n new CustomizationSetting\n {\n Id = \"taskbar-meet-now-group\",\n Name = \"Meet Now Button\",\n Description = \"Controls Meet Now button visibility in taskbar\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Icons\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\Explorer\",\n Name = \"HideSCAMeetNow\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, Meet Now button is shown\n DisabledValue = 1, // When toggle is OFF, Meet Now button is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Meet Now button visibility in taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n },\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\Explorer\",\n Name = \"HideSCAMeetNow\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, Meet Now button is shown (user level)\n DisabledValue = 1, // When toggle is OFF, Meet Now button is hidden (user level)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Meet Now button visibility (user level)\",\n IsPrimary = false,\n AbsenceMeansEnabled = true\n }\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All\n },\n new CustomizationSetting\n {\n Id = \"taskbar-search-box\",\n Name = \"Search in Taskbar\",\n Description = \"Controls search box visibility in taskbar\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Icons\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Search\",\n Name = \"SearchboxTaskbarMode\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 2, // When toggle is ON, search box is shown (2 = show search box)\n DisabledValue = 0, // When toggle is OFF, search box is hidden (0 = hide search box)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls search box visibility in taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new CustomizationSetting\n {\n Id = \"taskbar-copilot\",\n Name = \"Copilot Button\",\n Description = \"Controls Copilot button visibility in taskbar\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Icons\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowCopilotButton\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Copilot button is shown\n DisabledValue = 0, // When toggle is OFF, Copilot button is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls Copilot button visibility in taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new CustomizationSetting\n {\n Id = \"taskbar-left-align\",\n Name = \"Left Aligned Taskbar\",\n Description = \"Controls taskbar icons alignment\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Behavior\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"TaskbarAl\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, taskbar icons are left-aligned\n DisabledValue = 1, // When toggle is OFF, taskbar icons are center-aligned\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls taskbar icons alignment\",\n IsPrimary = true,\n AbsenceMeansEnabled = false\n }\n }\n },\n new CustomizationSetting\n {\n Id = \"taskbar-system-tray-icons\",\n Name = \"Show Hidden System Tray Icons (W10 Only)\",\n Description = \"Controls whether system tray icons are shown in the taskbar or hidden in the chevron menu\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"System Tray\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\",\n Name = \"EnableAutoTray\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls whether system tray icons are shown in the taskbar or hidden in the chevron menu\",\n IsPrimary = true,\n AbsenceMeansEnabled = false\n }\n }\n },\n new CustomizationSetting\n {\n Id = \"taskbar-task-view\",\n Name = \"Task View Button\",\n Description = \"Controls Task View button visibility in taskbar\",\n Category = CustomizationCategory.Taskbar,\n GroupName = \"Taskbar Icons\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Taskbar\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowTaskViewButton\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Task View button is shown\n DisabledValue = 0, // When toggle is OFF, Task View button is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Task View button visibility in taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n }\n }\n };\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/NullToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Converters\n{\n public class NullToVisibilityConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // If the value is null, return Visible, otherwise return Collapsed\n return value == null ? Visibility.Visible : Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/UpdateOptimizationsViewModel.cs", "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Infrastructure.Features.Common.Registry;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Update optimizations.\n /// \n public partial class UpdateOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The view model locator.\n /// The settings registry.\n public UpdateOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n }\n\n /// \n /// Loads the update settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load update optimizations\n var updateOptimizations = Core.Features.Optimize.Models.UpdateOptimizations.GetUpdateOptimizations();\n if (updateOptimizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in updateOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsUpdatingFromCode = true, // Set this to true to allow RefreshStatus to set the correct state\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Add to the settings collection\n Settings.Add(settingItem);\n }\n\n // Register settings with the settings registry if available\n foreach (var setting in Settings)\n {\n if (_settingsRegistry != null && !string.IsNullOrEmpty(setting.Id))\n {\n _settingsRegistry.RegisterSetting(setting);\n _logService.Log(LogLevel.Info, $\"Registered setting {setting.Id} in settings registry during creation\");\n }\n }\n\n // Refresh status for all settings to populate LinkedRegistrySettingsWithValues\n foreach (var setting in Settings)\n {\n await setting.RefreshStatus();\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading update optimizations: {ex.Message}\");\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all Windows Update settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, $\"Checking status for {Settings.Count} Windows Update settings\");\n\n foreach (var setting in Settings)\n {\n try\n {\n if (setting.RegistrySetting != null)\n {\n _logService.Log(LogLevel.Info, $\"Checking status for setting: {setting.Name}\");\n\n // Get the status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // Get the current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name}: {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Add to LinkedRegistrySettingsWithValues for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Checking linked registry settings status for: {setting.Name} with {setting.LinkedRegistrySettings.Settings.Count} registry entries\");\n\n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(regSetting.Hive);\n string fullPath = $\"{hiveString}\\\\{regSetting.SubKey}\";\n _logService.Log(LogLevel.Info, $\"Registry entry: {fullPath}\\\\{regSetting.Name}, EnabledValue={regSetting.EnabledValue}, DisabledValue={regSetting.DisabledValue}\");\n\n // Check if the key exists\n bool keyExists = _registryService.KeyExists(fullPath);\n _logService.Log(LogLevel.Info, $\"Key exists: {keyExists}\");\n\n if (keyExists)\n {\n // Check if the value exists and get its current value\n var currentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value: {currentValue ?? \"null\"}\");\n }\n }\n\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n _logService.Log(LogLevel.Info, $\"Combined status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name} (first entry): {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value for linked setting {regSetting.Name}: {regCurrentValue ?? \"null\"}\");\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Registry setting is null for {setting.Name}\");\n setting.Status = RegistrySettingStatus.Unknown;\n setting.StatusMessage = \"Registry setting information is missing\";\n }\n\n // If this is a grouped setting, update child settings too\n if (setting.IsGroupedSetting && setting.ChildSettings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Updating {setting.ChildSettings.Count} child settings for {setting.Name}\");\n foreach (var childSetting in setting.ChildSettings)\n {\n if (childSetting.RegistrySetting != null)\n {\n var status = await _registryService.GetSettingStatusAsync(childSetting.RegistrySetting);\n childSetting.Status = status;\n\n var currentValue = await _registryService.GetCurrentValueAsync(childSetting.RegistrySetting);\n childSetting.CurrentValue = currentValue;\n\n childSetting.StatusMessage = GetStatusMessage(childSetting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Child setting {childSetting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n childSetting.IsUpdatingFromCode = true;\n try\n {\n childSetting.IsSelected = shouldBeSelected;\n }\n finally\n {\n childSetting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating status for setting {setting.Name}: {ex.Message}\");\n setting.Status = RegistrySettingStatus.Error;\n setting.StatusMessage = $\"Error: {ex.Message}\";\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Windows Update setting statuses: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0)\n return;\n\n var selectedCount = Settings.Count(setting => setting.IsSelected);\n IsSelected = selectedCount == Settings.Count;\n }\n\n /// \n /// Gets a user-friendly status message for a setting.\n /// \n /// The setting to get the status message for.\n /// A user-friendly status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied =>\n \"This setting is enabled (toggle is ON).\",\n\n RegistrySettingStatus.NotApplied =>\n setting.CurrentValue == null\n ? \"This setting is not applied (registry value does not exist).\"\n : \"This setting is disabled (toggle is OFF).\",\n\n RegistrySettingStatus.Modified =>\n \"This setting has a custom value that differs from both enabled and disabled values.\",\n\n RegistrySettingStatus.Error =>\n \"An error occurred while checking this setting's status.\",\n\n _ => \"The status of this setting is unknown.\"\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/PowerShellHelper.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Helper class for common PowerShell execution patterns.\n /// \n public static class PowerShellHelper\n {\n /// \n /// Executes a PowerShell script with progress reporting and error handling.\n /// \n /// The PowerShell instance to use.\n /// The script to execute.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// The collection of PSObjects returned by the script.\n public static async Task> ExecuteScriptAsync(\n this PowerShell powerShell,\n string script,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (powerShell == null)\n {\n throw new ArgumentNullException(nameof(powerShell));\n }\n\n if (string.IsNullOrWhiteSpace(script))\n {\n throw new ArgumentException(\"Script cannot be null or empty\", nameof(script));\n }\n\n powerShell.AddScript(script);\n\n // Add event handlers for progress reporting\n if (progress != null)\n {\n powerShell.Streams.Information.DataAdded += (sender, e) =>\n {\n var info = powerShell.Streams.Information[e.Index];\n progress.Report(new TaskProgressDetail\n {\n DetailedMessage = info.MessageData.ToString(),\n LogLevel = LogLevel.Info\n });\n };\n\n powerShell.Streams.Error.DataAdded += (sender, e) =>\n {\n var error = powerShell.Streams.Error[e.Index];\n progress.Report(new TaskProgressDetail\n {\n DetailedMessage = error.Exception?.Message ?? error.ToString(),\n LogLevel = LogLevel.Error\n });\n };\n\n powerShell.Streams.Warning.DataAdded += (sender, e) =>\n {\n var warning = powerShell.Streams.Warning[e.Index];\n progress.Report(new TaskProgressDetail\n {\n DetailedMessage = warning.Message,\n LogLevel = LogLevel.Warning\n });\n };\n\n powerShell.Streams.Progress.DataAdded += (sender, e) =>\n {\n var progressRecord = powerShell.Streams.Progress[e.Index];\n var percentComplete = progressRecord.PercentComplete;\n if (percentComplete >= 0 && percentComplete <= 100)\n {\n progress.Report(new TaskProgressDetail\n {\n Progress = percentComplete,\n StatusText = progressRecord.Activity,\n DetailedMessage = progressRecord.StatusDescription\n });\n }\n };\n }\n\n // Execute the script\n return await Task.Run(() => powerShell.Invoke(), cancellationToken);\n }\n\n /// \n /// Executes a PowerShell script asynchronously.\n /// \n /// The PowerShell instance to use.\n /// Optional cancellation token.\n /// The data collection of PSObjects returned by the script.\n public static async Task> InvokeAsync(\n this PowerShell powerShell,\n CancellationToken cancellationToken = default)\n {\n if (powerShell == null)\n {\n throw new ArgumentNullException(nameof(powerShell));\n }\n\n var output = new PSDataCollection();\n var asyncResult = powerShell.BeginInvoke(null, output);\n\n await Task.Run(() =>\n {\n while (!asyncResult.IsCompleted)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n powerShell.Stop();\n cancellationToken.ThrowIfCancellationRequested();\n }\n Thread.Sleep(100);\n }\n powerShell.EndInvoke(asyncResult);\n }, cancellationToken);\n\n return output;\n }\n\n /// \n /// Parses a result string in the format \"STATUS|Message|RebootRequired\".\n /// \n /// The result string to parse.\n /// The name of the item being installed.\n /// Optional progress reporter.\n /// The log service for logging.\n /// An operation result indicating success or failure with error details.\n public static OperationResult ParseResultString(\n string resultString,\n string itemName,\n IProgress? progress = null,\n ILogService? logService = null)\n {\n if (string.IsNullOrEmpty(resultString))\n {\n progress?.Report(new TaskProgressDetail\n {\n StatusText = \"Script returned no result\",\n LogLevel = LogLevel.Error\n });\n logService?.LogError($\"Empty result returned when processing: {itemName}\");\n return OperationResult.Failed(\"Script returned no result\");\n }\n\n var parts = resultString.Split('|');\n if (parts.Length < 2)\n {\n progress?.Report(new TaskProgressDetail\n {\n StatusText = \"Error processing script result\",\n LogLevel = LogLevel.Error\n });\n logService?.LogError($\"Unexpected script output format for {itemName}: {resultString}\");\n return OperationResult.Failed(\"Unexpected script output format: \" + resultString);\n }\n\n string status = parts[0];\n string message = parts[1];\n bool rebootRequired = parts.Length > 2 && bool.TryParse(parts[2], out bool req) && req;\n\n if (status.Equals(\"SUCCESS\", StringComparison.OrdinalIgnoreCase))\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 100,\n StatusText = $\"Successfully processed: {itemName}\",\n DetailedMessage = message\n });\n logService?.LogSuccess($\"Successfully processed: {itemName}. {message}\");\n\n if (rebootRequired)\n {\n progress?.Report(new TaskProgressDetail\n {\n StatusText = \"A system restart is required to complete the installation\",\n DetailedMessage = \"Please restart your computer to complete the installation\",\n LogLevel = LogLevel.Warning\n });\n logService?.LogWarning($\"A system restart is required for {itemName}\");\n }\n return OperationResult.Succeeded(true);\n }\n else // FAILURE\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Failed to process: {itemName}\",\n DetailedMessage = message,\n LogLevel = LogLevel.Error\n });\n logService?.LogError($\"Failed to process: {itemName}. {message}\");\n return OperationResult.Failed(message);\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Properties/Settings.Designer.cs", "namespace Winhance.WPF.Properties {\n \n [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator\", \"17.0.0.0\")]\n internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {\n \n private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));\n \n public static Settings Default {\n get {\n return defaultInstance;\n }\n }\n \n [global::System.Configuration.UserScopedSettingAttribute()]\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n [global::System.Configuration.DefaultSettingValueAttribute(\"True\")]\n public bool IsDarkTheme {\n get {\n return ((bool)(this[\"IsDarkTheme\"]));\n }\n set {\n this[\"IsDarkTheme\"] = value;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/SpecialAppHandlerService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Service for handling special applications that require custom removal processes.\n /// \n public class SpecialAppHandlerService : ISpecialAppHandlerService\n {\n private readonly ILogService _logService;\n private readonly SpecialAppHandler[] _handlers;\n private readonly ISystemServices _systemServices;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The system services.\n public SpecialAppHandlerService(ILogService logService, ISystemServices systemServices)\n {\n _logService = logService;\n _systemServices = systemServices;\n _handlers = SpecialAppHandler.GetPredefinedHandlers();\n }\n\n /// \n public async Task RemoveSpecialAppAsync(string appHandlerType)\n {\n try\n {\n _logService.LogInformation(\n $\"Removing special app with handler type: {appHandlerType}\"\n );\n\n bool success = false;\n\n switch (appHandlerType)\n {\n case \"Edge\":\n success = await RemoveEdgeAsync();\n break;\n case \"OneDrive\":\n success = await RemoveOneDriveAsync();\n break;\n case \"OneNote\":\n success = await RemoveOneNoteAsync();\n break;\n default:\n _logService.LogError($\"Unknown special handler type: {appHandlerType}\");\n return false;\n }\n\n if (success)\n {\n _logService.LogSuccess($\"Successfully removed special app: {appHandlerType}\");\n }\n else\n {\n _logService.LogError($\"Failed to remove special app: {appHandlerType}\");\n }\n\n return success;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing special app: {appHandlerType}\", ex);\n return false;\n }\n }\n\n /// \n public async Task RemoveEdgeAsync()\n {\n try\n {\n _logService.LogInformation(\"Starting Edge removal process\");\n\n var handler = GetHandler(\"Edge\");\n if (handler == null)\n {\n _logService.LogError(\"Edge handler not found\");\n return false;\n }\n\n // Store the Edge removal script\n var scriptPath = Path.GetDirectoryName(handler.ScriptPath);\n Directory.CreateDirectory(scriptPath);\n\n File.WriteAllText(handler.ScriptPath, handler.RemovalScriptContent);\n _logService.LogInformation($\"Edge removal script saved to {handler.ScriptPath}\");\n\n // Execute the saved script file directly\n var processStartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-ExecutionPolicy Bypass -File \\\"{handler.ScriptPath}\\\"\",\n UseShellExecute = false,\n CreateNoWindow = true,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n };\n\n _logService.LogInformation($\"Executing Edge removal script: {handler.ScriptPath}\");\n var process = System.Diagnostics.Process.Start(processStartInfo);\n\n if (process != null)\n {\n string output = await process.StandardOutput.ReadToEndAsync();\n string error = await process.StandardError.ReadToEndAsync();\n\n await process.WaitForExitAsync();\n\n if (!string.IsNullOrEmpty(output))\n {\n _logService.LogInformation($\"Script output: {output}\");\n }\n\n if (!string.IsNullOrEmpty(error))\n {\n _logService.LogError($\"Script error: {error}\");\n }\n }\n else\n {\n _logService.LogError(\"Failed to start PowerShell process for Edge removal\");\n }\n\n // Register scheduled task to prevent reinstallation\n using var taskPowerShell = PowerShellFactory.CreateForAppxCommands(\n _logService,\n _systemServices\n );\n var taskCommand =\n $@\"\n Register-ScheduledTask -TaskName '{handler.ScheduledTaskName}' `\n -Action (New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-ExecutionPolicy Bypass -File \"\"{handler.ScriptPath}\"\"') `\n -Trigger (New-ScheduledTaskTrigger -AtStartup) `\n -User 'SYSTEM' `\n -RunLevel Highest `\n -Settings (New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries) `\n -Force\n \";\n taskPowerShell.AddScript(taskCommand);\n await Task.Run(() => taskPowerShell.Invoke());\n\n _logService.LogSuccess(\"Edge removal completed successfully\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Edge removal failed\", ex);\n return false;\n }\n }\n\n /// \n public async Task RemoveOneDriveAsync()\n {\n try\n {\n _logService.LogInformation(\"Starting OneDrive removal process\");\n\n var handler = GetHandler(\"OneDrive\");\n if (handler == null)\n {\n _logService.LogError(\"OneDrive handler not found\");\n return false;\n }\n\n // Store the OneDrive removal script\n var scriptPath = Path.GetDirectoryName(handler.ScriptPath);\n Directory.CreateDirectory(scriptPath);\n\n File.WriteAllText(handler.ScriptPath, handler.RemovalScriptContent);\n _logService.LogInformation(\n $\"OneDrive removal script saved to {handler.ScriptPath}\"\n );\n\n // Execute the saved script file directly\n var processStartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-ExecutionPolicy Bypass -File \\\"{handler.ScriptPath}\\\"\",\n UseShellExecute = false,\n CreateNoWindow = true,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n };\n\n _logService.LogInformation(\n $\"Executing OneDrive removal script: {handler.ScriptPath}\"\n );\n var process = System.Diagnostics.Process.Start(processStartInfo);\n\n if (process != null)\n {\n string output = await process.StandardOutput.ReadToEndAsync();\n string error = await process.StandardError.ReadToEndAsync();\n\n await process.WaitForExitAsync();\n\n if (!string.IsNullOrEmpty(output))\n {\n _logService.LogInformation($\"Script output: {output}\");\n }\n\n if (!string.IsNullOrEmpty(error))\n {\n _logService.LogError($\"Script error: {error}\");\n }\n }\n else\n {\n _logService.LogError(\"Failed to start PowerShell process for OneDrive removal\");\n }\n\n // Register scheduled task to prevent reinstallation\n using var taskPowerShell = PowerShellFactory.CreateForAppxCommands(\n _logService,\n _systemServices\n );\n var taskCommand =\n $@\"\n Register-ScheduledTask -TaskName '{handler.ScheduledTaskName}' `\n -Action (New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-ExecutionPolicy Bypass -File \"\"{handler.ScriptPath}\"\"') `\n -Trigger (New-ScheduledTaskTrigger -AtStartup) `\n -User 'SYSTEM' `\n -RunLevel Highest `\n -Settings (New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries) `\n -Force\n \";\n taskPowerShell.AddScript(taskCommand);\n await Task.Run(() => taskPowerShell.Invoke());\n\n _logService.LogSuccess(\"OneDrive removal completed successfully\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"OneDrive removal failed\", ex);\n return false;\n }\n }\n\n /// \n public async Task RemoveOneNoteAsync()\n {\n try\n {\n _logService.LogInformation(\"Starting OneNote removal process\");\n\n var handler = GetHandler(\"OneNote\");\n if (handler == null)\n {\n _logService.LogError(\"OneNote handler not found\");\n return false;\n }\n\n // Store the OneNote removal script\n var scriptPath = Path.GetDirectoryName(handler.ScriptPath);\n Directory.CreateDirectory(scriptPath);\n\n File.WriteAllText(handler.ScriptPath, handler.RemovalScriptContent);\n _logService.LogInformation($\"OneNote removal script saved to {handler.ScriptPath}\");\n\n // Execute the saved script file directly\n var processStartInfo = new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"powershell.exe\",\n Arguments = $\"-ExecutionPolicy Bypass -File \\\"{handler.ScriptPath}\\\"\",\n UseShellExecute = false,\n CreateNoWindow = true,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n };\n\n _logService.LogInformation(\n $\"Executing OneNote removal script: {handler.ScriptPath}\"\n );\n var process = System.Diagnostics.Process.Start(processStartInfo);\n\n if (process != null)\n {\n string output = await process.StandardOutput.ReadToEndAsync();\n string error = await process.StandardError.ReadToEndAsync();\n\n await process.WaitForExitAsync();\n\n if (!string.IsNullOrEmpty(output))\n {\n _logService.LogInformation($\"Script output: {output}\");\n }\n\n if (!string.IsNullOrEmpty(error))\n {\n _logService.LogError($\"Script error: {error}\");\n }\n }\n else\n {\n _logService.LogError(\"Failed to start PowerShell process for OneNote removal\");\n }\n\n // Register scheduled task to prevent reinstallation\n using var taskPowerShell = PowerShellFactory.CreateForAppxCommands(\n _logService,\n _systemServices\n );\n var taskCommand =\n $@\"\n Register-ScheduledTask -TaskName '{handler.ScheduledTaskName}' `\n -Action (New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-ExecutionPolicy Bypass -File \"\"{handler.ScriptPath}\"\"') `\n -Trigger (New-ScheduledTaskTrigger -AtStartup) `\n -User 'SYSTEM' `\n -RunLevel Highest `\n -Settings (New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries) `\n -Force\n \";\n taskPowerShell.AddScript(taskCommand);\n await Task.Run(() => taskPowerShell.Invoke());\n\n _logService.LogSuccess(\"OneNote removal completed successfully\");\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"OneNote removal failed\", ex);\n return false;\n }\n }\n\n /// \n public SpecialAppHandler? GetHandler(string handlerType)\n {\n return _handlers.FirstOrDefault(h =>\n h.HandlerType.Equals(handlerType, StringComparison.OrdinalIgnoreCase)\n );\n }\n\n /// \n public IEnumerable GetAllHandlers()\n {\n return _handlers;\n }\n\n // SetExecutionPolicy is now handled by PowerShellFactory\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/GamingandPerformanceOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Infrastructure.Features.Common.Registry;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Gaming and Performance optimizations.\n /// \n public partial class GamingandPerformanceOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n private readonly ICommandService _commandService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The command service.\n /// The view model locator.\n /// The settings registry.\n public GamingandPerformanceOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n ICommandService commandService,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n _commandService = commandService;\n }\n\n /// \n /// Loads the Gaming and Performance optimizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Gaming and Performance optimizations\n var gamingOptimizations = Core.Features.Optimize.Models.GamingandPerformanceOptimizations.GetGamingandPerformanceOptimizations();\n if (gamingOptimizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in gamingOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService, _commandService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsUpdatingFromCode = true, // Set this to true to allow RefreshStatus to set the correct state\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Info, $\"No registry settings found for {setting.Name}\");\n }\n \n // Set up command settings if available\n if (setting.CommandSettings.Count > 0)\n {\n settingItem.CommandSettings = setting.CommandSettings;\n _logService.Log(LogLevel.Info, $\"Setting up command settings for {setting.Name} with {setting.CommandSettings.Count} commands\");\n \n // Log details about each command setting for debugging\n foreach (var cmdSetting in setting.CommandSettings)\n {\n _logService.Log(LogLevel.Info, $\"Command setting: {cmdSetting.Id}, EnabledCommand={cmdSetting.EnabledCommand}, DisabledCommand={cmdSetting.DisabledCommand}, IsPrimary={cmdSetting.IsPrimary}\");\n }\n }\n\n // Add to the settings collection\n Settings.Add(settingItem);\n }\n\n // Register settings with the settings registry if available\n foreach (var setting in Settings)\n {\n if (_settingsRegistry != null && !string.IsNullOrEmpty(setting.Id))\n {\n _settingsRegistry.RegisterSetting(setting);\n _logService.Log(LogLevel.Info, $\"Registered setting {setting.Id} in settings registry during creation\");\n }\n }\n\n // Refresh status for all settings to populate LinkedRegistrySettingsWithValues\n foreach (var setting in Settings)\n {\n await setting.RefreshStatus();\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading Gaming and Performance optimizations: {ex.Message}\");\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all gaming and performance settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, $\"Checking status for {Settings.Count} gaming and performance settings\");\n\n foreach (var setting in Settings)\n {\n try\n {\n if (setting.RegistrySetting != null)\n {\n _logService.Log(LogLevel.Info, $\"Checking status for setting: {setting.Name}\");\n\n // Get the status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // Get the current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name}: {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Add to LinkedRegistrySettingsWithValues for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Checking linked registry settings status for: {setting.Name} with {setting.LinkedRegistrySettings.Settings.Count} registry entries\");\n\n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n string hiveString = RegistryExtensions.GetRegistryHiveString(regSetting.Hive);\n string fullPath = $\"{hiveString}\\\\{regSetting.SubKey}\";\n _logService.Log(LogLevel.Info, $\"Registry entry: {fullPath}\\\\{regSetting.Name}, EnabledValue={regSetting.EnabledValue}, DisabledValue={regSetting.DisabledValue}\");\n\n // Check if the key exists\n bool keyExists = _registryService.KeyExists(fullPath);\n _logService.Log(LogLevel.Info, $\"Key exists: {keyExists}\");\n\n if (keyExists)\n {\n // Check if the value exists and get its current value\n var currentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value: {currentValue ?? \"null\"}\");\n }\n }\n\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n _logService.Log(LogLevel.Info, $\"Combined status for {setting.Name}: {status}\");\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n _logService.Log(LogLevel.Info, $\"Current value for {setting.Name} (first entry): {currentValue ?? \"null\"}\");\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n _logService.Log(LogLevel.Info, $\"Current value for linked setting {regSetting.Name}: {regCurrentValue ?? \"null\"}\");\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Registry setting is null for {setting.Name}\");\n setting.Status = RegistrySettingStatus.Unknown;\n setting.StatusMessage = \"Registry setting information is missing\";\n }\n\n // If this is a grouped setting, update child settings too\n if (setting.IsGroupedSetting && setting.ChildSettings.Count > 0)\n {\n _logService.Log(LogLevel.Info, $\"Updating {setting.ChildSettings.Count} child settings for {setting.Name}\");\n foreach (var childSetting in setting.ChildSettings)\n {\n if (childSetting.RegistrySetting != null)\n {\n var status = await _registryService.GetSettingStatusAsync(childSetting.RegistrySetting);\n childSetting.Status = status;\n\n var currentValue = await _registryService.GetCurrentValueAsync(childSetting.RegistrySetting);\n childSetting.CurrentValue = currentValue;\n\n childSetting.StatusMessage = GetStatusMessage(childSetting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Child setting {childSetting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n childSetting.IsUpdatingFromCode = true;\n try\n {\n childSetting.IsSelected = shouldBeSelected;\n }\n finally\n {\n childSetting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error updating status for setting {setting.Name}: {ex.Message}\");\n setting.Status = RegistrySettingStatus.Error;\n setting.StatusMessage = $\"Error: {ex.Message}\";\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking gaming and performance setting statuses: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0)\n return;\n\n var selectedCount = Settings.Count(setting => setting.IsSelected);\n IsSelected = selectedCount == Settings.Count;\n }\n\n /// \n /// Gets a user-friendly status message for a setting.\n /// \n /// The setting to get the status message for.\n /// A user-friendly status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied =>\n \"This setting is enabled (toggle is ON).\",\n\n RegistrySettingStatus.NotApplied =>\n setting.CurrentValue == null\n ? \"This setting is not applied (registry value does not exist).\"\n : \"This setting is disabled (toggle is OFF).\",\n\n RegistrySettingStatus.Modified =>\n \"This setting has a custom value that differs from both enabled and disabled values.\",\n\n RegistrySettingStatus.Error =>\n \"An error occurred while checking this setting's status.\",\n\n _ => \"The status of this setting is unknown.\"\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/ViewModels/StartMenuCustomizationsViewModel.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Extensions;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Customize.ViewModels\n{\n /// \n /// ViewModel for Start Menu customizations.\n /// \n public partial class StartMenuCustomizationsViewModel : BaseSettingsViewModel\n {\n private readonly ISystemServices _systemServices;\n private bool _isWindows11;\n\n /// \n /// Gets the command to clean the Start Menu.\n /// \n [RelayCommand]\n public async Task CleanStartMenu()\n {\n try\n {\n // Start task with progress\n _progressService.StartTask(\"Cleaning Start Menu...\");\n \n // Update initial progress\n _progressService.UpdateDetailedProgress(new TaskProgressDetail\n {\n StatusText = \"Cleaning Start Menu...\",\n Progress = 0\n });\n\n // Determine Windows version\n _isWindows11 = _systemServices.IsWindows11();\n\n // Clean Start Menu\n await Task.Run(() =>\n {\n StartMenuCustomizations.CleanStartMenu(_isWindows11, _systemServices);\n });\n\n // Log success\n _logService.Log(LogLevel.Info, \"Start Menu cleaned successfully\");\n\n // Update completion progress\n _progressService.UpdateDetailedProgress(new TaskProgressDetail\n {\n StatusText = \"Start Menu cleaned successfully\",\n Progress = 100\n });\n \n // Complete the task\n _progressService.CompleteTask();\n }\n catch (Exception ex)\n {\n // Log error\n _logService.Log(LogLevel.Error, $\"Error cleaning Start Menu: {ex.Message}\");\n\n // Update error progress\n _progressService.UpdateDetailedProgress(new TaskProgressDetail\n {\n StatusText = $\"Error cleaning Start Menu: {ex.Message}\",\n Progress = 100\n });\n \n // Complete the task\n _progressService.CompleteTask();\n }\n }\n\n /// \n /// Gets the command to execute an action.\n /// \n [RelayCommand]\n public async Task ExecuteAction(ApplicationAction? action)\n {\n if (action == null) return;\n\n try\n {\n // Execute the registry action if present\n if (action.RegistrySetting != null)\n {\n string hiveString = action.RegistrySetting.Hive.ToString();\n if (hiveString == \"LocalMachine\") hiveString = \"HKLM\";\n else if (hiveString == \"CurrentUser\") hiveString = \"HKCU\";\n else if (hiveString == \"ClassesRoot\") hiveString = \"HKCR\";\n else if (hiveString == \"Users\") hiveString = \"HKU\";\n else if (hiveString == \"CurrentConfig\") hiveString = \"HKCC\";\n\n string fullPath = $\"{hiveString}\\\\{action.RegistrySetting.SubKey}\";\n _registryService.SetValue(\n fullPath,\n action.RegistrySetting.Name,\n action.RegistrySetting.RecommendedValue,\n action.RegistrySetting.ValueType);\n }\n\n // Execute custom action if present\n if (action.CustomAction != null)\n {\n await action.CustomAction();\n }\n\n _logService.Log(LogLevel.Info, $\"Action '{action.Name}' executed successfully\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error executing action '{action.Name}': {ex.Message}\");\n }\n }\n\n /// \n /// Gets the collection of Start Menu actions.\n /// \n public ObservableCollection Actions { get; } = new();\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The system services.\n public StartMenuCustomizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n ISystemServices systemServices)\n : base(progressService, registryService, logService)\n {\n _systemServices = systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n _isWindows11 = _systemServices.IsWindows11();\n }\n\n /// \n /// Loads the Start Menu customizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Start Menu customizations\n var startMenuCustomizations = Core.Features.Customize.Models.StartMenuCustomizations.GetStartMenuCustomizations();\n if (startMenuCustomizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in startMenuCustomizations.Settings.OrderBy(s => s.Name))\n {\n // Skip Windows 11 specific settings on Windows 10\n if (!_isWindows11 && setting.IsWindows11Only)\n {\n continue;\n }\n\n // Skip Windows 10 specific settings on Windows 11\n if (_isWindows11 && setting.IsWindows10Only)\n {\n continue;\n }\n\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n ControlType = setting.ControlType,\n IsWindows11Only = setting.IsWindows11Only,\n IsWindows10Only = setting.IsWindows10Only\n };\n\n // Add any actions\n var actionsProperty = setting.GetType().GetProperty(\"Actions\");\n if (actionsProperty != null && \n actionsProperty.GetValue(setting) is IEnumerable actions && \n actions.Any())\n {\n // We need to handle this differently since the Actions property doesn't exist in ApplicationSetting\n // This is a temporary workaround until we refactor the code properly\n }\n\n // Set up the registry settings\n if (setting.RegistrySettings != null && setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings != null && setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n var linkedSettings = new LinkedRegistrySettings();\n foreach (var regSetting in setting.RegistrySettings)\n {\n linkedSettings.Settings.Add(regSetting);\n _logService.Log(LogLevel.Info, $\"Adding linked registry setting for {setting.Name}: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}\");\n }\n settingItem.LinkedRegistrySettings = linkedSettings;\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for settings\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Initializes the Start Menu actions.\n /// \n private void InitializeActions()\n {\n Actions.Clear();\n\n // Add Clean Start Menu action\n Actions.Add(new ApplicationAction\n {\n Id = \"clean-start-menu\",\n Name = \"Clean Start Menu\",\n Description = \"Cleans the Start Menu by removing pinned apps and restoring the default layout\",\n CustomAction = async () =>\n {\n await CleanStartMenu();\n return true;\n }\n });\n }\n\n /// \n /// Checks the status of all Start Menu settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n foreach (var setting in Settings)\n {\n // Get status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n setting.Status = status;\n\n // Get current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n setting.CurrentValue = currentValue;\n\n // Set IsRegistryValueNull property based on current value\n setting.IsRegistryValueNull = currentValue == null;\n\n // Update LinkedRegistrySettingsWithValues for tooltip display\n var linkedRegistrySettingsWithValues = new ObservableCollection();\n \n // Get the LinkedRegistrySettings property\n var linkedRegistrySettings = setting.LinkedRegistrySettings;\n \n if (linkedRegistrySettings != null && linkedRegistrySettings.Settings.Count > 0)\n {\n // For linked settings, get fresh values from registry\n bool anyNull = false;\n foreach (var regSetting in linkedRegistrySettings.Settings)\n {\n string hiveString = regSetting.Hive.ToString();\n if (hiveString == \"LocalMachine\") hiveString = \"HKLM\";\n else if (hiveString == \"CurrentUser\") hiveString = \"HKCU\";\n else if (hiveString == \"ClassesRoot\") hiveString = \"HKCR\";\n else if (hiveString == \"Users\") hiveString = \"HKU\";\n else if (hiveString == \"CurrentConfig\") hiveString = \"HKCC\";\n \n var regCurrentValue = _registryService.GetValue(\n $\"{hiveString}\\\\{regSetting.SubKey}\",\n regSetting.Name);\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n linkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // For linked settings, set IsRegistryValueNull if any value is null\n setting.IsRegistryValueNull = anyNull;\n }\n else if (setting.RegistrySetting != null)\n {\n // For single setting\n linkedRegistrySettingsWithValues.Add(new LinkedRegistrySettingWithValue(setting.RegistrySetting, currentValue));\n // IsRegistryValueNull is already set above\n }\n \n setting.LinkedRegistrySettingsWithValues = linkedRegistrySettingsWithValues;\n\n // Set status message\n string statusMessage = GetStatusMessage(setting);\n setting.StatusMessage = statusMessage;\n\n // Set the IsUpdatingFromCode flag to prevent automatic application\n setting.IsUpdatingFromCode = true;\n\n try\n {\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n // Reset the flag\n setting.IsUpdatingFromCode = false;\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Start Menu setting statuses: {ex.Message}\");\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n // Get status\n var status = setting.Status;\n string message = status switch\n {\n RegistrySettingStatus.Applied => \"Setting is enabled (toggle is ON)\",\n RegistrySettingStatus.NotApplied => \"Setting is disabled (toggle is OFF)\",\n RegistrySettingStatus.Modified => \"Setting has a custom value different from both enabled and disabled values\",\n RegistrySettingStatus.Error => \"Error checking setting status\",\n _ => \"Unknown status\"\n };\n\n // Add current value if available\n var currentValue = setting.CurrentValue;\n if (currentValue != null)\n {\n message += $\"\\nCurrent value: {currentValue}\";\n }\n\n // Add enabled value if available\n var registrySetting = setting.RegistrySetting;\n object? enabledValue = registrySetting?.EnabledValue ?? registrySetting?.RecommendedValue;\n if (enabledValue != null)\n {\n message += $\"\\nEnabled value (ON): {enabledValue}\";\n }\n\n // Add disabled value if available\n object? disabledValue = registrySetting?.DisabledValue ?? registrySetting?.DefaultValue;\n if (disabledValue != null)\n {\n message += $\"\\nDisabled value (OFF): {disabledValue}\";\n }\n\n return message;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Interfaces/IThemeService.cs", "using System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.Customize.Interfaces\n{\n /// \n /// Interface for theme-related operations.\n /// \n public interface IThemeService\n {\n /// \n /// Checks if dark mode is enabled.\n /// \n /// True if dark mode is enabled; otherwise, false.\n bool IsDarkModeEnabled();\n\n /// \n /// Sets the theme mode.\n /// \n /// True to enable dark mode; false to enable light mode.\n /// True if the operation succeeded; otherwise, false.\n bool SetThemeMode(bool isDarkMode);\n\n /// \n /// Sets the theme mode and optionally changes the wallpaper.\n /// \n /// True to enable dark mode; false to enable light mode.\n /// True to change the wallpaper; otherwise, false.\n /// A task representing the asynchronous operation.\n Task ApplyThemeAsync(bool isDarkMode, bool changeWallpaper);\n\n /// \n /// Gets the name of the current theme.\n /// \n /// The name of the current theme (\"Light Mode\" or \"Dark Mode\").\n string GetCurrentThemeName();\n\n /// \n /// Refreshes the Windows GUI to apply theme changes.\n /// \n /// True to restart Explorer; otherwise, false.\n /// A task representing the asynchronous operation.\n Task RefreshGUIAsync(bool restartExplorer);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/MoreMenu.xaml.cs", "using System;\nusing System.IO;\nusing System.Windows;\nusing System.Windows.Controls;\nusing Winhance.WPF.Features.Common.Utilities;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// Interaction logic for MoreMenu.xaml\n /// \n public partial class MoreMenu : UserControl\n {\n public MoreMenu()\n {\n try\n {\n LogToStartupLog(\"MoreMenu constructor starting\");\n InitializeComponent();\n LogToStartupLog(\"MoreMenu constructor completed successfully\");\n }\n catch (Exception ex)\n {\n LogToStartupLog($\"ERROR in MoreMenu constructor: {ex.Message}\");\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n throw; // Re-throw to ensure the error is properly handled\n }\n }\n\n /// \n /// Logs a message directly to the WinhanceStartupLog.txt file\n /// \n private void LogToStartupLog(string message)\n {\n#if DEBUG\n try\n {\n string logsDir = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\"\n );\n string logFile = Path.Combine(logsDir, \"WinhanceStartupLog.txt\");\n\n // Ensure the logs directory exists\n if (!Directory.Exists(logsDir))\n {\n Directory.CreateDirectory(logsDir);\n }\n\n // Format the log message with timestamp\n string formattedMessage =\n $\"[{DateTime.Now:yyyy/MM/dd HH:mm:ss}] [MoreMenu] {message}\";\n\n // Append to the log file\n using (StreamWriter writer = File.AppendText(logFile))\n {\n writer.WriteLine(formattedMessage);\n }\n }\n catch\n {\n // Ignore errors in logging to avoid cascading issues\n }\n#endif\n }\n\n /// \n /// Shows the context menu at the specified placement target\n /// \n /// The UI element that the context menu should be positioned relative to\n public void ShowMenu(UIElement placementTarget)\n {\n try\n {\n LogToStartupLog(\"ShowMenu method called\");\n LogToStartupLog($\"placementTarget exists: {placementTarget != null}\");\n LogToStartupLog($\"DataContext exists: {DataContext != null}\");\n LogToStartupLog(\n $\"DataContext type: {(DataContext != null ? DataContext.GetType().FullName : \"null\")}\"\n );\n\n // Get the context menu from resources\n var contextMenu = Resources[\"MoreButtonContextMenu\"] as ContextMenu;\n LogToStartupLog($\"ContextMenu from resources exists: {contextMenu != null}\");\n\n if (contextMenu != null)\n {\n try\n {\n // Ensure the context menu has the same DataContext as the control\n LogToStartupLog(\"Setting context menu DataContext\");\n contextMenu.DataContext = this.DataContext;\n LogToStartupLog(\n $\"Context menu DataContext set: {contextMenu.DataContext != null}\"\n );\n\n // Add a handler to log when menu items are clicked\n foreach (var item in contextMenu.Items)\n {\n if (item is MenuItem menuItem)\n {\n LogToStartupLog(\n $\"Menu item: {menuItem.Header}, Command bound: {menuItem.Command != null}\"\n );\n\n // Add a Click handler to log when the item is clicked\n menuItem.Click += (s, e) =>\n {\n LogToStartupLog($\"Menu item clicked: {menuItem.Header}\");\n if (menuItem.Command != null)\n {\n LogToStartupLog(\n $\"Command can execute: {menuItem.Command.CanExecute(null)}\"\n );\n }\n };\n }\n }\n\n // Set the placement target\n LogToStartupLog(\"Setting placement target\");\n contextMenu.PlacementTarget = placementTarget;\n LogToStartupLog(\"Placement target set successfully\");\n\n // Set placement mode to Right to show menu to the right of the button\n LogToStartupLog(\"Setting placement mode\");\n contextMenu.Placement = System\n .Windows\n .Controls\n .Primitives\n .PlacementMode\n .Right;\n LogToStartupLog(\"Placement mode set successfully\");\n\n // No horizontal or vertical offset\n LogToStartupLog(\"Setting offset values\");\n contextMenu.HorizontalOffset = 0;\n contextMenu.VerticalOffset = 0;\n LogToStartupLog(\"Offset values set successfully\");\n\n // Open the context menu\n LogToStartupLog(\"About to open context menu\");\n contextMenu.IsOpen = true;\n LogToStartupLog(\"Context menu opened successfully\");\n }\n catch (Exception menuEx)\n {\n LogToStartupLog($\"ERROR configuring context menu: {menuEx.Message}\");\n LogToStartupLog($\"Stack trace: {menuEx.StackTrace}\");\n }\n }\n else\n {\n LogToStartupLog(\"ERROR: ContextMenu from resources is null, cannot show menu\");\n }\n }\n catch (Exception ex)\n {\n LogToStartupLog($\"ERROR in ShowMenu method: {ex.Message}\");\n LogToStartupLog($\"Stack trace: {ex.StackTrace}\");\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppDiscoveryService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service for discovering and querying applications on the system.\n/// \npublic class AppDiscoveryService\n : Winhance.Core.Features.SoftwareApps.Interfaces.IAppDiscoveryService\n{\n private readonly ILogService _logService;\n private readonly ExternalAppCatalog _externalAppCatalog;\n private readonly WindowsAppCatalog _windowsAppCatalog;\n private readonly CapabilityCatalog _capabilityCatalog;\n private readonly FeatureCatalog _featureCatalog;\n private readonly TimeSpan _powershellTimeout = TimeSpan.FromSeconds(10); // Add a timeout for PowerShell commands\n private Dictionary _installationStatusCache = new Dictionary(\n StringComparer.OrdinalIgnoreCase\n );\n private DateTime _lastCacheRefresh = DateTime.MinValue;\n private readonly TimeSpan _cacheLifetime = TimeSpan.FromMinutes(5);\n private readonly object _cacheLock = new object();\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public AppDiscoveryService(ILogService logService)\n {\n _logService = logService;\n _externalAppCatalog = ExternalAppCatalog.CreateDefault();\n _windowsAppCatalog = WindowsAppCatalog.CreateDefault();\n _capabilityCatalog = CapabilityCatalog.CreateDefault();\n _featureCatalog = FeatureCatalog.CreateDefault();\n }\n\n /// \n public async Task> GetInstallableAppsAsync()\n {\n try\n {\n _logService.LogInformation(\"Getting installable external apps list\");\n var installableApps = _externalAppCatalog.ExternalApps.ToList();\n\n // Return the apps without checking installation status initially\n // This will allow the UI to load faster\n _logService.LogInformation($\"Found {installableApps.Count} installable external apps\");\n return installableApps;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error retrieving installable external apps\", ex);\n return new List();\n }\n }\n\n /// \n public async Task> GetStandardAppsAsync()\n {\n try\n {\n _logService.LogInformation(\"Getting standard Windows apps list\");\n var standardApps = _windowsAppCatalog.WindowsApps.ToList();\n\n // Return the apps without checking installation status initially\n // This will allow the UI to load faster\n _logService.LogInformation($\"Found {standardApps.Count} standard Windows apps\");\n return standardApps;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error retrieving standard Windows apps\", ex);\n return new List();\n }\n }\n\n /// \n public async Task> GetCapabilitiesAsync()\n {\n try\n {\n _logService.LogInformation(\"Getting Windows capabilities list\");\n var capabilities = _capabilityCatalog.Capabilities.ToList();\n\n // Return the capabilities without checking installation status initially\n // This will allow the UI to load faster\n _logService.LogInformation($\"Found {capabilities.Count} capabilities\");\n return capabilities;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error retrieving capabilities\", ex);\n return new List();\n }\n }\n\n /// \n public async Task> GetOptionalFeaturesAsync()\n {\n try\n {\n _logService.LogInformation(\"Getting Windows optional features list\");\n var features = _featureCatalog.Features.ToList();\n\n // Return the features without checking installation status initially\n // This will allow the UI to load faster\n _logService.LogInformation($\"Found {features.Count} optional features\");\n return features;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error retrieving optional features\", ex);\n return new List();\n }\n }\n\n /// \n public async Task IsAppInstalledAsync(string packageName)\n {\n return await IsAppInstalledAsync(packageName, CancellationToken.None);\n }\n\n /// \n public async Task IsAppInstalledAsync(\n string packageName,\n CancellationToken cancellationToken = default\n )\n {\n try\n {\n // Check cache first\n lock (_cacheLock)\n {\n if (_installationStatusCache.TryGetValue(packageName, out bool cachedStatus))\n {\n // Only use cache if it's fresh\n if (DateTime.Now - _lastCacheRefresh < _cacheLifetime)\n {\n return cachedStatus;\n }\n }\n }\n\n // Determine item type more efficiently by using a type flag in the item itself\n // This avoids searching through collections each time\n bool isCapability = _capabilityCatalog.Capabilities.Any(c =>\n c.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase)\n );\n bool isFeature =\n !isCapability\n && _featureCatalog.Features.Any(f =>\n f.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase)\n );\n\n bool isInstalled = false;\n\n // Check if this app has subpackages\n string[]? subPackages = null;\n if (!isCapability && !isFeature)\n {\n // Find the app definition to check for subpackages\n var appDefinition = _windowsAppCatalog.WindowsApps.FirstOrDefault(a =>\n a.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (appDefinition?.SubPackages != null && appDefinition.SubPackages.Length > 0)\n {\n subPackages = appDefinition.SubPackages;\n _logService.LogInformation(\n $\"App {packageName} has {subPackages.Length} subpackages\"\n );\n }\n }\n\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n\n if (isCapability)\n {\n // Check capability status\n powerShell.AddScript(\n @\"\n param($capabilityName)\n try {\n $capability = Get-WindowsCapability -Online |\n Where-Object { $_.Name -like \"\"$capabilityName*\"\" } |\n Select-Object -First 1\n return $capability -ne $null -and $capability.State -eq 'Installed'\n }\n catch {\n return $false\n }\n \"\n );\n powerShell.AddParameter(\"capabilityName\", packageName);\n }\n else if (isFeature)\n {\n // Check feature status\n powerShell.AddScript(\n @\"\n param($featureName)\n try {\n $feature = Get-WindowsOptionalFeature -Online |\n Where-Object { $_.FeatureName -eq $featureName }\n return $feature -ne $null -and $feature.State -eq 'Enabled'\n }\n catch {\n return $false\n }\n \"\n );\n powerShell.AddParameter(\"featureName\", packageName);\n }\n else\n {\n // Check standard app status using the same approach as the original PowerShell script\n // But also check subpackages if the main package is not installed\n using var powerShellForAppx = PowerShellFactory.CreateForAppxCommands(_logService);\n powerShellForAppx.AddScript(\n @\"\n param($packageName, $subPackages)\n try {\n # Check main package\n $appx = Get-AppxPackage -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $packageName }\n $isInstalled = ($appx -ne $null)\n Write-Output \"\"Checking if $packageName is installed: $isInstalled\"\"\n \n # If not installed and we have subpackages, check those too\n if (-not $isInstalled -and $subPackages -ne $null) {\n foreach ($subPackage in $subPackages) {\n Write-Output \"\"Checking subpackage: $subPackage\"\"\n $subAppx = Get-AppxPackage -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq $subPackage }\n if ($subAppx -ne $null) {\n $isInstalled = $true\n Write-Output \"\"Subpackage $subPackage is installed\"\"\n break\n }\n }\n }\n \n return $isInstalled\n }\n catch {\n Write-Output \"\"Error checking if $packageName is installed: $_\"\"\n return $false\n }\n \"\n );\n powerShellForAppx.AddParameter(\"packageName\", packageName);\n powerShellForAppx.AddParameter(\"subPackages\", subPackages);\n\n // Execute with timeout\n var task = Task.Run(() => powerShellForAppx.Invoke());\n if (await Task.WhenAny(task, Task.Delay(_powershellTimeout)) == task)\n {\n var result = await task;\n isInstalled = result.FirstOrDefault();\n }\n else\n {\n _logService.LogWarning(\n $\"Timeout checking installation status for {packageName}\"\n );\n isInstalled = false;\n }\n }\n\n // Cache the result\n lock (_cacheLock)\n {\n _installationStatusCache[packageName] = isInstalled;\n _lastCacheRefresh = DateTime.Now;\n }\n\n return isInstalled;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking if item is installed: {packageName}\", ex);\n return false;\n }\n }\n\n /// \n /// Efficiently checks installation status for multiple items at once.\n /// \n /// The package names to check.\n /// A dictionary mapping package names to their installation status.\n public async Task> GetInstallationStatusBatchAsync(\n IEnumerable packageNames\n )\n {\n var result = new Dictionary(StringComparer.OrdinalIgnoreCase);\n var packageList = packageNames.ToList();\n\n if (!packageList.Any())\n return result;\n\n try\n {\n // Check for special apps that need custom detection logic\n var oneNotePackage = \"Microsoft.Office.OneNote\";\n bool hasOneNote = packageList.Any(p =>\n p.Equals(oneNotePackage, StringComparison.OrdinalIgnoreCase)\n );\n bool oneNoteInstalled = false;\n\n // If OneNote is in the list, check it separately using our special detection\n if (hasOneNote)\n {\n oneNoteInstalled = await IsOneNoteInstalledAsync();\n _logService.LogInformation(\n $\"OneNote special registry check result: {oneNoteInstalled}\"\n );\n // Remove OneNote from the list as we'll handle it separately\n packageList = packageList\n .Where(p => !p.Equals(oneNotePackage, StringComparison.OrdinalIgnoreCase))\n .ToList();\n }\n\n // Group items by type for batch processing\n var capabilities = packageList\n .Where(p =>\n _capabilityCatalog.Capabilities.Any(c =>\n c.PackageName.Equals(p, StringComparison.OrdinalIgnoreCase)\n )\n )\n .ToList();\n\n var features = packageList\n .Where(p =>\n _featureCatalog.Features.Any(f =>\n f.PackageName.Equals(p, StringComparison.OrdinalIgnoreCase)\n )\n )\n .ToList();\n\n var standardApps = packageList.Except(capabilities).Except(features).ToList();\n\n // Process capabilities in batch\n if (capabilities.Any())\n {\n var capabilityStatuses = await GetCapabilitiesStatusBatchAsync(capabilities);\n foreach (var pair in capabilityStatuses)\n {\n result[pair.Key] = pair.Value;\n }\n }\n\n // Process features in batch\n if (features.Any())\n {\n var featureStatuses = await GetFeaturesStatusBatchAsync(features);\n foreach (var pair in featureStatuses)\n {\n result[pair.Key] = pair.Value;\n }\n }\n\n // Process standard apps in batch\n if (standardApps.Any())\n {\n var appStatuses = await GetStandardAppsStatusBatchAsync(standardApps);\n foreach (var pair in appStatuses)\n {\n result[pair.Key] = pair.Value;\n }\n }\n\n // Add OneNote result if it was in the original list\n if (hasOneNote)\n {\n // Check if OneNote is also detected via AppX package\n bool appxOneNoteInstalled = false;\n if (result.TryGetValue(oneNotePackage, out bool appxInstalled))\n {\n appxOneNoteInstalled = appxInstalled;\n }\n\n // Use either the registry check or AppX check - if either is true, OneNote is installed\n result[oneNotePackage] = oneNoteInstalled || appxOneNoteInstalled;\n _logService.LogInformation(\n $\"Final OneNote installation status: {result[oneNotePackage]} (Registry: {oneNoteInstalled}, AppX: {appxOneNoteInstalled})\"\n );\n }\n\n // Cache all results\n lock (_cacheLock)\n {\n foreach (var pair in result)\n {\n _installationStatusCache[pair.Key] = pair.Value;\n }\n _lastCacheRefresh = DateTime.Now;\n }\n\n return result;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking batch installation status\", ex);\n return packageList.ToDictionary(p => p, p => false, StringComparer.OrdinalIgnoreCase);\n }\n }\n\n private async Task> GetCapabilitiesStatusBatchAsync(\n List capabilities\n )\n {\n var result = new Dictionary(StringComparer.OrdinalIgnoreCase);\n\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n\n // Get all installed capabilities in one query\n powerShell.AddScript(\n @\"\n try {\n $installedCapabilities = Get-WindowsCapability -Online | Where-Object { $_.State -eq 'Installed' }\n return $installedCapabilities | Select-Object -ExpandProperty Name\n }\n catch {\n return @()\n }\n \"\n );\n\n var task = Task.Run(() => powerShell.Invoke());\n if (await Task.WhenAny(task, Task.Delay(_powershellTimeout)) == task)\n {\n var installedCapabilities = (await task).ToList();\n\n // Check each capability against the installed list\n foreach (var capability in capabilities)\n {\n result[capability] = installedCapabilities.Any(c =>\n c.StartsWith(capability, StringComparison.OrdinalIgnoreCase)\n );\n }\n }\n else\n {\n _logService.LogWarning(\"Timeout getting installed capabilities\");\n foreach (var capability in capabilities)\n {\n result[capability] = false;\n }\n }\n\n return result;\n }\n\n private async Task> GetFeaturesStatusBatchAsync(List features)\n {\n var result = new Dictionary(StringComparer.OrdinalIgnoreCase);\n\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n\n // Get all enabled features in one query\n powerShell.AddScript(\n @\"\n try {\n $enabledFeatures = Get-WindowsOptionalFeature -Online | Where-Object { $_.State -eq 'Enabled' }\n return $enabledFeatures | Select-Object -ExpandProperty FeatureName\n }\n catch {\n return @()\n }\n \"\n );\n\n var task = Task.Run(() => powerShell.Invoke());\n if (await Task.WhenAny(task, Task.Delay(_powershellTimeout)) == task)\n {\n var enabledFeatures = (await task).ToList();\n\n // Check each feature against the enabled list\n foreach (var feature in features)\n {\n result[feature] = enabledFeatures.Any(f =>\n f.Equals(feature, StringComparison.OrdinalIgnoreCase)\n );\n }\n }\n else\n {\n _logService.LogWarning(\"Timeout getting enabled features\");\n foreach (var feature in features)\n {\n result[feature] = false;\n }\n }\n\n return result;\n }\n\n private async Task> GetStandardAppsStatusBatchAsync(List apps)\n {\n var result = new Dictionary(StringComparer.OrdinalIgnoreCase);\n\n using var powerShell = PowerShellFactory.CreateForAppxCommands(_logService);\n // No need to set execution policy as it's already done in the factory\n\n // Get all installed apps in one query using the same approach as the original PowerShell script\n powerShell.AddScript(\n @\"\n try {\n $installedApps = @(Get-AppxPackage | Select-Object -ExpandProperty Name)\n \n # Log the count for diagnostic purposes\n Write-Output \"\"Found $($installedApps.Count) installed apps\"\"\n \n # Return the array of names\n return $installedApps\n }\n catch {\n Write-Output \"\"Error getting installed apps: $_\"\"\n return @()\n }\n \"\n );\n\n var task = Task.Run(() => powerShell.Invoke());\n if (await Task.WhenAny(task, Task.Delay(_powershellTimeout)) == task)\n {\n var installedApps = (await task).ToList();\n\n // Check each app against the installed list\n foreach (var app in apps)\n {\n // First check if the main package is installed\n bool isInstalled = installedApps.Any(a =>\n a.Equals(app, StringComparison.OrdinalIgnoreCase)\n );\n\n // If not installed, check if it has subpackages and if any of them are installed\n if (!isInstalled)\n {\n var appDefinition = _windowsAppCatalog.WindowsApps.FirstOrDefault(a =>\n a.PackageName.Equals(app, StringComparison.OrdinalIgnoreCase)\n );\n\n if (appDefinition?.SubPackages != null && appDefinition.SubPackages.Length > 0)\n {\n foreach (var subPackage in appDefinition.SubPackages)\n {\n if (\n installedApps.Any(a =>\n a.Equals(subPackage, StringComparison.OrdinalIgnoreCase)\n )\n )\n {\n isInstalled = true;\n _logService.LogInformation(\n $\"App {app} is installed via subpackage {subPackage}\"\n );\n break;\n }\n }\n }\n }\n\n result[app] = isInstalled;\n }\n }\n else\n {\n _logService.LogWarning(\"Timeout getting installed apps\");\n foreach (var app in apps)\n {\n result[app] = false;\n }\n }\n\n return result;\n }\n\n /// \n public async Task IsEdgeInstalledAsync()\n {\n try\n {\n _logService.LogInformation(\"Checking if Microsoft Edge is installed\");\n\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n\n // Only check the specific registry key as requested\n powerShell.AddScript(\n @\"\n try {\n $result = Get-ItemProperty \"\"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\msedge.exe\"\" -ErrorAction SilentlyContinue\n return $result -ne $null\n }\n catch {\n Write-Output \"\"Error checking Edge registry key: $($_.Exception.Message)\"\"\n return $false\n }\n \"\n );\n\n var result = await ExecuteWithTimeoutAsync(powerShell, 15);\n bool isInstalled = result.FirstOrDefault();\n\n _logService.LogInformation($\"Edge registry check result: {isInstalled}\");\n return isInstalled;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking Edge installation\", ex);\n return false;\n }\n }\n\n /// \n public async Task IsOneDriveInstalledAsync()\n {\n try\n {\n _logService.LogInformation(\"Checking if OneDrive is installed\");\n\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n\n // Check the specific registry keys\n powerShell.AddScript(\n @\"\n try {\n # Check the two specific registry keys\n $hklmKey = Get-ItemProperty \"\"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneDriveSetup.exe\"\" -ErrorAction SilentlyContinue\n $hkcuKey = Get-ItemProperty \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneDriveSetup.exe\"\" -ErrorAction SilentlyContinue\n \n # Return true if either key exists\n return ($hklmKey -ne $null) -or ($hkcuKey -ne $null)\n }\n catch {\n Write-Output \"\"Error checking OneDrive registry: $($_.Exception.Message)\"\"\n return $false\n }\n \"\n );\n\n var result = await ExecuteWithTimeoutAsync(powerShell, 15);\n bool isInstalled = result.FirstOrDefault();\n\n _logService.LogInformation($\"OneDrive registry check result: {isInstalled}\");\n return isInstalled;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking OneDrive installation\", ex);\n return false;\n }\n }\n\n /// \n public async Task IsOneNoteInstalledAsync()\n {\n try\n {\n _logService.LogInformation(\"Checking if OneNote is installed\");\n\n // First, try a simpler, more direct approach without recursive searches\n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n\n // Use a more targeted, non-recursive approach for better performance and reliability\n powerShell.AddScript(\n @\"\n try {\n # Check for OneNote in common registry locations using direct paths instead of recursive searches\n \n # Check standard uninstall keys\n $installed = $false\n \n # Check for OneNote in standard uninstall locations\n $hklmKeys = Get-ChildItem \"\"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\"\" -ErrorAction SilentlyContinue | \n Get-ItemProperty -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like \"\"*OneNote*\"\" }\n if ($hklmKeys) { $installed = $true }\n \n $hkcuKeys = Get-ChildItem \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\"\" -ErrorAction SilentlyContinue | \n Get-ItemProperty -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like \"\"*OneNote*\"\" }\n if ($hkcuKeys) { $installed = $true }\n \n # Check for Wow6432Node registry keys (for 32-bit apps on 64-bit Windows)\n $hklmWowKeys = Get-ChildItem \"\"HKLM:\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\"\" -ErrorAction SilentlyContinue | \n Get-ItemProperty -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like \"\"*OneNote*\"\" }\n if ($hklmWowKeys) { $installed = $true }\n \n # Check for UWP/Store app version\n try {\n $appxPackage = Get-AppxPackage -Name Microsoft.Office.OneNote -ErrorAction SilentlyContinue\n if ($appxPackage) { $installed = $true }\n } catch {\n # Ignore errors with AppX commands\n }\n \n return $installed\n }\n catch {\n Write-Output \"\"Error checking OneNote registry: $($_.Exception.Message)\"\"\n return $false\n }\n \"\n );\n\n // Use a shorter timeout to prevent hanging\n var result = await ExecuteWithTimeoutAsync(powerShell, 10);\n bool isInstalled = result.FirstOrDefault();\n\n _logService.LogInformation($\"OneNote registry check result: {isInstalled}\");\n return isInstalled;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking OneNote installation\", ex);\n // Don't crash the application if OneNote check fails\n return false;\n }\n }\n\n // SetExecutionPolicy is now handled by PowerShellFactory\n\n /// \n /// Clears the installation status cache, forcing fresh checks on next query.\n /// Call this after installing or removing items.\n /// \n public void ClearInstallationStatusCache()\n {\n lock (_cacheLock)\n {\n _installationStatusCache.Clear();\n }\n }\n\n /// \n /// Executes a PowerShell command with a timeout.\n /// \n /// The type of result to return.\n /// The PowerShell instance.\n /// The timeout in seconds.\n /// The result of the PowerShell command.\n private async Task> ExecuteWithTimeoutAsync(\n PowerShell powerShell,\n int timeoutSeconds\n )\n {\n // Create a cancellation token source for the timeout\n using var cancellationTokenSource = new CancellationTokenSource();\n\n try\n {\n // Set up the timeout\n cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(timeoutSeconds));\n\n // Run the PowerShell command with cancellation support\n var task = Task.Run(\n () =>\n {\n try\n {\n // Check if cancellation was requested before starting\n if (cancellationTokenSource.Token.IsCancellationRequested)\n {\n _logService.LogWarning(\n \"PowerShell execution cancelled before starting\"\n );\n return new System.Collections.ObjectModel.Collection();\n }\n\n // Execute the PowerShell command\n return powerShell.Invoke();\n }\n catch (Exception innerEx)\n {\n _logService.LogError(\n $\"Error in PowerShell execution thread: {innerEx.Message}\",\n innerEx\n );\n return new System.Collections.ObjectModel.Collection();\n }\n },\n cancellationTokenSource.Token\n );\n\n // Wait for completion or timeout\n if (\n await Task.WhenAny(\n task,\n Task.Delay(TimeSpan.FromSeconds(timeoutSeconds), cancellationTokenSource.Token)\n ) == task\n )\n {\n // Task completed within timeout\n if (task.IsCompletedSuccessfully)\n {\n return await task;\n }\n else if (task.IsFaulted)\n {\n _logService.LogError(\n $\"PowerShell task faulted: {task.Exception?.Message}\",\n task.Exception\n );\n }\n else if (task.IsCanceled)\n {\n _logService.LogWarning(\"PowerShell task was cancelled\");\n }\n }\n else\n {\n // Task timed out, attempt to cancel it\n _logService.LogWarning(\n $\"PowerShell execution timed out after {timeoutSeconds} seconds\"\n );\n cancellationTokenSource.Cancel();\n\n // Try to stop the PowerShell pipeline if it's still running\n try\n {\n powerShell.Stop();\n }\n catch (Exception stopEx)\n {\n _logService.LogWarning($\"Error stopping PowerShell pipeline: {stopEx.Message}\");\n }\n }\n\n // Return empty collection if we reached here (timeout or error)\n return new System.Collections.ObjectModel.Collection();\n }\n catch (OperationCanceledException)\n {\n _logService.LogWarning(\n $\"PowerShell execution cancelled after {timeoutSeconds} seconds\"\n );\n return new System.Collections.ObjectModel.Collection();\n }\n catch (Exception ex)\n {\n _logService.LogError(\n $\"Error executing PowerShell command with timeout: {ex.Message}\",\n ex\n );\n return new System.Collections.ObjectModel.Collection();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/InstalledStatusToTextConverter.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Converters;\n\npublic class InstalledStatusToTextConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (bool)value ? \"Installed\" : \"Not Installed\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/ConfigurationItem.cs", "using System;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents an item in a configuration file.\n /// \n public class ConfigurationItem\n {\n /// \n /// Gets or sets the name of the item.\n /// \n public string Name { get; set; }\n\n /// \n /// Gets or sets the package name of the item.\n /// \n public string PackageName { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the item is selected.\n /// \n public bool IsSelected { get; set; }\n \n /// \n /// Gets or sets the type of control used for this item.\n /// \n public ControlType ControlType { get; set; } = ControlType.BinaryToggle;\n \n /// \n /// Gets or sets the selected value for ComboBox controls.\n /// This is used when ControlType is ComboBox.\n /// \n public string SelectedValue { get; set; }\n \n /// \n /// Gets or sets additional properties for the item.\n /// This can be used to store custom properties like wallpaper change preference.\n /// \n public Dictionary CustomProperties { get; set; } = new Dictionary();\n \n /// \n /// Ensures that SelectedValue is set for ComboBox controls based on SliderValue and available options.\n /// \n public void EnsureSelectedValueIsSet()\n {\n // Only process ComboBox controls with null SelectedValue\n if (ControlType == ControlType.ComboBox && string.IsNullOrEmpty(SelectedValue))\n {\n // For Power Plan\n if (Name?.Contains(\"Power Plan\") == true ||\n (CustomProperties.TryGetValue(\"Id\", out var id) && id?.ToString() == \"PowerPlanComboBox\"))\n {\n // Try to get the value from PowerPlanOptions if available\n if (CustomProperties.TryGetValue(\"PowerPlanOptions\", out var options) &&\n options is List powerPlanOptions &&\n powerPlanOptions.Count > 0 &&\n CustomProperties.TryGetValue(\"SliderValue\", out var sliderValue))\n {\n int index = Convert.ToInt32(sliderValue);\n if (index >= 0 && index < powerPlanOptions.Count)\n {\n SelectedValue = powerPlanOptions[index];\n }\n }\n // If PowerPlanOptions is not available, use default values\n else if (CustomProperties.TryGetValue(\"SliderValue\", out var sv))\n {\n int index = Convert.ToInt32(sv);\n string[] defaultOptions = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n if (index >= 0 && index < defaultOptions.Length)\n {\n SelectedValue = defaultOptions[index];\n }\n }\n \n // If we still don't have a SelectedValue, add PowerPlanOptions\n if (string.IsNullOrEmpty(SelectedValue) && CustomProperties.TryGetValue(\"SliderValue\", out var sv2))\n {\n int index = Convert.ToInt32(sv2);\n string[] defaultOptions = { \"Balanced\", \"High Performance\", \"Ultimate Performance\" };\n if (index >= 0 && index < defaultOptions.Length)\n {\n SelectedValue = defaultOptions[index];\n CustomProperties[\"PowerPlanOptions\"] = new List(defaultOptions);\n }\n }\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/InstalledStatusToColorConverter.cs", "using System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Converters;\n\npublic class InstalledStatusToColorConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (bool)value \n ? new SolidColorBrush(Color.FromRgb(0, 255, 60)) // Electric Green (#00FF3C) \n : new SolidColorBrush(Color.FromRgb(255, 40, 0)); // Ferrari Red (#FF2800)\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/ApplicationCloseService.cs", "using System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for handling application close functionality\n /// \n public class ApplicationCloseService : IApplicationCloseService\n {\n private readonly ILogService _logService;\n private readonly string _preferencesFilePath;\n \n /// \n /// Initializes a new instance of the class\n /// \n /// Service for logging\n public ApplicationCloseService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n \n // Set up the preferences file path\n _preferencesFilePath = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Config\",\n \"UserPreferences.json\"\n );\n }\n \n /// \n public async Task CloseApplicationWithSupportDialogAsync()\n {\n try\n {\n _logService.LogInformation(\"Closing application with support dialog check\");\n \n // Check if we should show the dialog\n bool showDialog = await ShouldShowSupportDialogAsync();\n \n if (showDialog)\n {\n _logService.LogInformation(\"Showing donation dialog\");\n \n // Show the dialog\n string supportMessage = \"Your support helps keep this project going!\";\n var dialog = await DonationDialog.ShowDonationDialogAsync(\n \"Support Winhance\",\n supportMessage,\n \"Click 'Yes' to show your support!\"\n );\n \n _logService.LogInformation($\"Donation dialog completed with result: {dialog?.DialogResult}, DontShowAgain: {dialog?.DontShowAgain}\");\n \n // Save the \"Don't show again\" preference if checked\n if (dialog != null && dialog.DontShowAgain)\n {\n _logService.LogInformation(\"Saving DontShowSupport preference\");\n await SaveDontShowSupportPreferenceAsync(true);\n }\n \n // Open the donation page if the user clicked Yes\n if (dialog?.DialogResult == true)\n {\n _logService.LogInformation(\"User clicked Yes, opening donation page\");\n try\n {\n var psi = new ProcessStartInfo\n {\n FileName = \"https://ko-fi.com/memstechtips\",\n UseShellExecute = true,\n };\n Process.Start(psi);\n _logService.LogInformation(\"Donation page opened successfully\");\n }\n catch (Exception openEx)\n {\n _logService.LogError($\"Error opening donation page: {openEx.Message}\", openEx);\n }\n }\n }\n else\n {\n _logService.LogInformation(\"Skipping donation dialog due to user preference\");\n }\n \n // Close the application\n _logService.LogInformation(\"Shutting down application\");\n Application.Current.Dispatcher.Invoke(() => Application.Current.Shutdown());\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in CloseApplicationWithSupportDialogAsync: {ex.Message}\", ex);\n \n // Fallback to direct application shutdown\n try\n {\n _logService.LogInformation(\"Falling back to Application.Current.Shutdown()\");\n Application.Current.Dispatcher.Invoke(() => Application.Current.Shutdown());\n }\n catch (Exception shutdownEx)\n {\n _logService.LogError($\"Error shutting down application: {shutdownEx.Message}\", shutdownEx);\n \n // Last resort\n Environment.Exit(0);\n }\n }\n }\n \n /// \n public async Task ShouldShowSupportDialogAsync()\n {\n try\n {\n _logService.LogInformation($\"Checking preferences file: {_preferencesFilePath}\");\n \n // Check if the preference file exists and contains the DontShowSupport setting\n if (File.Exists(_preferencesFilePath))\n {\n string json = await File.ReadAllTextAsync(_preferencesFilePath);\n _logService.LogInformation($\"Preferences file content: {json}\");\n \n // Check if the preference is set to true\n if (\n json.Contains(\"\\\"DontShowSupport\\\": true\")\n || json.Contains(\"\\\"DontShowSupport\\\":true\")\n || json.Contains(\"\\\"DontShowSupport\\\": 1\")\n || json.Contains(\"\\\"DontShowSupport\\\":1\")\n )\n {\n _logService.LogInformation(\"DontShowSupport is set to true, skipping dialog\");\n return false;\n }\n }\n \n // Default to showing the dialog\n return true;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking donation dialog preference: {ex.Message}\", ex);\n // Default to showing the dialog if there's an error\n return true;\n }\n }\n \n /// \n public async Task SaveDontShowSupportPreferenceAsync(bool dontShow)\n {\n try\n {\n // Get the preferences directory path\n string preferencesDir = Path.GetDirectoryName(_preferencesFilePath);\n \n // Create the directory if it doesn't exist\n if (!Directory.Exists(preferencesDir))\n {\n Directory.CreateDirectory(preferencesDir);\n }\n \n // Create or update the preferences file\n string json = \"{}\";\n if (File.Exists(_preferencesFilePath))\n {\n json = await File.ReadAllTextAsync(_preferencesFilePath);\n }\n \n // Simple JSON manipulation (not ideal but should work for this case)\n if (json == \"{}\")\n {\n json = \"{ \\\"DontShowSupport\\\": \" + (dontShow ? \"true\" : \"false\") + \" }\";\n }\n else if (json.Contains(\"\\\"DontShowSupport\\\":\") || json.Contains(\"\\\"DontShowSupport\\\": \"))\n {\n json = json.Replace(\"\\\"DontShowSupport\\\": true\", \"\\\"DontShowSupport\\\": \" + (dontShow ? \"true\" : \"false\"));\n json = json.Replace(\"\\\"DontShowSupport\\\": false\", \"\\\"DontShowSupport\\\": \" + (dontShow ? \"true\" : \"false\"));\n json = json.Replace(\"\\\"DontShowSupport\\\":true\", \"\\\"DontShowSupport\\\":\" + (dontShow ? \"true\" : \"false\"));\n json = json.Replace(\"\\\"DontShowSupport\\\":false\", \"\\\"DontShowSupport\\\":\" + (dontShow ? \"true\" : \"false\"));\n }\n else\n {\n // Remove the closing brace\n json = json.TrimEnd('}');\n // Add a comma if there are other properties\n if (json.TrimEnd().EndsWith(\"}\"))\n {\n json += \",\";\n }\n // Add the new property and closing brace\n json += \" \\\"DontShowSupport\\\": \" + (dontShow ? \"true\" : \"false\") + \" }\";\n }\n \n // Write the updated JSON back to the file\n await File.WriteAllTextAsync(_preferencesFilePath, json);\n _logService.LogInformation($\"Successfully saved DontShowSupport preference: {dontShow}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error saving DontShowSupport preference: {ex.Message}\", ex);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppRemovalService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service for removing standard applications from the system.\n/// \npublic class AppRemovalService : IAppRemovalService\n{\n private readonly ILogService _logService;\n private readonly ISpecialAppHandlerService _specialAppHandlerService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IScriptTemplateProvider _scriptTemplateProvider;\n private readonly ISystemServices _systemServices;\n private readonly IRegistryService _registryService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The special app handler service.\n /// The app discovery service.\n /// The script template provider.\n /// The system services.\n public AppRemovalService(\n ILogService logService,\n ISpecialAppHandlerService specialAppHandlerService,\n IAppDiscoveryService appDiscoveryService,\n IScriptTemplateProvider scriptTemplateProvider,\n ISystemServices systemServices,\n IRegistryService registryService)\n {\n _logService = logService;\n _specialAppHandlerService = specialAppHandlerService;\n _appDiscoveryService = appDiscoveryService;\n _scriptTemplateProvider = scriptTemplateProvider;\n _systemServices = systemServices;\n _registryService = registryService;\n }\n\n /// \n public async Task> RemoveAppAsync(\n AppInfo appInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (appInfo == null)\n {\n throw new ArgumentNullException(nameof(appInfo));\n }\n // Call the other overload and return its result\n return await RemoveAppAsync(appInfo.PackageName, progress, cancellationToken);\n }\n\n /// \n /// Removes an application by package name.\n /// \n /// The package name of the application to remove.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n public async Task> RemoveAppAsync(\n string packageName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n try\n {\n _logService.LogInformation($\"Removing app: {packageName}\");\n \n // Get all standard apps to find the app definition\n var allRemovableApps = (await _appDiscoveryService.GetStandardAppsAsync()).ToList();\n \n // Find the app definition that matches the current app\n var appDefinition = allRemovableApps.FirstOrDefault(a =>\n a.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase));\n \n // Get subpackages if any\n string[]? subPackages = appDefinition?.SubPackages;\n if (subPackages != null && subPackages.Length > 0)\n {\n _logService.LogInformation($\"App {packageName} has {subPackages.Length} subpackages that will also be removed\");\n }\n \n // Handle standard app removal\n using var powerShell = PowerShellFactory.CreateForAppxCommands(_logService, _systemServices);\n // No need to set execution policy as it's already done in the factory\n \n powerShell.AddScript(@\"\n param($packageName, $subPackages)\n try {\n $success = $true\n \n # Remove the main app package\n $packagesToRemove = Get-AppxPackage | Where-Object { $_.Name -eq $packageName }\n \n if ($packagesToRemove -ne $null -and $packagesToRemove.Count -gt 0) {\n $packagesToRemove | ForEach-Object {\n Write-Output \"\"Removing package: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }\n }\n \n # Also remove the provisioned package\n $provPackages = Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq $packageName }\n \n if ($provPackages -ne $null -and $provPackages.Count -gt 0) {\n $provPackages | ForEach-Object {\n Write-Output \"\"Removing provisioned package: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }\n }\n \n # If we have subpackages, remove those too\n if ($subPackages -ne $null) {\n foreach ($subPackage in $subPackages) {\n Write-Output \"\"Processing subpackage: $subPackage\"\"\n \n # Remove the subpackage\n $subPackagesToRemove = Get-AppxPackage | Where-Object { $_.Name -eq $subPackage }\n \n if ($subPackagesToRemove -ne $null -and $subPackagesToRemove.Count -gt 0) {\n $subPackagesToRemove | ForEach-Object {\n Write-Output \"\"Removing subpackage: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }\n }\n \n # Also remove the provisioned subpackage\n $subProvPackages = Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq $subPackage }\n \n if ($subProvPackages -ne $null -and $subProvPackages.Count -gt 0) {\n $subProvPackages | ForEach-Object {\n Write-Output \"\"Removing provisioned subpackage: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }\n }\n }\n }\n \n # Check if the main package is still installed\n $stillInstalled = Get-AppxPackage | Where-Object { $_.Name -eq $packageName }\n $mainPackageRemoved = ($stillInstalled -eq $null -or $stillInstalled.Count -eq 0)\n \n # Check if any subpackages are still installed\n $subPackagesRemoved = $true\n if ($subPackages -ne $null) {\n foreach ($subPackage in $subPackages) {\n $stillInstalledSub = Get-AppxPackage | Where-Object { $_.Name -eq $subPackage }\n if ($stillInstalledSub -ne $null -and $stillInstalledSub.Count -gt 0) {\n $subPackagesRemoved = $false\n Write-Output \"\"Subpackage $subPackage is still installed\"\"\n break\n }\n }\n }\n \n # Return true only if both main package and all subpackages are removed\n return $mainPackageRemoved -and $subPackagesRemoved\n }\n catch {\n Write-Error \"\"Error removing package: $_\"\"\n return $false\n }\n \");\n powerShell.AddParameter(\"packageName\", packageName);\n powerShell.AddParameter(\"subPackages\", subPackages);\n \n var result = await Task.Run(() => powerShell.Invoke());\n var success = result.FirstOrDefault();\n \n if (!success)\n {\n _logService.LogError($\"Failed to remove app: {packageName}\");\n }\n else\n {\n _logService.LogSuccess($\"Successfully removed app: {packageName}\");\n \n // Apply registry settings for this app if it has any\n try\n {\n // If we found the app definition and it has registry settings, apply them\n if (appDefinition?.RegistrySettings != null && appDefinition.RegistrySettings.Length > 0)\n {\n _logService.LogInformation($\"Found {appDefinition.RegistrySettings.Length} registry settings for {packageName}\");\n var registrySettings = appDefinition.RegistrySettings.ToList();\n \n // Apply the registry settings\n var settingsApplied = await ApplyRegistrySettingsAsync(registrySettings);\n if (settingsApplied)\n {\n _logService.LogSuccess($\"Successfully applied registry settings for {packageName}\");\n }\n else\n {\n _logService.LogWarning($\"Some registry settings for {packageName} could not be applied\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error applying registry settings for {packageName}\", ex);\n }\n }\n // Return success status after handling registry settings\n return success\n ? OperationResult.Succeeded(true)\n : OperationResult.Failed($\"Failed to remove app: {packageName}\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing app: {packageName}\", ex);\n // Return failure with exception details\n return OperationResult.Failed($\"Error removing app: {packageName}\", ex);\n }\n }\n\n /// \n public Task> GenerateRemovalScriptAsync(AppInfo appInfo)\n {\n if (appInfo == null)\n {\n throw new ArgumentNullException(nameof(appInfo));\n }\n\n try\n {\n // Generate a script for removing the app using the pipeline approach\n string script = $@\"\n# Script to remove {appInfo.Name} ({appInfo.PackageName})\n# Generated by Winhance on {DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\")}\n\ntry {{\n # Remove the main app package\n $packagesToRemove = Get-AppxPackage | Where-Object {{ $_.Name -eq '{appInfo.PackageName}' }}\n \n if ($packagesToRemove -ne $null -and $packagesToRemove.Count -gt 0) {{\n $packagesToRemove | ForEach-Object {{\n Write-Output \"\"Removing package: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }}\n }}\n \n # Also remove the provisioned package\n $provPackages = Get-AppxProvisionedPackage -Online | Where-Object {{ $_.DisplayName -eq '{appInfo.PackageName}' }}\n \n if ($provPackages -ne $null -and $provPackages.Count -gt 0) {{\n $provPackages | ForEach-Object {{\n Write-Output \"\"Removing provisioned package: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }}\n }}\";\n\n // Add subpackage removal if the app has subpackages\n if (appInfo.SubPackages != null && appInfo.SubPackages.Length > 0)\n {\n script += $@\"\n \n # Remove subpackages\";\n\n foreach (var subPackage in appInfo.SubPackages)\n {\n script += $@\"\n Write-Output \"\"Processing subpackage: {subPackage}\"\"\n \n # Remove the subpackage\n $subPackagesToRemove = Get-AppxPackage | Where-Object {{ $_.Name -eq '{subPackage}' }}\n \n if ($subPackagesToRemove -ne $null -and $subPackagesToRemove.Count -gt 0) {{\n $subPackagesToRemove | ForEach-Object {{\n Write-Output \"\"Removing subpackage: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }}\n }}\n \n # Also remove the provisioned subpackage\n $subProvPackages = Get-AppxProvisionedPackage -Online | Where-Object {{ $_.DisplayName -eq '{subPackage}' }}\n \n if ($subProvPackages -ne $null -and $subProvPackages.Count -gt 0) {{\n $subProvPackages | ForEach-Object {{\n Write-Output \"\"Removing provisioned subpackage: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }}\n }}\";\n }\n }\n\n // Close the try-catch block\n script += $@\"\n}} catch {{\n # Error handling without output\n}}\n\";\n return Task.FromResult(OperationResult.Succeeded(script));\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error generating removal script for {appInfo.PackageName}\", ex);\n return Task.FromResult(OperationResult.Failed($\"Error generating removal script: {ex.Message}\", ex));\n }\n }\n\n\n /// \n public async Task> RemoveAppsInBatchAsync(\n List apps)\n {\n if (apps == null)\n {\n throw new ArgumentNullException(nameof(apps));\n }\n\n return await RemoveAppsInBatchAsync(apps.Select(a => a.PackageName).ToList());\n }\n\n /// \n public async Task> RemoveAppsInBatchAsync(\n List packageNames)\n {\n var results = new List<(string Name, bool Success, string? Error)>();\n \n try\n {\n _logService.LogInformation($\"Starting batch removal of {packageNames.Count} apps\");\n \n using var powerShell = PowerShellFactory.CreateForAppxCommands(_logService, _systemServices);\n // No need to set execution policy as it's already done in the factory\n \n // Get all standard apps to find app definitions (do this once for the batch)\n var allApps = (await _appDiscoveryService.GetStandardAppsAsync()).ToList();\n \n foreach (var packageName in packageNames)\n {\n try\n {\n _logService.LogInformation($\"Removing app: {packageName}\");\n \n // Find the app definition that matches the current app\n var appDefinition = allApps.FirstOrDefault(a =>\n a.PackageName.Equals(packageName, StringComparison.OrdinalIgnoreCase));\n \n // Get subpackages if any\n string[]? subPackages = appDefinition?.SubPackages;\n if (subPackages != null && subPackages.Length > 0)\n {\n _logService.LogInformation($\"App {packageName} has {subPackages.Length} subpackages that will also be removed\");\n }\n \n powerShell.Commands.Clear();\n \n powerShell.AddScript(@\"\n param($packageName, $subPackages)\n try {\n $success = $true\n \n # Remove the main app package\n $packagesToRemove = Get-AppxPackage | Where-Object { $_.Name -eq $packageName }\n \n if ($packagesToRemove -ne $null -and $packagesToRemove.Count -gt 0) {\n $packagesToRemove | ForEach-Object {\n Write-Output \"\"Removing package: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }\n }\n \n # Also remove the provisioned package\n $provPackages = Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq $packageName }\n \n if ($provPackages -ne $null -and $provPackages.Count -gt 0) {\n $provPackages | ForEach-Object {\n Write-Output \"\"Removing provisioned package: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }\n }\n \n # If we have subpackages, remove those too\n if ($subPackages -ne $null) {\n foreach ($subPackage in $subPackages) {\n Write-Output \"\"Processing subpackage: $subPackage\"\"\n \n # Remove the subpackage\n $subPackagesToRemove = Get-AppxPackage | Where-Object { $_.Name -eq $subPackage }\n \n if ($subPackagesToRemove -ne $null -and $subPackagesToRemove.Count -gt 0) {\n $subPackagesToRemove | ForEach-Object {\n Write-Output \"\"Removing subpackage: $($_.PackageFullName)\"\"\n Remove-AppxPackage -Package $_.PackageFullName -ErrorAction SilentlyContinue\n }\n }\n \n # Also remove the provisioned subpackage\n $subProvPackages = Get-AppxProvisionedPackage -Online | Where-Object { $_.DisplayName -eq $subPackage }\n \n if ($subProvPackages -ne $null -and $subProvPackages.Count -gt 0) {\n $subProvPackages | ForEach-Object {\n Write-Output \"\"Removing provisioned subpackage: $($_.PackageName)\"\"\n Remove-AppxProvisionedPackage -Online -PackageName $_.PackageName -ErrorAction SilentlyContinue\n }\n }\n }\n }\n \n # Check if the main package is still installed\n $stillInstalled = Get-AppxPackage | Where-Object { $_.Name -eq $packageName }\n $mainPackageRemoved = ($stillInstalled -eq $null -or $stillInstalled.Count -eq 0)\n \n # Check if any subpackages are still installed\n $subPackagesRemoved = $true\n if ($subPackages -ne $null) {\n foreach ($subPackage in $subPackages) {\n $stillInstalledSub = Get-AppxPackage | Where-Object { $_.Name -eq $subPackage }\n if ($stillInstalledSub -ne $null -and $stillInstalledSub.Count -gt 0) {\n $subPackagesRemoved = $false\n Write-Output \"\"Subpackage $subPackage is still installed\"\"\n break\n }\n }\n }\n \n # Return true only if both main package and all subpackages are removed\n return $mainPackageRemoved -and $subPackagesRemoved\n }\n catch {\n Write-Error \"\"Error removing package: $_\"\"\n return $false\n }\n \");\n powerShell.AddParameter(\"packageName\", packageName);\n powerShell.AddParameter(\"subPackages\", subPackages);\n \n var result = await Task.Run(() => powerShell.Invoke());\n var success = result.FirstOrDefault();\n results.Add((packageName, success, success ? null : \"Failed to remove app\"));\n _logService.LogInformation($\"Removal of {packageName} {(success ? \"succeeded\" : \"failed\")}\");\n \n // Apply registry settings for this app if it has any and removal was successful\n if (success)\n {\n try\n {\n // If we found the app definition and it has registry settings, apply them\n if (appDefinition?.RegistrySettings != null && appDefinition.RegistrySettings.Length > 0)\n {\n _logService.LogInformation($\"Found {appDefinition.RegistrySettings.Length} registry settings for {packageName}\");\n var registrySettings = appDefinition.RegistrySettings.ToList();\n \n // Apply the registry settings\n var settingsApplied = await ApplyRegistrySettingsAsync(registrySettings);\n if (settingsApplied)\n {\n _logService.LogSuccess($\"Successfully applied registry settings for {packageName}\");\n }\n else\n {\n _logService.LogWarning($\"Some registry settings for {packageName} could not be applied\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error applying registry settings for {packageName}\", ex);\n }\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing app {packageName}\", ex);\n results.Add((packageName, false, $\"Error: {ex.Message}\"));\n }\n }\n \n return results;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error removing standard apps\", ex);\n return packageNames.Select(p => (p, false, $\"Error: {ex.Message}\")).ToList();\n }\n }\n\n /// \n public async Task ApplyRegistrySettingsAsync(List settings)\n {\n try\n {\n _logService.LogInformation($\"Applying {settings.Count} registry settings\");\n \n bool allSucceeded = true;\n \n foreach (var setting in settings)\n {\n try\n {\n _logService.LogInformation($\"Applying registry setting: {setting.Path}\\\\{setting.Name}\");\n \n bool success;\n if (setting.Value == null)\n {\n // If value is null, delete the registry value\n _logService.LogInformation($\"Deleting registry value: {setting.Path}\\\\{setting.Name}\");\n success = _registryService.DeleteValue(setting.Path, setting.Name);\n }\n else\n {\n // If value is not null, set the registry value\n // First ensure the key exists\n if (!_registryService.KeyExists(setting.Path))\n {\n _registryService.CreateKey(setting.Path);\n }\n \n // Set the registry value\n success = _registryService.SetValue(setting.Path, setting.Name, setting.Value, setting.ValueKind);\n }\n \n if (!success)\n {\n _logService.LogError($\"Failed to apply registry setting: {setting.Path}\\\\{setting.Name}\");\n allSucceeded = false;\n }\n else\n {\n _logService.LogSuccess($\"Successfully applied registry setting: {setting.Path}\\\\{setting.Name}\");\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error applying registry setting: {setting.Path}\\\\{setting.Name}\", ex);\n allSucceeded = false;\n }\n }\n \n return allSucceeded;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error applying registry settings\", ex);\n return false;\n }\n }\n\n // SetExecutionPolicy is now handled by PowerShellFactory\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ViewModelRefresher.cs", "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Threading;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for refreshing view models after configuration changes.\n /// \n public class ViewModelRefresher : IViewModelRefresher\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public ViewModelRefresher(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Refreshes a view model after configuration changes.\n /// \n /// The view model to refresh.\n /// A task representing the asynchronous operation.\n public async Task RefreshViewModelAsync(object viewModel)\n {\n try\n {\n // Special handling for OptimizeViewModel\n if (viewModel is Winhance.WPF.Features.Optimize.ViewModels.OptimizeViewModel optimizeViewModel)\n {\n _logService.Log(LogLevel.Debug, \"Refreshing OptimizeViewModel and its child view models\");\n \n // Refresh child view models first\n var childViewModels = new object[]\n {\n optimizeViewModel.GamingandPerformanceOptimizationsViewModel,\n optimizeViewModel.PrivacyOptimizationsViewModel,\n optimizeViewModel.UpdateOptimizationsViewModel,\n optimizeViewModel.PowerSettingsViewModel,\n optimizeViewModel.WindowsSecuritySettingsViewModel,\n optimizeViewModel.ExplorerOptimizationsViewModel,\n optimizeViewModel.NotificationOptimizationsViewModel,\n optimizeViewModel.SoundOptimizationsViewModel\n };\n \n foreach (var childViewModel in childViewModels)\n {\n if (childViewModel != null)\n {\n // Try to refresh each child view model\n await RefreshChildViewModelAsync(childViewModel);\n }\n }\n \n // Then reload the main view model's items to reflect changes in child view models\n await optimizeViewModel.LoadItemsAsync();\n \n // Notify UI of changes using a safer approach\n try\n {\n // Try to find a method that takes a string parameter\n var methods = optimizeViewModel.GetType().GetMethods(\n System.Reflection.BindingFlags.Public |\n System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance)\n .Where(m => (m.Name == \"RaisePropertyChanged\" || m.Name == \"OnPropertyChanged\") &&\n m.GetParameters().Length == 1 &&\n m.GetParameters()[0].ParameterType == typeof(string))\n .ToList();\n \n if (methods.Any())\n {\n var method = methods.First();\n // Refresh key properties\n // Execute property change notifications on the UI thread\n ExecuteOnUIThread(() => {\n method.Invoke(optimizeViewModel, new object[] { \"Items\" });\n method.Invoke(optimizeViewModel, new object[] { \"IsInitialized\" });\n method.Invoke(optimizeViewModel, new object[] { \"IsLoading\" });\n _logService.Log(LogLevel.Debug, $\"Refreshed OptimizeViewModel properties using {method.Name} on UI thread\");\n });\n }\n else\n {\n // If no suitable method is found, try using RefreshCommand\n var refreshCommand = optimizeViewModel.GetType().GetProperty(\"RefreshCommand\")?.GetValue(optimizeViewModel) as System.Windows.Input.ICommand;\n if (refreshCommand != null && refreshCommand.CanExecute(null))\n {\n ExecuteOnUIThread(() => {\n refreshCommand.Execute(null);\n _logService.Log(LogLevel.Debug, \"Refreshed OptimizeViewModel using RefreshCommand on UI thread\");\n });\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error refreshing OptimizeViewModel: {ex.Message}\");\n }\n \n return;\n }\n \n // Standard refresh logic for other view models\n // Try multiple refresh methods in order of preference\n \n // 1. First try RefreshCommand if available\n var refreshCommandProperty = viewModel.GetType().GetProperty(\"RefreshCommand\");\n if (refreshCommandProperty != null)\n {\n var refreshCommand = refreshCommandProperty.GetValue(viewModel) as System.Windows.Input.ICommand;\n if (refreshCommand != null && refreshCommand.CanExecute(null))\n {\n ExecuteOnUIThread(() => {\n refreshCommand.Execute(null);\n _logService.Log(LogLevel.Debug, $\"Refreshed {viewModel.GetType().Name} using RefreshCommand on UI thread\");\n });\n return;\n }\n }\n \n // 2. Try RaisePropertyChanged for the Items property if the view model implements INotifyPropertyChanged\n if (viewModel is System.ComponentModel.INotifyPropertyChanged)\n {\n try\n {\n // Use a safer approach to find property changed methods\n var methods = viewModel.GetType().GetMethods(\n System.Reflection.BindingFlags.Public |\n System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance)\n .Where(m => (m.Name == \"RaisePropertyChanged\" || m.Name == \"OnPropertyChanged\") &&\n m.GetParameters().Length == 1 &&\n m.GetParameters()[0].ParameterType == typeof(string))\n .ToList();\n \n if (methods.Any())\n {\n var method = methods.First();\n ExecuteOnUIThread(() => {\n method.Invoke(viewModel, new object[] { \"Items\" });\n _logService.Log(LogLevel.Debug, $\"Refreshed {viewModel.GetType().Name} using {method.Name} on UI thread\");\n });\n return;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error finding property changed method: {ex.Message}\");\n // Continue with other refresh methods\n }\n }\n \n // 3. Try LoadItemsAsync method\n var loadItemsMethod = viewModel.GetType().GetMethod(\"LoadItemsAsync\");\n if (loadItemsMethod != null)\n {\n await (Task)loadItemsMethod.Invoke(viewModel, null);\n return;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error refreshing UI: {ex.Message}\");\n }\n }\n\n /// \n /// Refreshes a child view model after configuration changes.\n /// \n /// The child view model to refresh.\n /// A task representing the asynchronous operation.\n public async Task RefreshChildViewModelAsync(object childViewModel)\n {\n try\n {\n // Try to find and call CheckSettingStatusesAsync method\n var checkStatusMethod = childViewModel.GetType().GetMethod(\"CheckSettingStatusesAsync\");\n if (checkStatusMethod != null)\n {\n await (Task)checkStatusMethod.Invoke(childViewModel, null);\n _logService.Log(LogLevel.Debug, $\"Called CheckSettingStatusesAsync on {childViewModel.GetType().Name}\");\n }\n \n // Try to notify property changes using a safer approach\n if (childViewModel is System.ComponentModel.INotifyPropertyChanged)\n {\n try\n {\n // Use a safer approach to find the right PropertyChanged event\n var propertyChangedEvent = childViewModel.GetType().GetEvent(\"PropertyChanged\");\n if (propertyChangedEvent != null)\n {\n // Try to find a method that raises the PropertyChanged event\n // Look for a method that takes a string parameter first\n var methods = childViewModel.GetType().GetMethods(\n System.Reflection.BindingFlags.Public |\n System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance)\n .Where(m => (m.Name == \"RaisePropertyChanged\" || m.Name == \"OnPropertyChanged\") &&\n m.GetParameters().Length == 1 &&\n m.GetParameters()[0].ParameterType == typeof(string))\n .ToList();\n \n if (methods.Any())\n {\n var method = methods.First();\n // Refresh Settings property and IsSelected property on UI thread\n ExecuteOnUIThread(() => {\n method.Invoke(childViewModel, new object[] { \"Settings\" });\n method.Invoke(childViewModel, new object[] { \"IsSelected\" });\n _logService.Log(LogLevel.Debug, $\"Refreshed properties on {childViewModel.GetType().Name} using {method.Name} on UI thread\");\n });\n }\n else\n {\n // If no method with string parameter is found, try to find a method that takes PropertyChangedEventArgs\n var refreshCommand = childViewModel.GetType().GetProperty(\"RefreshCommand\")?.GetValue(childViewModel) as System.Windows.Input.ICommand;\n if (refreshCommand != null && refreshCommand.CanExecute(null))\n {\n ExecuteOnUIThread(() => {\n refreshCommand.Execute(null);\n _logService.Log(LogLevel.Debug, $\"Refreshed {childViewModel.GetType().Name} using RefreshCommand on UI thread\");\n });\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error refreshing child view model properties: {ex.Message}\");\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Debug, $\"Error refreshing child view model: {ex.Message}\");\n }\n }\n \n /// \n /// Executes an action on the UI thread.\n /// \n /// The action to execute.\n private void ExecuteOnUIThread(Action action)\n {\n try\n {\n // Check if we have access to a dispatcher\n if (Application.Current != null && Application.Current.Dispatcher != null)\n {\n // Check if we're already on the UI thread\n if (Application.Current.Dispatcher.CheckAccess())\n {\n // We're on the UI thread, execute directly\n action();\n }\n else\n {\n // We're not on the UI thread, invoke on the UI thread\n Application.Current.Dispatcher.Invoke(action, DispatcherPriority.Background);\n }\n }\n else\n {\n // No dispatcher available, execute directly\n action();\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error executing action on UI thread: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n \n // Try to execute the action directly as a fallback\n try\n {\n action();\n }\n catch (Exception innerEx)\n {\n _logService.Log(LogLevel.Error, $\"Error executing action directly: {innerEx.Message}\");\n }\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/JsonParameterSerializer.cs", "using System;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Text;\nusing System.Text.Json;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n public class JsonParameterSerializer : IParameterSerializer\n {\n private readonly JsonSerializerOptions _options = new()\n {\n PropertyNameCaseInsensitive = true,\n WriteIndented = false\n };\n\n public int MaxParameterSize { get; set; } = 1024 * 1024; // 1MB default\n public bool UseCompression { get; set; } = true;\n\n public string Serialize(object parameter)\n {\n if (parameter == null) return null;\n \n var json = JsonSerializer.Serialize(parameter, _options);\n \n if (UseCompression && json.Length > 1024) // Compress if over 1KB\n {\n var bytes = Encoding.UTF8.GetBytes(json);\n using var output = new MemoryStream();\n using (var gzip = new GZipStream(output, CompressionMode.Compress))\n {\n gzip.Write(bytes, 0, bytes.Length);\n }\n return Convert.ToBase64String(output.ToArray());\n }\n \n return json;\n }\n\n // Corrected signature to match IParameterSerializer\n public object Deserialize(Type targetType, string value)\n {\n if (string.IsNullOrWhiteSpace(value)) return null;\n\n try\n {\n if (IsCompressed(value)) // Use 'value' parameter\n {\n var bytes = Convert.FromBase64String(value); // Use 'value' parameter\n using var input = new MemoryStream(bytes);\n using var output = new MemoryStream();\n using (var gzip = new GZipStream(input, CompressionMode.Decompress))\n {\n gzip.CopyTo(output);\n }\n var json = Encoding.UTF8.GetString(output.ToArray());\n return JsonSerializer.Deserialize(json, targetType, _options);\n }\n\n return JsonSerializer.Deserialize(value, targetType, _options); // Use 'value' parameter\n }\n catch (JsonException ex)\n {\n throw new InvalidOperationException(\"Failed to deserialize parameter\", ex);\n }\n catch (Exception ex) when (ex is FormatException || ex is InvalidDataException)\n {\n throw new InvalidOperationException(\"Invalid compressed parameter format\", ex);\n }\n }\n\n public T Deserialize(string serialized)\n {\n if (string.IsNullOrWhiteSpace(serialized)) return default;\n\n try\n {\n if (IsCompressed(serialized))\n {\n var bytes = Convert.FromBase64String(serialized);\n using var input = new MemoryStream(bytes);\n using var output = new MemoryStream();\n using (var gzip = new GZipStream(input, CompressionMode.Decompress))\n {\n gzip.CopyTo(output);\n }\n var json = Encoding.UTF8.GetString(output.ToArray());\n return JsonSerializer.Deserialize(json, _options);\n }\n \n return JsonSerializer.Deserialize(serialized, _options);\n }\n catch (JsonException ex)\n {\n throw new InvalidOperationException($\"Failed to deserialize parameter to type {typeof(T).Name}\", ex);\n }\n catch (Exception ex) when (ex is FormatException || ex is InvalidDataException)\n {\n throw new InvalidOperationException(\"Invalid compressed parameter format\", ex);\n }\n }\n\n private bool IsCompressed(string input)\n {\n if (string.IsNullOrEmpty(input)) return false;\n try\n {\n // Simple check - compressed data is base64 and starts with H4sI (GZip magic number)\n return input.Length > 4 && \n input.StartsWith(\"H4sI\") && \n input.Length % 4 == 0;\n }\n catch\n {\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/UacSettingsService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading.Tasks;\nusing Newtonsoft.Json;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for managing UAC settings persistence.\n /// \n public class UacSettingsService : IUacSettingsService\n {\n private const string CustomUacSettingsKey = \"CustomUacSettings\";\n private readonly UserPreferencesService _userPreferencesService;\n private readonly ILogService _logService;\n \n // Cache for custom UAC settings during the current session\n private CustomUacSettings _cachedSettings;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The user preferences service.\n /// The log service.\n public UacSettingsService(UserPreferencesService userPreferencesService, ILogService logService)\n {\n _userPreferencesService = userPreferencesService ?? throw new ArgumentNullException(nameof(userPreferencesService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Saves custom UAC settings.\n /// \n /// The ConsentPromptBehaviorAdmin registry value.\n /// The PromptOnSecureDesktop registry value.\n /// A task representing the asynchronous operation.\n public async Task SaveCustomUacSettingsAsync(int consentPromptValue, int secureDesktopValue)\n {\n try\n {\n // Create a CustomUacSettings object\n var settings = new CustomUacSettings(consentPromptValue, secureDesktopValue);\n \n // Cache the settings\n _cachedSettings = settings;\n \n // Save to user preferences\n await _userPreferencesService.SetPreferenceAsync(CustomUacSettingsKey, settings);\n \n _logService.Log(LogLevel.Info, \n $\"Saved custom UAC settings: ConsentPrompt={consentPromptValue}, SecureDesktop={secureDesktopValue}\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving custom UAC settings: {ex.Message}\");\n }\n }\n\n /// \n /// Loads custom UAC settings.\n /// \n /// A CustomUacSettings object if settings exist, null otherwise.\n public async Task LoadCustomUacSettingsAsync()\n {\n try\n {\n // Try to get from cache first\n if (_cachedSettings != null)\n {\n return _cachedSettings;\n }\n \n // Try to load from preferences\n var settings = await _userPreferencesService.GetPreferenceAsync(CustomUacSettingsKey, default(CustomUacSettings));\n if (settings != null)\n {\n // Cache the settings\n _cachedSettings = settings;\n return settings;\n }\n \n return null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading custom UAC settings: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Checks if custom UAC settings exist.\n /// \n /// True if custom settings exist, false otherwise.\n public async Task HasCustomUacSettingsAsync()\n {\n try\n {\n // Check cache first\n if (_cachedSettings != null)\n {\n return true;\n }\n \n // Check user preferences\n var settings = await _userPreferencesService.GetPreferenceAsync(CustomUacSettingsKey, null);\n return settings != null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking for custom UAC settings: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Gets custom UAC settings if they exist.\n /// \n /// The ConsentPromptBehaviorAdmin registry value.\n /// The PromptOnSecureDesktop registry value.\n /// True if custom settings were retrieved, false otherwise.\n public bool TryGetCustomUacValues(out int consentPromptValue, out int secureDesktopValue)\n {\n // Initialize out parameters\n consentPromptValue = 0;\n secureDesktopValue = 0;\n \n try\n {\n // Check cache first\n if (_cachedSettings != null)\n {\n consentPromptValue = _cachedSettings.ConsentPromptValue;\n secureDesktopValue = _cachedSettings.SecureDesktopValue;\n return true;\n }\n \n // Try to load from preferences (completely synchronously)\n string preferencesFilePath = GetPreferencesFilePath();\n if (File.Exists(preferencesFilePath))\n {\n try\n {\n string json = File.ReadAllText(preferencesFilePath);\n var preferences = JsonConvert.DeserializeObject>(json);\n \n if (preferences != null && preferences.ContainsKey(CustomUacSettingsKey))\n {\n var settingsToken = preferences[CustomUacSettingsKey];\n var settings = JsonConvert.DeserializeObject(settingsToken.ToString());\n \n if (settings != null)\n {\n // Cache the settings\n _cachedSettings = settings;\n \n consentPromptValue = settings.ConsentPromptValue;\n secureDesktopValue = settings.SecureDesktopValue;\n return true;\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error reading preferences file: {ex.Message}\");\n }\n }\n \n return false;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting custom UAC values: {ex.Message}\");\n\n return false;\n }\n }\n \n /// \n /// Gets the path to the user preferences file.\n /// \n /// The full path to the user preferences file.\n private string GetPreferencesFilePath()\n {\n // Get the LocalApplicationData folder (e.g., C:\\Users\\Username\\AppData\\Local)\n string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n \n // Combine with Winhance/Config\n string appDataPath = Path.Combine(localAppData, \"Winhance\", \"Config\");\n \n // Ensure the directory exists\n if (!Directory.Exists(appDataPath))\n {\n Directory.CreateDirectory(appDataPath);\n }\n \n // Return the full path to the preferences file\n return Path.Combine(appDataPath, \"UserPreferences.json\");\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/WindowsSecurityOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.Common.ViewModels;\n// Use UacLevel from Core.Models.Enums for the UI\nusing UacLevel = Winhance.Core.Models.Enums.UacLevel;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Windows Security optimizations.\n /// \n public partial class WindowsSecurityOptimizationsViewModel : BaseViewModel\n {\n private readonly IRegistryService _registryService;\n private readonly ILogService _logService;\n private readonly ISystemServices _systemServices;\n private readonly IUacSettingsService _uacSettingsService;\n\n /// \n /// Gets or sets a value indicating whether the view model is selected.\n /// \n [ObservableProperty]\n private bool _isSelected;\n\n /// \n /// Gets or sets the selected UAC level.\n /// \n [ObservableProperty]\n private UacLevel _selectedUacLevel;\n\n /// \n /// Gets or sets a value indicating whether the view model has visible settings.\n /// \n [ObservableProperty]\n private bool _hasVisibleSettings = true;\n\n /// \n /// Gets or sets a value indicating whether the UAC level is being applied.\n /// \n [ObservableProperty]\n private bool _isApplyingUacLevel;\n \n /// \n /// Gets or sets a value indicating whether a custom UAC setting is detected.\n /// \n [ObservableProperty]\n private bool _hasCustomUacSetting;\n\n /// \n /// Gets the collection of available UAC levels with their display names.\n /// \n public ObservableCollection> UacLevelOptions { get; } = new();\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The system services.\n /// The UAC settings service.\n public WindowsSecurityOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n ISystemServices systemServices,\n IUacSettingsService uacSettingsService\n )\n : base(progressService, logService, new Features.Common.Services.MessengerService())\n {\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _systemServices = systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n _uacSettingsService = uacSettingsService ?? throw new ArgumentNullException(nameof(uacSettingsService));\n\n // Initialize UAC level options (excluding Custom initially)\n foreach (var kvp in UacOptimizations.UacLevelNames)\n {\n // Skip the Custom option initially - it will be added dynamically when needed\n if (kvp.Key != UacLevel.Custom)\n {\n UacLevelOptions.Add(new KeyValuePair(kvp.Key, kvp.Value));\n }\n }\n\n // Subscribe to property changes to handle UAC level changes\n this.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(SelectedUacLevel))\n {\n HandleUACLevelChange();\n }\n };\n }\n\n /// \n /// Gets the collection of settings.\n /// \n public ObservableCollection Settings { get; } =\n new ObservableCollection();\n\n /// \n /// Handles changes to the UAC notification level.\n /// \n private void HandleUACLevelChange()\n {\n try\n {\n IsApplyingUacLevel = true;\n \n // Set the UAC level using the system service - no conversion needed\n _systemServices.SetUacLevel(SelectedUacLevel);\n \n string levelName = UacOptimizations.UacLevelNames.TryGetValue(SelectedUacLevel, out string name) ? name : SelectedUacLevel.ToString();\n LogInfo($\"UAC Notification Level set to {levelName}\");\n }\n catch (Exception ex)\n {\n LogError($\"Error setting UAC notification level: {ex.Message}\");\n }\n finally\n {\n IsApplyingUacLevel = false;\n }\n }\n \n // Conversion methods removed as we're now using UacLevel directly\n\n /// \n /// Gets the display name of the UAC level.\n /// \n /// The UAC level.\n /// The display name of the UAC level.\n private string GetUacLevelDisplayName(UacLevel level)\n {\n return UacOptimizations.UacLevelNames.TryGetValue(level, out string name) ? name : level.ToString();\n }\n\n /// \n /// Loads the settings.\n /// \n /// A task representing the asynchronous operation.\n public async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n LogInfo(\"Loading UAC notification level setting\");\n\n // Clear existing settings\n Settings.Clear();\n\n // Add a searchable item for the UAC dropdown\n var uacDropdownItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = \"UACDropdown\",\n Name = \"User Account Control Notification Level\",\n Description = \"Controls when Windows notifies you about changes to your computer\",\n GroupName = \"Windows Security Settings\",\n IsVisible = true,\n ControlType = ControlType.Dropdown,\n };\n Settings.Add(uacDropdownItem);\n LogInfo(\"Added searchable item for UAC dropdown\");\n\n // Load UAC notification level\n try\n {\n // Get the UAC level from the system service (now returns Core UacLevel directly)\n SelectedUacLevel = _systemServices.GetUacLevel();\n \n // Check if we have a custom UAC setting in the registry\n bool hasCustomUacInRegistry = (SelectedUacLevel == UacLevel.Custom);\n \n // Check if we have custom UAC settings saved in preferences (using synchronous method to avoid deadlocks)\n bool hasCustomSettingsInPreferences = _uacSettingsService.TryGetCustomUacValues(out _, out _);\n \n // Set flag if we have custom settings either in registry or preferences\n HasCustomUacSetting = hasCustomUacInRegistry || hasCustomSettingsInPreferences;\n \n // If it's a custom setting, add the Custom option to the dropdown if not already present\n if (HasCustomUacSetting)\n {\n // Check if the Custom option is already in the dropdown\n bool customOptionExists = false;\n foreach (var option in UacLevelOptions)\n {\n if (option.Key == UacLevel.Custom)\n {\n customOptionExists = true;\n break;\n }\n }\n \n // Add the Custom option if it doesn't exist\n if (!customOptionExists)\n {\n UacLevelOptions.Add(new KeyValuePair(\n UacLevel.Custom, \n UacOptimizations.UacLevelNames[UacLevel.Custom]));\n LogInfo(\"Added Custom UAC setting option to dropdown\");\n }\n \n // Log the custom UAC settings values\n if (_uacSettingsService.TryGetCustomUacValues(out int consentPromptValue, out int secureDesktopValue))\n {\n LogInfo($\"Custom UAC setting detected: ConsentPrompt={consentPromptValue}, SecureDesktop={secureDesktopValue}\");\n }\n }\n else\n {\n // If not a custom setting, remove the Custom option if it exists\n for (int i = UacLevelOptions.Count - 1; i >= 0; i--)\n {\n if (UacLevelOptions[i].Key == UacLevel.Custom)\n {\n UacLevelOptions.RemoveAt(i);\n LogInfo(\"Removed Custom UAC setting option from dropdown\");\n break;\n }\n }\n }\n \n string levelName = GetUacLevelDisplayName(SelectedUacLevel);\n LogInfo($\"Loaded UAC Notification Level: {levelName}\");\n }\n catch (Exception ex)\n {\n LogError($\"Error loading UAC notification level: {ex.Message}\");\n SelectedUacLevel = UacLevel.NotifyChangesOnly; // Default to standard notification level if there's an error\n HasCustomUacSetting = false;\n }\n\n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n LogError($\"Error loading Windows security settings: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all settings.\n /// \n /// A task representing the asynchronous operation.\n public async Task CheckSettingStatusesAsync()\n {\n try\n {\n IsLoading = true;\n LogInfo(\"Checking UAC notification level status\");\n\n // Refresh UAC notification level\n await LoadSettingsAsync();\n\n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n LogError($\"Error checking UAC notification level status: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Applies the selected settings.\n /// \n /// Progress reporter.\n /// A task representing the asynchronous operation.\n public async Task ApplySettingsAsync(\n IProgress progress\n )\n {\n try\n {\n IsLoading = true;\n IsApplyingUacLevel = true;\n \n progress.Report(\n new Winhance.Core.Features.Common.Models.TaskProgressDetail\n {\n StatusText = \"Applying UAC notification level setting...\",\n Progress = 0,\n }\n );\n\n // Apply UAC notification level using the system service directly\n // No conversion needed as we're now using UacLevel directly\n _systemServices.SetUacLevel(SelectedUacLevel);\n \n string levelName = GetUacLevelDisplayName(SelectedUacLevel);\n LogInfo($\"UAC Notification Level set to {levelName}\");\n \n progress.Report(\n new Winhance.Core.Features.Common.Models.TaskProgressDetail\n {\n StatusText = $\"{levelName} UAC notification level applied\",\n Progress = 1.0,\n }\n );\n \n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n LogError($\"Error applying UAC notification level: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n IsApplyingUacLevel = false;\n }\n }\n\n /// \n /// Restores the default settings.\n /// \n /// Progress reporter.\n /// A task representing the asynchronous operation.\n public async Task RestoreDefaultsAsync(\n IProgress progress\n )\n {\n try\n {\n IsLoading = true;\n progress.Report(\n new Winhance.Core.Features.Common.Models.TaskProgressDetail\n {\n StatusText = \"Restoring UAC notification level to default...\",\n Progress = 0,\n }\n );\n\n // Set UAC notification level to default (Notify when apps try to make changes)\n SelectedUacLevel = UacLevel.NotifyChangesOnly;\n progress.Report(\n new Winhance.Core.Features.Common.Models.TaskProgressDetail\n {\n StatusText = \"Applying UAC notification level...\",\n Progress = 0.5,\n }\n );\n\n // Apply the changes\n await ApplySettingsAsync(progress);\n\n progress.Report(\n new Winhance.Core.Features.Common.Models.TaskProgressDetail\n {\n StatusText = \"UAC notification level restored to default\",\n Progress = 1.0,\n }\n );\n }\n catch (Exception ex)\n {\n LogError($\"Error restoring UAC notification level: {ex.Message}\");\n throw;\n }\n finally\n {\n IsLoading = false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/SpecialAppHandler.cs", "using System;\nusing System.IO;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a handler for special applications that require custom removal processes.\n/// \npublic class SpecialAppHandler\n{\n /// \n /// Gets or sets the unique identifier for the special handler type.\n /// \n public string HandlerType { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the display name of the application.\n /// \n public string DisplayName { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the description of the application.\n /// \n public string Description { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the script content for removing the application.\n /// \n public string RemovalScriptContent { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the name of the scheduled task to create for preventing reinstallation.\n /// \n public string ScheduledTaskName { get; init; } = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether the application is currently installed.\n /// \n public bool IsInstalled { get; set; }\n\n /// \n /// Gets the path where the removal script will be saved.\n /// \n public string ScriptPath => Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n \"Winhance\",\n \"Scripts\",\n $\"{HandlerType}Removal.ps1\");\n\n /// \n /// Gets a collection of predefined special app handlers.\n /// \n /// A collection of special app handlers.\n public static SpecialAppHandler[] GetPredefinedHandlers()\n {\n return new[]\n {\n new SpecialAppHandler\n {\n HandlerType = \"Edge\",\n DisplayName = \"Microsoft Edge\",\n Description = \"Microsoft's web browser (requires special removal process)\",\n RemovalScriptContent = GetEdgeRemovalScript(),\n ScheduledTaskName = \"Winhance\\\\EdgeRemoval\"\n },\n new SpecialAppHandler\n {\n HandlerType = \"OneDrive\",\n DisplayName = \"OneDrive\",\n Description = \"Microsoft's cloud storage service (requires special removal process)\",\n RemovalScriptContent = GetOneDriveRemovalScript(),\n ScheduledTaskName = \"Winhance\\\\OneDriveRemoval\"\n },\n new SpecialAppHandler\n {\n HandlerType = \"OneNote\",\n DisplayName = \"Microsoft OneNote\",\n Description = \"Microsoft's note-taking application (requires special removal process)\",\n RemovalScriptContent = GetOneNoteRemovalScript(),\n ScheduledTaskName = \"Winhance\\\\OneNoteRemoval\"\n },\n };\n }\n\n private static string GetEdgeRemovalScript()\n {\n return @\"\n# EdgeRemoval.ps1\n# Standalone script to remove Microsoft Edge\n# Source: Winhance (https://github.com/memstechtips/Winhance)\n\n# stop edge running\n$stop = \"\"MicrosoftEdgeUpdate\"\", \"\"OneDrive\"\", \"\"WidgetService\"\", \"\"Widgets\"\", \"\"msedge\"\", \"\"msedgewebview2\"\"\n$stop | ForEach-Object { Stop-Process -Name $_ -Force -ErrorAction SilentlyContinue }\n# uninstall copilot\nGet-AppxPackage -allusers *Microsoft.Windows.Ai.Copilot.Provider* | Remove-AppxPackage\n# disable edge updates regedit\nreg add \"\"HKLM\\SOFTWARE\\Microsoft\\EdgeUpdate\"\" /v \"\"DoNotUpdateToEdgeWithChromium\"\" /t REG_DWORD /d \"\"1\"\" /f | Out-Null\n# allow edge uninstall regedit\nreg add \"\"HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\EdgeUpdateDev\"\" /v \"\"AllowUninstall\"\" /t REG_SZ /f | Out-Null\n# new folder to uninstall edge\nNew-Item -Path \"\"$env:SystemRoot\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\"\" -ItemType Directory -ErrorAction SilentlyContinue | Out-Null\n# new file to uninstall edge\nNew-Item -Path \"\"$env:SystemRoot\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\"\" -ItemType File -Name \"\"MicrosoftEdge.exe\"\" -ErrorAction SilentlyContinue | Out-Null\n# find edge uninstall string\n$regview = [Microsoft.Win32.RegistryView]::Registry32\n$microsoft = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $regview).\nOpenSubKey(\"\"SOFTWARE\\Microsoft\"\", $true)\n$uninstallregkey = $microsoft.OpenSubKey(\"\"Windows\\CurrentVersion\\Uninstall\\Microsoft Edge\"\")\ntry {\n $uninstallstring = $uninstallregkey.GetValue(\"\"UninstallString\"\") + \"\" --force-uninstall\"\"\n}\ncatch {\n}\n# uninstall edge\nStart-Process cmd.exe \"\"/c $uninstallstring\"\" -WindowStyle Hidden -Wait\n# remove folder file\nRemove-Item -Recurse -Force \"\"$env:SystemRoot\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\"\" -ErrorAction SilentlyContinue | Out-Null\n# find edgeupdate.exe\n$edgeupdate = @(); \"\"LocalApplicationData\"\", \"\"ProgramFilesX86\"\", \"\"ProgramFiles\"\" | ForEach-Object {\n $folder = [Environment]::GetFolderPath($_)\n $edgeupdate += Get-ChildItem \"\"$folder\\Microsoft\\EdgeUpdate\\*.*.*.*\\MicrosoftEdgeUpdate.exe\"\" -rec -ea 0\n}\n# find edgeupdate & allow uninstall regedit\n$global:REG = \"\"HKCU:\\SOFTWARE\"\", \"\"HKLM:\\SOFTWARE\"\", \"\"HKCU:\\SOFTWARE\\Policies\"\", \"\"HKLM:\\SOFTWARE\\Policies\"\", \"\"HKCU:\\SOFTWARE\\WOW6432Node\"\", \"\"HKLM:\\SOFTWARE\\WOW6432Node\"\", \"\"HKCU:\\SOFTWARE\\WOW6432Node\\Policies\"\", \"\"HKLM:\\SOFTWARE\\WOW6432Node\\Policies\"\"\nforeach ($location in $REG) { Remove-Item \"\"$location\\Microsoft\\EdgeUpdate\"\" -recurse -force -ErrorAction SilentlyContinue }\n# uninstall edgeupdate\nforeach ($path in $edgeupdate) {\n if (Test-Path $path) { Start-Process -Wait $path -Args \"\"/unregsvc\"\" | Out-Null }\n do { Start-Sleep 3 } while ((Get-Process -Name \"\"setup\"\", \"\"MicrosoftEdge*\"\" -ErrorAction SilentlyContinue).Path -like \"\"*\\Microsoft\\Edge*\"\")\n if (Test-Path $path) { Start-Process -Wait $path -Args \"\"/uninstall\"\" | Out-Null }\n do { Start-Sleep 3 } while ((Get-Process -Name \"\"setup\"\", \"\"MicrosoftEdge*\"\" -ErrorAction SilentlyContinue).Path -like \"\"*\\Microsoft\\Edge*\"\")\n}\n# remove edgewebview regedit\ncmd /c \"\"reg delete `\"\"HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Microsoft EdgeWebView`\"\" /f >nul 2>&1\"\"\ncmd /c \"\"reg delete `\"\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Microsoft EdgeWebView`\"\" /f >nul 2>&1\"\"\n# remove folders edge edgecore edgeupdate edgewebview temp\nRemove-Item -Recurse -Force \"\"$env:SystemDrive\\Program Files (x86)\\Microsoft\"\" -ErrorAction SilentlyContinue | Out-Null\n# remove edge shortcuts\nRemove-Item -Recurse -Force \"\"$env:SystemDrive\\Windows\\System32\\config\\systemprofile\\AppData\\Roaming\\Microsoft\\Internet Explorer\\Quick Launch\\Microsoft Edge.lnk\"\" -ErrorAction SilentlyContinue | Out-Null\nRemove-Item -Recurse -Force \"\"$env:ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Edge.lnk\"\" -ErrorAction SilentlyContinue | Out-Null\n\n$fileSystemProfiles = Get-ChildItem -Path \"\"C:\\Users\"\" -Directory | Where-Object { \n $_.Name -notin @('Public', 'Default', 'Default User', 'All Users') -and \n (Test-Path -Path \"\"$($_.FullName)\\NTUSER.DAT\"\")\n}\n\n# Loop through each user profile and clean up Edge shortcuts\nforeach ($profile in $fileSystemProfiles) {\n $userProfilePath = $profile.FullName\n \n # Define user-specific paths to clean\n $edgeShortcutPaths = @(\n \"\"$userProfilePath\\AppData\\Roaming\\Microsoft\\Internet Explorer\\Quick Launch\\Microsoft Edge.lnk\"\",\n \"\"$userProfilePath\\Desktop\\Microsoft Edge.lnk\"\",\n \"\"$userProfilePath\\AppData\\Roaming\\Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar\\Microsoft Edge.lnk\"\",\n \"\"$userProfilePath\\AppData\\Roaming\\Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar\\Tombstones\\Microsoft Edge.lnk\"\",\n \"\"$userProfilePath\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Edge.lnk\"\"\n )\n\n # Remove Edge shortcuts for each user\n foreach ($path in $edgeShortcutPaths) {\n if (Test-Path -Path $path -PathType Leaf) {\n Remove-Item -Path $path -Force -ErrorAction SilentlyContinue\n }\n }\n}\n\n# Clean up common locations\n$commonShortcutPaths = @(\n \"\"$env:PUBLIC\\Desktop\\Microsoft Edge.lnk\"\",\n \"\"$env:ALLUSERSPROFILE\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Edge.lnk\"\",\n \"\"C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Edge.lnk\"\"\n)\n\nforeach ($path in $commonShortcutPaths) {\n if (Test-Path -Path $path -PathType Leaf) {\n Remove-Item -Path $path -Force -ErrorAction SilentlyContinue\n }\n}\n\n# Removes Edge in Task Manager Startup Apps for All Users\n# Get all user profiles on the system\n$userProfiles = Get-CimInstance -ClassName Win32_UserProfile | \nWhere-Object { -not $_.Special -and $_.SID -notmatch 'S-1-5-18|S-1-5-19|S-1-5-20' }\n\nforeach ($profile in $userProfiles) {\n $sid = $profile.SID\n $hiveLoaded = $false\n\n if (-not (Test-Path \"\"Registry::HKEY_USERS\\$sid\"\")) {\n $userRegPath = Join-Path $profile.LocalPath \"\"NTUSER.DAT\"\"\n if (Test-Path $userRegPath) {\n reg load \"\"HKU\\$sid\"\" $userRegPath | Out-Null\n $hiveLoaded = $true\n Start-Sleep -Seconds 2\n }\n }\n\n $runKeyPath = \"\"Registry::HKEY_USERS\\$sid\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\"\"\n\n if (Test-Path $runKeyPath) {\n $properties = Get-ItemProperty -Path $runKeyPath\n $edgeEntries = $properties.PSObject.Properties | \n Where-Object { $_.Name -like 'MicrosoftEdgeAutoLaunch*' }\n\n foreach ($entry in $edgeEntries) {\n Remove-ItemProperty -Path $runKeyPath -Name $entry.Name -Force\n }\n }\n\n if ($hiveLoaded) {\n [gc]::Collect()\n Start-Sleep -Seconds 2\n reg unload \"\"HKU\\$sid\"\" | Out-Null\n }\n}\n\";\n }\n\n private static string GetOneNoteRemovalScript()\n {\n return @\"# OneNoteRemoval.ps1\n# Standalone script to remove Microsoft OneNote\n# Source: Winhance (https://github.com/memstechtips/Winhance)\n\ntry {\n # Stop OneNote processes\n $processesToStop = @(\"\"OneNote\"\", \"\"ONENOTE\"\", \"\"ONENOTEM\"\")\n foreach ($processName in $processesToStop) { \n Get-Process -Name $processName -ErrorAction SilentlyContinue | \n Stop-Process -Force -ErrorAction SilentlyContinue\n }\n Start-Sleep -Seconds 1\n}\ncatch {\n # Continue if process stopping fails\n}\n\n# Remove OneNote AppX package (Windows 10 version)\nGet-AppxPackage -AllUsers *OneNote* | Remove-AppxPackage\n\n# Check and execute uninstall strings from registry (Windows 11 version)\n$registryPaths = @(\n \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneNote*\"\",\n \"\"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneNote*\"\",\n \"\"HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneNote*\"\"\n)\n\nforeach ($regPathPattern in $registryPaths) {\n try {\n $regPaths = Get-ChildItem -Path $regPathPattern -ErrorAction SilentlyContinue\n foreach ($regPath in $regPaths) {\n $uninstallString = (Get-ItemProperty -Path $regPath.PSPath -ErrorAction SilentlyContinue).UninstallString\n if ($uninstallString) {\n if ($uninstallString -match '^\\\"\"([^\\\"\"]+)\\\"\"(.*)$') {\n $exePath = $matches[1]\n $args = $matches[2].Trim()\n Start-Process -FilePath $exePath -ArgumentList $args -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n else {\n Start-Process -FilePath $uninstallString -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n }\n }\n }\n catch {\n # Continue if registry operation fails\n continue\n }\n}\n\n# Try to uninstall using the Office setup\n$officeUninstallPaths = @(\n \"\"$env:ProgramFiles\\Microsoft Office\\Office16\\setup.exe\"\",\n \"\"$env:ProgramFiles\\Microsoft Office\\root\\Office16\\setup.exe\"\",\n \"\"$env:ProgramFiles(x86)\\Microsoft Office\\Office16\\setup.exe\"\",\n \"\"$env:ProgramFiles(x86)\\Microsoft Office\\root\\Office16\\setup.exe\"\"\n)\n\nforeach ($path in $officeUninstallPaths) {\n try {\n if (Test-Path $path) {\n Start-Process -FilePath $path -ArgumentList \"\"/uninstall OneNote /config OneNoteRemoval.xml\"\" -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if uninstall fails\n continue\n }\n}\n\n# Remove OneNote scheduled tasks\ntry {\n Get-ScheduledTask -ErrorAction SilentlyContinue | \n Where-Object { $_.TaskName -match 'OneNote' -and $_.TaskName -ne 'OneNoteRemoval' } | \n ForEach-Object { \n Unregister-ScheduledTask -TaskName $_.TaskName -Confirm:$false -ErrorAction SilentlyContinue \n }\n}\ncatch {\n # Continue if task removal fails\n}\n\n# Remove OneNote from startup\ntry {\n Remove-ItemProperty -Path \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\"\" -Name \"\"OneNote*\"\" -ErrorAction SilentlyContinue\n}\ncatch {\n # Continue if registry operations fail\n}\n\n# Files to remove (single items)\n$filesToRemove = @(\n \"\"$env:ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\OneNote.lnk\"\",\n \"\"$env:PUBLIC\\Desktop\\OneNote.lnk\"\"\n)\n\n# Remove single files\nforeach ($file in $filesToRemove) {\n try {\n if (Test-Path $file) {\n Remove-Item $file -Force -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if file removal fails\n continue\n }\n}\n\n# Folders that need special handling\n$foldersToRemove = @(\n \"\"$env:ProgramFiles\\Microsoft\\OneNote\"\",\n \"\"$env:ProgramFiles(x86)\\Microsoft\\OneNote\"\",\n \"\"$env:LOCALAPPDATA\\Microsoft\\OneNote\"\"\n)\n\n# Remove folders\nforeach ($folder in $foldersToRemove) {\n try {\n if (Test-Path $folder) {\n Remove-Item -Path $folder -Force -Recurse -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if folder removal fails\n continue\n }\n}\n\n# Clean up per-user OneNote shortcuts\n$userProfiles = Get-ChildItem -Path \"\"C:\\Users\"\" -Directory | Where-Object { \n $_.Name -notin @('Public', 'Default', 'Default User', 'All Users') -and \n (Test-Path -Path \"\"$($_.FullName)\\NTUSER.DAT\"\")\n}\n\nforeach ($profile in $userProfiles) {\n $userProfilePath = $profile.FullName\n \n # Define user-specific paths to clean\n $oneNoteShortcutPaths = @(\n \"\"$userProfilePath\\Desktop\\OneNote.lnk\"\",\n \"\"$userProfilePath\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\OneNote.lnk\"\"\n )\n\n # Remove OneNote shortcuts for each user\n foreach ($path in $oneNoteShortcutPaths) {\n if (Test-Path -Path $path -PathType Leaf) {\n Remove-Item -Path $path -Force -ErrorAction SilentlyContinue\n }\n }\n}\n\";\n }\n\n private static string GetOneDriveRemovalScript()\n {\n return @\"\n# OneDriveRemoval.ps1\n# Standalone script to remove Microsoft OneDrive\n# Source: Winhance (https://github.com/memstechtips/Winhance)\n\ntry {\n # Stop OneDrive processes\n $processesToStop = @(\"\"OneDrive\"\", \"\"FileCoAuth\"\", \"\"FileSyncHelper\"\")\n foreach ($processName in $processesToStop) { \n Get-Process -Name $processName -ErrorAction SilentlyContinue | \n Stop-Process -Force -ErrorAction SilentlyContinue\n }\n Start-Sleep -Seconds 1\n}\ncatch {\n # Continue if process stopping fails\n}\n\n# Check and execute uninstall strings from registry\n$registryPaths = @(\n \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneDriveSetup.exe\"\",\n \"\"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\OneDriveSetup.exe\"\"\n)\n\nforeach ($regPath in $registryPaths) {\n try {\n if (Test-Path $regPath) {\n $uninstallString = (Get-ItemProperty -Path $regPath -ErrorAction Stop).UninstallString\n if ($uninstallString) {\n if ($uninstallString -match '^\"\"([^\"\"]+)\"\"(.*)$') {\n $exePath = $matches[1]\n $args = $matches[2].Trim()\n Start-Process -FilePath $exePath -ArgumentList $args -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n else {\n Start-Process -FilePath $uninstallString -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n }\n }\n }\n catch {\n # Continue if registry operation fails\n continue\n }\n}\n\ntry {\n # Remove OneDrive AppX package\n Get-AppxPackage -Name \"\"*OneDrive*\"\" -ErrorAction SilentlyContinue | \n Remove-AppxPackage -ErrorAction SilentlyContinue\n}\ncatch {\n # Continue if AppX removal fails\n}\n\n# Uninstall OneDrive using setup files\n$oneDrivePaths = @(\n \"\"$env:SystemRoot\\SysWOW64\\OneDriveSetup.exe\"\",\n \"\"$env:SystemRoot\\System32\\OneDriveSetup.exe\"\",\n \"\"$env:LOCALAPPDATA\\Microsoft\\OneDrive\\OneDrive.exe\"\"\n)\n\nforeach ($path in $oneDrivePaths) {\n try {\n if (Test-Path $path) {\n Start-Process -FilePath $path -ArgumentList \"\"/uninstall\"\" -NoNewWindow -Wait -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if uninstall fails\n continue\n }\n}\n\ntry {\n # Remove OneDrive scheduled tasks\n Get-ScheduledTask -ErrorAction SilentlyContinue | \n Where-Object { $_.TaskName -match 'OneDrive' -and $_.TaskName -ne 'OneDriveRemoval' } | \n ForEach-Object { \n Unregister-ScheduledTask -TaskName $_.TaskName -Confirm:$false -ErrorAction SilentlyContinue \n }\n}\ncatch {\n # Continue if task removal fails\n}\n\ntry {\n # Configure registry settings\n $regPath = \"\"HKLM:\\SOFTWARE\\Policies\\Microsoft\\OneDrive\"\"\n if (-not (Test-Path $regPath)) {\n New-Item -Path $regPath -Force -ErrorAction SilentlyContinue | Out-Null\n }\n Set-ItemProperty -Path $regPath -Name \"\"KFMBlockOptIn\"\" -Value 1 -Type DWord -Force -ErrorAction SilentlyContinue\n \n # Remove OneDrive from startup\n Remove-ItemProperty -Path \"\"HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\"\" -Name \"\"OneDriveSetup\"\" -ErrorAction SilentlyContinue\n \n # Remove OneDrive from Navigation Pane\n Remove-Item -Path \"\"Registry::HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Desktop\\NameSpace\\{018D5C66-4533-4307-9B53-224DE2ED1FE6}\"\" -Recurse -Force -ErrorAction SilentlyContinue\n}\ncatch {\n # Continue if registry operations fail\n}\n\n# Function to handle robust folder removal\nfunction Remove-OneDriveFolder {\n param ([string]$folderPath)\n \n if (-not (Test-Path $folderPath)) {\n return\n }\n \n try {\n # Stop OneDrive processes if they're running\n Get-Process -Name \"\"OneDrive\"\" -ErrorAction SilentlyContinue | \n Stop-Process -Force -ErrorAction SilentlyContinue\n \n # Take ownership and grant permissions\n $null = Start-Process \"\"takeown.exe\"\" -ArgumentList \"\"/F `\"\"$folderPath`\"\" /R /A /D Y\"\" -Wait -NoNewWindow -PassThru -ErrorAction SilentlyContinue\n $null = Start-Process \"\"icacls.exe\"\" -ArgumentList \"\"`\"\"$folderPath`\"\" /grant administrators:F /T\"\" -Wait -NoNewWindow -PassThru -ErrorAction SilentlyContinue\n \n # Try direct removal\n Remove-Item -Path $folderPath -Force -Recurse -ErrorAction SilentlyContinue\n }\n catch {\n try {\n # If direct removal fails, create and execute a cleanup batch file\n $batchPath = \"\"$env:TEMP\\RemoveOneDrive_$(Get-Random).bat\"\"\n $batchContent = @\"\"\n@echo off\ntimeout /t 2 /nobreak > nul\ntakeown /F \"\"$folderPath\"\" /R /A /D Y\nicacls \"\"$folderPath\"\" /grant administrators:F /T\nrd /s /q \"\"$folderPath\"\"\ndel /F /Q \"\"%~f0\"\"\n\"\"@\n Set-Content -Path $batchPath -Value $batchContent -Force -ErrorAction SilentlyContinue\n Start-Process \"\"cmd.exe\"\" -ArgumentList \"\"/c $batchPath\"\" -WindowStyle Hidden -ErrorAction SilentlyContinue\n }\n catch {\n # Continue if batch file cleanup fails\n }\n }\n}\n\n# Files to remove (single items)\n$filesToRemove = @(\n \"\"$env:ALLUSERSPROFILE\\Users\\Default\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\OneDrive.lnk\"\",\n \"\"$env:ALLUSERSPROFILE\\Users\\Default\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\OneDrive.exe\"\",\n \"\"$env:PUBLIC\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\OneDrive.lnk\"\",\n \"\"$env:PUBLIC\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\OneDrive.exe\"\",\n \"\"$env:SystemRoot\\System32\\OneDriveSetup.exe\"\",\n \"\"$env:SystemRoot\\SysWOW64\\OneDriveSetup.exe\"\",\n \"\"$env:LOCALAPPDATA\\Microsoft\\OneDrive\\OneDrive.exe\"\",\n \"\"$env:ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\OneDrive.lnk\"\"\n)\n\n# Remove single files\nforeach ($file in $filesToRemove) {\n try {\n if (Test-Path $file) {\n Remove-Item $file -Force -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if file removal fails\n continue\n }\n}\n\n# Folders that need special handling\n$foldersToRemove = @(\n \"\"$env:ProgramFiles\\Microsoft\\OneDrive\"\",\n \"\"$env:ProgramFiles\\Microsoft OneDrive\"\",\n \"\"$env:LOCALAPPDATA\\Microsoft\\OneDrive\"\"\n)\n\n# Remove folders with robust method\nforeach ($folder in $foldersToRemove) {\n try {\n Remove-OneDriveFolder -folderPath $folder\n }\n catch {\n # Continue if folder removal fails\n continue\n }\n}\n\n# Additional cleanup for stubborn setup files\n$setupFiles = @(\n \"\"$env:SystemRoot\\System32\\OneDriveSetup.exe\"\",\n \"\"$env:SystemRoot\\SysWOW64\\OneDriveSetup.exe\"\"\n)\n\nforeach ($file in $setupFiles) {\n if (Test-Path $file) {\n try {\n # Take ownership and grant full permissions\n $null = Start-Process \"\"takeown.exe\"\" -ArgumentList \"\"/F `\"\"$file`\"\"\"\" -Wait -NoNewWindow -PassThru -ErrorAction SilentlyContinue\n $null = Start-Process \"\"icacls.exe\"\" -ArgumentList \"\"`\"\"$file`\"\" /grant administrators:F\"\" -Wait -NoNewWindow -PassThru -ErrorAction SilentlyContinue\n \n # Attempt direct removal\n Remove-Item -Path $file -Force -ErrorAction SilentlyContinue\n \n # If file still exists, schedule it for deletion on next reboot\n if (Test-Path $file) {\n $pendingRename = \"\"$file.pending\"\"\n Move-Item -Path $file -Destination $pendingRename -Force -ErrorAction SilentlyContinue\n Start-Process \"\"cmd.exe\"\" -ArgumentList \"\"/c del /F /Q `\"\"$pendingRename`\"\"\"\" -WindowStyle Hidden -ErrorAction SilentlyContinue\n }\n }\n catch {\n # Continue if cleanup fails\n continue\n }\n }\n}\n\";\n }\n\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Converters/BooleanToVisibilityConverter.cs", "using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Converters;\n\npublic class BooleanToVisibilityConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (bool)value ? Visibility.Visible : Visibility.Collapsed;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (Visibility)value == Visibility.Visible;\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/InternetConnectivityService.cs", "using System;\nusing System.Net.Http;\nusing System.Net.NetworkInformation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service for checking and monitoring internet connectivity.\n /// \n public class InternetConnectivityService : IInternetConnectivityService, IDisposable\n {\n // List of reliable domains to check for internet connectivity\n private static readonly string[] _connectivityCheckUrls = new string[]\n {\n \"https://www.microsoft.com\",\n \"https://www.google.com\",\n \"https://www.cloudflare.com\",\n };\n\n // HttpClient for internet connectivity checks\n private readonly HttpClient _httpClient;\n\n // Cache the internet connectivity status to avoid frequent checks\n private bool? _cachedInternetStatus = null;\n private DateTime _lastInternetCheckTime = DateTime.MinValue;\n private readonly TimeSpan _internetStatusCacheDuration = TimeSpan.FromSeconds(10); // Cache for 10 seconds\n private readonly ILogService _logService;\n \n // Monitoring-related fields\n private CancellationTokenSource _monitoringCts;\n private Task _monitoringTask;\n private bool _isMonitoring;\n private int _monitoringIntervalSeconds;\n\n /// \n /// Event that is raised when the internet connectivity status changes.\n /// \n public event EventHandler ConnectivityChanged;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public InternetConnectivityService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n\n // Initialize HttpClient with a timeout\n _httpClient = new HttpClient();\n _httpClient.Timeout = TimeSpan.FromSeconds(5); // Short timeout for connectivity checks\n }\n\n /// \n /// Checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// True if internet is connected, false otherwise.\n public bool IsInternetConnected(bool forceCheck = false)\n {\n try\n {\n // Return cached result if it's still valid and force check is not requested\n if (\n !forceCheck\n && _cachedInternetStatus.HasValue\n && (DateTime.Now - _lastInternetCheckTime) < _internetStatusCacheDuration\n )\n {\n _logService.LogInformation(\n $\"Using cached internet connectivity status: {_cachedInternetStatus.Value}\"\n );\n return _cachedInternetStatus.Value;\n }\n\n // First check: NetworkInterface.GetIsNetworkAvailable()\n bool isNetworkAvailable = NetworkInterface.GetIsNetworkAvailable();\n if (!isNetworkAvailable)\n {\n _logService.LogInformation(\n \"Network is not available according to NetworkInterface.GetIsNetworkAvailable()\"\n );\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n return false;\n }\n\n // Second check: Ping network interfaces\n bool hasInternetAccess = false;\n try\n {\n NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();\n foreach (NetworkInterface ni in interfaces)\n {\n if (\n ni.OperationalStatus == OperationalStatus.Up\n && (\n ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211\n || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet\n )\n && ni.GetIPProperties().GatewayAddresses.Count > 0\n )\n {\n hasInternetAccess = true;\n break;\n }\n }\n\n if (!hasInternetAccess)\n {\n _logService.LogInformation(\n \"No active network interfaces with gateway addresses found\"\n );\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.LogWarning($\"Error checking network interfaces: {ex.Message}\");\n // Continue to the next check even if this one fails\n }\n\n // Third check: Try to connect to reliable domains\n foreach (string url in _connectivityCheckUrls)\n {\n try\n {\n // Make a HEAD request to minimize data transfer\n var request = new HttpRequestMessage(HttpMethod.Head, url);\n var response = _httpClient.SendAsync(request).GetAwaiter().GetResult();\n\n if (response.IsSuccessStatusCode)\n {\n _logService.LogInformation($\"Successfully connected to {url}\");\n _cachedInternetStatus = true;\n _lastInternetCheckTime = DateTime.Now;\n return true;\n }\n }\n catch (Exception ex)\n {\n _logService.LogInformation($\"Failed to connect to {url}: {ex.Message}\");\n // Try the next URL\n }\n }\n\n // If we get here, all connectivity checks failed\n _logService.LogWarning(\"All internet connectivity checks failed\");\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n return false;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking internet connectivity\", ex);\n return false;\n }\n }\n\n /// \n /// Asynchronously checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// Cancellation token for the operation.\n /// True if internet is connected, false otherwise.\n public async Task IsInternetConnectedAsync(\n bool forceCheck = false,\n CancellationToken cancellationToken = default,\n bool userInitiatedCancellation = false\n )\n {\n try\n {\n // Check for cancellation before doing anything\n if (cancellationToken.IsCancellationRequested)\n {\n _logService.LogInformation(userInitiatedCancellation ? \"Internet connectivity check was cancelled by user\" : \"Internet connectivity check was cancelled as part of operation cancellation\");\n throw new OperationCanceledException(cancellationToken);\n }\n \n // Return cached result if it's still valid and force check is not requested\n if (\n !forceCheck\n && _cachedInternetStatus.HasValue\n && (DateTime.Now - _lastInternetCheckTime) < _internetStatusCacheDuration\n )\n {\n _logService.LogInformation(\n $\"Using cached internet connectivity status: {_cachedInternetStatus.Value}\"\n );\n return _cachedInternetStatus.Value;\n }\n\n // First check: NetworkInterface.GetIsNetworkAvailable()\n bool isNetworkAvailable = NetworkInterface.GetIsNetworkAvailable();\n if (!isNetworkAvailable)\n {\n _logService.LogInformation(\n \"Network is not available according to NetworkInterface.GetIsNetworkAvailable()\"\n );\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false));\n \n return false;\n }\n\n // Second check: Ping network interfaces\n bool hasInternetAccess = false;\n try\n {\n // Check for cancellation before network interface check\n if (cancellationToken.IsCancellationRequested)\n {\n _logService.LogInformation(userInitiatedCancellation ? \"Internet connectivity check was cancelled by user\" : \"Internet connectivity check was cancelled as part of operation cancellation\");\n throw new OperationCanceledException(cancellationToken);\n }\n \n NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();\n foreach (NetworkInterface ni in interfaces)\n {\n if (\n ni.OperationalStatus == OperationalStatus.Up\n && (\n ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211\n || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet\n )\n && ni.GetIPProperties().GatewayAddresses.Count > 0\n )\n {\n hasInternetAccess = true;\n break;\n }\n }\n\n if (!hasInternetAccess)\n {\n _logService.LogInformation(\n \"No active network interfaces with gateway addresses found\"\n );\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false));\n \n return false;\n }\n }\n catch (OperationCanceledException)\n {\n // This is a user-initiated cancellation, not a connectivity issue\n _logService.LogInformation(userInitiatedCancellation ? \"Internet connectivity check was cancelled by user\" : \"Internet connectivity check was cancelled as part of operation cancellation\");\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false, userInitiatedCancellation));\n \n throw; // Re-throw to be handled by the caller\n }\n catch (Exception ex)\n {\n _logService.LogWarning($\"Error checking network interfaces: {ex.Message}\");\n // Continue to the next check even if this one fails\n }\n\n // Third check: Try to connect to reliable domains\n foreach (string url in _connectivityCheckUrls)\n {\n try\n {\n // Check for cancellation before making the request\n if (cancellationToken.IsCancellationRequested)\n {\n // This is a user-initiated cancellation, not a connectivity issue\n _logService.LogInformation(userInitiatedCancellation ? \"Internet connectivity check was cancelled by user\" : \"Internet connectivity check was cancelled as part of operation cancellation\");\n throw new OperationCanceledException(cancellationToken);\n }\n \n // Make a HEAD request to minimize data transfer\n var request = new HttpRequestMessage(HttpMethod.Head, url);\n var response = await _httpClient.SendAsync(request, cancellationToken);\n\n if (response.IsSuccessStatusCode)\n {\n _logService.LogInformation($\"Successfully connected to {url}\");\n _cachedInternetStatus = true;\n _lastInternetCheckTime = DateTime.Now;\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(true));\n \n return true;\n }\n }\n catch (OperationCanceledException)\n {\n // This is a user-initiated cancellation, not a connectivity issue\n _logService.LogInformation(userInitiatedCancellation ? \"Internet connectivity check was cancelled by user\" : \"Internet connectivity check was cancelled as part of operation cancellation\");\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false, userInitiatedCancellation));\n \n throw; // Re-throw to be handled by the caller\n }\n catch (Exception ex)\n {\n _logService.LogInformation($\"Failed to connect to {url}: {ex.Message}\");\n // Try the next URL\n }\n }\n\n // If we get here, all connectivity checks failed\n _logService.LogWarning(\"All internet connectivity checks failed\");\n _cachedInternetStatus = false;\n _lastInternetCheckTime = DateTime.Now;\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false));\n \n return false;\n }\n catch (OperationCanceledException)\n {\n // This is a user-initiated cancellation, not a connectivity issue\n _logService.LogInformation(\"Internet connectivity check was cancelled by user\");\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false, true));\n \n throw; // Re-throw to be handled by the caller\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error checking internet connectivity\", ex);\n \n // Raise the event if monitoring is active\n OnConnectivityChanged(new ConnectivityChangedEventArgs(false));\n \n return false;\n }\n }\n \n /// \n /// Starts monitoring internet connectivity at the specified interval.\n /// \n /// The interval in seconds between connectivity checks.\n /// Cancellation token to stop monitoring.\n /// A task representing the monitoring operation.\n public async Task StartMonitoringAsync(int intervalSeconds = 5, CancellationToken cancellationToken = default)\n {\n if (_isMonitoring)\n {\n _logService.LogWarning(\"Internet connectivity monitoring is already active\");\n return;\n }\n \n _monitoringIntervalSeconds = intervalSeconds;\n _monitoringCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n _isMonitoring = true;\n \n _logService.LogInformation($\"Starting internet connectivity monitoring with {intervalSeconds} second interval\");\n \n _monitoringTask = Task.Run(async () =>\n {\n try\n {\n bool? lastStatus = null;\n \n while (!_monitoringCts.Token.IsCancellationRequested)\n {\n try\n {\n bool currentStatus = await IsInternetConnectedAsync(true, _monitoringCts.Token);\n \n // Only raise the event if the status has changed\n if (lastStatus == null || lastStatus.Value != currentStatus)\n {\n _logService.LogInformation($\"Internet connectivity status changed: {currentStatus}\");\n lastStatus = currentStatus;\n }\n \n // Wait for the specified interval\n await Task.Delay(TimeSpan.FromSeconds(_monitoringIntervalSeconds), _monitoringCts.Token);\n }\n catch (OperationCanceledException)\n {\n // Check if this is a user-initiated cancellation or just the monitoring being stopped\n if (_monitoringCts.Token.IsCancellationRequested)\n {\n _logService.LogInformation(\"Internet connectivity monitoring was cancelled\");\n break;\n }\n \n // If it's a user-initiated cancellation during a connectivity check, continue monitoring\n _logService.LogInformation(\"Internet connectivity check was cancelled by user, continuing monitoring\");\n await Task.Delay(TimeSpan.FromSeconds(_monitoringIntervalSeconds), _monitoringCts.Token);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error during internet connectivity monitoring\", ex);\n await Task.Delay(TimeSpan.FromSeconds(_monitoringIntervalSeconds), _monitoringCts.Token);\n }\n }\n }\n catch (OperationCanceledException)\n {\n // Expected when monitoring is stopped\n _logService.LogInformation(\"Internet connectivity monitoring was stopped\");\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error in internet connectivity monitoring task\", ex);\n }\n finally\n {\n _isMonitoring = false;\n }\n }, _monitoringCts.Token);\n \n await Task.CompletedTask;\n }\n \n /// \n /// Stops monitoring internet connectivity.\n /// \n public void StopMonitoring()\n {\n if (!_isMonitoring)\n {\n return;\n }\n \n _logService.LogInformation(\"Stopping internet connectivity monitoring\");\n \n try\n {\n _monitoringCts?.Cancel();\n _monitoringCts?.Dispose();\n _monitoringCts = null;\n _monitoringTask = null;\n _isMonitoring = false;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error stopping internet connectivity monitoring\", ex);\n }\n }\n \n /// \n /// Raises the ConnectivityChanged event.\n /// \n /// The event arguments.\n protected virtual void OnConnectivityChanged(ConnectivityChangedEventArgs args)\n {\n if (_isMonitoring)\n {\n ConnectivityChanged?.Invoke(this, args);\n }\n }\n \n /// \n /// Disposes the resources used by the service.\n /// \n public void Dispose()\n {\n StopMonitoring();\n _httpClient?.Dispose();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/ConfigurationViewModelBase.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// Base class for view models that handle configuration saving and loading.\n /// \n /// The type of setting item.\n public abstract class ConfigurationViewModelBase : ObservableObject where T : class, ISettingItem\n {\n private readonly IConfigurationService _configurationService;\n private readonly ILogService _logService;\n private readonly IDialogService _dialogService;\n\n /// \n /// Gets the configuration type for this view model.\n /// \n public abstract string ConfigType { get; }\n\n /// \n /// Gets the settings collection.\n /// \n public abstract ObservableCollection Settings { get; }\n\n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n\n /// \n /// Gets the command to save the unified configuration.\n /// \n public IAsyncRelayCommand SaveUnifiedConfigCommand { get; }\n\n /// \n /// Gets the command to import the unified configuration.\n /// \n public IAsyncRelayCommand ImportUnifiedConfigCommand { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The configuration service.\n /// The log service.\n /// The dialog service.\n protected ConfigurationViewModelBase(\n IConfigurationService configurationService,\n ILogService logService,\n IDialogService dialogService)\n {\n _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n\n // Create commands\n // SaveConfigCommand and ImportConfigCommand removed as part of unified configuration cleanup\n SaveUnifiedConfigCommand = new AsyncRelayCommand(SaveUnifiedConfig);\n ImportUnifiedConfigCommand = new AsyncRelayCommand(ImportUnifiedConfig);\n }\n\n // SaveConfig and ImportConfig methods removed as part of unified configuration cleanup\n\n /// \n /// Saves a unified configuration file containing settings for multiple parts of the application.\n /// \n /// A task representing the asynchronous operation.\n protected virtual async Task SaveUnifiedConfig()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Starting to save unified configuration\");\n \n // Create a dictionary of sections with their availability and item counts\n var sections = new Dictionary\n {\n { \"WindowsApps\", (false, false, 0) },\n { \"ExternalApps\", (false, false, 0) },\n { \"Customize\", (false, false, 0) },\n { \"Optimize\", (false, false, 0) }\n };\n \n // Always include the current section\n sections[ConfigType] = (true, true, Settings.Count);\n \n // Show the unified configuration save dialog\n var result = await _dialogService.ShowUnifiedConfigurationSaveDialogAsync(\n \"Save Unified Configuration\",\n \"Select which sections to include in the unified configuration:\",\n sections);\n \n if (result == null)\n {\n _logService.Log(LogLevel.Info, \"Save unified configuration canceled by user\");\n return false;\n }\n \n // Get the selected sections\n var selectedSections = result.Where(kvp => kvp.Value).Select(kvp => kvp.Key).ToList();\n \n if (!selectedSections.Any())\n {\n _logService.Log(LogLevel.Info, \"No sections selected for unified configuration\");\n _dialogService.ShowMessage(\"No sections selected\", \"Please select at least one section to include in the unified configuration.\");\n return false;\n }\n \n // Create a dictionary of sections and their settings\n var sectionSettings = new Dictionary>();\n \n // Add the current section's settings\n sectionSettings[ConfigType] = Settings;\n \n // Create a unified configuration\n var unifiedConfig = _configurationService.CreateUnifiedConfiguration(sectionSettings, selectedSections);\n \n // Save the unified configuration\n bool saveResult = await _configurationService.SaveUnifiedConfigurationAsync(unifiedConfig);\n \n if (saveResult)\n {\n _logService.Log(LogLevel.Info, \"Unified configuration saved successfully\");\n \n // Show a success message\n _dialogService.ShowMessage(\n \"The unified configuration has been saved successfully.\",\n \"Unified Configuration Saved\");\n }\n else\n {\n _logService.Log(LogLevel.Info, \"Save unified configuration canceled by user\");\n }\n\n return saveResult;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving unified configuration: {ex.Message}\");\n await _dialogService.ShowErrorAsync(\"Error\", $\"Error saving unified configuration: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Imports a unified configuration file.\n /// \n /// A task representing the asynchronous operation.\n protected virtual async Task ImportUnifiedConfig()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Starting to import unified configuration\");\n \n // Load the unified configuration\n var unifiedConfig = await _configurationService.LoadUnifiedConfigurationAsync();\n \n if (unifiedConfig == null)\n {\n _logService.Log(LogLevel.Info, \"Import unified configuration canceled by user\");\n return false;\n }\n \n // Check which sections are available in the unified configuration\n var sections = new Dictionary();\n \n // Check WindowsApps section\n if (unifiedConfig.WindowsApps != null && unifiedConfig.WindowsApps.Items != null)\n {\n sections[\"WindowsApps\"] = (true, true, unifiedConfig.WindowsApps.Items.Count);\n }\n else\n {\n sections[\"WindowsApps\"] = (false, false, 0);\n }\n \n // Check ExternalApps section\n if (unifiedConfig.ExternalApps != null && unifiedConfig.ExternalApps.Items != null)\n {\n sections[\"ExternalApps\"] = (true, true, unifiedConfig.ExternalApps.Items.Count);\n }\n else\n {\n sections[\"ExternalApps\"] = (false, false, 0);\n }\n \n // Check Customize section\n if (unifiedConfig.Customize != null && unifiedConfig.Customize.Items != null)\n {\n sections[\"Customize\"] = (true, true, unifiedConfig.Customize.Items.Count);\n }\n else\n {\n sections[\"Customize\"] = (false, false, 0);\n }\n \n // Check Optimize section\n if (unifiedConfig.Optimize != null && unifiedConfig.Optimize.Items != null)\n {\n sections[\"Optimize\"] = (true, true, unifiedConfig.Optimize.Items.Count);\n }\n else\n {\n sections[\"Optimize\"] = (false, false, 0);\n }\n \n // Show the unified configuration import dialog\n var result = await _dialogService.ShowUnifiedConfigurationImportDialogAsync(\n \"Import Unified Configuration\",\n \"Select which sections to import from the unified configuration:\",\n sections);\n \n if (result == null)\n {\n _logService.Log(LogLevel.Info, \"Import unified configuration canceled by user\");\n return false;\n }\n \n // Get the selected sections\n var selectedSections = result.Where(kvp => kvp.Value).Select(kvp => kvp.Key).ToList();\n \n if (!selectedSections.Any())\n {\n _logService.Log(LogLevel.Info, \"No sections selected for import\");\n _dialogService.ShowMessage(\"Please select at least one section to import from the unified configuration.\", \"No sections selected\");\n return false;\n }\n \n // Check if the current section is selected\n if (!selectedSections.Contains(ConfigType))\n {\n _logService.Log(LogLevel.Info, $\"Section {ConfigType} is not selected for import\");\n _dialogService.ShowMessage(\n $\"The {ConfigType} section is not selected for import.\",\n \"Section Not Selected\");\n return false;\n }\n \n // Extract the current section from the unified configuration\n var configFile = _configurationService.ExtractSectionFromUnifiedConfiguration(unifiedConfig, ConfigType);\n \n if (configFile != null && configFile.Items != null && configFile.Items.Any())\n {\n _logService.Log(LogLevel.Info, $\"Successfully extracted {ConfigType} section with {configFile.Items.Count} items\");\n \n // Update the settings based on the loaded configuration\n int updatedCount = await ApplyConfigurationToSettings(configFile);\n \n _logService.Log(LogLevel.Info, $\"{ConfigType} configuration imported successfully. Updated {updatedCount} settings.\");\n \n // Get the names of all items that were set to IsSelected = true\n var selectedItems = Settings.Where(item => item.IsSelected).Select(item => item.Name).ToList();\n \n // Show dialog with the list of imported items\n CustomDialog.ShowInformation(\n \"Configuration Imported\",\n \"Configuration imported successfully.\",\n selectedItems,\n $\"The imported settings have been applied.\"\n );\n\n return true;\n }\n else\n {\n _logService.Log(LogLevel.Info, $\"No {ConfigType} configuration imported\");\n return false;\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error importing unified configuration: {ex.Message}\");\n await _dialogService.ShowErrorAsync(\"Error\", $\"Error importing unified configuration: {ex.Message}\");\n return false;\n }\n }\n\n /// \n /// Applies a loaded configuration to the settings.\n /// \n /// The configuration file to apply.\n /// The number of settings that were updated.\n protected virtual async Task ApplyConfigurationToSettings(ConfigurationFile configFile)\n {\n // This method should be overridden by derived classes to apply the configuration to their specific settings\n await Task.CompletedTask; // To keep the async signature\n return 0;\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/Methods/RegistryVerificationMethod.cs", "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Verification;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods\n{\n /// \n /// Verifies if a package is installed by checking the Windows Registry.\n /// This checks both 64-bit and 32-bit registry views.\n /// \n public class RegistryVerificationMethod : VerificationMethodBase\n {\n private const string UninstallKeyPath =\n @\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\";\n private const string UninstallKeyPathWow6432Node =\n @\"SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n public RegistryVerificationMethod()\n : base(\"Registry\", priority: 10) { }\n\n /// \n protected override async Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken = default\n )\n {\n return await Task.Run(\n () =>\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n // Check 64-bit registry view\n using (\n var baseKey = RegistryKey.OpenBaseKey(\n RegistryHive.LocalMachine,\n RegistryView.Registry64\n )\n )\n using (var uninstallKey = baseKey.OpenSubKey(UninstallKeyPath, writable: false))\n {\n var result = CheckRegistryKey(uninstallKey, packageId, null);\n if (result.IsVerified)\n {\n return result;\n }\n }\n\n // Check 32-bit registry view\n using (\n var baseKey = RegistryKey.OpenBaseKey(\n RegistryHive.LocalMachine,\n RegistryView.Registry32\n )\n )\n using (\n var uninstallKey = baseKey.OpenSubKey(\n UninstallKeyPathWow6432Node,\n writable: false\n )\n )\n {\n return CheckRegistryKey(uninstallKey, packageId, null);\n }\n },\n cancellationToken\n );\n }\n\n /// \n /// Checks a registry key for the presence of a package.\n /// \n /// The registry key to check.\n /// The package ID to look for.\n /// The version to check for, or null to check for any version.\n /// A indicating whether the package was found.\n private static VerificationResult CheckRegistryKey(\n RegistryKey uninstallKey,\n string packageId,\n string version\n )\n {\n if (uninstallKey == null)\n {\n return VerificationResult.Failure(\"Registry key not found\");\n }\n\n foreach (var subKeyName in uninstallKey.GetSubKeyNames())\n {\n using (var subKey = uninstallKey.OpenSubKey(subKeyName))\n {\n var displayName = subKey?.GetValue(\"DisplayName\") as string;\n if (string.IsNullOrEmpty(displayName))\n {\n continue;\n }\n\n // Check if the display name matches the package ID (case insensitive)\n if (displayName.IndexOf(packageId, StringComparison.OrdinalIgnoreCase) >= 0)\n {\n // If a version is specified, check if it matches\n if (version != null)\n {\n var displayVersion = subKey.GetValue(\"DisplayVersion\") as string;\n if (\n !string.Equals(\n displayVersion,\n version,\n StringComparison.OrdinalIgnoreCase\n )\n )\n {\n continue;\n }\n }\n\n var installLocation = subKey.GetValue(\"InstallLocation\") as string;\n var uninstallString = subKey.GetValue(\"UninstallString\") as string;\n var foundVersion = subKey.GetValue(\"DisplayVersion\") as string;\n\n return VerificationResult.Success(foundVersion);\n }\n }\n }\n\n return VerificationResult.Failure($\"Package '{packageId}' not found in registry\");\n }\n\n /// \n protected override async Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(version))\n {\n throw new ArgumentException(\n \"Version cannot be null or whitespace.\",\n nameof(version)\n );\n }\n\n return await VerifyPresenceAsync(packageId, cancellationToken).ConfigureAwait(false);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/CapabilityRemovalService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Management.Automation;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\nusing Winhance.Infrastructure.Features.Common.Utilities;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service for removing Windows capabilities from the system.\n/// \npublic class CapabilityRemovalService : ICapabilityRemovalService\n{\n private readonly ILogService _logService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IScheduledTaskService _scheduledTaskService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The app discovery service.\n /// The scheduled task service.\n public CapabilityRemovalService(\n ILogService logService,\n IAppDiscoveryService appDiscoveryService,\n IScheduledTaskService scheduledTaskService)\n {\n _logService = logService;\n _appDiscoveryService = appDiscoveryService;\n _scheduledTaskService = scheduledTaskService;\n }\n\n /// \n public async Task RemoveCapabilityAsync(\n CapabilityInfo capabilityInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (capabilityInfo == null)\n {\n throw new ArgumentNullException(nameof(capabilityInfo));\n }\n // Call the other overload and return its result\n return await RemoveCapabilityAsync(capabilityInfo.PackageName, progress, cancellationToken);\n }\n\n /// \n public async Task RemoveCapabilityAsync(\n string capabilityName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n try\n {\n progress?.Report(new TaskProgressDetail { Progress = 0, StatusText = $\"Starting removal of {capabilityName}...\" });\n _logService.LogInformation($\"Removing capability: {capabilityName}\");\n \n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n \n // Step 1: Get a list of all installed capabilities that match the pattern\n List capabilityNames = new List();\n try\n {\n powerShell.Commands.Clear();\n powerShell.AddScript($@\"\n Get-WindowsCapability -Online |\n Where-Object {{ $_.Name -like '{capabilityName}*' }} |\n Select-Object -ExpandProperty Name\n \");\n\n capabilityNames = (await Task.Run(() => powerShell.Invoke())).ToList();\n _logService.LogInformation($\"Found {capabilityNames.Count} capabilities matching '{capabilityName}*'\");\n \n // Log the found capabilities\n foreach (var capName in capabilityNames)\n {\n _logService.LogInformation($\"Found installed capability: {capName}\");\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error retrieving Windows capabilities for '{capabilityName}': {ex.Message}. Will proceed with empty capability list.\");\n // Continue with empty capability list\n }\n\n // If no capabilities found with exact name, try with a more flexible pattern\n if (capabilityNames == null || !capabilityNames.Any())\n {\n try\n {\n // Try with a more flexible pattern that might include tildes\n powerShell.Commands.Clear();\n powerShell.AddScript($@\"\n Get-WindowsCapability -Online |\n Where-Object {{ $_.Name -match '{capabilityName}' }} |\n Select-Object -ExpandProperty Name\n \");\n\n capabilityNames = (await Task.Run(() => powerShell.Invoke())).ToList();\n _logService.LogInformation($\"Found {capabilityNames.Count} capabilities with flexible pattern matching '{capabilityName}'\");\n \n // Log the found capabilities\n foreach (var capName in capabilityNames)\n {\n _logService.LogInformation($\"Found installed capability with flexible pattern: {capName}\");\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error retrieving capabilities with flexible pattern: {ex.Message}\");\n }\n }\n\n bool overallSuccess = true;\n \n if (capabilityNames != null && capabilityNames.Any())\n {\n int totalCapabilities = capabilityNames.Count;\n int currentCapability = 0;\n \n foreach (var capName in capabilityNames)\n {\n currentCapability++;\n progress?.Report(new TaskProgressDetail {\n Progress = (currentCapability * 100) / totalCapabilities,\n StatusText = $\"Removing capability {currentCapability} of {totalCapabilities}: {capName}\"\n });\n \n _logService.LogInformation($\"Removing installed capability: {capName}\");\n\n // Step 2: Remove the capability\n bool success = false;\n try\n {\n powerShell.Commands.Clear();\n powerShell.AddScript($@\"\n Remove-WindowsCapability -Name '{capName}' -Online -ErrorAction SilentlyContinue\n return $?\n \");\n\n var result = await Task.Run(() => powerShell.Invoke());\n success = result.FirstOrDefault();\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing capability '{capName}': {ex.Message}\");\n success = false;\n }\n\n if (success)\n {\n _logService.LogSuccess($\"Successfully removed capability: {capName}\");\n }\n else\n {\n _logService.LogError($\"Failed to remove capability: {capName}\");\n overallSuccess = false;\n }\n }\n \n // Update BloatRemoval.ps1 script and register scheduled task\n if (overallSuccess)\n {\n try\n {\n // Pass the full capability names (with version numbers) to the script update service\n var script = await UpdateBloatRemovalScriptAsync(capabilityNames);\n \n // Register the scheduled task to run the script at startup\n try\n {\n bool taskRegistered = await RegisterBloatRemovalTaskAsync(script);\n if (taskRegistered)\n {\n _logService.LogSuccess($\"Scheduled task registered for BloatRemoval.ps1\");\n }\n else\n {\n _logService.LogWarning($\"Failed to register scheduled task for BloatRemoval.ps1, but continuing operation\");\n }\n }\n catch (Exception taskEx)\n {\n _logService.LogError($\"Error registering scheduled task: {taskEx.Message}\");\n // Don't fail the removal if task registration fails\n }\n }\n catch (Exception scriptEx)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script: {scriptEx.Message}\");\n // Don't fail the removal if script update fails\n }\n }\n \n progress?.Report(new TaskProgressDetail {\n Progress = 100,\n StatusText = overallSuccess ? $\"Successfully removed all capabilities\" : $\"Some capabilities could not be removed\",\n DetailedMessage = $\"Removed {capabilityNames.Count} capabilities matching {capabilityName}\",\n LogLevel = overallSuccess ? LogLevel.Success : LogLevel.Warning\n });\n \n return overallSuccess;\n }\n else\n {\n _logService.LogInformation($\"No installed capabilities found matching: {capabilityName}*\");\n progress?.Report(new TaskProgressDetail {\n Progress = 100,\n StatusText = $\"No installed capabilities found matching: {capabilityName}*\",\n LogLevel = LogLevel.Warning\n });\n \n // Consider it a success if nothing needs to be removed\n return true;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing capability: {capabilityName}\", ex);\n progress?.Report(new TaskProgressDetail {\n Progress = 0,\n StatusText = $\"Error removing {capabilityName}: {ex.Message}\",\n LogLevel = LogLevel.Error\n });\n return false;\n }\n }\n\n // Add missing CanRemoveCapabilityAsync method\n /// \n public Task CanRemoveCapabilityAsync(CapabilityInfo capabilityInfo)\n {\n // Basic implementation: Assume all found capabilities can be removed.\n // TODO: Add actual checks if needed (e.g., dependencies)\n return Task.FromResult(true);\n }\n\n\n /// \n public async Task> RemoveCapabilitiesInBatchAsync(\n List capabilities)\n {\n if (capabilities == null)\n {\n throw new ArgumentNullException(nameof(capabilities));\n }\n\n return await RemoveCapabilitiesInBatchAsync(capabilities.Select(c => c.PackageName).ToList());\n }\n\n /// \n public async Task> RemoveCapabilitiesInBatchAsync(\n List capabilityNames)\n {\n var results = new List<(string Name, bool Success, string? Error)>();\n \n try\n {\n _logService.LogInformation($\"Removing {capabilityNames.Count} Windows capabilities\");\n \n using var powerShell = PowerShellFactory.CreateWindowsPowerShell(_logService);\n // No need to set execution policy as it's already done in the factory\n \n foreach (var capability in capabilityNames)\n {\n try\n {\n _logService.LogInformation($\"Removing capability: {capability}\");\n \n // Step 1: Get a list of all installed capabilities that match the pattern\n List matchingCapabilities = new List();\n try\n {\n powerShell.Commands.Clear();\n powerShell.AddScript($@\"\n Get-WindowsCapability -Online |\n Where-Object {{ $_.Name -like '{capability}*' -and $_.State -eq 'Installed' }} |\n Select-Object -ExpandProperty Name\n \");\n\n matchingCapabilities = (await Task.Run(() => powerShell.Invoke())).ToList();\n _logService.LogInformation($\"Found {matchingCapabilities.Count} capabilities matching '{capability}*' for batch removal\");\n \n // Log the found capabilities\n foreach (var capName in matchingCapabilities)\n {\n _logService.LogInformation($\"Found installed capability for batch removal: {capName}\");\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error retrieving Windows capabilities for batch removal '{capability}': {ex.Message}. Will proceed with empty capability list.\");\n // Continue with empty capability list\n }\n\n bool success = true;\n string? error = null;\n \n if (matchingCapabilities != null && matchingCapabilities.Any())\n {\n foreach (var capName in matchingCapabilities)\n {\n _logService.LogInformation($\"Removing installed capability in batch: {capName}\");\n\n // Step 2: Remove the capability\n bool capSuccess = false;\n try\n {\n powerShell.Commands.Clear();\n powerShell.AddScript($@\"\n Remove-WindowsCapability -Name '{capName}' -Online -ErrorAction SilentlyContinue\n return $?\n \");\n\n var capResult = await Task.Run(() => powerShell.Invoke());\n capSuccess = capResult.FirstOrDefault();\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error removing capability in batch '{capName}': {ex.Message}\");\n capSuccess = false;\n }\n\n if (capSuccess)\n {\n _logService.LogSuccess($\"Successfully removed capability in batch: {capName}\");\n }\n else\n {\n _logService.LogError($\"Failed to remove capability in batch: {capName}\");\n success = false;\n error = $\"Failed to remove one or more capabilities\";\n }\n }\n }\n else\n {\n _logService.LogInformation($\"No installed capabilities found matching for batch removal: {capability}*\");\n // Consider it a success if nothing needs to be removed\n success = true;\n }\n \n // If successful, update the BloatRemoval.ps1 script with the full capability names\n if (success && matchingCapabilities.Any())\n {\n try\n {\n await UpdateBloatRemovalScriptAsync(matchingCapabilities);\n _logService.LogInformation($\"Updated BloatRemoval.ps1 script with full capability names for batch removal\");\n }\n catch (Exception scriptEx)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for batch capability removal: {scriptEx.Message}\");\n // Don't fail the removal if script update fails\n }\n }\n \n results.Add((capability, success, error));\n }\n catch (Exception ex)\n {\n results.Add((capability, false, ex.Message));\n _logService.LogError($\"Error removing capability: {capability}\", ex);\n }\n }\n \n return results;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error removing capabilities\", ex);\n return capabilityNames.Select(c => (c, false, $\"Error: {ex.Message}\")).ToList();\n }\n }\n\n // SetExecutionPolicy is now handled by PowerShellFactory\n /// \n /// Updates the BloatRemoval.ps1 script to add the removed capabilities to it.\n /// \n /// The list of capability names with version numbers.\n /// The updated removal script.\n private async Task UpdateBloatRemovalScriptAsync(List capabilityNames)\n {\n try\n {\n // Get the script update service\n var scriptUpdateService = GetScriptUpdateService();\n if (scriptUpdateService == null)\n {\n _logService.LogWarning(\"Script update service not available\");\n throw new InvalidOperationException(\"Script update service not available\");\n }\n \n // Update the script with the full capability names (including version numbers)\n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n \n _logService.LogInformation($\"Updating BloatRemoval.ps1 script for {capabilityNames.Count} capabilities\");\n \n try\n {\n var script = await scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n capabilityNames,\n appsWithRegistry,\n appSubPackages,\n false); // false = removal operation, so add to script\n \n _logService.LogInformation($\"Successfully updated BloatRemoval.ps1 script for capabilities\");\n return script;\n }\n catch (FileNotFoundException)\n {\n _logService.LogInformation($\"BloatRemoval.ps1 script not found. It will be created when needed.\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in script update service for capabilities: {ex.Message}\", ex);\n throw;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for capabilities: {ex.Message}\", ex);\n throw;\n }\n }\n\n /// \n /// Updates the BloatRemoval.ps1 script to add the removed capability to it.\n /// \n /// The capability name.\n /// The updated removal script.\n private async Task UpdateBloatRemovalScriptAsync(string capabilityName)\n {\n try\n {\n // Get the script update service\n var scriptUpdateService = GetScriptUpdateService();\n if (scriptUpdateService == null)\n {\n _logService.LogWarning(\"Script update service not available\");\n throw new InvalidOperationException(\"Script update service not available\");\n }\n \n // Update the script\n var appNames = new List { capabilityName };\n var appsWithRegistry = new Dictionary>();\n var appSubPackages = new Dictionary();\n \n _logService.LogInformation($\"Updating BloatRemoval.ps1 script for capability: {capabilityName}\");\n \n try\n {\n var script = await scriptUpdateService.UpdateExistingBloatRemovalScriptAsync(\n appNames,\n appsWithRegistry,\n appSubPackages,\n false); // false = removal operation, so add to script\n \n _logService.LogInformation($\"Successfully updated BloatRemoval.ps1 script for capability: {capabilityName}\");\n return script;\n }\n catch (FileNotFoundException)\n {\n _logService.LogInformation($\"BloatRemoval.ps1 script not found. It will be created when needed.\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in script update service for capability: {capabilityName}\", ex);\n throw;\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating BloatRemoval.ps1 script for capability: {capabilityName}\", ex);\n throw;\n }\n }\n /// \n /// Registers a scheduled task to run the BloatRemoval script at startup.\n /// \n /// The removal script to register.\n /// True if the task was registered successfully, false otherwise.\n private async Task RegisterBloatRemovalTaskAsync(RemovalScript script)\n {\n try\n {\n if (script == null)\n {\n _logService.LogError(\"Cannot register scheduled task: Script is null\");\n return false;\n }\n \n _logService.LogInformation(\"Registering scheduled task for BloatRemoval.ps1\");\n \n \n // Register the scheduled task\n bool success = await _scheduledTaskService.RegisterScheduledTaskAsync(script);\n \n if (success)\n {\n _logService.LogSuccess(\"Successfully registered scheduled task for BloatRemoval.ps1\");\n }\n else\n {\n _logService.LogError(\"Failed to register scheduled task for BloatRemoval.ps1\");\n }\n \n return success;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error registering scheduled task for BloatRemoval.ps1\", ex);\n return false;\n }\n }\n \n /// \n /// Gets the script update service.\n /// \n /// The script update service or null if not available.\n private IScriptUpdateService? GetScriptUpdateService()\n {\n try\n {\n // This is a simplified implementation. In a real application, you would use dependency injection.\n // For now, we'll create a new instance directly.\n // Use the injected _appDiscoveryService instead of creating a new instance\n var scriptContentModifier = new ScriptContentModifier(_logService);\n return new ScriptUpdateService(_logService, _appDiscoveryService, scriptContentModifier);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to get script update service\", ex);\n return null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/CustomDialog.xaml.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n public partial class CustomDialog : Window\n {\n\n public CustomDialog()\n {\n InitializeComponent();\n DataContext = this;\n }\n\n private void PrimaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = true;\n Close();\n }\n\n private void SecondaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = false;\n Close();\n }\n\n private void TertiaryButton_Click(object sender, RoutedEventArgs e)\n {\n // Explicitly set DialogResult to null for Cancel\n DialogResult = null;\n\n Close();\n }\n\n public static CustomDialog CreateConfirmationDialog(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = new CustomDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"QuestionIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.MessageContent.Text = message;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"Yes\";\n dialog.SecondaryButton.Content = \"No\";\n\n return dialog;\n }\n\n public static CustomDialog CreateConfirmationDialog(\n string title,\n string headerText,\n IEnumerable items,\n string footerText\n )\n {\n string message = items != null ? string.Join(Environment.NewLine, items) : string.Empty;\n return CreateConfirmationDialog(title, headerText, message, footerText);\n }\n\n public static CustomDialog CreateInformationDialog(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = new CustomDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"InfoIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.MessageContent.Text = message;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"OK\";\n dialog.SecondaryButton.Visibility = Visibility.Collapsed;\n\n return dialog;\n }\n\n public static CustomDialog CreateInformationDialog(\n string title,\n string headerText,\n IEnumerable items,\n string footerText,\n bool useMultiColumnLayout = false\n )\n {\n string message = items != null ? string.Join(Environment.NewLine, items) : string.Empty;\n return CreateInformationDialog(title, headerText, message, footerText);\n }\n\n public static bool? ShowConfirmation(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = CreateConfirmationDialog(title, headerText, message, footerText);\n return dialog.ShowDialog();\n }\n\n public static bool? ShowConfirmation(\n string title,\n string headerText,\n IEnumerable items,\n string footerText\n )\n {\n var dialog = CreateConfirmationDialog(title, headerText, items, footerText);\n return dialog.ShowDialog();\n }\n\n public static void ShowInformation(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = CreateInformationDialog(title, headerText, message, footerText);\n dialog.ShowDialog();\n }\n\n public static void ShowInformation(\n string title,\n string headerText,\n IEnumerable items,\n string footerText\n )\n {\n var dialog = CreateInformationDialog(title, headerText, items, footerText);\n dialog.ShowDialog();\n }\n\n public static CustomDialog CreateYesNoCancelDialog(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = new CustomDialog { Title = title };\n\n dialog.DialogIcon.Source = Application.Current.Resources[\"QuestionIcon\"] as ImageSource;\n dialog.HeaderText.Text = headerText;\n dialog.MessageContent.Text = message;\n dialog.FooterText.Text = footerText;\n\n dialog.PrimaryButton.Content = \"Yes\";\n dialog.SecondaryButton.Content = \"No\";\n dialog.TertiaryButton.Content = \"Cancel\";\n\n // Ensure the Cancel button is visible and properly styled\n dialog.TertiaryButton.Visibility = Visibility.Visible;\n dialog.TertiaryButton.IsCancel = true;\n\n return dialog;\n }\n\n public static CustomDialog CreateYesNoCancelDialog(\n string title,\n string headerText,\n IEnumerable items,\n string footerText\n )\n {\n string message = items != null ? string.Join(Environment.NewLine, items) : string.Empty;\n return CreateYesNoCancelDialog(title, headerText, message, footerText);\n }\n\n public static bool? ShowYesNoCancel(\n string title,\n string headerText,\n string message,\n string footerText\n )\n {\n var dialog = CreateYesNoCancelDialog(title, headerText, message, footerText);\n\n // Add event handler for the Closing event to ensure DialogResult is set correctly\n dialog.Closing += (sender, e) =>\n {\n // If DialogResult is not explicitly set (e.g., if the dialog is closed by clicking outside or pressing Escape),\n // set it to null to indicate Cancel\n if (dialog.DialogResult == null) { }\n };\n\n // Add event handler for the KeyDown event to handle Escape key\n dialog.KeyDown += (sender, e) =>\n {\n if (e.Key == System.Windows.Input.Key.Escape)\n {\n dialog.DialogResult = null;\n dialog.Close();\n }\n };\n\n // Show the dialog and get the result\n var result = dialog.ShowDialog();\n\n return result;\n }\n\n public static bool? ShowYesNoCancel(\n string title,\n string headerText,\n IEnumerable items,\n string footerText\n )\n {\n var dialog = CreateYesNoCancelDialog(title, headerText, items, footerText);\n\n // Add event handler for the Closing event to ensure DialogResult is set correctly\n dialog.Closing += (sender, e) =>\n {\n // If DialogResult is not explicitly set (e.g., if the dialog is closed by clicking outside or pressing Escape),\n // set it to null to indicate Cancel\n if (dialog.DialogResult == null) { }\n };\n\n // Add event handler for the KeyDown event to handle Escape key\n dialog.KeyDown += (sender, e) =>\n {\n if (e.Key == System.Windows.Input.Key.Escape)\n {\n dialog.DialogResult = null;\n dialog.Close();\n }\n };\n\n // Show the dialog and get the result\n var result = dialog.ShowDialog();\n\n return result;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/SearchableViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// Base view model class that provides search functionality.\n /// \n /// The type of items to search, must implement ISearchable.\n public abstract partial class SearchableViewModel : AppListViewModel where T : class, ISearchable\n {\n private readonly ISearchService _searchService;\n\n // Backing field for the search text\n private string _searchText = string.Empty;\n\n /// \n /// Gets or sets the search text.\n /// \n public virtual string SearchText\n {\n get => _searchText;\n set\n {\n if (SetProperty(ref _searchText, value))\n {\n IsSearchActive = !string.IsNullOrWhiteSpace(value);\n ApplySearch();\n }\n }\n }\n\n /// \n /// Gets a value indicating whether search is active.\n /// \n [ObservableProperty]\n private bool _isSearchActive;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The search service.\n /// The package manager.\n protected SearchableViewModel(\n ITaskProgressService progressService,\n ISearchService searchService,\n IPackageManager? packageManager = null) \n : base(progressService, packageManager)\n {\n _searchService = searchService ?? throw new ArgumentNullException(nameof(searchService));\n }\n\n /// \n /// Applies the current search text to filter items.\n /// \n protected abstract void ApplySearch();\n\n /// \n /// Filters a collection of items based on the current search text.\n /// \n /// The collection of items to filter.\n /// A filtered collection of items that match the search text.\n protected IEnumerable FilterItems(IEnumerable items)\n {\n Console.WriteLine($\"SearchableViewModel.FilterItems: Filtering {items.Count()} items with search text '{SearchText}'\");\n \n // Log items before filtering\n foreach (var item in items)\n {\n var itemName = item.GetType().GetProperty(\"Name\")?.GetValue(item)?.ToString();\n var itemGroupName = item.GetType().GetProperty(\"GroupName\")?.GetValue(item)?.ToString();\n \n if (itemName?.Contains(\"Web Search\") == true || itemGroupName?.Contains(\"Search\") == true)\n {\n Console.WriteLine($\"SearchableViewModel.FilterItems: Found item before filtering - Name: '{itemName}', GroupName: '{itemGroupName}'\");\n }\n }\n \n var result = _searchService.FilterItems(items, SearchText);\n \n // Log filtered results\n Console.WriteLine($\"SearchableViewModel.FilterItems: Filtered result count: {result.Count()}\");\n \n return result;\n }\n\n /// \n /// Asynchronously filters a collection of items based on the current search text.\n /// \n /// The collection of items to filter.\n /// A task that represents the asynchronous operation. The task result contains a filtered collection of items that match the search text.\n protected Task> FilterItemsAsync(IEnumerable items)\n {\n return _searchService.FilterItemsAsync(items, SearchText);\n }\n\n /// \n /// Clears the search text.\n /// \n protected void ClearSearch()\n {\n SearchText = string.Empty;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/UnifiedConfigurationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Services.Configuration;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for managing unified configuration operations across the application.\n /// \n public class UnifiedConfigurationService : IUnifiedConfigurationService\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly IConfigurationService _configurationService;\n private readonly ILogService _logService;\n private readonly IDialogService _dialogService;\n private readonly IRegistryService _registryService;\n private readonly ConfigurationCollectorService _collectorService;\n private readonly IConfigurationApplierService _applierService;\n private readonly ConfigurationUIService _uiService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The configuration service.\n /// The log service.\n /// The dialog service.\n /// The registry service.\n public UnifiedConfigurationService(\n IServiceProvider serviceProvider,\n IConfigurationService configurationService,\n ILogService logService,\n IDialogService dialogService,\n IRegistryService registryService)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _registryService = registryService ?? throw new ArgumentNullException(nameof(registryService));\n \n // Initialize helper services\n _collectorService = new ConfigurationCollectorService(serviceProvider, logService);\n _applierService = serviceProvider.GetRequiredService();\n _uiService = new ConfigurationUIService(logService);\n }\n\n /// \n /// Creates a unified configuration file containing settings from all view models.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file.\n public async Task CreateUnifiedConfigurationAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Creating unified configuration from all view models\");\n \n // Collect settings from all view models\n var sectionSettings = await _collectorService.CollectAllSettingsAsync();\n \n // Create a list of all available sections - include all sections by default\n var availableSections = new List { \"WindowsApps\", \"ExternalApps\", \"Customize\", \"Optimize\" };\n\n // Create and return the unified configuration\n var unifiedConfig = _configurationService.CreateUnifiedConfiguration(sectionSettings, availableSections);\n \n _logService.Log(LogLevel.Info, \"Successfully created unified configuration from all view models\");\n \n return unifiedConfig;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error creating unified configuration: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Saves a unified configuration file.\n /// \n /// The unified configuration to save.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n public async Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile config)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Saving unified configuration\");\n \n bool saveResult = await _configurationService.SaveUnifiedConfigurationAsync(config);\n \n if (saveResult)\n {\n _logService.Log(LogLevel.Info, \"Unified configuration saved successfully\");\n // Success dialog is now shown only in MainViewModel to avoid duplicate dialogs\n }\n else\n {\n _logService.Log(LogLevel.Info, \"Save unified configuration canceled by user\");\n }\n \n return saveResult;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error saving unified configuration: {ex.Message}\");\n _dialogService.ShowMessage($\"Error saving unified configuration: {ex.Message}\", \"Error\");\n return false;\n }\n }\n\n /// \n /// Loads a unified configuration file.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file if successful, null otherwise.\n public async Task LoadUnifiedConfigurationAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Loading unified configuration\");\n \n var unifiedConfig = await _configurationService.LoadUnifiedConfigurationAsync();\n \n if (unifiedConfig == null)\n {\n _logService.Log(LogLevel.Info, \"Load unified configuration canceled by user\");\n return null;\n }\n \n _logService.Log(LogLevel.Info, $\"Configuration loaded with sections: WindowsApps ({unifiedConfig.WindowsApps.Items.Count} items), \" +\n $\"ExternalApps ({unifiedConfig.ExternalApps.Items.Count} items), \" +\n $\"Customize ({unifiedConfig.Customize.Items.Count} items), \" +\n $\"Optimize ({unifiedConfig.Optimize.Items.Count} items)\");\n \n return unifiedConfig;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading unified configuration: {ex.Message}\");\n _dialogService.ShowMessage($\"Error loading unified configuration: {ex.Message}\", \"Error\");\n return null;\n }\n }\n\n /// \n /// Shows the unified configuration dialog to let the user select which sections to include.\n /// \n /// The unified configuration file.\n /// Whether this is a save dialog (true) or an import dialog (false).\n /// A dictionary of section names and their selection state.\n public async Task> ShowUnifiedConfigurationDialogAsync(UnifiedConfigurationFile config, bool isSaveDialog)\n {\n return await _uiService.ShowUnifiedConfigurationDialogAsync(config, isSaveDialog);\n }\n\n /// \n /// Applies a unified configuration to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n public async Task ApplyUnifiedConfigurationAsync(UnifiedConfigurationFile config, IEnumerable selectedSections)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Applying unified configuration to selected sections: {string.Join(\", \", selectedSections)}\");\n \n // Log the contents of the unified configuration\n _logService.Log(LogLevel.Debug, $\"Unified configuration contains: \" +\n $\"WindowsApps: {config.WindowsApps?.Items?.Count ?? 0} items, \" +\n $\"ExternalApps: {config.ExternalApps?.Items?.Count ?? 0} items, \" +\n $\"Customize: {config.Customize?.Items?.Count ?? 0} items, \" +\n $\"Optimize: {config.Optimize?.Items?.Count ?? 0} items\");\n \n // Validate the configuration\n if (config == null)\n {\n _logService.Log(LogLevel.Error, \"Unified configuration is null\");\n return false;\n }\n \n // Validate the selected sections\n if (selectedSections == null || !selectedSections.Any())\n {\n _logService.Log(LogLevel.Error, \"No sections selected for import\");\n return false;\n }\n \n // Apply the configuration to the selected sections\n var sectionResults = await _applierService.ApplySectionsAsync(config, selectedSections);\n \n // Log the results for each section\n _logService.Log(LogLevel.Info, \"Import results by section:\");\n foreach (var sectionResult in sectionResults)\n {\n _logService.Log(LogLevel.Info, $\" {sectionResult.Key}: {(sectionResult.Value ? \"Success\" : \"Failed\")}\");\n }\n \n bool overallResult = sectionResults.All(r => r.Value);\n _logService.Log(LogLevel.Info, $\"Finished applying unified configuration to selected sections. Overall result: {(overallResult ? \"Success\" : \"Partial failure\")}\");\n \n return overallResult;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying unified configuration: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n return false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScriptContentModifier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\n/// \n/// Implementation of IScriptContentModifier that provides methods for modifying script content.\n/// \npublic class ScriptContentModifier : IScriptContentModifier\n{\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public ScriptContentModifier(ILogService logService)\n {\n _logService = logService;\n }\n\n /// \n public string RemoveCapabilityFromScript(string scriptContent, string capabilityName)\n {\n // Find the capabilities array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$capabilities = @(\");\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $capabilities array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the capabilities array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find end of $capabilities array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the capabilities in the array\n var capabilities = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var capability = trimmedLine.Trim('\\'', '\"', ' ', ',');\n capabilities.Add(capability);\n }\n }\n\n // Check if the capability is in the array\n bool removed =\n capabilities.RemoveAll(c =>\n c.Equals(capabilityName, StringComparison.OrdinalIgnoreCase)\n ) > 0;\n\n if (!removed)\n {\n // Capability not found in the array\n return scriptContent;\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$capabilities = @(\");\n\n // Add capabilities without trailing comma on the last item\n for (int i = 0; i < capabilities.Count; i++)\n {\n string capability = capabilities[i];\n if (i < capabilities.Count - 1)\n {\n newArrayContent.AppendLine($\" '{capability}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{capability}'\");\n }\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n\n /// \n public string RemovePackageFromScript(string scriptContent, string packageName)\n {\n // Find the packages array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$packages = @(\");\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the packages array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\"Could not find end of $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the packages in the array\n var packages = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var package = trimmedLine.Trim('\\'', '\"', ' ', ',');\n packages.Add(package);\n }\n }\n\n // Check if the package is in the array\n bool removed =\n packages.RemoveAll(p => p.Equals(packageName, StringComparison.OrdinalIgnoreCase)) > 0;\n\n if (!removed)\n {\n // Package not found in the array\n return scriptContent;\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$packages = @(\");\n\n // Add packages without trailing comma on the last item\n for (int i = 0; i < packages.Count; i++)\n {\n string package = packages[i];\n if (i < packages.Count - 1)\n {\n newArrayContent.AppendLine($\" '{package}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{package}'\");\n }\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n\n /// \n public string RemoveOptionalFeatureFromScript(string scriptContent, string featureName)\n {\n // Check if the optional features section exists\n int sectionStartIndex = scriptContent.IndexOf(\"# Disable Optional Features\");\n if (sectionStartIndex == -1)\n {\n // Optional features section doesn't exist, so nothing to remove\n return scriptContent;\n }\n\n // Find the optional features array\n int arrayStartIndex = scriptContent.IndexOf(\"$optionalFeatures = @(\", sectionStartIndex);\n if (arrayStartIndex == -1)\n {\n _logService.LogWarning(\"Could not find $optionalFeatures array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the optional features array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n _logService.LogWarning(\n \"Could not find end of $optionalFeatures array in BloatRemoval.ps1\"\n );\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the optional features in the array\n var optionalFeatures = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var feature = trimmedLine.Trim('\\'', '\"', ' ', ',');\n optionalFeatures.Add(feature);\n }\n }\n\n // Check if the feature is in the array\n bool removed =\n optionalFeatures.RemoveAll(f =>\n f.Equals(featureName, StringComparison.OrdinalIgnoreCase)\n ) > 0;\n\n if (!removed)\n {\n // Feature not found in the array\n return scriptContent;\n }\n\n // If the array is now empty, remove the entire optional features section\n if (optionalFeatures.Count == 0)\n {\n // Find the end of the optional features section\n int sectionEndIndex = scriptContent.IndexOf(\n \"foreach ($feature in $optionalFeatures) {\",\n arrayEndIndex\n );\n if (sectionEndIndex != -1)\n {\n sectionEndIndex = scriptContent.IndexOf(\"}\", sectionEndIndex);\n if (sectionEndIndex != -1)\n {\n sectionEndIndex = scriptContent.IndexOf('\\n', sectionEndIndex);\n if (sectionEndIndex != -1)\n {\n // Remove the entire section\n return scriptContent.Substring(0, sectionStartIndex)\n + scriptContent.Substring(sectionEndIndex + 1);\n }\n }\n }\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$optionalFeatures = @(\");\n\n // Add features without trailing comma on the last item\n for (int i = 0; i < optionalFeatures.Count; i++)\n {\n string feature = optionalFeatures[i];\n if (i < optionalFeatures.Count - 1)\n {\n newArrayContent.AppendLine($\" '{feature}',\");\n }\n else\n {\n newArrayContent.AppendLine($\" '{feature}'\");\n }\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n\n /// \n public string RemoveAppRegistrySettingsFromScript(string scriptContent, string appName)\n {\n // Find the registry settings section\n int registrySection = scriptContent.IndexOf(\"# Registry settings\");\n if (registrySection == -1)\n {\n return scriptContent;\n }\n\n // Generate possible section headers for this app\n var possibleSectionHeaders = new List\n {\n $\"# Registry settings for {appName}\",\n $\"# Registry settings for Microsoft.{appName}\",\n };\n\n // Add variations without \"Microsoft.\" prefix if it already has it\n if (appName.StartsWith(\"Microsoft.\", StringComparison.OrdinalIgnoreCase))\n {\n string nameWithoutPrefix = appName.Substring(\"Microsoft.\".Length);\n possibleSectionHeaders.Add($\"# Registry settings for {nameWithoutPrefix}\");\n }\n\n // Add common variations\n possibleSectionHeaders.Add($\"# Registry settings for {appName}_8wekyb3d8bbwe\");\n\n // For Copilot specifically, add known variations\n if (appName.Contains(\"Copilot\", StringComparison.OrdinalIgnoreCase))\n {\n possibleSectionHeaders.Add(\"# Registry settings for Copilot\");\n possibleSectionHeaders.Add(\"# Registry settings for Microsoft.Copilot\");\n possibleSectionHeaders.Add(\"# Registry settings for Windows.Copilot\");\n }\n\n // For Xbox/GamingApp specifically, add known variations\n if (\n appName.Contains(\"Xbox\", StringComparison.OrdinalIgnoreCase)\n || appName.Equals(\"Microsoft.GamingApp\", StringComparison.OrdinalIgnoreCase)\n )\n {\n possibleSectionHeaders.Add(\"# Registry settings for Xbox\");\n possibleSectionHeaders.Add(\"# Registry settings for Microsoft.Xbox\");\n possibleSectionHeaders.Add(\"# Registry settings for GamingApp\");\n }\n\n // Find the earliest matching section header\n int appSection = -1;\n string matchedHeader = null;\n\n foreach (var header in possibleSectionHeaders)\n {\n int index = scriptContent.IndexOf(header, registrySection);\n if (index != -1 && (appSection == -1 || index < appSection))\n {\n appSection = index;\n matchedHeader = header;\n }\n }\n\n if (appSection == -1)\n {\n _logService.LogInformation($\"No registry settings found for {appName} in the script\");\n return scriptContent;\n }\n\n _logService.LogInformation(\n $\"Found registry settings for {appName} with header: {matchedHeader}\"\n );\n\n // Find the end of the app section (next section or end of file)\n int nextSection = scriptContent.IndexOf(\n \"# Registry settings for\",\n appSection + matchedHeader.Length\n );\n if (nextSection == -1)\n {\n // Look for the next major section\n nextSection = scriptContent.IndexOf(\"# Prevent apps from reinstalling\", appSection);\n if (nextSection == -1)\n {\n // If no next section, just return the original content\n _logService.LogWarning(\n $\"Could not find end of registry settings section for {appName}\"\n );\n return scriptContent;\n }\n }\n\n // Remove the app registry settings section\n _logService.LogInformation($\"Removing registry settings for {appName} from script\");\n return scriptContent.Substring(0, appSection) + scriptContent.Substring(nextSection);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ConfigurationApplierService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for applying configuration settings to different view models.\n /// \n public class ConfigurationApplierService : IConfigurationApplierService\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n private readonly IEnumerable _sectionAppliers;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n /// The section-specific configuration appliers.\n public ConfigurationApplierService(\n IServiceProvider serviceProvider,\n ILogService logService,\n IEnumerable sectionAppliers)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _sectionAppliers = sectionAppliers ?? throw new ArgumentNullException(nameof(sectionAppliers));\n }\n\n /// \n /// Applies configuration settings to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A dictionary of section names and their application result.\n public async Task> ApplySectionsAsync(UnifiedConfigurationFile config, IEnumerable selectedSections)\n {\n var sectionResults = new Dictionary();\n \n // Use a cancellation token with a timeout to prevent hanging\n using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120)); // Increased timeout\n var cancellationToken = cancellationTokenSource.Token;\n \n // Track execution time\n var startTime = DateTime.Now;\n _logService.Log(LogLevel.Info, $\"Starting ApplySectionsAsync at {startTime}\");\n \n foreach (var section in selectedSections)\n {\n var sectionStartTime = DateTime.Now;\n _logService.Log(LogLevel.Info, $\"Processing section: {section} at {sectionStartTime}\");\n \n // Check for cancellation\n if (cancellationToken.IsCancellationRequested)\n {\n _logService.Log(LogLevel.Warning, $\"Skipping section {section} due to timeout\");\n sectionResults[section] = false;\n continue;\n }\n \n // Extract the section from the unified configuration\n var configFile = ExtractSectionFromUnifiedConfiguration(config, section);\n \n if (configFile == null)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to extract section {section} from unified configuration\");\n sectionResults[section] = false;\n continue;\n }\n \n if (configFile.Items == null || !configFile.Items.Any())\n {\n _logService.Log(LogLevel.Warning, $\"Section {section} is empty or not included in the unified configuration\");\n sectionResults[section] = false;\n continue;\n }\n \n _logService.Log(LogLevel.Info, $\"Extracted section {section} with {configFile.Items.Count} items\");\n \n // Apply the configuration to the appropriate view model\n bool sectionResult = false;\n \n try\n {\n // Find the appropriate section applier\n var sectionApplier = _sectionAppliers.FirstOrDefault(a => a.SectionName.Equals(section, StringComparison.OrdinalIgnoreCase));\n \n if (sectionApplier != null)\n {\n _logService.Log(LogLevel.Info, $\"Starting to apply configuration for section {section}\");\n \n // Apply with timeout protection\n var applyTask = sectionApplier.ApplyConfigAsync(configFile);\n \n // Set a section-specific timeout (longer for Optimize section which has power plan operations)\n int timeoutMs = section.Equals(\"Optimize\", StringComparison.OrdinalIgnoreCase) ? 60000 : 30000; // Increased timeouts\n \n _logService.Log(LogLevel.Info, $\"Setting timeout of {timeoutMs}ms for section {section}\");\n \n // Create a separate cancellation token source for this section\n using var sectionCts = new CancellationTokenSource(timeoutMs);\n var sectionCancellationToken = sectionCts.Token;\n \n try\n {\n // Wait for the task to complete or timeout\n var delayTask = Task.Delay(timeoutMs, sectionCancellationToken);\n var completedTask = await Task.WhenAny(applyTask, delayTask);\n \n if (completedTask == applyTask)\n {\n sectionResult = await applyTask;\n _logService.Log(LogLevel.Info, $\"Section {section} applied with result: {sectionResult}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"Applying section {section} timed out after {timeoutMs}ms\");\n \n // Try to cancel the operation if possible\n sectionCts.Cancel();\n \n // Log detailed information about the section\n _logService.Log(LogLevel.Warning, $\"Section {section} details: {configFile.Items?.Count ?? 0} items\");\n \n sectionResult = false;\n }\n }\n catch (OperationCanceledException)\n {\n _logService.Log(LogLevel.Warning, $\"Section {section} application was canceled\");\n sectionResult = false;\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No applier found for section: {section}\");\n sectionResult = false;\n }\n \n // If we have items but didn't update any, consider it a success\n // This handles the case where all items are already in the desired state\n if (!sectionResult && configFile.Items != null && configFile.Items.Any())\n {\n _logService.Log(LogLevel.Info, $\"No items were updated in section {section}, but considering it a success since configuration was applied\");\n sectionResult = true;\n }\n }\n catch (TaskCanceledException)\n {\n _logService.Log(LogLevel.Warning, $\"Applying section {section} was canceled due to timeout\");\n sectionResult = false;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying configuration to section {section}: {ex.Message}\");\n _logService.Log(LogLevel.Debug, $\"Exception details: {ex}\");\n sectionResult = false;\n }\n \n sectionResults[section] = sectionResult;\n }\n \n // Calculate and log execution time\n var endTime = DateTime.Now;\n var executionTime = endTime - startTime;\n _logService.Log(LogLevel.Info, $\"Completed ApplySectionsAsync in {executionTime.TotalSeconds:F2} seconds\");\n \n // Log summary of results\n foreach (var result in sectionResults)\n {\n _logService.Log(LogLevel.Info, $\"Section {result.Key}: {(result.Value ? \"Success\" : \"Failed\")}\");\n }\n \n return sectionResults;\n }\n\n private ConfigurationFile ExtractSectionFromUnifiedConfiguration(UnifiedConfigurationFile unifiedConfig, string section)\n {\n try\n {\n var configFile = new ConfigurationFile\n {\n ConfigType = section,\n Items = new List()\n };\n\n switch (section)\n {\n case \"WindowsApps\":\n configFile.Items = unifiedConfig.WindowsApps.Items;\n break;\n case \"ExternalApps\":\n configFile.Items = unifiedConfig.ExternalApps.Items;\n break;\n case \"Customize\":\n configFile.Items = unifiedConfig.Customize.Items;\n break;\n case \"Optimize\":\n configFile.Items = unifiedConfig.Optimize.Items;\n break;\n default:\n _logService.Log(LogLevel.Warning, $\"Unknown section: {section}\");\n return null;\n }\n\n return configFile;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error extracting section {section}: {ex.Message}\");\n return null;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/BaseViewModel.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Runtime.CompilerServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// Base view model class that implements INotifyPropertyChanged and provides common functionality.\n /// \n public abstract class BaseViewModel : ObservableObject, IDisposable, IViewModel\n {\n private readonly ITaskProgressService _progressService;\n private readonly ILogService _logService;\n private readonly IMessengerService _messengerService;\n private bool _isDisposed;\n private bool _isLoading;\n private string _statusText = string.Empty;\n private double _currentProgress;\n private bool _isIndeterminate;\n private ObservableCollection _logMessages =\n new ObservableCollection();\n private bool _areDetailsExpanded;\n private bool _canCancelTask;\n private bool _isTaskRunning;\n private ICommand _cancelCommand;\n\n /// \n /// Gets or sets whether the view model is loading.\n /// \n public bool IsLoading\n {\n get => _isLoading;\n protected set => SetProperty(ref _isLoading, value);\n }\n\n /// \n /// Gets the command to cancel the current task.\n /// \n public ICommand CancelCommand =>\n _cancelCommand ??= new RelayCommand(CancelCurrentTask, () => CanCancelTask);\n\n /// \n /// Gets or sets the status text.\n /// \n public string StatusText\n {\n get => _statusText;\n protected set => SetProperty(ref _statusText, value);\n }\n\n /// \n /// Gets or sets the current progress value (0-100).\n /// \n public double CurrentProgress\n {\n get => _currentProgress;\n protected set => SetProperty(ref _currentProgress, value);\n }\n\n /// \n /// Gets or sets whether the progress is indeterminate.\n /// \n public bool IsIndeterminate\n {\n get => _isIndeterminate;\n protected set => SetProperty(ref _isIndeterminate, value);\n }\n\n /// \n /// Gets the collection of log messages.\n /// \n public ObservableCollection LogMessages => _logMessages;\n\n /// \n /// Gets or sets whether the details are expanded.\n /// \n public bool AreDetailsExpanded\n {\n get => _areDetailsExpanded;\n set => SetProperty(ref _areDetailsExpanded, value);\n }\n\n /// \n /// Gets or sets whether the task can be cancelled.\n /// \n public bool CanCancelTask\n {\n get => _canCancelTask;\n protected set => SetProperty(ref _canCancelTask, value);\n }\n\n /// \n /// Gets or sets whether a task is running.\n /// \n public bool IsTaskRunning\n {\n get => _isTaskRunning;\n protected set => SetProperty(ref _isTaskRunning, value);\n }\n\n /// \n /// Gets the command to cancel the current task.\n /// \n public ICommand CancelTaskCommand { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The log service.\n /// The messenger service.\n protected BaseViewModel(\n ITaskProgressService progressService,\n ILogService logService,\n IMessengerService messengerService\n )\n {\n _progressService =\n progressService ?? throw new ArgumentNullException(nameof(progressService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _messengerService =\n messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n\n // Subscribe to progress service events\n if (_progressService != null)\n {\n _progressService.ProgressUpdated -= ProgressService_ProgressUpdated;\n _progressService.ProgressUpdated += ProgressService_ProgressUpdated;\n _progressService.LogMessageAdded -= ProgressService_LogMessageAdded;\n _progressService.LogMessageAdded += ProgressService_LogMessageAdded;\n }\n\n CancelTaskCommand = new RelayCommand(\n CancelCurrentTask,\n () => CanCancelTask && IsTaskRunning\n );\n _cancelCommand = CancelTaskCommand; // Ensure both commands point to the same implementation\n }\n\n /// \n /// Initializes a new instance of the class.\n /// This constructor is for backward compatibility.\n /// \n /// The task progress service.\n /// The messenger service.\n protected BaseViewModel(\n ITaskProgressService progressService,\n IMessengerService messengerService\n )\n : this(\n progressService,\n new Core.Features.Common.Services.LogService(),\n messengerService\n ) { }\n\n /// \n /// Initializes a new instance of the class.\n /// This constructor is for backward compatibility.\n /// \n /// The task progress service.\n protected BaseViewModel(ITaskProgressService progressService)\n : this(\n progressService,\n new Core.Features.Common.Services.LogService(),\n new Features.Common.Services.MessengerService()\n ) { }\n\n /// \n /// Disposes of the resources used by the ViewModel\n /// \n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n /// \n /// Disposes of the resources used by the ViewModel\n /// \n /// Whether to dispose of managed resources\n protected virtual void Dispose(bool disposing)\n {\n if (!_isDisposed)\n {\n if (disposing)\n {\n // Unsubscribe from events\n _progressService.ProgressUpdated -= ProgressService_ProgressUpdated;\n _progressService.LogMessageAdded -= ProgressService_LogMessageAdded;\n\n // Unregister from messenger\n if (_messengerService != null)\n {\n _messengerService.Unregister(this);\n }\n }\n\n _isDisposed = true;\n }\n }\n\n /// \n /// Finalizer to ensure resources are released\n /// \n ~BaseViewModel()\n {\n Dispose(false);\n }\n\n /// \n /// Called when the view model is navigated to\n /// \n /// Navigation parameter\n public virtual void OnNavigatedTo(object? parameter = null)\n {\n // Base implementation does nothing\n // Derived classes should override if they need to handle parameters\n }\n\n /// \n /// Handles the ProgressUpdated event of the progress service.\n /// \n /// The source of the event.\n /// The progress detail.\n private void ProgressService_ProgressUpdated(\n object? sender,\n Winhance.Core.Features.Common.Models.TaskProgressDetail detail\n )\n {\n // Update local properties\n IsLoading = _progressService.IsTaskRunning;\n StatusText = detail.StatusText ?? string.Empty;\n CurrentProgress = detail.Progress ?? 0;\n IsIndeterminate = detail.IsIndeterminate;\n IsTaskRunning = _progressService.IsTaskRunning;\n CanCancelTask =\n _progressService.IsTaskRunning\n && _progressService.CurrentTaskCancellationSource != null;\n\n // Send a message for UI updates that may occur in other threads\n _messengerService.Send(\n new TaskProgressMessage\n {\n Progress = detail.Progress ?? 0,\n StatusText = detail.StatusText ?? string.Empty,\n IsIndeterminate = detail.IsIndeterminate,\n IsTaskRunning = _progressService.IsTaskRunning,\n CanCancel =\n _progressService.IsTaskRunning\n && _progressService.CurrentTaskCancellationSource != null,\n }\n );\n }\n\n /// \n /// Handles the LogMessageAdded event of the progress service.\n /// \n /// The source of the event.\n /// The log message.\n private void ProgressService_LogMessageAdded(object? sender, string message)\n {\n if (string.IsNullOrEmpty(message))\n return;\n\n // Add to local collection\n var logMessageViewModel = new LogMessageViewModel\n {\n Message = message,\n Level = LogLevel.Info, // Default to Info since we don't have level information\n Timestamp = DateTime.Now,\n };\n\n LogMessages.Add(logMessageViewModel);\n\n // Auto-expand details on error or warning (we can't determine this from the string message)\n\n // Send a message for UI updates that may occur in other threads\n _messengerService.Send(\n new LogMessage\n {\n Message = message,\n Level = LogLevel.Info, // Default to Info since we don't have level information\n Exception = null,\n }\n );\n }\n\n /// \n /// Cancels the current task.\n /// \n protected void CancelCurrentTask()\n {\n if (_progressService.CurrentTaskCancellationSource != null && CanCancelTask)\n {\n _logService.LogInformation(\"User requested task cancellation\");\n _progressService.CancelCurrentTask();\n }\n }\n\n /// \n /// Executes an operation with progress reporting.\n /// \n /// The operation to execute.\n /// The name of the task.\n /// Whether the progress is indeterminate.\n /// A task representing the asynchronous operation.\n protected async Task ExecuteWithProgressAsync(\n Func operation,\n string taskName,\n bool isIndeterminate = false\n )\n {\n try\n {\n _progressService.StartTask(taskName, isIndeterminate);\n await operation(_progressService);\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in {taskName}: {ex.Message}\", ex);\n _progressService.AddLogMessage($\"Error: {ex.Message}\");\n throw;\n }\n finally\n {\n if (_progressService.IsTaskRunning)\n {\n _progressService.CompleteTask();\n }\n }\n }\n\n /// \n /// Executes an operation with progress reporting and returns a result.\n /// \n /// The type of the result.\n /// The operation to execute.\n /// The name of the task.\n /// Whether the progress is indeterminate.\n /// A task representing the asynchronous operation.\n protected async Task ExecuteWithProgressAsync(\n Func> operation,\n string taskName,\n bool isIndeterminate = false\n )\n {\n try\n {\n _progressService.StartTask(taskName, isIndeterminate);\n return await operation(_progressService);\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in {taskName}: {ex.Message}\", ex);\n _progressService.AddLogMessage($\"Error: {ex.Message}\");\n throw;\n }\n finally\n {\n if (_progressService.IsTaskRunning)\n {\n _progressService.CompleteTask();\n }\n }\n }\n\n /// \n /// Executes an operation with detailed progress reporting.\n /// \n /// The operation to execute.\n /// The name of the task.\n /// Whether the progress is indeterminate.\n /// A task representing the asynchronous operation.\n protected async Task ExecuteWithProgressAsync(\n Func<\n IProgress,\n CancellationToken,\n Task\n > operation,\n string taskName,\n bool isIndeterminate = false\n )\n {\n try\n {\n // Clear previous log messages\n LogMessages.Clear();\n\n _progressService.StartTask(taskName, isIndeterminate);\n var progress = _progressService.CreateDetailedProgress();\n var cancellationToken = _progressService.CurrentTaskCancellationSource.Token;\n\n await operation(progress, cancellationToken);\n }\n catch (OperationCanceledException)\n {\n _progressService.AddLogMessage(\"Operation cancelled by user\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in {taskName}: {ex.Message}\", ex);\n _progressService.AddLogMessage($\"Error: {ex.Message}\");\n throw;\n }\n finally\n {\n if (_progressService.IsTaskRunning)\n {\n _progressService.CompleteTask();\n }\n }\n }\n\n /// \n /// Executes an operation with detailed progress reporting and returns a result.\n /// \n /// The type of the result.\n /// The operation to execute.\n /// The name of the task.\n /// Whether the progress is indeterminate.\n /// A task representing the asynchronous operation.\n protected async Task ExecuteWithProgressAsync(\n Func<\n IProgress,\n CancellationToken,\n Task\n > operation,\n string taskName,\n bool isIndeterminate = false\n )\n {\n try\n {\n // Clear previous log messages\n LogMessages.Clear();\n\n _progressService.StartTask(taskName, isIndeterminate);\n var progress = _progressService.CreateDetailedProgress();\n var cancellationToken = _progressService.CurrentTaskCancellationSource.Token;\n\n return await operation(progress, cancellationToken);\n }\n catch (OperationCanceledException)\n {\n _progressService.AddLogMessage(\"Operation cancelled by user\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error in {taskName}: {ex.Message}\", ex);\n _progressService.AddLogMessage($\"Error: {ex.Message}\");\n throw;\n }\n finally\n {\n if (_progressService.IsTaskRunning)\n {\n _progressService.CompleteTask();\n }\n }\n }\n\n /// \n /// Gets the progress service.\n /// \n protected ITaskProgressService ProgressService => _progressService;\n\n /// \n /// Logs an informational message.\n /// \n /// The message to log.\n protected void LogInfo(string message)\n {\n _logService.LogInformation(message);\n }\n\n /// \n /// Logs an error message.\n /// \n /// The message to log.\n /// The exception associated with the error, if any.\n protected void LogError(string message, Exception? exception = null)\n {\n _logService.LogError(message, exception);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/PackageManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Manages packages and applications on the system.\n /// Acts as a facade for more specialized services.\n /// \n public class PackageManager : IPackageManager\n {\n private readonly IAppRemovalService _appRemovalService;\n private readonly AppRemovalServiceAdapter _appRemovalServiceAdapter;\n private readonly ICapabilityRemovalService _capabilityRemovalService;\n private readonly IFeatureRemovalService _featureRemovalService;\n\n /// \n public ILogService LogService { get; }\n\n /// \n public IAppService AppDiscoveryService { get; }\n\n /// \n /// \n /// This property is maintained for backward compatibility.\n /// It returns an adapter that converts IAppRemovalService to IInstallationService<AppInfo>.\n /// New code should use dependency injection to get IAppRemovalService directly.\n /// \n public IInstallationService AppRemovalService => _appRemovalServiceAdapter;\n\n /// \n public ISpecialAppHandlerService SpecialAppHandlerService { get; }\n\n /// \n public IScriptGenerationService ScriptGenerationService { get; }\n\n /// \n public ISystemServices SystemServices { get; }\n\n /// \n public INotificationService NotificationService { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n /// The app discovery service.\n /// The installation service.\n /// The special app handler service.\n /// The script generation service.\n public PackageManager(\n ILogService logService,\n IAppService appDiscoveryService,\n IAppRemovalService appRemovalService,\n ICapabilityRemovalService capabilityRemovalService,\n IFeatureRemovalService featureRemovalService,\n ISpecialAppHandlerService specialAppHandlerService,\n IScriptGenerationService scriptGenerationService,\n ISystemServices systemServices,\n INotificationService notificationService\n )\n {\n LogService = logService;\n AppDiscoveryService = appDiscoveryService;\n _appRemovalService = appRemovalService;\n _appRemovalServiceAdapter = new AppRemovalServiceAdapter(appRemovalService);\n _capabilityRemovalService = capabilityRemovalService;\n _featureRemovalService = featureRemovalService;\n SpecialAppHandlerService = specialAppHandlerService;\n ScriptGenerationService = scriptGenerationService;\n SystemServices = systemServices;\n NotificationService = notificationService;\n }\n\n /// \n public async Task> GetInstallableAppsAsync()\n {\n return await AppDiscoveryService.GetInstallableAppsAsync();\n }\n\n /// \n public async Task> GetStandardAppsAsync()\n {\n return await AppDiscoveryService.GetStandardAppsAsync();\n }\n\n /// \n public async Task> GetCapabilitiesAsync()\n {\n return await AppDiscoveryService.GetCapabilitiesAsync();\n }\n\n /// \n public async Task> GetOptionalFeaturesAsync()\n {\n return await AppDiscoveryService.GetOptionalFeaturesAsync();\n }\n\n /// \n public async Task RemoveAppAsync(string packageName, bool isCapability)\n {\n // Get all standard apps to check the app type\n var allRemovableApps = (await AppDiscoveryService.GetStandardAppsAsync()).ToList();\n var appInfo = allRemovableApps.FirstOrDefault(a => a.PackageName == packageName);\n\n // If not found in standard apps and isCapability is true, create a CapabilityInfo directly\n if (appInfo == null && isCapability)\n {\n LogService.LogInformation(\n $\"App not found in standard apps but isCapability is true. Treating {packageName} as a capability.\"\n );\n return await _capabilityRemovalService.RemoveCapabilityAsync(\n new CapabilityInfo { Name = packageName, PackageName = packageName }\n );\n }\n else if (appInfo == null)\n {\n LogService.LogWarning($\"App not found: {packageName}\");\n return false;\n }\n\n // First check if this is a special app that requires special handling\n if (appInfo.RequiresSpecialHandling && !string.IsNullOrEmpty(appInfo.SpecialHandlerType))\n {\n LogService.LogInformation(\n $\"Using special handler for app: {packageName}, handler type: {appInfo.SpecialHandlerType}\"\n );\n \n bool success = false;\n switch (appInfo.SpecialHandlerType)\n {\n case \"Edge\":\n success = await SpecialAppHandlerService.RemoveEdgeAsync();\n break;\n case \"OneDrive\":\n success = await SpecialAppHandlerService.RemoveOneDriveAsync();\n break;\n case \"OneNote\":\n success = await SpecialAppHandlerService.RemoveOneNoteAsync();\n break;\n default:\n success = await SpecialAppHandlerService.RemoveSpecialAppAsync(\n appInfo.SpecialHandlerType\n );\n break;\n }\n \n if (success)\n {\n LogService.LogSuccess($\"Successfully removed special app: {packageName}\");\n }\n else\n {\n LogService.LogError($\"Failed to remove special app: {packageName}\");\n }\n \n return success; // Exit early, don't continue with standard removal process\n }\n\n // If not a special app, proceed with normal removal based on app type\n bool result = false;\n switch (appInfo.Type)\n {\n case AppType.OptionalFeature:\n result = await _featureRemovalService.RemoveFeatureAsync(\n new FeatureInfo { Name = packageName }\n );\n break;\n case AppType.Capability:\n result = await _capabilityRemovalService.RemoveCapabilityAsync(\n new CapabilityInfo { Name = packageName, PackageName = packageName }\n );\n break;\n \n case AppType.StandardApp:\n default:\n var appResult = await _appRemovalService.RemoveAppAsync(appInfo);\n result = appResult.Success && appResult.Result;\n break;\n }\n\n // Only create and register BloatRemoval script for non-special apps\n if (!appInfo.RequiresSpecialHandling)\n {\n // Prepare data for the correct CreateBatchRemovalScriptAsync overload\n var appNamesList = new List { packageName };\n var appsWithRegistry = new Dictionary>();\n\n if (appInfo?.RegistrySettings != null && appInfo.RegistrySettings.Length > 0)\n {\n appsWithRegistry[packageName] = appInfo.RegistrySettings.ToList();\n }\n\n try\n {\n // Call the overload that returns RemovalScript\n var removalScript = await ScriptGenerationService.CreateBatchRemovalScriptAsync(\n appNamesList,\n appsWithRegistry\n );\n\n // Save the RemovalScript object\n await ScriptGenerationService.SaveScriptAsync(removalScript);\n\n // Register the RemovalScript object\n await ScriptGenerationService.RegisterRemovalTaskAsync(removalScript);\n }\n catch (Exception ex)\n {\n LogService.LogError(\n $\"Failed to create or register removal script for {packageName}\",\n ex\n );\n // Don't change result value, as the app removal itself might have succeeded\n }\n }\n \n return result;\n }\n\n /// \n public async Task IsAppInstalledAsync(\n string packageName,\n CancellationToken cancellationToken = default\n )\n {\n var status = await AppDiscoveryService.GetBatchInstallStatusAsync(\n new[] { packageName }\n );\n return status.TryGetValue(packageName, out var isInstalled) && isInstalled;\n }\n\n /// \n public async Task RemoveEdgeAsync()\n {\n return await SpecialAppHandlerService.RemoveEdgeAsync();\n }\n\n /// \n public async Task RemoveOneDriveAsync()\n {\n return await SpecialAppHandlerService.RemoveOneDriveAsync();\n }\n\n /// \n public async Task RemoveOneNoteAsync()\n {\n return await SpecialAppHandlerService.RemoveOneNoteAsync();\n }\n\n /// \n public async Task RemoveSpecialAppAsync(string appHandlerType)\n {\n return await SpecialAppHandlerService.RemoveSpecialAppAsync(appHandlerType);\n }\n\n /// \n public async Task> RemoveAppsInBatchAsync(\n List<(string PackageName, bool IsCapability, string? SpecialHandlerType)> apps\n )\n {\n var results = new List<(string Name, bool Success, string? Error)>();\n var standardApps = new List();\n var capabilities = new List();\n var features = new List();\n var specialHandlers = new Dictionary>();\n\n // Get all standard apps to check for optional features\n var allRemovableApps = (await AppDiscoveryService.GetStandardAppsAsync()).ToList();\n\n // Categorize apps by type\n foreach (var app in apps)\n {\n if (app.SpecialHandlerType != null)\n {\n if (!specialHandlers.ContainsKey(app.SpecialHandlerType))\n {\n specialHandlers[app.SpecialHandlerType] = new List();\n }\n specialHandlers[app.SpecialHandlerType].Add(app.PackageName);\n }\n else\n {\n // Check app type\n var appInfo = allRemovableApps.FirstOrDefault(a =>\n a.PackageName.Equals(app.PackageName, StringComparison.OrdinalIgnoreCase)\n );\n\n if (appInfo != null)\n {\n switch (appInfo.Type)\n {\n case AppType.OptionalFeature:\n features.Add(new FeatureInfo { Name = app.PackageName });\n break;\n case AppType.Capability:\n capabilities.Add(new CapabilityInfo {\n Name = app.PackageName,\n PackageName = app.PackageName\n });\n break;\n case AppType.StandardApp:\n default:\n standardApps.Add(appInfo);\n break;\n }\n }\n else\n {\n // If we couldn't determine the app type from the app info, use the IsCapability flag\n if (app.IsCapability)\n {\n LogService.LogInformation(\n $\"App not found in standard apps but IsCapability is true. Treating {app.PackageName} as a capability.\"\n );\n capabilities.Add(new CapabilityInfo {\n Name = app.PackageName,\n PackageName = app.PackageName,\n });\n }\n else\n {\n standardApps.Add(new AppInfo { PackageName = app.PackageName });\n }\n }\n }\n }\n\n // Process standard apps\n if (standardApps.Any())\n {\n foreach (var app in standardApps)\n {\n try\n {\n await _appRemovalService.RemoveAppAsync(app); // Pass AppInfo object\n results.Add((app.PackageName, true, null));\n }\n catch (Exception ex)\n {\n results.Add((app.PackageName, false, ex.Message));\n }\n }\n }\n\n // Process capabilities\n if (capabilities.Any())\n {\n foreach (var capability in capabilities)\n {\n try\n {\n await _capabilityRemovalService.RemoveCapabilityAsync(capability); // Pass CapabilityInfo object\n results.Add((capability.Name, true, null));\n }\n catch (Exception ex)\n {\n results.Add((capability.Name, false, ex.Message));\n }\n }\n }\n\n // Process optional features\n if (features.Any())\n {\n foreach (var feature in features)\n {\n try\n {\n await _featureRemovalService.RemoveFeatureAsync(feature); // Pass FeatureInfo object\n results.Add((feature.Name, true, null));\n }\n catch (Exception ex)\n {\n results.Add((feature.Name, false, ex.Message));\n }\n }\n }\n\n // Process special handlers\n foreach (var handler in specialHandlers)\n {\n switch (handler.Key)\n {\n case \"Edge\":\n foreach (var app in handler.Value)\n {\n var success = await SpecialAppHandlerService.RemoveEdgeAsync();\n results.Add((app, success, success ? null : \"Failed to remove Edge\"));\n }\n break;\n case \"OneDrive\":\n foreach (var app in handler.Value)\n {\n var success = await SpecialAppHandlerService.RemoveOneDriveAsync();\n results.Add(\n (app, success, success ? null : \"Failed to remove OneDrive\")\n );\n }\n break;\n case \"OneNote\":\n foreach (var app in handler.Value)\n {\n var success = await SpecialAppHandlerService.RemoveOneNoteAsync();\n results.Add(\n (app, success, success ? null : \"Failed to remove OneNote\")\n );\n }\n break;\n default:\n foreach (var app in handler.Value)\n {\n var success = await SpecialAppHandlerService.RemoveSpecialAppAsync(\n handler.Key\n );\n results.Add(\n (app, success, success ? null : $\"Failed to remove {handler.Key}\")\n );\n }\n break;\n }\n }\n\n // Create batch removal script for successful removals (excluding special apps)\n try\n {\n var successfulApps = results.Where(r => r.Success).Select(r => r.Name).ToList();\n \n // Filter out special apps from the successful apps list\n var nonSpecialSuccessfulAppInfos = allRemovableApps\n .Where(a => successfulApps.Contains(a.PackageName)\n && (!a.RequiresSpecialHandling || string.IsNullOrEmpty(a.SpecialHandlerType))\n )\n .ToList();\n\n LogService.LogInformation(\n $\"Creating batch removal script for {nonSpecialSuccessfulAppInfos.Count} non-special apps\"\n );\n \n foreach (var app in nonSpecialSuccessfulAppInfos)\n {\n try\n {\n await ScriptGenerationService.UpdateBloatRemovalScriptForInstalledAppAsync(app);\n }\n catch (Exception ex)\n {\n LogService.LogWarning(\n $\"Failed to update removal script for {app.PackageName}: {ex.Message}\"\n );\n }\n }\n }\n catch (Exception ex)\n {\n LogService.LogError(\"Failed to create batch removal script\", ex);\n }\n\n return results;\n }\n\n /// \n public async Task RegisterRemovalTaskAsync(RemovalScript script)\n {\n // Call the correct overload that takes a RemovalScript object\n await ScriptGenerationService.RegisterRemovalTaskAsync(script);\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/NotificationOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\n\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Notifications optimizations.\n /// \n public class NotificationOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDialogService _dialogService;\n private readonly IDependencyManager _dependencyManager;\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dialog service.\n /// The dependency manager.\n /// The view model locator.\n /// The settings registry.\n public NotificationOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDialogService dialogService,\n IDependencyManager dependencyManager,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));\n _dependencyManager = dependencyManager ?? throw new ArgumentNullException(nameof(dependencyManager));\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n _logService.Log(LogLevel.Info, \"NotificationOptimizationsViewModel instance created\");\n }\n\n /// \n /// Loads the Notifications settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n _logService.Log(LogLevel.Info, \"NotificationOptimizationsViewModel.LoadSettingsAsync: Starting to load notification optimizations\");\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Notification optimizations from NotificationOptimizations\n var notificationOptimizations = Core.Features.Optimize.Models.NotificationOptimizations.GetNotificationOptimizations();\n _logService.Log(LogLevel.Info, $\"NotificationOptimizationsViewModel.LoadSettingsAsync: Got {notificationOptimizations?.Settings?.Count ?? 0} notification optimizations\");\n if (notificationOptimizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in notificationOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = false, // Always initialize as unchecked\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Register the setting in the settings registry if available\n if (_settingsRegistry != null && !string.IsNullOrEmpty(settingItem.Id))\n {\n _settingsRegistry.RegisterSetting(settingItem);\n _logService.Log(LogLevel.Info, $\"Registered setting {settingItem.Id} in settings registry during creation\");\n }\n\n Settings.Add(settingItem);\n _logService.Log(LogLevel.Info, $\"NotificationOptimizationsViewModel.LoadSettingsAsync: Added setting {setting.Name} to collection\");\n }\n\n // Set up property change handlers for checkboxes\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n\n _logService.Log(LogLevel.Info, $\"NotificationOptimizationsViewModel.LoadSettingsAsync: Added {Settings.Count} settings to collection\");\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n\n await Task.CompletedTask;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error loading notification settings: {ex.Message}\");\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all Notifications settings.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"NotificationOptimizationsViewModel.CheckSettingStatusesAsync: Checking status for {Settings.Count} settings\");\n\n foreach (var setting in Settings)\n {\n if (setting.RegistrySetting != null)\n {\n // Get status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n setting.Status = status;\n\n // Get current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n setting.CurrentValue = currentValue;\n \n // Set IsRegistryValueNull property based on current value\n setting.IsRegistryValueNull = currentValue == null;\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking notification setting statuses: {ex.Message}\");\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied => \"Applied\",\n RegistrySettingStatus.NotApplied => \"Not Applied\",\n RegistrySettingStatus.Error => \"Error\",\n RegistrySettingStatus.Unknown => \"Unknown\",\n _ => \"Unknown\"\n };\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0) return;\n\n bool allSelected = Settings.All(s => s.IsSelected);\n bool anySelected = Settings.Any(s => s.IsSelected);\n\n IsSelected = allSelected;\n }\n\n /// \n /// Converts a RegistryHive enum to its string representation (HKCU, HKLM, etc.)\n /// \n /// The registry hive.\n /// The string representation of the registry hive.\n private string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => hive.ToString()\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/FeatureScriptModifier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Implementation of IFeatureScriptModifier that provides methods for modifying feature-related script content.\n /// \n public class FeatureScriptModifier : IFeatureScriptModifier\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public FeatureScriptModifier(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string RemoveOptionalFeatureFromScript(string scriptContent, string featureName)\n {\n // Check if the optional features section exists\n int sectionStartIndex = scriptContent.IndexOf(\"# Disable Optional Features\");\n if (sectionStartIndex == -1)\n {\n // Optional features section doesn't exist, so nothing to remove\n return scriptContent;\n }\n\n // Find the optional features array\n int arrayStartIndex = scriptContent.IndexOf(\"$optionalFeatures = @(\", sectionStartIndex);\n if (arrayStartIndex == -1)\n {\n Console.WriteLine(\"Could not find $optionalFeatures array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the optional features array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n Console.WriteLine(\"Could not find end of $optionalFeatures array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the optional features in the array\n var optionalFeatures = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var feature = trimmedLine.Trim('\\'', '\"', ' ', ',');\n optionalFeatures.Add(feature);\n }\n }\n\n // Check if the feature is in the array\n bool removed =\n optionalFeatures.RemoveAll(f =>\n f.Equals(featureName, StringComparison.OrdinalIgnoreCase)\n ) > 0;\n\n if (!removed)\n {\n // Feature not found in the array\n return scriptContent;\n }\n\n // If the array is now empty, remove the entire optional features section\n if (optionalFeatures.Count == 0)\n {\n // Find the end of the optional features section\n int sectionEndIndex = scriptContent.IndexOf(\n \"foreach ($feature in $optionalFeatures) {\",\n arrayEndIndex\n );\n if (sectionEndIndex != -1)\n {\n sectionEndIndex = scriptContent.IndexOf(\"}\", sectionEndIndex);\n if (sectionEndIndex != -1)\n {\n sectionEndIndex = scriptContent.IndexOf('\\n', sectionEndIndex);\n if (sectionEndIndex != -1)\n {\n // Remove the entire section\n return scriptContent.Substring(0, sectionStartIndex)\n + scriptContent.Substring(sectionEndIndex + 1);\n }\n }\n }\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$optionalFeatures = @(\");\n\n foreach (var feature in optionalFeatures)\n {\n newArrayContent.AppendLine($\" '{feature}'\");\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGetInstallationServiceAdapter.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Infrastructure.Features.Common.Services;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Adapter that implements the legacy IWinGetInstallationService using the new IWinGetInstaller.\n /// \n public class WinGetInstallationServiceAdapter : IWinGetInstallationService, IDisposable\n {\n private readonly IWinGetInstaller _winGetInstaller;\n private readonly ITaskProgressService _taskProgressService;\n private bool _disposed;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The WinGet installer service.\n /// The task progress service.\n public WinGetInstallationServiceAdapter(\n IWinGetInstaller winGetInstaller,\n ITaskProgressService taskProgressService)\n {\n _winGetInstaller = winGetInstaller ?? throw new ArgumentNullException(nameof(winGetInstaller));\n _taskProgressService = taskProgressService ?? throw new ArgumentNullException(nameof(taskProgressService));\n }\n\n /// \n public async Task InstallWithWingetAsync(\n string packageName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default,\n string? displayName = null)\n {\n if (string.IsNullOrWhiteSpace(packageName))\n throw new ArgumentException(\"Package name cannot be null or empty\", nameof(packageName));\n\n var displayNameToUse = displayName ?? packageName;\n var progressWrapper = new ProgressAdapter(progress);\n \n try\n {\n // Report initial progress\n progressWrapper.Report(0, $\"Starting installation of {displayNameToUse}...\");\n\n // Check if WinGet is installed first\n bool wingetInstalled = await IsWinGetInstalledAsync().ConfigureAwait(false);\n if (!wingetInstalled)\n {\n progressWrapper.Report(10, \"WinGet is not installed. Installing WinGet first...\");\n \n // Install WinGet\n await InstallWinGetAsync(progress).ConfigureAwait(false);\n \n // Verify WinGet installation was successful\n wingetInstalled = await IsWinGetInstalledAsync().ConfigureAwait(false);\n if (!wingetInstalled)\n {\n progressWrapper.Report(0, \"Failed to install WinGet. Cannot proceed with application installation.\");\n return false;\n }\n \n progressWrapper.Report(30, $\"WinGet installed successfully. Continuing with {displayNameToUse} installation...\");\n }\n\n // Now use the WinGet installer to install the package\n var result = await _winGetInstaller.InstallPackageAsync(\n packageName,\n new InstallationOptions\n {\n // Configure installation options as needed\n Silent = true\n },\n displayNameToUse, // Pass the display name to use in progress reporting\n cancellationToken)\n .ConfigureAwait(false);\n\n if (result.Success)\n {\n progressWrapper.Report(100, $\"Successfully installed {displayNameToUse}\");\n return true;\n }\n \n progressWrapper.Report(0, $\"Failed to install {displayNameToUse}: {result.Message}\");\n return false;\n }\n catch (Exception ex)\n {\n progressWrapper.Report(0, $\"Error installing {displayNameToUse}: {ex.Message}\");\n throw;\n }\n }\n\n /// \n public async Task InstallWinGetAsync(IProgress? progress = null)\n {\n // Check if WinGet is already installed\n if (await IsWinGetInstalledAsync().ConfigureAwait(false))\n {\n progress?.Report(new TaskProgressDetail { StatusText = \"WinGet is already installed\" });\n return;\n }\n\n var progressWrapper = new ProgressAdapter(progress);\n \n try\n {\n progressWrapper.Report(0, \"Downloading WinGet installer...\");\n \n // Force a search operation which will trigger WinGet installation if it's not found\n // This leverages the WinGetInstaller's built-in mechanism to install WinGet when needed\n try \n {\n // We use a simple search operation to trigger the WinGet installation process\n // The dot (.) is a simple search term that will match everything\n progressWrapper.Report(20, \"Installing WinGet...\");\n \n var searchResult = await _winGetInstaller.SearchPackagesAsync(\n \".\", // Simple search term\n null, // No search options\n CancellationToken.None)\n .ConfigureAwait(false);\n \n progressWrapper.Report(80, \"WinGet installation in progress...\");\n \n // If we get here, WinGet should be installed\n progressWrapper.Report(100, \"WinGet installed successfully\");\n }\n catch (Exception ex)\n {\n progressWrapper.Report(0, $\"Error installing WinGet: {ex.Message}\");\n throw;\n }\n \n // Verify WinGet installation\n bool isInstalled = await IsWinGetInstalledAsync().ConfigureAwait(false);\n if (!isInstalled)\n {\n progressWrapper.Report(0, \"WinGet installation verification failed\");\n throw new InvalidOperationException(\"WinGet installation could not be verified\");\n }\n }\n catch (Exception ex)\n {\n progressWrapper.Report(0, $\"Error installing WinGet: {ex.Message}\");\n throw;\n }\n }\n\n /// \n public async Task IsWinGetInstalledAsync()\n {\n try\n {\n // Try to list packages to check if WinGet is working\n var result = await _winGetInstaller.SearchPackagesAsync(\".\").ConfigureAwait(false);\n return result != null;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n /// \n /// Releases the unmanaged resources used by the \n /// and optionally releases the managed resources.\n /// \n /// True to release both managed and unmanaged resources; false to release only unmanaged resources.\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n // Dispose managed resources here if needed\n }\n\n _disposed = true;\n }\n }\n\n /// \n /// Adapter to convert between IProgress and IProgress\n /// \n private class ProgressAdapter\n {\n private readonly IProgress? _progress;\n\n public ProgressAdapter(IProgress? progress)\n {\n _progress = progress;\n }\n\n public void Report(int progress, string status)\n {\n _progress?.Report(new TaskProgressDetail\n {\n Progress = progress,\n StatusText = status,\n LogLevel = progress == 100 ? LogLevel.Info : LogLevel.Debug\n });\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/MaterialSymbol.xaml.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Media;\nusing Winhance.WPF.Features.Common.Resources;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// Interaction logic for MaterialSymbol.xaml\n /// \n public partial class MaterialSymbol : UserControl\n {\n public static readonly DependencyProperty IconProperty = DependencyProperty.Register(\n \"Icon\", typeof(string), typeof(MaterialSymbol), \n new PropertyMetadata(string.Empty, OnIconChanged));\n\n public static readonly DependencyProperty IconTextProperty = DependencyProperty.Register(\n \"IconText\", typeof(string), typeof(MaterialSymbol), \n new PropertyMetadata(string.Empty));\n\n public string Icon\n {\n get { return (string)GetValue(IconProperty); }\n set { SetValue(IconProperty, value); }\n }\n\n public string IconText\n {\n get { return (string)GetValue(IconTextProperty); }\n set { SetValue(IconTextProperty, value); }\n }\n\n public MaterialSymbol()\n {\n InitializeComponent();\n }\n\n private static void OnIconChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is MaterialSymbol control && e.NewValue is string iconName)\n {\n control.IconText = MaterialSymbols.GetIcon(iconName);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Utilities/FileLogger.cs", "using System;\nusing System.IO;\nusing System.Threading;\n\nnamespace Winhance.WPF.Features.Common.Utilities\n{\n /// \n /// Utility class for direct file logging, used for diagnostic purposes.\n /// \n public static class FileLogger\n {\n private static readonly object _lockObject = new object();\n private const string LOG_FOLDER = \"DiagnosticLogs\";\n \n // Logging is disabled as CloseButtonDiagnostics.txt is no longer used\n private static readonly bool _loggingEnabled = false;\n\n /// \n /// Logs a message to the diagnostic log file.\n /// \n /// The source of the log message (e.g., class name)\n /// The message to log\n public static void Log(string source, string message)\n {\n // Early return if logging is disabled\n if (!_loggingEnabled)\n return;\n \n try\n {\n string logPath = GetLogFilePath();\n string timestamp = DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss.fff\");\n string threadId = Thread.CurrentThread.ManagedThreadId.ToString();\n string logMessage = $\"[{timestamp}] [Thread:{threadId}] [{source}] {message}\";\n\n lock (_lockObject)\n {\n // Ensure directory exists\n Directory.CreateDirectory(Path.GetDirectoryName(logPath));\n File.AppendAllText(logPath, logMessage + Environment.NewLine);\n }\n }\n catch\n {\n // Ignore errors in logging to avoid affecting the application\n }\n }\n\n /// \n /// Gets the full path to the log file.\n /// \n /// The full path to the log file\n public static string GetLogFilePath()\n {\n string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n string winhancePath = Path.Combine(appDataPath, \"Winhance\");\n string logFolderPath = Path.Combine(winhancePath, LOG_FOLDER);\n // Using a placeholder filename since logging is disabled\n return Path.Combine(logFolderPath, \"diagnostics.log\");\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/RegistryScriptModifier.cs", "using System;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Implementation of IRegistryScriptModifier that provides methods for modifying registry-related script content.\n /// \n public class RegistryScriptModifier : IRegistryScriptModifier\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public RegistryScriptModifier(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string RemoveAppRegistrySettingsFromScript(string scriptContent, string appName)\n {\n // Find the registry settings section\n int registrySection = scriptContent.IndexOf(\"# Registry settings\");\n if (registrySection == -1)\n {\n return scriptContent;\n }\n\n // Generate possible section headers for this app\n var possibleSectionHeaders = new List\n {\n $\"# Registry settings for {appName}\",\n $\"# Registry settings for Microsoft.{appName}\",\n };\n\n // Add variations without \"Microsoft.\" prefix if it already has it\n if (appName.StartsWith(\"Microsoft.\", StringComparison.OrdinalIgnoreCase))\n {\n string nameWithoutPrefix = appName.Substring(\"Microsoft.\".Length);\n possibleSectionHeaders.Add($\"# Registry settings for {nameWithoutPrefix}\");\n }\n\n // Add common variations\n possibleSectionHeaders.Add($\"# Registry settings for {appName}_8wekyb3d8bbwe\");\n\n // For Copilot specifically, add known variations\n if (appName.Contains(\"Copilot\", StringComparison.OrdinalIgnoreCase))\n {\n possibleSectionHeaders.Add(\"# Registry settings for Copilot\");\n possibleSectionHeaders.Add(\"# Registry settings for Microsoft.Copilot\");\n possibleSectionHeaders.Add(\"# Registry settings for Windows.Copilot\");\n }\n\n // For Xbox/GamingApp specifically, add known variations\n if (\n appName.Contains(\"Xbox\", StringComparison.OrdinalIgnoreCase)\n || appName.Equals(\"Microsoft.GamingApp\", StringComparison.OrdinalIgnoreCase)\n )\n {\n possibleSectionHeaders.Add(\"# Registry settings for Xbox\");\n possibleSectionHeaders.Add(\"# Registry settings for Microsoft.Xbox\");\n possibleSectionHeaders.Add(\"# Registry settings for GamingApp\");\n }\n\n // Find the earliest matching section header\n int appSection = -1;\n string matchedHeader = null;\n\n foreach (var header in possibleSectionHeaders)\n {\n int index = scriptContent.IndexOf(header, registrySection);\n if (index != -1 && (appSection == -1 || index < appSection))\n {\n appSection = index;\n matchedHeader = header;\n }\n }\n\n if (appSection == -1)\n {\n Console.WriteLine($\"No registry settings found for {appName} in the script\");\n return scriptContent;\n }\n\n Console.WriteLine($\"Found registry settings for {appName} with header: {matchedHeader}\");\n\n // Find the end of the app section (next section or end of file)\n int nextSection = scriptContent.IndexOf(\n \"# Registry settings for\",\n appSection + matchedHeader.Length\n );\n if (nextSection == -1)\n {\n // Look for the next major section\n nextSection = scriptContent.IndexOf(\"# Prevent apps from reinstalling\", appSection);\n if (nextSection == -1)\n {\n // If no next section, just return the original content\n Console.WriteLine($\"Could not find end of registry settings section for {appName}\");\n return scriptContent;\n }\n }\n\n // Remove the app registry settings section\n Console.WriteLine($\"Removing registry settings for {appName} from script\");\n return scriptContent.Substring(0, appSection) + scriptContent.Substring(nextSection);\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Customize/ViewModels/TaskbarCustomizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Extensions;\nusing Winhance.Core.Features.Customize.Enums;\nusing Winhance.Core.Features.Customize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\nusing Winhance.Infrastructure.Features.Common.Registry;\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Customize.ViewModels\n{\n /// \n /// ViewModel for Taskbar customizations.\n /// \n public partial class TaskbarCustomizationsViewModel : BaseSettingsViewModel\n {\n private readonly ISystemServices _systemServices;\n private bool _isWindows11;\n\n /// \n /// Gets the command to clean the taskbar.\n /// \n public IAsyncRelayCommand CleanTaskbarCommand { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The system services.\n public TaskbarCustomizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n ISystemServices systemServices)\n : base(progressService, registryService, logService)\n {\n _systemServices = systemServices ?? throw new ArgumentNullException(nameof(systemServices));\n _isWindows11 = _systemServices.IsWindows11();\n \n // Initialize the CleanTaskbarCommand\n CleanTaskbarCommand = new AsyncRelayCommand(ExecuteCleanTaskbarAsync);\n }\n\n /// \n /// Executes the clean taskbar operation.\n /// \n private async Task ExecuteCleanTaskbarAsync()\n {\n try\n {\n _progressService.StartTask(\"Cleaning taskbar...\");\n _logService.LogInformation(\"Cleaning taskbar started\");\n \n // Call the static method from TaskbarCustomizations class\n await TaskbarCustomizations.CleanTaskbar(_systemServices, _logService);\n \n // Update the status text and complete the task\n _progressService.UpdateProgress(100, \"Taskbar cleaned successfully!\");\n _progressService.CompleteTask();\n _logService.LogInformation(\"Taskbar cleaned successfully\");\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error cleaning taskbar: {ex.Message}\", ex);\n // Update the status text with the error message\n _progressService.UpdateProgress(0, $\"Error cleaning taskbar: {ex.Message}\");\n _progressService.CancelCurrentTask();\n }\n }\n\n /// \n /// Loads the Taskbar customizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Taskbar customizations\n var taskbarCustomizations = Core.Features.Customize.Models.TaskbarCustomizations.GetTaskbarCustomizations();\n if (taskbarCustomizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in taskbarCustomizations.Settings.OrderBy(s => s.Name))\n {\n // Skip Windows 11 specific settings on Windows 10\n if (!_isWindows11 && setting.IsWindows11Only)\n {\n continue;\n }\n\n // Skip Windows 10 specific settings on Windows 11\n if (_isWindows11 && setting.IsWindows10Only)\n {\n continue;\n }\n\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n ControlType = setting.ControlType,\n IsWindows11Only = setting.IsWindows11Only,\n IsWindows10Only = setting.IsWindows10Only\n };\n\n // Add any actions\n var actionsProperty = setting.GetType().GetProperty(\"Actions\");\n if (actionsProperty != null && \n actionsProperty.GetValue(setting) is IEnumerable actions && \n actions.Any())\n {\n // We need to handle this differently since the Actions property doesn't exist in ApplicationSetting\n // This is a temporary workaround until we refactor the code properly\n }\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for settings\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/ExplorerOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\n\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Explorer optimizations.\n /// \n public partial class ExplorerOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDependencyManager _dependencyManager;\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dependency manager.\n /// The view model locator.\n /// The settings registry.\n public ExplorerOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDependencyManager dependencyManager,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _dependencyManager = dependencyManager ?? throw new ArgumentNullException(nameof(dependencyManager));\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n }\n\n /// \n /// Loads the Explorer optimizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Explorer optimizations from ExplorerOptimizations\n var explorerOptimizations = Core.Features.Optimize.Models.ExplorerOptimizations.GetExplorerOptimizations();\n if (explorerOptimizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in explorerOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = false, // Always initialize as unchecked\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Register the setting in the settings registry if available\n if (_settingsRegistry != null && !string.IsNullOrEmpty(settingItem.Id))\n {\n _settingsRegistry.RegisterSetting(settingItem);\n _logService.Log(LogLevel.Info, $\"Registered setting {settingItem.Id} in settings registry during creation\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for settings\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all Explorer optimizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n foreach (var setting in Settings)\n {\n if (setting.RegistrySetting != null)\n {\n // Get status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n setting.Status = status;\n\n // Get current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n setting.CurrentValue = currentValue;\n \n // Set IsRegistryValueNull property based on current value\n setting.IsRegistryValueNull = currentValue == null;\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Explorer optimization statuses: {ex.Message}\");\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied => \"Applied\",\n RegistrySettingStatus.NotApplied => \"Not Applied\",\n RegistrySettingStatus.Modified => \"Modified\",\n RegistrySettingStatus.Error => \"Error\",\n RegistrySettingStatus.Unknown => \"Unknown\",\n _ => \"Unknown\"\n };\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0) return;\n\n bool allSelected = Settings.All(s => s.IsSelected);\n bool anySelected = Settings.Any(s => s.IsSelected);\n\n IsSelected = allSelected;\n }\n\n /// \n /// Converts a RegistryHive enum to its string representation (HKCU, HKLM, etc.)\n /// \n /// The registry hive.\n /// The string representation of the registry hive.\n private string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => hive.ToString()\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/ViewModels/SoundOptimizationsViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Models;\nusing Microsoft.Win32;\n\nusing Winhance.WPF.Features.Common.Extensions;\n\nnamespace Winhance.WPF.Features.Optimize.ViewModels\n{\n /// \n /// ViewModel for Sound optimizations.\n /// \n public partial class SoundOptimizationsViewModel : BaseSettingsViewModel\n {\n private readonly IDependencyManager _dependencyManager;\n private readonly IViewModelLocator? _viewModelLocator;\n private readonly ISettingsRegistry? _settingsRegistry;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n /// The dependency manager.\n /// The view model locator.\n /// The settings registry.\n public SoundOptimizationsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService,\n IDependencyManager dependencyManager,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n : base(progressService, registryService, logService)\n {\n _dependencyManager = dependencyManager ?? throw new ArgumentNullException(nameof(dependencyManager));\n _viewModelLocator = viewModelLocator;\n _settingsRegistry = settingsRegistry;\n }\n\n /// \n /// Loads the Sound optimizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load Sound optimizations\n var soundOptimizations = Core.Features.Optimize.Models.SoundOptimizations.GetSoundOptimizations();\n if (soundOptimizations?.Settings != null)\n {\n // Add settings sorted alphabetically by name\n foreach (var setting in soundOptimizations.Settings.OrderBy(s => s.Name))\n {\n // Create ApplicationSettingItem directly\n var settingItem = new ApplicationSettingItem(_registryService, null, _logService)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = false, // Always initialize as unchecked\n GroupName = setting.GroupName,\n Dependencies = setting.Dependencies,\n ControlType = ControlType.BinaryToggle // Default to binary toggle\n };\n\n // Set up the registry settings\n if (setting.RegistrySettings.Count == 1)\n {\n // Single registry setting\n settingItem.RegistrySetting = setting.RegistrySettings[0];\n _logService.Log(LogLevel.Info, $\"Setting up single registry setting for {setting.Name}: {setting.RegistrySettings[0].Hive}\\\\{setting.RegistrySettings[0].SubKey}\\\\{setting.RegistrySettings[0].Name}\");\n }\n else if (setting.RegistrySettings.Count > 1)\n {\n // Linked registry settings\n settingItem.LinkedRegistrySettings = setting.CreateLinkedRegistrySettings();\n _logService.Log(LogLevel.Info, $\"Setting up linked registry settings for {setting.Name} with {setting.RegistrySettings.Count} entries and logic {setting.LinkedSettingsLogic}\");\n \n // Log details about each registry entry for debugging\n foreach (var regSetting in setting.RegistrySettings)\n {\n _logService.Log(LogLevel.Info, $\"Linked registry entry: {regSetting.Hive}\\\\{regSetting.SubKey}\\\\{regSetting.Name}, IsPrimary={regSetting.IsPrimary}\");\n }\n }\n else\n {\n _logService.Log(LogLevel.Warning, $\"No registry settings found for {setting.Name}\");\n }\n\n // Register the setting in the settings registry if available\n if (_settingsRegistry != null && !string.IsNullOrEmpty(settingItem.Id))\n {\n _settingsRegistry.RegisterSetting(settingItem);\n _logService.Log(LogLevel.Info, $\"Registered setting {settingItem.Id} in settings registry during creation\");\n }\n\n Settings.Add(settingItem);\n }\n\n // Set up property change handlers for settings\n foreach (var setting in Settings)\n {\n setting.PropertyChanged += (s, e) =>\n {\n if (e.PropertyName == nameof(ApplicationSettingItem.IsSelected))\n {\n UpdateIsSelectedState();\n }\n };\n }\n }\n\n // Check setting statuses\n await CheckSettingStatusesAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Checks the status of all Sound optimizations.\n /// \n /// A task representing the asynchronous operation.\n public override async Task CheckSettingStatusesAsync()\n {\n try\n {\n foreach (var setting in Settings)\n {\n if (setting.RegistrySetting != null)\n {\n // Get status\n var status = await _registryService.GetSettingStatusAsync(setting.RegistrySetting);\n setting.Status = status;\n\n // Get current value\n var currentValue = await _registryService.GetCurrentValueAsync(setting.RegistrySetting);\n setting.CurrentValue = currentValue;\n \n // Set IsRegistryValueNull property based on current value\n setting.IsRegistryValueNull = currentValue == null;\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n else if (setting.LinkedRegistrySettings != null && setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n // Get the combined status of all linked settings\n var status = await _registryService.GetLinkedSettingsStatusAsync(setting.LinkedRegistrySettings);\n setting.Status = status;\n\n // For current value display, use the first setting's value\n if (setting.LinkedRegistrySettings.Settings.Count > 0)\n {\n var firstSetting = setting.LinkedRegistrySettings.Settings[0];\n var currentValue = await _registryService.GetCurrentValueAsync(firstSetting);\n setting.CurrentValue = currentValue;\n\n // Check for null registry values\n bool anyNull = false;\n\n // Populate the LinkedRegistrySettingsWithValues collection for tooltip display\n setting.LinkedRegistrySettingsWithValues.Clear();\n foreach (var regSetting in setting.LinkedRegistrySettings.Settings)\n {\n var regCurrentValue = await _registryService.GetCurrentValueAsync(regSetting);\n \n if (regCurrentValue == null)\n {\n anyNull = true;\n }\n \n setting.LinkedRegistrySettingsWithValues.Add(new Winhance.WPF.Features.Common.Models.LinkedRegistrySettingWithValue(regSetting, regCurrentValue));\n }\n \n // Set IsRegistryValueNull for linked settings\n setting.IsRegistryValueNull = anyNull;\n }\n\n // Set status message\n setting.StatusMessage = GetStatusMessage(setting);\n\n // Update IsSelected based on status\n bool shouldBeSelected = status == RegistrySettingStatus.Applied;\n\n // Set the checkbox state to match the registry state\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} status is {status}, setting IsSelected to {shouldBeSelected}\");\n setting.IsUpdatingFromCode = true;\n try\n {\n setting.IsSelected = shouldBeSelected;\n }\n finally\n {\n setting.IsUpdatingFromCode = false;\n }\n }\n }\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking Sound setting statuses: {ex.Message}\");\n }\n }\n\n /// \n /// Gets the status message for a setting.\n /// \n /// The setting.\n /// The status message.\n private string GetStatusMessage(ApplicationSettingItem setting)\n {\n return setting.Status switch\n {\n RegistrySettingStatus.Applied => \"Applied\",\n RegistrySettingStatus.NotApplied => \"Not Applied\",\n RegistrySettingStatus.Modified => \"Modified\",\n RegistrySettingStatus.Error => \"Error\",\n RegistrySettingStatus.Unknown => \"Unknown\",\n _ => \"Unknown\"\n };\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n private void UpdateIsSelectedState()\n {\n if (Settings.Count == 0) return;\n\n bool allSelected = Settings.All(s => s.IsSelected);\n bool anySelected = Settings.Any(s => s.IsSelected);\n\n IsSelected = allSelected;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/CapabilityScriptModifier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Implementation of ICapabilityScriptModifier that provides methods for modifying capability-related script content.\n /// \n public class CapabilityScriptModifier : ICapabilityScriptModifier\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public CapabilityScriptModifier(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string RemoveCapabilityFromScript(string scriptContent, string capabilityName)\n {\n // Find the capabilities array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$capabilities = @(\");\n if (arrayStartIndex == -1)\n {\n Console.WriteLine(\"Could not find $capabilities array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the capabilities array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n Console.WriteLine(\"Could not find end of $capabilities array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the capabilities in the array\n var capabilities = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var capability = trimmedLine.Trim('\\'', '\"', ' ', ',');\n capabilities.Add(capability);\n }\n }\n\n // Check if the capability is in the array\n bool removed =\n capabilities.RemoveAll(c =>\n c.Equals(capabilityName, StringComparison.OrdinalIgnoreCase)\n ) > 0;\n\n if (!removed)\n {\n // Capability not found in the array\n return scriptContent;\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$capabilities = @(\");\n\n foreach (var capability in capabilities)\n {\n newArrayContent.AppendLine($\" '{capability}'\");\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/VersionService.cs", "using System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Net.Http;\nusing System.Reflection;\nusing System.Text.Json;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n public class VersionService : IVersionService\n {\n private readonly ILogService _logService;\n private readonly HttpClient _httpClient;\n private readonly string _latestReleaseApiUrl = \"https://api.github.com/repos/memstechtips/Winhance/releases/latest\";\n private readonly string _latestReleaseDownloadUrl = \"https://github.com/memstechtips/Winhance/releases/latest/download/Winhance.Installer.exe\";\n private readonly string _userAgent = \"Winhance-Update-Checker\";\n \n public VersionService(ILogService logService)\n {\n _logService = logService;\n _httpClient = new HttpClient();\n _httpClient.DefaultRequestHeaders.Add(\"User-Agent\", _userAgent);\n }\n \n public VersionInfo GetCurrentVersion()\n {\n try\n {\n // Get the assembly version\n Assembly assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();\n string? location = assembly.Location;\n \n if (string.IsNullOrEmpty(location))\n {\n _logService.Log(LogLevel.Error, \"Could not determine assembly location for version check\");\n return CreateDefaultVersion();\n }\n \n // Get the assembly file version which will be in the format v25.05.02\n FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(location);\n string fileVersion = fileVersionInfo.FileVersion ?? \"v0.0.0\";\n \n // If the version doesn't start with 'v', add it\n if (!fileVersion.StartsWith(\"v\"))\n {\n fileVersion = $\"v{fileVersion}\";\n }\n \n return VersionInfo.FromTag(fileVersion);\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting current version: {ex.Message}\", ex);\n return CreateDefaultVersion();\n }\n }\n \n public async Task CheckForUpdateAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Checking for updates...\");\n \n // Get the latest release information from GitHub API\n HttpResponseMessage response = await _httpClient.GetAsync(_latestReleaseApiUrl);\n response.EnsureSuccessStatusCode();\n \n string responseBody = await response.Content.ReadAsStringAsync();\n using JsonDocument doc = JsonDocument.Parse(responseBody);\n \n // Extract the tag name (version) from the response\n string tagName = doc.RootElement.GetProperty(\"tag_name\").GetString() ?? \"v0.0.0\";\n string htmlUrl = doc.RootElement.GetProperty(\"html_url\").GetString() ?? string.Empty;\n DateTime publishedAt = doc.RootElement.TryGetProperty(\"published_at\", out JsonElement publishedElement) && \n DateTime.TryParse(publishedElement.GetString(), out DateTime published) \n ? published \n : DateTime.MinValue;\n \n VersionInfo latestVersion = VersionInfo.FromTag(tagName);\n latestVersion.DownloadUrl = _latestReleaseDownloadUrl;\n \n // Compare with current version\n VersionInfo currentVersion = GetCurrentVersion();\n latestVersion.IsUpdateAvailable = latestVersion.IsNewerThan(currentVersion);\n \n _logService.Log(LogLevel.Info, $\"Current version: {currentVersion.Version}, Latest version: {latestVersion.Version}, Update available: {latestVersion.IsUpdateAvailable}\");\n \n return latestVersion;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking for updates: {ex.Message}\", ex);\n return new VersionInfo { IsUpdateAvailable = false };\n }\n }\n \n public async Task DownloadAndInstallUpdateAsync()\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Downloading update...\");\n \n // Create a temporary file to download the installer\n string tempPath = Path.Combine(Path.GetTempPath(), \"Winhance.Installer.exe\");\n \n // Download the installer\n byte[] installerBytes = await _httpClient.GetByteArrayAsync(_latestReleaseDownloadUrl);\n await File.WriteAllBytesAsync(tempPath, installerBytes);\n \n _logService.Log(LogLevel.Info, $\"Update downloaded to {tempPath}, launching installer...\");\n \n // Launch the installer\n Process.Start(new ProcessStartInfo\n {\n FileName = tempPath,\n UseShellExecute = true\n });\n \n _logService.Log(LogLevel.Info, \"Installer launched successfully\");\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error downloading or installing update: {ex.Message}\", ex);\n throw;\n }\n }\n \n private VersionInfo CreateDefaultVersion()\n {\n // Create a default version based on the current date\n DateTime now = DateTime.Now;\n string versionTag = $\"v{now.Year - 2000:D2}.{now.Month:D2}.{now.Day:D2}\";\n \n return new VersionInfo\n {\n Version = versionTag,\n ReleaseDate = now\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/PackageScriptModifier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Implementation of IPackageScriptModifier that provides methods for modifying package-related script content.\n /// \n public class PackageScriptModifier : IPackageScriptModifier\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logging service.\n public PackageScriptModifier(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string RemovePackageFromScript(string scriptContent, string packageName)\n {\n // Find the packages array section in the script\n int arrayStartIndex = scriptContent.IndexOf(\"$packages = @(\");\n if (arrayStartIndex == -1)\n {\n Console.WriteLine(\"Could not find $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Find the end of the packages array\n int arrayEndIndex = scriptContent.IndexOf(\")\", arrayStartIndex);\n if (arrayEndIndex == -1)\n {\n Console.WriteLine(\"Could not find end of $packages array in BloatRemoval.ps1\");\n return scriptContent;\n }\n\n // Extract the array content\n string arrayContent = scriptContent.Substring(\n arrayStartIndex,\n arrayEndIndex - arrayStartIndex + 1\n );\n\n // Parse the packages in the array\n var packages = new List();\n var lines = arrayContent.Split('\\n');\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n if (trimmedLine.StartsWith(\"'\") || trimmedLine.StartsWith(\"\\\"\"))\n {\n var package = trimmedLine.Trim('\\'', '\"', ' ', ',');\n packages.Add(package);\n }\n }\n\n // Check if the package is in the array\n bool removed =\n packages.RemoveAll(p => p.Equals(packageName, StringComparison.OrdinalIgnoreCase)) > 0;\n\n if (!removed)\n {\n // Package not found in the array\n return scriptContent;\n }\n\n // Rebuild the array content\n var newArrayContent = new StringBuilder();\n newArrayContent.AppendLine(\"$packages = @(\");\n\n foreach (var package in packages)\n {\n newArrayContent.AppendLine($\" '{package}'\");\n }\n\n newArrayContent.Append(\")\");\n\n // Replace the old array content with the new one\n return scriptContent.Substring(0, arrayStartIndex)\n + newArrayContent.ToString()\n + scriptContent.Substring(arrayEndIndex + 1);\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Utilities/WinGetOutputParser.cs", "using System;\nusing System.IO;\nusing System.Text.RegularExpressions;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Utilities\n{\n /// \n /// Parses WinGet command output and generates appropriate progress updates.\n /// \n public class WinGetOutputParser\n {\n private readonly ILogService _logService;\n private InstallationState _currentState = InstallationState.Starting;\n private string _downloadFileName;\n private bool _isVerifying;\n private string _lastProgressLine;\n private int _lastPercentage;\n private bool _hasStarted = false;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// Optional log service for debugging.\n public WinGetOutputParser(ILogService logService = null)\n {\n _logService = logService;\n }\n\n /// \n /// Parses a line of WinGet output and generates an appropriate progress update.\n /// Uses an indeterminate progress indicator and displays raw WinGet output.\n /// \n /// The line of output to parse.\n /// An InstallationProgress object with the current progress information, or null if no update is needed.\n public InstallationProgress ParseOutputLine(string outputLine)\n {\n if (string.IsNullOrWhiteSpace(outputLine))\n {\n return null;\n }\n\n _logService?.LogInformation($\"WinGet output: {outputLine}\");\n \n // If this is the first output line, transition from Starting state\n if (!_hasStarted)\n {\n _hasStarted = true;\n _currentState = InstallationState.Resolving;\n \n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = 0,\n IsIndeterminate = true,\n };\n }\n\n // Check for verification messages\n if (outputLine.Contains(\"Verifying\"))\n {\n _logService?.LogInformation(\"Verification step detected\");\n _currentState = InstallationState.Verifying;\n _isVerifying = true;\n\n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = 0,\n IsIndeterminate = true,\n };\n }\n\n // Check for installation messages\n if (\n outputLine.Contains(\"Installing\")\n || outputLine.Contains(\"installation\")\n || (_isVerifying && !outputLine.Contains(\"Verifying\"))\n )\n {\n _logService?.LogInformation(\"Installation step detected\");\n _currentState = InstallationState.Installing;\n _isVerifying = false;\n\n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = 0,\n IsIndeterminate = true,\n };\n }\n\n // Check for download information\n if (\n (\n outputLine.Contains(\"Downloading\")\n || outputLine.Contains(\"download\")\n || outputLine.Contains(\"KB\")\n || outputLine.Contains(\"MB\")\n || outputLine.Contains(\"GB\")\n )\n )\n {\n _logService?.LogInformation($\"Download information detected: {outputLine}\");\n\n // Set the current state to Downloading\n _currentState = InstallationState.Downloading;\n\n // Create a progress update with a generic downloading message\n return new InstallationProgress\n {\n Status = \"Downloading package files. This might take a while, please wait...\",\n Percentage = 0, // Not used in indeterminate mode\n IsIndeterminate = true, // Use indeterminate progress\n // Set Operation to help identify this is a download operation\n Operation = \"Downloading\"\n };\n }\n\n // Check for installation status\n if (outputLine.Contains(\"%\"))\n {\n var percentageMatch = Regex.Match(outputLine, @\"(\\d+)%\");\n if (percentageMatch.Success)\n {\n int percentage = int.Parse(percentageMatch.Groups[1].Value);\n _lastPercentage = percentage;\n _lastProgressLine = outputLine;\n\n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = percentage,\n IsIndeterminate = false,\n };\n }\n }\n\n // Check for completion\n if (\n outputLine.Contains(\"Successfully installed\")\n || outputLine.Contains(\"completed successfully\")\n || outputLine.Contains(\"installation complete\")\n )\n {\n _logService?.LogInformation(\"Installation completed successfully\");\n _currentState = InstallationState.Completing;\n\n return new InstallationProgress\n {\n Status = \"Installation completed successfully!\",\n Percentage = 100,\n IsIndeterminate = false,\n // Note: The installation is complete, but we don't have an IsComplete property\n // so we just set the percentage to 100 and a clear status message\n };\n }\n\n // Check for errors\n if (\n outputLine.Contains(\"error\")\n || outputLine.Contains(\"failed\")\n || outputLine.Contains(\"Error:\")\n || outputLine.Contains(\"Failed:\")\n )\n {\n _logService?.LogError($\"Installation error detected: {outputLine}\");\n\n return new InstallationProgress\n {\n Status = $\"Error: {outputLine.Trim()}\",\n Percentage = 0,\n IsIndeterminate = false,\n // Note: We don't have HasError or ErrorMessage properties\n // so we just include the error in the Status\n };\n }\n\n // For other lines, return the last progress if available\n if (!string.IsNullOrEmpty(_lastProgressLine) && _lastPercentage > 0)\n {\n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = _lastPercentage,\n IsIndeterminate = false,\n };\n }\n\n // For other lines, just return the current state\n return new InstallationProgress\n {\n Status = GetStatusMessage(_currentState),\n Percentage = 0,\n IsIndeterminate = true,\n };\n }\n\n /// \n /// Gets a status message appropriate for the current installation state.\n /// \n private string GetStatusMessage(InstallationState state)\n {\n switch (state)\n {\n case InstallationState.Starting:\n return \"Preparing for installation...\";\n case InstallationState.Resolving:\n return \"Resolving package dependencies...\";\n case InstallationState.Downloading:\n return \"Downloading package files. This might take a while, please wait...\";\n case InstallationState.Verifying:\n return \"Verifying package integrity...\";\n case InstallationState.Installing:\n return \"Installing application...\";\n case InstallationState.Configuring:\n return \"Configuring application settings...\";\n case InstallationState.Completing:\n return \"Finalizing installation...\";\n default:\n return \"Processing...\";\n }\n }\n }\n\n /// \n /// Represents the different states of a WinGet installation process.\n /// \n public enum InstallationState\n {\n /// \n /// The installation process is starting.\n /// \n Starting,\n\n /// \n /// The package dependencies are being resolved.\n /// \n Resolving,\n\n /// \n /// Package files are being downloaded.\n /// \n Downloading,\n\n /// \n /// Package integrity is being verified.\n /// \n Verifying,\n\n /// \n /// The application is being installed.\n /// \n Installing,\n\n /// \n /// The application is being configured.\n /// \n Configuring,\n\n /// \n /// The installation process is completing.\n /// \n Completing,\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/ConfigurationUIService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for handling UI-related operations for configuration management.\n /// \n public class ConfigurationUIService\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public ConfigurationUIService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Shows the unified configuration dialog to let the user select which sections to include.\n /// \n /// The unified configuration file.\n /// Whether this is a save dialog (true) or an import dialog (false).\n /// A dictionary of section names and their selection state.\n public async Task> ShowUnifiedConfigurationDialogAsync(UnifiedConfigurationFile config, bool isSaveDialog)\n {\n try\n {\n _logService.Log(LogLevel.Info, $\"Showing unified configuration dialog (isSaveDialog: {isSaveDialog})\");\n \n // Create a dictionary of sections with their availability and item counts\n var sectionInfo = new Dictionary\n {\n { \"WindowsApps\", (true, config.WindowsApps.Items.Count > 0, config.WindowsApps.Items.Count) },\n { \"ExternalApps\", (true, config.ExternalApps.Items.Count > 0, config.ExternalApps.Items.Count) },\n { \"Customize\", (true, config.Customize.Items.Count > 0, config.Customize.Items.Count) },\n { \"Optimize\", (true, config.Optimize.Items.Count > 0, config.Optimize.Items.Count) }\n };\n \n // Create and show the dialog\n var dialog = new UnifiedConfigurationDialog(\n isSaveDialog ? \"Save Configuration\" : \"Select Configuration Sections\",\n isSaveDialog ? \"Select which sections you want to save to the unified configuration.\" : \"Select which sections you want to import from the unified configuration.\",\n sectionInfo,\n isSaveDialog);\n \n dialog.Owner = Application.Current.MainWindow;\n bool? dialogResult = dialog.ShowDialog();\n \n if (dialogResult != true)\n {\n _logService.Log(LogLevel.Info, \"User canceled unified configuration dialog\");\n return new Dictionary();\n }\n \n // Get the selected sections from the dialog\n var result = dialog.GetResult();\n \n _logService.Log(LogLevel.Info, $\"Selected sections: {string.Join(\", \", result.Where(kvp => kvp.Value).Select(kvp => kvp.Key))}\");\n \n return result;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error showing unified configuration dialog: {ex.Message}\");\n return new Dictionary();\n }\n }\n\n /// \n /// Shows a success message for configuration operations.\n /// \n /// The title of the message.\n /// The message to show.\n /// The sections that were affected.\n /// Additional information to show.\n public void ShowSuccessMessage(string title, string message, List sections, string additionalInfo)\n {\n CustomDialog.ShowInformation(title, message, sections, additionalInfo);\n }\n\n /// \n /// Shows an error message for configuration operations.\n /// \n /// The title of the message.\n /// The message to show.\n public void ShowErrorMessage(string title, string message)\n {\n MessageBox.Show(message, title, MessageBoxButton.OK, MessageBoxImage.Error);\n }\n\n /// \n /// Shows a confirmation dialog for configuration operations.\n /// \n /// The title of the dialog.\n /// The message to show.\n /// True if the user confirmed, false otherwise.\n public bool ShowConfirmationDialog(string title, string message)\n {\n var result = MessageBox.Show(message, title, MessageBoxButton.YesNo, MessageBoxImage.Question);\n return result == MessageBoxResult.Yes;\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/SearchService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Service for handling search operations across different types of items.\n /// \n public class SearchService : ISearchService\n {\n /// \n /// Filters a collection of items based on a search term.\n /// \n /// The type of items to filter.\n /// The collection of items to filter.\n /// The search term to filter by.\n /// A filtered collection of items that match the search term.\n public IEnumerable FilterItems(IEnumerable items, string searchTerm) where T : ISearchable\n {\n // Add console logging for debugging\n Console.WriteLine($\"SearchService.FilterItems: Filtering with search term '{searchTerm}'\");\n \n if (string.IsNullOrWhiteSpace(searchTerm))\n {\n Console.WriteLine($\"SearchService.FilterItems: Search term is empty, returning all {items.Count()} items\");\n return items;\n }\n\n // Just trim the search term, but don't convert to lowercase\n // We'll handle case insensitivity in the MatchesSearch method\n searchTerm = searchTerm.Trim();\n Console.WriteLine($\"SearchService.FilterItems: Normalized search term '{searchTerm}'\");\n Console.WriteLine($\"SearchService.FilterItems: Starting search with term '{searchTerm}'\");\n \n // Log items before filtering\n int totalItems = items.Count();\n Console.WriteLine($\"SearchService.FilterItems: Total items before filtering: {totalItems}\");\n \n // Apply filtering and log results\n var filteredItems = items.Where(item => {\n bool matches = item.MatchesSearch(searchTerm);\n \n // Log details for all items to help diagnose search issues\n var itemName = item.GetType().GetProperty(\"Name\")?.GetValue(item)?.ToString();\n var itemGroupName = item.GetType().GetProperty(\"GroupName\")?.GetValue(item)?.ToString();\n \n // Log all items for better debugging\n Console.WriteLine($\"SearchService.FilterItems: Checking item '{itemName}' (Group: '{itemGroupName}') - matches: {matches}\");\n \n return matches;\n }).ToList();\n \n Console.WriteLine($\"SearchService.FilterItems: Found {filteredItems.Count} matching items out of {totalItems}\");\n \n return filteredItems;\n }\n\n /// \n /// Asynchronously filters a collection of items based on a search term.\n /// \n /// The type of items to filter.\n /// The collection of items to filter.\n /// The search term to filter by.\n /// A task that represents the asynchronous operation. The task result contains a filtered collection of items that match the search term.\n public Task> FilterItemsAsync(IEnumerable items, string searchTerm) where T : ISearchable\n {\n return Task.FromResult(FilterItems(items, searchTerm));\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/MoreMenuViewModel.cs", "using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Runtime.CompilerServices;\nusing System.Windows;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Views;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// ViewModel for the More menu functionality\n /// \n public class MoreMenuViewModel : ObservableObject\n {\n private readonly ILogService _logService;\n private readonly IVersionService _versionService;\n private readonly IMessengerService _messengerService;\n private readonly IApplicationCloseService _applicationCloseService;\n private readonly IDialogService _dialogService;\n\n private string _versionInfo;\n\n /// \n /// Gets or sets the version information text displayed in the menu\n /// \n public string VersionInfo\n {\n get => _versionInfo;\n set => SetProperty(ref _versionInfo, value);\n }\n\n /// \n /// Command to check for application updates\n /// \n public ICommand CheckForUpdatesCommand { get; }\n\n /// \n /// Command to open the logs folder\n /// \n public ICommand OpenLogsCommand { get; }\n\n /// \n /// Command to open the scripts folder\n /// \n public ICommand OpenScriptsCommand { get; }\n\n /// \n /// Command to close the application\n /// \n public ICommand CloseApplicationCommand { get; }\n\n /// \n /// Constructor with dependency injection\n /// \n /// Service for logging\n /// Service for version information and updates\n /// Service for messaging between components\n public MoreMenuViewModel(\n ILogService logService,\n IVersionService versionService,\n IMessengerService messengerService,\n IApplicationCloseService applicationCloseService,\n IDialogService dialogService\n )\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _versionService =\n versionService ?? throw new ArgumentNullException(nameof(versionService));\n _messengerService =\n messengerService ?? throw new ArgumentNullException(nameof(messengerService));\n _applicationCloseService =\n applicationCloseService\n ?? throw new ArgumentNullException(nameof(applicationCloseService));\n _dialogService =\n dialogService\n ?? throw new ArgumentNullException(nameof(dialogService));\n\n // Initialize version info\n UpdateVersionInfo();\n\n // Initialize commands with explicit execute and canExecute methods\n CheckForUpdatesCommand = new RelayCommand(\n execute: () =>\n {\n _logService.LogInformation(\"CheckForUpdatesCommand executed\");\n CheckForUpdatesAsync();\n },\n canExecute: () => true\n );\n\n OpenLogsCommand = new RelayCommand(\n execute: () =>\n {\n _logService.LogInformation(\"OpenLogsCommand executed\");\n OpenLogs();\n },\n canExecute: () => true\n );\n\n OpenScriptsCommand = new RelayCommand(\n execute: () =>\n {\n _logService.LogInformation(\"OpenScriptsCommand executed\");\n OpenScripts();\n },\n canExecute: () => true\n );\n\n CloseApplicationCommand = new RelayCommand(\n execute: () =>\n {\n _logService.LogInformation(\"CloseApplicationCommand executed\");\n CloseApplication();\n },\n canExecute: () => true\n );\n }\n\n /// \n /// Updates the version information text\n /// \n private void UpdateVersionInfo()\n {\n try\n {\n // Get the current version from the version service\n VersionInfo versionInfo = _versionService.GetCurrentVersion();\n\n // Format the version text\n VersionInfo = $\"Winhance Version {versionInfo.Version}\";\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error updating version info: {ex.Message}\", ex);\n\n // Set a default version text in case of error\n VersionInfo = \"Winhance Version\";\n }\n }\n\n /// \n /// Checks for updates and shows appropriate dialog\n /// \n private async void CheckForUpdatesAsync()\n {\n try\n {\n _logService.LogInformation(\"Checking for updates from MoreMenu\");\n\n // Get the current version\n VersionInfo currentVersion = _versionService.GetCurrentVersion();\n _logService.LogInformation($\"Current version: {currentVersion.Version}\");\n\n // Check for updates\n VersionInfo latestVersion = await _versionService.CheckForUpdateAsync();\n _logService.LogInformation(\n $\"Latest version: {latestVersion.Version}, Update available: {latestVersion.IsUpdateAvailable}\"\n );\n\n if (latestVersion.IsUpdateAvailable)\n {\n // Show update dialog\n string title = \"Update Available\";\n string message = \"Good News! A New Version of Winhance is available.\";\n\n _logService.LogInformation(\"Showing update dialog\");\n // Show the update dialog\n await UpdateDialog.ShowAsync(\n title,\n message,\n currentVersion,\n latestVersion,\n async () =>\n {\n _logService.LogInformation(\n \"User initiated update download and installation\"\n );\n await _versionService.DownloadAndInstallUpdateAsync();\n }\n );\n }\n else\n {\n _logService.LogInformation(\"No updates available\");\n // Show a message that no update is available\n _dialogService.ShowInformationAsync(\n \"You have the latest version of Winhance.\",\n \"No Updates Available\"\n );\n }\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error checking for updates: {ex.Message}\", ex);\n\n // Show an error message\n _dialogService.ShowErrorAsync(\n $\"An error occurred while checking for updates: {ex.Message}\",\n \"Update Check Error\"\n );\n }\n }\n\n /// \n /// Opens the logs folder\n /// \n private void OpenLogs()\n {\n try\n {\n // Get the logs folder path\n string logsFolder = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),\n \"Winhance\",\n \"Logs\"\n );\n\n // Create the folder if it doesn't exist\n if (!Directory.Exists(logsFolder))\n {\n Directory.CreateDirectory(logsFolder);\n }\n\n // Open the logs folder using ProcessStartInfo with UseShellExecute=true\n var psi = new ProcessStartInfo\n {\n FileName = \"explorer.exe\",\n Arguments = logsFolder,\n UseShellExecute = true,\n };\n Process.Start(psi);\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error opening logs folder: {ex.Message}\", ex);\n\n // Show an error message\n _dialogService.ShowErrorAsync(\n $\"An error occurred while opening the logs folder: {ex.Message}\",\n \"Logs Folder Error\"\n );\n }\n }\n\n /// \n /// Opens the scripts folder\n /// \n private void OpenScripts()\n {\n try\n {\n // Get the scripts folder path\n string scriptsFolder = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n \"Winhance\",\n \"Scripts\"\n );\n\n // Create the folder if it doesn't exist\n if (!Directory.Exists(scriptsFolder))\n {\n Directory.CreateDirectory(scriptsFolder);\n }\n\n // Open the scripts folder using ProcessStartInfo with UseShellExecute=true\n var psi = new ProcessStartInfo\n {\n FileName = \"explorer.exe\",\n Arguments = scriptsFolder,\n UseShellExecute = true,\n };\n Process.Start(psi);\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error opening scripts folder: {ex.Message}\", ex);\n\n // Show an error message\n _dialogService.ShowErrorAsync(\n $\"An error occurred while opening the scripts folder: {ex.Message}\",\n \"Scripts Folder Error\"\n );\n }\n }\n\n /// \n /// Closes the application using the same behavior as the normal close button\n /// \n private async void CloseApplication()\n {\n try\n {\n _logService.LogInformation(\n \"Closing application from MoreMenu, delegating to ApplicationCloseService\"\n );\n await _applicationCloseService.CloseApplicationWithSupportDialogAsync();\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error closing application: {ex.Message}\", ex);\n\n // Fallback to direct application shutdown if everything else fails\n try\n {\n _logService.LogInformation(\"Falling back to Application.Current.Shutdown()\");\n Application.Current.Dispatcher.Invoke(() => Application.Current.Shutdown());\n }\n catch (Exception shutdownEx)\n {\n _logService.LogError(\n $\"Error shutting down application: {shutdownEx.Message}\",\n shutdownEx\n );\n\n // Last resort\n Environment.Exit(0);\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/BaseSettingsViewModel.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.Common.Extensions;\nusing Winhance.WPF.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// Base class for settings view models.\n /// \n /// The type of settings.\n public partial class BaseSettingsViewModel : ObservableObject\n where T : ApplicationSettingItem\n {\n protected readonly ITaskProgressService _progressService;\n protected readonly IRegistryService _registryService;\n protected readonly ILogService _logService;\n\n /// \n /// Gets the collection of settings.\n /// \n public ObservableCollection Settings { get; } = new();\n\n /// \n /// Gets or sets a value indicating whether the settings are being loaded.\n /// \n [ObservableProperty]\n private bool _isLoading;\n\n /// \n /// Gets or sets a value indicating whether all settings are selected.\n /// \n [ObservableProperty]\n private bool _isSelected;\n\n /// \n /// Gets or sets a value indicating whether the view model has visible settings.\n /// \n [ObservableProperty]\n private bool _hasVisibleSettings = true;\n\n /// \n /// Gets or sets the category name for this settings view model.\n /// \n [ObservableProperty]\n private string _categoryName = string.Empty;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The registry service.\n /// The log service.\n protected BaseSettingsViewModel(\n ITaskProgressService progressService,\n IRegistryService registryService,\n ILogService logService\n )\n {\n _progressService =\n progressService ?? throw new ArgumentNullException(nameof(progressService));\n _registryService =\n registryService ?? throw new ArgumentNullException(nameof(registryService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Loads the settings.\n /// \n /// A task representing the asynchronous operation.\n public virtual async Task LoadSettingsAsync()\n {\n try\n {\n IsLoading = true;\n\n // Clear existing settings\n Settings.Clear();\n\n // Load settings (to be implemented by derived classes)\n await Task.CompletedTask;\n\n // Refresh status for all settings after loading\n await RefreshAllSettingsStatusAsync();\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Refreshes the status of all settings.\n /// \n /// A task representing the asynchronous operation.\n protected async Task RefreshAllSettingsStatusAsync()\n {\n foreach (var setting in Settings)\n {\n await setting.RefreshStatus();\n }\n }\n\n /// \n /// Checks the status of all settings.\n /// \n /// A task representing the asynchronous operation.\n public virtual async Task CheckSettingStatusesAsync()\n {\n _logService.Log(\n LogLevel.Info,\n $\"Checking status of {Settings.Count} settings in {GetType().Name}\"\n );\n\n foreach (var setting in Settings)\n {\n if (setting.IsGroupHeader)\n {\n continue;\n }\n\n // Direct method call without reflection\n await setting.RefreshStatus();\n }\n\n // Update the overall IsSelected state\n UpdateIsSelectedState();\n }\n\n /// \n /// Updates the IsSelected state based on individual selections.\n /// \n protected void UpdateIsSelectedState()\n {\n var nonHeaderSettings = Settings.Where(s => !s.IsGroupHeader).ToList();\n if (nonHeaderSettings.Count == 0)\n {\n IsSelected = false;\n return;\n }\n\n IsSelected = nonHeaderSettings.All(s => s.IsSelected);\n }\n\n /// \n /// Executes the specified action asynchronously.\n /// \n /// The name of the action to execute.\n /// A task representing the asynchronous operation.\n public virtual async Task ExecuteActionAsync(string actionName)\n {\n _logService.Log(LogLevel.Info, $\"Executing action: {actionName}\");\n\n // Find the setting with the specified action\n foreach (var setting in Settings)\n {\n var action = setting.Actions.FirstOrDefault(a => a.Name == actionName);\n if (action != null)\n {\n _logService.Log(\n LogLevel.Info,\n $\"Found action {actionName} in setting {setting.Name}\"\n );\n\n await ExecuteActionAsync(action);\n return;\n }\n }\n\n _logService.Log(LogLevel.Warning, $\"Action {actionName} not found\");\n }\n\n /// \n /// Executes the specified action asynchronously.\n /// \n /// The action to execute.\n /// A task representing the asynchronous operation.\n public virtual async Task ExecuteActionAsync(ApplicationAction action)\n {\n if (action == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot execute null action\");\n return;\n }\n\n _logService.Log(LogLevel.Info, $\"Executing action: {action.Name}\");\n\n // Execute the registry action if present\n if (action.RegistrySetting != null)\n {\n string hiveString = action.RegistrySetting.Hive.ToString();\n if (hiveString == \"LocalMachine\")\n hiveString = \"HKLM\";\n else if (hiveString == \"CurrentUser\")\n hiveString = \"HKCU\";\n else if (hiveString == \"ClassesRoot\")\n hiveString = \"HKCR\";\n else if (hiveString == \"Users\")\n hiveString = \"HKU\";\n else if (hiveString == \"CurrentConfig\")\n hiveString = \"HKCC\";\n\n string fullPath = $\"{hiveString}\\\\{action.RegistrySetting.SubKey}\";\n _registryService.SetValue(\n fullPath,\n action.RegistrySetting.Name,\n action.RegistrySetting.RecommendedValue,\n action.RegistrySetting.ValueType\n );\n }\n\n // Execute custom action if present\n if (action.CustomAction != null)\n {\n await action.CustomAction();\n }\n\n _logService.Log(LogLevel.Info, $\"Action '{action.Name}' executed successfully\");\n }\n\n /// \n /// Applies the setting asynchronously.\n /// \n /// The setting to apply.\n /// A task representing the asynchronous operation.\n protected virtual async Task ApplySettingAsync(T setting)\n {\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot apply null setting\");\n return;\n }\n\n _logService.Log(LogLevel.Info, $\"Applying setting: {setting.Name}\");\n\n // Apply the setting based on its properties\n if (setting.RegistrySetting != null)\n {\n // Apply registry setting\n string hiveString = GetRegistryHiveString(setting.RegistrySetting.Hive);\n _registryService.SetValue(\n $\"{hiveString}\\\\{setting.RegistrySetting.SubKey}\",\n setting.RegistrySetting.Name,\n setting.IsSelected\n ? setting.RegistrySetting.RecommendedValue\n : setting.RegistrySetting.DefaultValue,\n setting.RegistrySetting.ValueType\n );\n }\n else if (\n setting.LinkedRegistrySettings != null\n && setting.LinkedRegistrySettings.Settings.Count > 0\n )\n {\n // Apply linked registry settings\n await _registryService.ApplyLinkedSettingsAsync(\n setting.LinkedRegistrySettings,\n setting.IsSelected\n );\n }\n\n _logService.Log(LogLevel.Info, $\"Setting {setting.Name} applied successfully\");\n\n // Add a small delay to ensure registry changes are processed\n await Task.Delay(50);\n }\n\n /// \n /// Gets the registry hive string.\n /// \n /// The registry hive.\n /// The registry hive string.\n private string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => throw new ArgumentOutOfRangeException(nameof(hive), hive, null),\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/OneDriveInstallationService.cs", "using System;\nusing System.IO;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that handles OneDrive installation.\n/// \npublic class OneDriveInstallationService : IOneDriveInstallationService, IDisposable\n{\n private readonly ILogService _logService;\n private readonly HttpClient _httpClient;\n private readonly string _tempDir = Path.Combine(Path.GetTempPath(), \"WinhanceInstaller\");\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public OneDriveInstallationService(ILogService logService)\n {\n _logService = logService;\n _httpClient = new HttpClient();\n Directory.CreateDirectory(_tempDir);\n }\n\n /// \n public async Task InstallOneDriveAsync(\n IProgress? progress,\n CancellationToken cancellationToken)\n {\n try\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Starting OneDrive installation...\",\n DetailedMessage = \"Downloading OneDrive installer from Microsoft\"\n });\n\n // Download OneDrive from the specific URL\n string downloadUrl = \"https://go.microsoft.com/fwlink/p/?LinkID=2182910\";\n string installerPath = Path.Combine(_tempDir, \"OneDriveSetup.exe\");\n\n using (var client = new HttpClient())\n {\n var response = await client.GetAsync(downloadUrl, cancellationToken);\n if (!response.IsSuccessStatusCode)\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Failed to download OneDrive installer\",\n DetailedMessage = $\"HTTP error: {response.StatusCode}\",\n LogLevel = LogLevel.Error\n });\n return false;\n }\n\n using (var fileStream = new FileStream(installerPath, FileMode.Create, FileAccess.Write, FileShare.None))\n {\n await response.Content.CopyToAsync(fileStream, cancellationToken);\n }\n }\n\n progress?.Report(new TaskProgressDetail\n {\n Progress = 50,\n StatusText = \"Installing OneDrive...\",\n DetailedMessage = \"Running OneDrive installer\"\n });\n\n // Run the installer\n using (var process = new System.Diagnostics.Process())\n {\n process.StartInfo.FileName = installerPath;\n process.StartInfo.Arguments = \"/silent\";\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.RedirectStandardError = true;\n process.StartInfo.CreateNoWindow = true;\n\n process.Start();\n await Task.Run(() => process.WaitForExit(), cancellationToken);\n\n bool success = process.ExitCode == 0;\n\n progress?.Report(new TaskProgressDetail\n {\n Progress = 100,\n StatusText = success ? \"OneDrive installed successfully\" : \"OneDrive installation failed\",\n DetailedMessage = $\"Installer exited with code: {process.ExitCode}\",\n LogLevel = success ? LogLevel.Success : LogLevel.Error\n });\n\n return success;\n }\n }\n catch (Exception ex)\n {\n progress?.Report(new TaskProgressDetail\n {\n Progress = 0,\n StatusText = \"Error installing OneDrive\",\n DetailedMessage = $\"Exception: {ex.Message}\",\n LogLevel = LogLevel.Error\n });\n return false;\n }\n }\n\n /// \n /// Disposes the resources used by the service.\n /// \n public void Dispose()\n {\n _httpClient.Dispose();\n GC.SuppressFinalize(this);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/ViewModelLocator.cs", "using System;\nusing System.Linq;\nusing System.Windows;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Interfaces;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Service for locating view models in the application.\n /// \n public class ViewModelLocator : IViewModelLocator\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public ViewModelLocator(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Finds a view model of the specified type in the application.\n /// \n /// The type of view model to find.\n /// The view model if found, otherwise null.\n public T? FindViewModel() where T : class\n {\n try\n {\n var app = Application.Current;\n if (app == null) return null;\n\n // Try to find the view model in the main window's DataContext hierarchy\n var mainWindow = app.MainWindow;\n if (mainWindow != null)\n {\n var mainViewModel = FindViewModelInWindow(mainWindow);\n if (mainViewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"Found {typeof(T).Name} in main window's DataContext\");\n return mainViewModel;\n }\n }\n\n // If we can't find it in the main window, try to find it in any open window\n foreach (Window window in app.Windows)\n {\n var viewModel = FindViewModelInWindow(window);\n if (viewModel != null)\n {\n _logService.Log(LogLevel.Info, $\"Found {typeof(T).Name} in window: {window.Title}\");\n return viewModel;\n }\n }\n\n _logService.Log(LogLevel.Warning, $\"Could not find {typeof(T).Name} in any window\");\n return null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error finding view model: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Finds a view model of the specified type in the specified window.\n /// \n /// The type of view model to find.\n /// The window to search in.\n /// The view model if found, otherwise null.\n public T? FindViewModelInWindow(Window window) where T : class\n {\n try\n {\n // Check if the window's DataContext is or contains the view model\n if (window.DataContext is T vm)\n {\n return vm;\n }\n\n // Check if the window's DataContext has a property that is the view model\n if (window.DataContext != null)\n {\n var type = window.DataContext.GetType();\n var properties = type.GetProperties();\n\n foreach (var property in properties)\n {\n if (property.PropertyType == typeof(T))\n {\n return property.GetValue(window.DataContext) as T;\n }\n }\n }\n\n // If not found in the DataContext, search the visual tree\n return FindViewModelInVisualTree(window);\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error finding view model in window: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Finds a view model of the specified type in the visual tree starting from the specified element.\n /// \n /// The type of view model to find.\n /// The starting element.\n /// The view model if found, otherwise null.\n public T? FindViewModelInVisualTree(DependencyObject element) where T : class\n {\n try\n {\n // Check if the element's DataContext is the view model\n if (element is FrameworkElement fe && fe.DataContext is T vm)\n {\n return vm;\n }\n\n // Recursively check children\n int childCount = System.Windows.Media.VisualTreeHelper.GetChildrenCount(element);\n for (int i = 0; i < childCount; i++)\n {\n var child = System.Windows.Media.VisualTreeHelper.GetChild(element, i);\n var result = FindViewModelInVisualTree(child);\n if (result != null)\n {\n return result;\n }\n }\n\n return null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error finding view model in visual tree: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Finds a view model by its name.\n /// \n /// The name of the view model to find.\n /// The view model if found, otherwise null.\n public object? FindViewModelByName(string viewModelName)\n {\n try\n {\n var app = Application.Current;\n if (app == null) return null;\n\n // Try to find the view model in any window's DataContext\n foreach (Window window in app.Windows)\n {\n if (window.DataContext != null)\n {\n var type = window.DataContext.GetType();\n if (type.Name == viewModelName || type.Name == $\"{viewModelName}ViewModel\")\n {\n return window.DataContext;\n }\n\n // Check if the DataContext has a property that is the view model\n var properties = type.GetProperties();\n foreach (var property in properties)\n {\n if (property.Name == viewModelName || property.PropertyType.Name == viewModelName ||\n property.Name == $\"{viewModelName}ViewModel\" || property.PropertyType.Name == $\"{viewModelName}ViewModel\")\n {\n return property.GetValue(window.DataContext);\n }\n }\n }\n }\n\n return null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error finding view model by name: {ex.Message}\");\n return null;\n }\n }\n\n /// \n /// Gets a property from a view model.\n /// \n /// The type of the property to get.\n /// The view model to get the property from.\n /// The name of the property to get.\n /// The property value if found, otherwise null.\n public T? GetPropertyFromViewModel(object viewModel, string propertyName) where T : class\n {\n try\n {\n var type = viewModel.GetType();\n var property = type.GetProperty(propertyName);\n if (property != null)\n {\n return property.GetValue(viewModel) as T;\n }\n\n return null;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error getting property from view model: {ex.Message}\");\n return null;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppLoadingService.cs", "using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Helpers;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n public class AppLoadingService : IAppLoadingService\n {\n private readonly IAppDiscoveryService _appDiscoveryService;\n private readonly IPackageManager _packageManager;\n private readonly ILogService _logService;\n private readonly ConcurrentDictionary _statusCache = new();\n\n public AppLoadingService(\n IAppDiscoveryService appDiscoveryService,\n IPackageManager packageManager,\n ILogService logService)\n {\n _appDiscoveryService = appDiscoveryService;\n _packageManager = packageManager;\n _logService = logService;\n }\n\n /// \n public async Task>> LoadAppsAsync()\n {\n try\n {\n var apps = await _appDiscoveryService.GetStandardAppsAsync();\n return OperationResult>.Succeeded(apps);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to load standard apps\", ex);\n return OperationResult>.Failed(\"Failed to load standard apps\", ex);\n }\n }\n\n // Removed LoadInstallableAppsAsync as it's not in the interface\n\n public async Task> LoadCapabilitiesAsync()\n {\n try\n {\n // This is a placeholder implementation\n // In a real implementation, this would query the system for available capabilities\n _logService.LogInformation(\"Loading Windows capabilities\");\n \n // Return an empty list for now\n return Enumerable.Empty();\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to load capabilities\", ex);\n return Enumerable.Empty();\n }\n }\n\n public async Task GetItemInstallStatusAsync(IInstallableItem item)\n {\n ValidationHelper.NotNull(item, nameof(item));\n ValidationHelper.NotNullOrEmpty(item.PackageId, nameof(item.PackageId));\n\n if (_statusCache.TryGetValue(item.PackageId, out var cachedStatus))\n {\n return cachedStatus;\n }\n\n var isInstalled = await _packageManager.IsAppInstalledAsync(item.PackageId);\n _statusCache[item.PackageId] = isInstalled;\n return isInstalled;\n }\n\n // Added missing GetInstallStatusAsync method\n /// \n public async Task> GetInstallStatusAsync(string appId)\n {\n try\n {\n ValidationHelper.NotNullOrEmpty(appId, nameof(appId));\n\n // Use the existing cache logic, assuming 'true' maps to Success\n if (_statusCache.TryGetValue(appId, out var cachedStatus))\n {\n return OperationResult.Succeeded(\n cachedStatus ? InstallStatus.Success : InstallStatus.NotFound\n );\n }\n\n var isInstalled = await _packageManager.IsAppInstalledAsync(appId);\n _statusCache[appId] = isInstalled;\n return OperationResult.Succeeded(\n isInstalled ? InstallStatus.Success : InstallStatus.NotFound\n );\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to get installation status for app {appId}\", ex);\n return OperationResult.Failed($\"Failed to get installation status: {ex.Message}\", ex);\n }\n }\n\n // Added missing SetInstallStatusAsync method\n /// \n public Task> SetInstallStatusAsync(string appId, InstallStatus status)\n {\n try\n {\n ValidationHelper.NotNullOrEmpty(appId, nameof(appId));\n // This service primarily reads status; setting might not be its responsibility\n // or might require interaction with the package manager.\n // For now, just update the cache.\n _logService.LogWarning($\"Attempting to set install status for {appId} to {status} (cache only).\");\n _statusCache[appId] = (status == InstallStatus.Success); // Corrected enum member\n return Task.FromResult(OperationResult.Succeeded(true)); // Assume cache update is always successful\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to set installation status for app {appId}\", ex);\n return Task.FromResult(OperationResult.Failed($\"Failed to set installation status: {ex.Message}\", ex));\n }\n }\n\n\n public async Task> GetBatchInstallStatusAsync(IEnumerable packageIds)\n {\n ValidationHelper.NotNull(packageIds, nameof(packageIds));\n \n var distinctIds = packageIds\n .Where(id => !string.IsNullOrWhiteSpace(id))\n .Distinct()\n .ToList();\n\n if (distinctIds.Count == 0)\n throw new ArgumentException(\"Must provide at least one valid package ID\", nameof(packageIds));\n var results = new Dictionary();\n\n foreach (var id in distinctIds)\n {\n if (_statusCache.TryGetValue(id, out var cachedStatus))\n {\n results[id] = cachedStatus;\n }\n else\n {\n var isInstalled = await _packageManager.IsAppInstalledAsync(id);\n _statusCache[id] = isInstalled;\n results[id] = isInstalled;\n }\n }\n\n return results;\n } // Removed extra closing brace here\n\n\n /// \n public async Task> RefreshInstallationStatusAsync(IEnumerable apps)\n {\n try\n {\n ValidationHelper.NotNull(apps, nameof(apps));\n\n var packageIds = apps\n .Where(app => app != null && !string.IsNullOrWhiteSpace(app.PackageID)) // Use PackageID from AppInfo\n .Select(app => app.PackageID)\n .Distinct();\n \n if (!packageIds.Any())\n {\n return OperationResult.Succeeded(true); // No apps to refresh\n }\n \n var statuses = await GetBatchInstallStatusAsync(packageIds);\n\n foreach (var app in apps) // Iterate through AppInfo\n {\n if (app != null && statuses.TryGetValue(app.PackageID, out var isInstalled)) // Use PackageID\n {\n _statusCache[app.PackageID] = isInstalled; // Use PackageID\n // Optionally update the IsInstalled property on the AppInfo object itself\n // app.IsInstalled = isInstalled; // This depends if AppInfo is mutable and if this side-effect is desired\n }\n }\n \n return OperationResult.Succeeded(true);\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to refresh installation status\", ex);\n return OperationResult.Failed(\"Failed to refresh installation status\", ex);\n }\n }\n\n public void ClearStatusCache()\n {\n _statusCache.Clear();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppInstallationCoordinatorService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Coordinates the installation of applications, handling connectivity monitoring,\n /// user notifications, and installation state management.\n /// \n public class AppInstallationCoordinatorService : IAppInstallationCoordinatorService\n {\n private readonly IAppInstallationService _appInstallationService;\n private readonly IInternetConnectivityService _connectivityService;\n private readonly ILogService _logService;\n private readonly INotificationService _notificationService;\n private readonly IDialogService _dialogService;\n \n /// \n /// Event that is raised when the installation status changes.\n /// \n public event EventHandler InstallationStatusChanged;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The application installation service.\n /// The internet connectivity service.\n /// The logging service.\n /// The notification service.\n /// The dialog service.\n public AppInstallationCoordinatorService(\n IAppInstallationService appInstallationService,\n IInternetConnectivityService connectivityService,\n ILogService logService,\n INotificationService notificationService = null,\n IDialogService dialogService = null)\n {\n _appInstallationService = appInstallationService ?? throw new ArgumentNullException(nameof(appInstallationService));\n _connectivityService = connectivityService ?? throw new ArgumentNullException(nameof(connectivityService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _notificationService = notificationService;\n _dialogService = dialogService;\n }\n\n /// \n /// Installs an application with connectivity monitoring and proper cancellation handling.\n /// \n /// The application information.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the installation operation with the result.\n public async Task InstallAppAsync(\n AppInfo appInfo,\n IProgress progress,\n CancellationToken cancellationToken = default)\n {\n if (appInfo == null)\n throw new ArgumentNullException(nameof(appInfo));\n \n // Create a linked cancellation token source that will be cancelled if either:\n // 1. The original cancellation token is cancelled (user initiated)\n // 2. We detect a connectivity issue and cancel the installation\n using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n \n // Update status\n var initialStatus = $\"Installing {appInfo.Name}...\";\n RaiseStatusChanged(appInfo, initialStatus);\n \n // Start connectivity monitoring\n var connectivityMonitoringTask = StartConnectivityMonitoring(appInfo, linkedCts);\n \n try\n {\n // Perform the installation\n var installationResult = await _appInstallationService.InstallAppAsync(\n appInfo, \n progress, \n linkedCts.Token);\n \n // Stop connectivity monitoring\n linkedCts.Cancel();\n try { await connectivityMonitoringTask; } catch (OperationCanceledException) { /* Expected */ }\n \n if (installationResult.Success)\n {\n var successMessage = $\"Successfully installed {appInfo.Name}\";\n RaiseStatusChanged(appInfo, successMessage, true, true);\n \n return new InstallationCoordinationResult\n {\n Success = true,\n AppInfo = appInfo\n };\n }\n else\n {\n var errorMessage = installationResult.ErrorMessage ?? $\"Failed to install {appInfo.Name}\";\n RaiseStatusChanged(appInfo, errorMessage, true, false);\n \n return new InstallationCoordinationResult\n {\n Success = false,\n ErrorMessage = errorMessage,\n AppInfo = appInfo\n };\n }\n }\n catch (OperationCanceledException)\n {\n // Stop connectivity monitoring\n linkedCts.Cancel();\n try { await connectivityMonitoringTask; } catch (OperationCanceledException) { /* Expected */ }\n \n // Determine if this was a user cancellation or a connectivity issue\n bool wasConnectivityIssue = await connectivityMonitoringTask.ContinueWith(t => \n {\n // If the task completed normally, check its result\n if (t.Status == TaskStatus.RanToCompletion)\n {\n return t.Result;\n }\n // If the task was cancelled, assume it was a user cancellation\n return false;\n });\n \n if (wasConnectivityIssue)\n {\n var connectivityMessage = $\"Installation of {appInfo.Name} was stopped due to internet connectivity issues\";\n RaiseStatusChanged(appInfo, connectivityMessage, true, false, false, true);\n \n return new InstallationCoordinationResult\n {\n Success = false,\n WasCancelled = false,\n WasConnectivityIssue = true,\n ErrorMessage = \"Internet connection lost during installation. Please check your network connection and try again.\",\n AppInfo = appInfo\n };\n }\n else\n {\n var cancelMessage = $\"Installation of {appInfo.Name} was cancelled by user\";\n RaiseStatusChanged(appInfo, cancelMessage, true, false, true);\n \n return new InstallationCoordinationResult\n {\n Success = false,\n WasCancelled = true,\n WasConnectivityIssue = false,\n ErrorMessage = \"Installation was cancelled by user\",\n AppInfo = appInfo\n };\n }\n }\n catch (Exception ex)\n {\n // Stop connectivity monitoring\n linkedCts.Cancel();\n try { await connectivityMonitoringTask; } catch (OperationCanceledException) { /* Expected */ }\n \n // Log the error\n _logService.LogError($\"Error installing {appInfo.Name}: {ex.Message}\", ex);\n \n // Check if the exception is related to internet connectivity\n bool isConnectivityIssue = ex.Message.Contains(\"internet\") || \n ex.Message.Contains(\"connection\") || \n ex.Message.Contains(\"network\") ||\n ex.Message.Contains(\"pipeline has been stopped\");\n \n string errorMessage = isConnectivityIssue\n ? \"Internet connection lost during installation. Please check your network connection and try again.\"\n : ex.Message;\n \n RaiseStatusChanged(appInfo, $\"Error installing {appInfo.Name}: {errorMessage}\", true, false, false, isConnectivityIssue);\n \n return new InstallationCoordinationResult\n {\n Success = false,\n WasCancelled = false,\n WasConnectivityIssue = isConnectivityIssue,\n ErrorMessage = errorMessage,\n AppInfo = appInfo\n };\n }\n }\n \n /// \n /// Starts monitoring internet connectivity during installation.\n /// \n /// The application information.\n /// The cancellation token source.\n /// A task that completes when monitoring is stopped, with a result indicating if a connectivity issue was detected.\n private async Task StartConnectivityMonitoring(AppInfo appInfo, CancellationTokenSource cts)\n {\n bool connectivityIssueDetected = false;\n \n // Set up connectivity change handler\n EventHandler connectivityChangedHandler = null;\n connectivityChangedHandler = (sender, args) =>\n {\n if (cts.Token.IsCancellationRequested)\n {\n return; // Installation already cancelled\n }\n \n if (args.IsUserCancelled)\n {\n // User cancelled the operation\n var message = $\"Installation of {appInfo.Name} was cancelled by user\";\n RaiseStatusChanged(appInfo, message, false, false, true);\n }\n else if (!args.IsConnected)\n {\n // Internet connection lost\n connectivityIssueDetected = true;\n \n var message = $\"Error: Internet connection lost while installing {appInfo.Name}. Installation stopped.\";\n RaiseStatusChanged(appInfo, message, false, false, false, true);\n \n // Show a notification if available\n _notificationService?.ShowToast(\n \"Internet Connection Lost\",\n \"Internet connection has been lost during installation. Installation has been stopped.\",\n ToastType.Error\n );\n \n // Show a dialog if available\n if (_dialogService != null)\n {\n // Fire and forget - we don't want to block the connectivity handler\n _ = _dialogService.ShowInformationAsync(\n $\"The installation of {appInfo.Name} has been stopped because internet connection was lost. Please check your network connection and try again when your internet connection is stable.\",\n \"Internet Connection Lost\"\n );\n }\n \n // Cancel the installation process\n cts.Cancel();\n }\n };\n \n try\n {\n // Subscribe to connectivity changes\n _connectivityService.ConnectivityChanged += connectivityChangedHandler;\n \n // Start monitoring connectivity\n await _connectivityService.StartMonitoringAsync(5, cts.Token);\n \n // Wait for the cancellation token to be triggered\n try\n {\n // This will throw when the token is cancelled\n await Task.Delay(-1, cts.Token);\n }\n catch (OperationCanceledException)\n {\n // Expected when installation completes or is cancelled\n }\n \n return connectivityIssueDetected;\n }\n finally\n {\n // Unsubscribe from connectivity changes\n if (connectivityChangedHandler != null)\n {\n _connectivityService.ConnectivityChanged -= connectivityChangedHandler;\n }\n \n // Stop monitoring connectivity\n _connectivityService.StopMonitoring();\n }\n }\n \n /// \n /// Raises the InstallationStatusChanged event.\n /// \n /// The application information.\n /// The status message.\n /// Whether the installation is complete.\n /// Whether the installation was successful.\n /// Whether the installation was cancelled by the user.\n /// Whether the installation failed due to connectivity issues.\n private void RaiseStatusChanged(\n AppInfo appInfo,\n string statusMessage,\n bool isComplete = false,\n bool isSuccess = false,\n bool isCancelled = false,\n bool isConnectivityIssue = false)\n {\n _logService.LogInformation(statusMessage);\n \n InstallationStatusChanged?.Invoke(\n this,\n new InstallationStatusChangedEventArgs(\n appInfo,\n statusMessage,\n isComplete,\n isSuccess,\n isCancelled,\n isConnectivityIssue\n )\n );\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/UacOptimizations.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Models.Enums;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class UacOptimizations\n{\n public const string RegistryPath = @\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\";\n public const string ConsentPromptName = \"ConsentPromptBehaviorAdmin\";\n public const string SecureDesktopName = \"PromptOnSecureDesktop\";\n public static readonly RegistryValueKind ValueKind = RegistryValueKind.DWord;\n\n // UAC settings require two registry values working together\n // ConsentPromptBehaviorAdmin controls the behavior type\n // PromptOnSecureDesktop controls whether the desktop is dimmed\n\n // Map from UacLevel enum to ConsentPromptBehaviorAdmin registry values\n public static readonly Dictionary UacLevelToConsentPromptValue = new()\n {\n { UacLevel.NeverNotify, 0 }, // Never notify\n { UacLevel.NotifyNoDesktopDim, 5 }, // Notify without dimming desktop\n { UacLevel.NotifyChangesOnly, 5 }, // Notify only for changes (default)\n { UacLevel.AlwaysNotify, 2 }, // Always notify\n };\n\n // Map from UacLevel enum to PromptOnSecureDesktop registry values\n public static readonly Dictionary UacLevelToSecureDesktopValue = new()\n {\n { UacLevel.NeverNotify, 0 }, // Secure desktop disabled\n { UacLevel.NotifyNoDesktopDim, 0 }, // Secure desktop disabled\n { UacLevel.NotifyChangesOnly, 1 }, // Secure desktop enabled\n { UacLevel.AlwaysNotify, 1 }, // Secure desktop enabled\n };\n\n // User-friendly names for each UAC level\n public static readonly Dictionary UacLevelNames = new()\n {\n { UacLevel.AlwaysNotify, \"Always notify\" },\n { UacLevel.NotifyChangesOnly, \"Notify when apps try to make changes\" },\n { UacLevel.NotifyNoDesktopDim, \"Notify when apps try to make changes (no dim)\" },\n { UacLevel.NeverNotify, \"Never notify\" },\n { UacLevel.Custom, \"Custom UAC Setting\" },\n };\n\n /// \n /// Helper method to get UacLevel from both registry values\n /// \n /// The ConsentPromptBehaviorAdmin registry value\n /// The PromptOnSecureDesktop registry value\n /// Optional UAC settings service to save custom values\n /// The corresponding UacLevel\n public static UacLevel GetUacLevelFromRegistryValues(\n int consentPromptValue,\n int secureDesktopValue,\n IUacSettingsService uacSettingsService = null\n )\n {\n // Check for exact matches of both values\n foreach (var level in UacLevelToConsentPromptValue.Keys)\n {\n if (\n UacLevelToConsentPromptValue[level] == consentPromptValue\n && UacLevelToSecureDesktopValue[level] == secureDesktopValue\n )\n {\n return level;\n }\n }\n\n // If no exact match, determine if it's one of the common non-standard combinations\n if (consentPromptValue == 0)\n {\n return UacLevel.NeverNotify; // ConsentPrompt=0 always means Never Notify\n }\n else if (consentPromptValue == 5)\n {\n // ConsentPrompt=5 with SecureDesktop determines dimming\n return secureDesktopValue == 0\n ? UacLevel.NotifyNoDesktopDim\n : UacLevel.NotifyChangesOnly;\n }\n else if (consentPromptValue == 2)\n {\n return UacLevel.AlwaysNotify; // ConsentPrompt=2 is Always Notify\n }\n\n // If we get here, we have a custom UAC setting\n // Save the custom values if we have a service\n if (uacSettingsService != null)\n {\n // Save asynchronously - fire and forget\n _ = Task.Run(() => uacSettingsService.SaveCustomUacSettingsAsync(consentPromptValue, secureDesktopValue));\n }\n \n return UacLevel.Custom;\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/InstallationOrchestrator.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Exceptions;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Orchestrates the installation and removal of applications, capabilities, and features.\n/// \npublic class InstallationOrchestrator : IInstallationOrchestrator\n{\n private readonly IAppInstallationService _appInstallationService;\n private readonly ICapabilityInstallationService _capabilityInstallationService;\n private readonly IFeatureInstallationService _featureInstallationService;\n private readonly IAppRemovalService _appRemovalService;\n private readonly ICapabilityRemovalService _capabilityRemovalService;\n private readonly IFeatureRemovalService _featureRemovalService;\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The app installation service.\n /// The capability installation service.\n /// The feature installation service.\n /// The app removal service.\n /// The capability removal service.\n /// The feature removal service.\n /// The log service.\n public InstallationOrchestrator(\n IAppInstallationService appInstallationService,\n ICapabilityInstallationService capabilityInstallationService,\n IFeatureInstallationService featureInstallationService,\n IAppRemovalService appRemovalService,\n ICapabilityRemovalService capabilityRemovalService,\n IFeatureRemovalService featureRemovalService,\n ILogService logService)\n {\n _appInstallationService = appInstallationService ?? throw new ArgumentNullException(nameof(appInstallationService));\n _capabilityInstallationService = capabilityInstallationService ?? throw new ArgumentNullException(nameof(capabilityInstallationService));\n _featureInstallationService = featureInstallationService ?? throw new ArgumentNullException(nameof(featureInstallationService));\n _appRemovalService = appRemovalService ?? throw new ArgumentNullException(nameof(appRemovalService));\n _capabilityRemovalService = capabilityRemovalService ?? throw new ArgumentNullException(nameof(capabilityRemovalService));\n _featureRemovalService = featureRemovalService ?? throw new ArgumentNullException(nameof(featureRemovalService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Installs an application, capability, or feature.\n /// \n /// The item to install.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the asynchronous operation.\n public async Task InstallAsync(\n IInstallableItem item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (item == null)\n {\n throw new ArgumentNullException(nameof(item));\n }\n\n _logService.LogInformation($\"Installing {item.DisplayName}\");\n\n try\n {\n if (item is AppInfo appInfo)\n {\n await _appInstallationService.InstallAppAsync(appInfo, progress, cancellationToken);\n }\n else if (item is CapabilityInfo capabilityInfo)\n {\n // Assuming InstallCapabilityAsync should be called for single items\n await _capabilityInstallationService.InstallCapabilityAsync(capabilityInfo, progress, cancellationToken);\n }\n else if (item is FeatureInfo featureInfo)\n {\n // Corrected method name\n await _featureInstallationService.InstallFeatureAsync(featureInfo, progress, cancellationToken);\n }\n else\n {\n throw new ArgumentException($\"Unsupported item type: {item.GetType().Name}\", nameof(item));\n }\n\n _logService.LogSuccess($\"Successfully installed {item.DisplayName}\");\n }\n catch (Exception ex) when (ex is not InstallationException)\n {\n _logService.LogError($\"Failed to install {item.DisplayName}\", ex);\n throw new InstallationException(item.DisplayName, $\"Installation failed for {item.DisplayName}\", false, ex);\n }\n }\n\n /// \n /// Removes an application, capability, or feature.\n /// \n /// The item to remove.\n /// A task representing the asynchronous operation.\n public async Task RemoveAsync(IInstallableItem item)\n {\n if (item == null)\n {\n throw new ArgumentNullException(nameof(item));\n }\n\n _logService.LogInformation($\"Removing {item.DisplayName}\");\n\n try\n {\n if (item is AppInfo appInfo)\n {\n await _appRemovalService.RemoveAppAsync(appInfo);\n }\n else if (item is CapabilityInfo capabilityInfo)\n {\n await _capabilityRemovalService.RemoveCapabilityAsync(capabilityInfo);\n }\n else if (item is FeatureInfo featureInfo)\n {\n await _featureRemovalService.RemoveFeatureAsync(featureInfo);\n }\n else\n {\n throw new ArgumentException($\"Unsupported item type: {item.GetType().Name}\", nameof(item));\n }\n\n _logService.LogSuccess($\"Successfully removed {item.DisplayName}\");\n }\n catch (Exception ex) when (ex is not RemovalException)\n {\n _logService.LogError($\"Failed to remove {item.DisplayName}\", ex);\n throw new RemovalException(item.DisplayName, ex.Message, true, ex);\n }\n }\n\n /// \n /// Installs multiple items in batch.\n /// \n /// The items to install.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the asynchronous operation.\n public async Task InstallBatchAsync(\n IEnumerable items,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (items == null)\n {\n throw new ArgumentNullException(nameof(items));\n }\n\n var itemsList = new List(items);\n _logService.LogInformation($\"Installing {itemsList.Count} items in batch\");\n\n int totalItems = itemsList.Count;\n int completedItems = 0;\n\n foreach (var item in itemsList)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n _logService.LogWarning(\"Batch installation cancelled\");\n break;\n }\n\n try\n {\n // Create a progress wrapper that scales the progress to the current item's portion\n var itemProgress = progress != null\n ? new Progress(detail =>\n {\n // Scale the progress to the current item's portion of the total\n double scaledProgress = (completedItems * 100.0 + (detail.Progress ?? 0)) / totalItems;\n \n progress.Report(new TaskProgressDetail\n {\n Progress = scaledProgress,\n StatusText = $\"[{completedItems + 1}/{totalItems}] {detail.StatusText}\",\n DetailedMessage = detail.DetailedMessage,\n LogLevel = detail.LogLevel\n });\n })\n : null;\n\n await InstallAsync(item, itemProgress, cancellationToken);\n completedItems++;\n\n // Report overall progress\n progress?.Report(new TaskProgressDetail\n {\n Progress = completedItems * 100.0 / totalItems,\n StatusText = $\"Completed {completedItems} of {totalItems} items\",\n DetailedMessage = $\"Successfully installed {item.DisplayName}\"\n });\n }\n catch (Exception ex) when (ex is not InstallationException)\n {\n _logService.LogError($\"Error installing {item.DisplayName}\", ex);\n \n // Report error but continue with next item\n progress?.Report(new TaskProgressDetail\n {\n Progress = completedItems * 100.0 / totalItems,\n StatusText = $\"Error installing {item.DisplayName}\",\n DetailedMessage = ex.Message,\n LogLevel = Winhance.Core.Features.Common.Enums.LogLevel.Error\n });\n\n throw new InstallationException($\"Error installing {item.DisplayName}: {ex.Message}\", ex);\n }\n }\n\n _logService.LogInformation($\"Batch installation completed. {completedItems} of {totalItems} items installed successfully.\");\n }\n\n /// \n /// Removes multiple items in batch.\n /// \n /// The items to remove.\n /// A list of results indicating success or failure for each item.\n public async Task> RemoveBatchAsync(\n IEnumerable items)\n {\n if (items == null)\n {\n throw new ArgumentNullException(nameof(items));\n }\n\n var itemsList = new List(items);\n _logService.LogInformation($\"Removing {itemsList.Count} items in batch\");\n\n var results = new List<(string Name, bool Success, string? Error)>();\n\n foreach (var item in itemsList)\n {\n try\n {\n await RemoveAsync(item);\n results.Add((item.DisplayName, true, null));\n }\n catch (Exception ex) when (ex is not RemovalException)\n {\n _logService.LogError($\"Error removing {item.DisplayName}\", ex);\n results.Add((item.DisplayName, false, new RemovalException(item.DisplayName, ex.Message, true, ex).Message));\n }\n }\n\n int successCount = results.Count(r => r.Success);\n _logService.LogInformation($\"Batch removal completed. {successCount} of {results.Count} items removed successfully.\");\n\n return results;\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Models/WindowsApp.cs", "using System;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing System.Linq;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Models\n{\n /// \n /// Represents the type of Windows app.\n /// \n public enum WindowsAppType\n {\n /// \n /// Standard Windows application.\n /// \n StandardApp,\n\n /// \n /// Windows capability.\n /// \n Capability,\n\n /// \n /// Windows optional feature.\n /// \n OptionalFeature,\n }\n\n /// \n /// Represents a Windows built-in application that can be installed or removed.\n /// This includes system components, default Windows apps, and capabilities.\n /// \n public partial class WindowsApp : ObservableObject, IInstallableItem, ISearchable\n {\n public string PackageId => PackageID;\n public string DisplayName => Name;\n public InstallItemType ItemType => AppType switch\n {\n WindowsAppType.Capability => InstallItemType.Capability,\n WindowsAppType.OptionalFeature => InstallItemType.Feature,\n _ => InstallItemType.WindowsApp\n };\n public bool RequiresRestart { get; set; }\n\n // List of package names that cannot be reinstalled via winget/Microsoft Store\n private static readonly string[] NonReinstallablePackages = new string[]\n {\n \"Microsoft.MicrosoftOfficeHub\",\n \"Microsoft.MSPaint\",\n \"Microsoft.Getstarted\",\n };\n\n [ObservableProperty]\n private string _name = string.Empty;\n\n [ObservableProperty]\n private string _description = string.Empty;\n\n [ObservableProperty]\n private string _packageName = string.Empty;\n\n [ObservableProperty]\n private string _packageID = string.Empty;\n\n [ObservableProperty]\n private string _category = string.Empty;\n\n [ObservableProperty]\n private bool _isInstalled;\n\n [ObservableProperty]\n private bool _isSelected;\n\n [ObservableProperty]\n private bool _isSpecialHandler;\n\n [ObservableProperty]\n private string _specialHandlerType = string.Empty;\n\n [ObservableProperty]\n private string[]? _subPackages;\n\n [ObservableProperty]\n private AppRegistrySetting[]? _registrySettings;\n\n [ObservableProperty]\n private bool _isSystemProtected;\n\n [ObservableProperty]\n private bool _isNotReinstallable;\n\n /// \n /// Gets or sets a value indicating whether the item can be reinstalled or reenabled after removal.\n /// \n [ObservableProperty]\n private bool _canBeReinstalled = true;\n\n /// \n /// Gets or sets the type of Windows app.\n /// \n [ObservableProperty]\n private WindowsAppType _appType = WindowsAppType.StandardApp;\n\n /// \n /// Determines if the app should show its description.\n /// \n public bool HasDescription => !string.IsNullOrEmpty(Description);\n\n /// \n /// Gets a value indicating whether this app is a Windows capability.\n /// \n public bool IsCapability => AppType == WindowsAppType.Capability;\n\n /// \n /// Gets a value indicating whether this app is a Windows optional feature.\n /// \n public bool IsOptionalFeature => AppType == WindowsAppType.OptionalFeature;\n\n /// \n /// Creates a WindowsApp instance from an AppInfo model.\n /// \n /// The AppInfo model containing the app's data.\n /// A new WindowsApp instance.\n public static WindowsApp FromAppInfo(AppInfo appInfo)\n {\n // Map AppType to WindowsAppType\n WindowsAppType appType;\n switch (appInfo.Type)\n {\n case Winhance.Core.Features.SoftwareApps.Models.AppType.Capability:\n appType = WindowsAppType.Capability;\n break;\n case Winhance.Core.Features.SoftwareApps.Models.AppType.OptionalFeature:\n appType = WindowsAppType.OptionalFeature;\n break;\n case Winhance.Core.Features.SoftwareApps.Models.AppType.StandardApp:\n default:\n appType = WindowsAppType.StandardApp;\n break;\n }\n\n var app = new WindowsApp\n {\n Name = appInfo.Name,\n Description = appInfo.Description,\n PackageName = appInfo.PackageName,\n PackageID = appInfo.PackageID,\n Category = appInfo.Category,\n IsInstalled = appInfo.IsInstalled,\n IsSpecialHandler = appInfo.RequiresSpecialHandling,\n SpecialHandlerType = appInfo.SpecialHandlerType ?? string.Empty,\n SubPackages = appInfo.SubPackages,\n RegistrySettings = appInfo.RegistrySettings,\n IsSystemProtected = appInfo.IsSystemProtected,\n IsSelected = true,\n CanBeReinstalled = appInfo.CanBeReinstalled,\n AppType = appType,\n };\n\n // Check if this app is in the list of non-reinstallable packages\n app.IsNotReinstallable = Array.Exists(\n NonReinstallablePackages,\n p => p.Equals(appInfo.PackageName, StringComparison.OrdinalIgnoreCase)\n );\n\n return app;\n }\n\n /// \n /// Creates a WindowsApp instance from a CapabilityInfo model.\n /// \n /// The CapabilityInfo model containing the capability's data.\n /// A new WindowsApp instance.\n public static WindowsApp FromCapabilityInfo(CapabilityInfo capabilityInfo)\n {\n var app = new WindowsApp\n {\n Name = capabilityInfo.Name,\n Description = capabilityInfo.Description,\n PackageName = capabilityInfo.PackageName,\n PackageID = capabilityInfo.PackageName, // Ensure PackageID is set for capabilities\n Category = capabilityInfo.Category,\n IsInstalled = capabilityInfo.IsInstalled,\n RegistrySettings = capabilityInfo.RegistrySettings,\n IsSystemProtected = capabilityInfo.IsSystemProtected,\n CanBeReinstalled = capabilityInfo.CanBeReenabled,\n IsSelected = true,\n AppType = WindowsAppType.Capability,\n };\n\n return app;\n }\n\n /// \n /// Creates a WindowsApp instance from a FeatureInfo model.\n /// \n /// The FeatureInfo model containing the feature's data.\n /// A new WindowsApp instance.\n public static WindowsApp FromFeatureInfo(FeatureInfo featureInfo)\n {\n var app = new WindowsApp\n {\n Name = featureInfo.Name,\n Description = featureInfo.Description,\n PackageName = featureInfo.PackageName,\n PackageID = featureInfo.PackageName, // Ensure PackageID is set for features\n Category = featureInfo.Category,\n IsInstalled = featureInfo.IsInstalled,\n RegistrySettings = featureInfo.RegistrySettings,\n IsSystemProtected = featureInfo.IsSystemProtected,\n CanBeReinstalled = featureInfo.CanBeReenabled,\n IsSelected = true,\n AppType = WindowsAppType.OptionalFeature,\n };\n\n return app;\n }\n\n /// \n /// Converts this WindowsApp to an AppInfo object.\n /// \n /// An AppInfo object with data from this WindowsApp.\n public AppInfo ToAppInfo()\n {\n // Map WindowsAppType to AppType\n Winhance.Core.Features.SoftwareApps.Models.AppType appType;\n switch (AppType)\n {\n case WindowsAppType.Capability:\n appType = Winhance.Core.Features.SoftwareApps.Models.AppType.Capability;\n break;\n case WindowsAppType.OptionalFeature:\n appType = Winhance.Core.Features.SoftwareApps.Models.AppType.OptionalFeature;\n break;\n case WindowsAppType.StandardApp:\n default:\n appType = Winhance.Core.Features.SoftwareApps.Models.AppType.StandardApp;\n break;\n }\n\n return new AppInfo\n {\n Name = Name,\n Description = Description,\n PackageName = PackageName,\n PackageID = PackageID,\n Category = Category,\n IsInstalled = IsInstalled,\n RequiresSpecialHandling = IsSpecialHandler,\n SpecialHandlerType = SpecialHandlerType,\n SubPackages = SubPackages,\n RegistrySettings = RegistrySettings,\n IsSystemProtected = IsSystemProtected,\n CanBeReinstalled = CanBeReinstalled,\n Type = appType,\n Version = string.Empty // Default to empty string for version\n };\n }\n \n /// \n /// Converts this WindowsApp to a CapabilityInfo object.\n /// \n /// A CapabilityInfo object with data from this WindowsApp.\n public CapabilityInfo ToCapabilityInfo()\n {\n if (AppType != WindowsAppType.Capability)\n {\n throw new InvalidOperationException(\"Cannot convert non-capability WindowsApp to CapabilityInfo\");\n }\n \n return new CapabilityInfo\n {\n Name = Name,\n Description = Description,\n PackageName = PackageName,\n Category = Category,\n IsInstalled = IsInstalled,\n RegistrySettings = RegistrySettings,\n IsSystemProtected = IsSystemProtected,\n CanBeReenabled = CanBeReinstalled\n };\n }\n \n /// \n /// Converts this WindowsApp to a FeatureInfo object.\n /// \n /// A FeatureInfo object with data from this WindowsApp.\n public FeatureInfo ToFeatureInfo()\n {\n if (AppType != WindowsAppType.OptionalFeature)\n {\n throw new InvalidOperationException(\"Cannot convert non-feature WindowsApp to FeatureInfo\");\n }\n \n return new FeatureInfo\n {\n Name = Name,\n Description = Description,\n PackageName = PackageName,\n Category = Category,\n IsInstalled = IsInstalled,\n RegistrySettings = RegistrySettings,\n IsSystemProtected = IsSystemProtected,\n CanBeReenabled = CanBeReinstalled\n };\n }\n\n /// \n /// Determines if the app matches the given search term.\n /// \n /// The search term to match against.\n /// True if the app matches the search term, false otherwise.\n public bool MatchesSearch(string searchTerm)\n {\n if (string.IsNullOrWhiteSpace(searchTerm))\n {\n return true;\n }\n\n searchTerm = searchTerm.ToLowerInvariant();\n \n // Check if the search term matches any of the searchable properties\n return Name.ToLowerInvariant().Contains(searchTerm) ||\n (!string.IsNullOrEmpty(Description) && Description.ToLowerInvariant().Contains(searchTerm)) ||\n (!string.IsNullOrEmpty(PackageName) && PackageName.ToLowerInvariant().Contains(searchTerm)) ||\n (!string.IsNullOrEmpty(Category) && Category.ToLowerInvariant().Contains(searchTerm));\n }\n\n /// \n /// Gets the searchable properties of the app.\n /// \n /// An array of property names that should be searched.\n public string[] GetSearchableProperties()\n {\n return new[] { nameof(Name), nameof(Description), nameof(PackageName), nameof(Category) };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/InstallationStatusService.cs", "using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.SoftwareApps.Exceptions;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n public class InstallationStatusService : IInstallationStatusService\n {\n private readonly IPackageManager _packageManager;\n private readonly ConcurrentDictionary _statusCache = new();\n private readonly ILogService _logService;\n\n public InstallationStatusService(IPackageManager packageManager, ILogService logService)\n {\n _packageManager = packageManager;\n _logService = logService;\n }\n\n public Task SetInstallStatusAsync(string appId, InstallStatus status)\n {\n try\n {\n _logService.LogInformation($\"Setting install status for {appId} to {status}\");\n bool isInstalled = status == InstallStatus.Success;\n _statusCache.AddOrUpdate(appId, isInstalled, (k, v) => isInstalled);\n _logService.LogInformation($\"Successfully set status for {appId}\");\n return Task.FromResult(true);\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to set install status for {appId}\", ex);\n return Task.FromResult(false);\n }\n }\n\n public async Task GetInstallStatusAsync(string appId)\n {\n try\n {\n if (_statusCache.TryGetValue(appId, out var cachedStatus))\n {\n _logService.LogInformation($\"Retrieved cached status for {appId}\");\n return cachedStatus ? InstallStatus.Success : InstallStatus.Failed;\n }\n\n _logService.LogInformation($\"Querying package manager for {appId}\");\n var isInstalled = await _packageManager.IsAppInstalledAsync(appId);\n _statusCache.TryAdd(appId, isInstalled);\n \n _logService.LogInformation($\"Install status for {appId}: {isInstalled}\");\n return isInstalled ? InstallStatus.Success : InstallStatus.Failed;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to get install status for {appId}\", ex);\n return InstallStatus.Failed;\n }\n }\n\n public async Task RefreshStatusAsync(IEnumerable appIds)\n {\n var result = new RefreshResult();\n var errors = new Dictionary();\n\n try\n {\n _logService.LogInformation(\"Refreshing installation status for batch of apps\");\n \n foreach (var appId in appIds.Distinct())\n {\n try\n {\n var isInstalled = await _packageManager.IsAppInstalledAsync(appId);\n _statusCache.AddOrUpdate(appId, isInstalled, (k, v) => isInstalled);\n result.SuccessCount++;\n }\n catch (Exception ex)\n {\n errors[appId] = ex.Message;\n result.FailedCount++;\n _logService.LogError($\"Failed to refresh status for {appId}\", ex);\n }\n }\n \n result.Errors = errors;\n _logService.LogSuccess(\"Successfully refreshed installation status\");\n return result;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to refresh installation status\", ex);\n throw new InstallationStatusException(\"Failed to refresh installation status\", ex);\n }\n }\n\n public async Task RefreshInstallationStatusAsync(\n IEnumerable items,\n CancellationToken cancellationToken = default)\n {\n try\n {\n _logService.LogInformation(\"Refreshing installation status for batch of items\");\n \n var packageIds = items.Select(i => i.PackageId).Distinct();\n var statuses = await GetBatchInstallStatusAsync(packageIds, cancellationToken);\n \n foreach (var item in items)\n {\n cancellationToken.ThrowIfCancellationRequested();\n \n if (statuses.TryGetValue(item.PackageId, out var isInstalled))\n {\n _statusCache.TryAdd(item.PackageId, isInstalled);\n }\n }\n \n _logService.LogSuccess(\"Successfully refreshed installation status\");\n }\n catch (OperationCanceledException)\n {\n _logService.LogWarning(\"Installation status refresh was cancelled\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to refresh installation status\", ex);\n throw new InstallationStatusException(\"Failed to refresh installation status\", ex);\n }\n }\n\n public async Task GetItemInstallStatusAsync(\n IInstallableItem item,\n CancellationToken cancellationToken = default)\n {\n try\n {\n if (_statusCache.TryGetValue(item.PackageId, out var cachedStatus))\n {\n _logService.LogInformation($\"Retrieved cached status for {item.PackageId}\");\n return cachedStatus;\n }\n\n _logService.LogInformation($\"Querying package manager for {item.PackageId}\");\n var isInstalled = await _packageManager.IsAppInstalledAsync(item.PackageId, cancellationToken);\n _statusCache.TryAdd(item.PackageId, isInstalled);\n \n _logService.LogInformation($\"Install status for {item.PackageId}: {isInstalled}\");\n return isInstalled;\n }\n catch (OperationCanceledException)\n {\n _logService.LogWarning($\"Install status check for {item.PackageId} was cancelled\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Failed to get install status for {item.PackageId}\", ex);\n throw new InstallationStatusException($\"Failed to get install status for {item.PackageId}\", ex);\n }\n }\n\n public async Task> GetBatchInstallStatusAsync(\n IEnumerable packageIds,\n CancellationToken cancellationToken = default)\n {\n try\n {\n var distinctIds = packageIds.Distinct().ToList();\n var results = new Dictionary();\n _logService.LogInformation($\"Getting batch install status for {distinctIds.Count} packages\");\n\n foreach (var id in distinctIds)\n {\n cancellationToken.ThrowIfCancellationRequested();\n \n if (_statusCache.TryGetValue(id, out var cachedStatus))\n {\n results[id] = cachedStatus;\n _logService.LogInformation($\"Using cached status for {id}\");\n }\n else\n {\n var isInstalled = await _packageManager.IsAppInstalledAsync(id, cancellationToken);\n _statusCache.TryAdd(id, isInstalled);\n results[id] = isInstalled;\n _logService.LogInformation($\"Retrieved fresh status for {id}: {isInstalled}\");\n }\n }\n\n _logService.LogSuccess(\"Completed batch install status check\");\n return results;\n }\n catch (OperationCanceledException)\n {\n _logService.LogWarning(\"Batch install status check was cancelled\");\n throw;\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to get batch install status\", ex);\n throw new InstallationStatusException(\"Failed to get batch install status\", ex);\n }\n }\n\n public void ClearStatusCache()\n {\n try\n {\n _logService.LogInformation(\"Clearing installation status cache\");\n _statusCache.Clear();\n _logService.LogSuccess(\"Successfully cleared installation status cache\");\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Failed to clear installation status cache\", ex);\n throw new InstallationStatusException(\"Failed to clear installation status cache\", ex);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/DonationDialog.xaml.cs", "using System;\nusing System.Threading.Tasks;\nusing System.Windows;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Donation dialog that extends CustomDialog with a \"Don't show this again\" checkbox\n /// \n public partial class DonationDialog : Window\n {\n // Default text content for the donation dialog\n private static readonly string DefaultTitle = \"Support Winhance\";\n private static readonly string DefaultSupportMessage = \"Your support helps keep this project going!\";\n private static readonly string DefaultFooterText = \"Click 'Yes' to show your support!\";\n\n public bool DontShowAgain => DontShowAgainCheckBox.IsChecked ?? false;\n\n public DonationDialog()\n {\n InitializeComponent();\n DataContext = this;\n }\n\n private void PrimaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = true;\n Close();\n }\n\n private void SecondaryButton_Click(object sender, RoutedEventArgs e)\n {\n DialogResult = false;\n Close();\n }\n \n private void TertiaryButton_Click(object sender, RoutedEventArgs e)\n {\n // Explicitly set DialogResult to null for Cancel\n DialogResult = null;\n Close();\n }\n\n /// \n /// Creates and shows a donation dialog with the specified parameters.\n /// This method ensures the dialog is properly modal and blocks the main window.\n /// \n /// The dialog title (optional - uses default if null)\n /// The support message (optional - uses default if null)\n /// The footer text (optional - uses default if null)\n /// The dialog instance with DialogResult set\n public static async Task ShowDonationDialogAsync(string title = null, string supportMessage = null, string footerText = null)\n {\n try\n {\n var dialog = new DonationDialog\n {\n Title = title ?? DefaultTitle,\n WindowStartupLocation = WindowStartupLocation.CenterOwner,\n ShowInTaskbar = false,\n ResizeMode = ResizeMode.NoResize,\n WindowStyle = WindowStyle.None,\n AllowsTransparency = true\n };\n\n // Set the support message and footer text\n dialog.SupportMessageText.Text = supportMessage ?? DefaultSupportMessage;\n dialog.FooterText.Text = footerText ?? DefaultFooterText;\n \n // Set button content\n dialog.PrimaryButton.Content = \"Yes\";\n dialog.SecondaryButton.Content = \"No\";\n\n // Set the owner to the main window to ensure it appears on top\n if (Application.Current.MainWindow != null && Application.Current.MainWindow != dialog)\n {\n dialog.Owner = Application.Current.MainWindow;\n dialog.Topmost = true; // Ensure it stays on top\n }\n else\n {\n // Try to find the main window another way\n foreach (Window window in Application.Current.Windows)\n {\n if (window != dialog && window.IsVisible)\n {\n dialog.Owner = window;\n dialog.Topmost = true;\n break;\n }\n }\n }\n\n // Make the dialog visible and focused\n dialog.Visibility = Visibility.Visible;\n dialog.Activate();\n dialog.Focus();\n \n // Show the dialog and wait for it to complete\n dialog.ShowDialog();\n \n // Return the dialog\n return dialog;\n }\n catch (Exception ex)\n {\n // Show error message\n MessageBox.Show($\"Error showing donation dialog: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n \n // Create a dummy dialog with error result\n var errorDialog = new DonationDialog();\n errorDialog.DialogResult = false;\n return errorDialog;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/Methods/AppxPackageVerificationMethod.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Management;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification.Methods\n{\n /// \n /// Verifies UWP app installations by querying the AppX package manager.\n /// \n public class AppxPackageVerificationMethod : VerificationMethodBase\n {\n /// \n /// Initializes a new instance of the class.\n /// \n public AppxPackageVerificationMethod()\n : base(\"AppxPackage\", priority: 15) { }\n\n /// \n protected override async Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken\n )\n {\n return await Task.Run(\n () =>\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n try\n {\n var packages = GetAppxPackages();\n var matchingPackage = packages.FirstOrDefault(p =>\n p.Name.Equals(packageId, StringComparison.OrdinalIgnoreCase)\n || p.PackageFullName.StartsWith(\n packageId,\n StringComparison.OrdinalIgnoreCase\n )\n );\n\n if (matchingPackage != null)\n {\n return new VerificationResult\n {\n IsVerified = true,\n Message =\n $\"Found UWP package: {matchingPackage.Name} (Version: {matchingPackage.Version})\",\n MethodUsed = \"AppxPackage\",\n AdditionalInfo = matchingPackage,\n };\n }\n\n return VerificationResult.Failure(\n $\"UWP package '{packageId}' not found\"\n );\n }\n catch (Exception ex)\n {\n return VerificationResult.Failure(\n $\"Error checking UWP packages: {ex.Message}\"\n );\n }\n },\n cancellationToken\n )\n .ConfigureAwait(false);\n }\n\n /// \n protected override async Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken\n )\n {\n var result = await VerifyPresenceAsync(packageId, cancellationToken)\n .ConfigureAwait(false);\n if (!result.IsVerified)\n return result;\n\n // Extract the version from the additional info\n var installedVersion = (result.AdditionalInfo as AppxPackageInfo)?.Version;\n if (string.IsNullOrEmpty(installedVersion))\n return VerificationResult.Failure(\n $\"Could not determine installed version for UWP package '{packageId}'\",\n \"AppxPackage\"\n );\n\n // Simple version comparison (this could be enhanced with proper version comparison logic)\n if (!installedVersion.Equals(version, StringComparison.OrdinalIgnoreCase))\n return VerificationResult.Failure(\n $\"Version mismatch for UWP package '{packageId}'. Installed: {installedVersion}, Expected: {version}\",\n \"AppxPackage\"\n );\n\n return result;\n }\n\n private static List GetAppxPackages()\n {\n var packages = new List();\n\n try\n {\n // Method 1: Using Get-AppxPackage via PowerShell (more reliable for current user)\n using (var ps = System.Management.Automation.PowerShell.Create())\n {\n var results = ps.AddCommand(\"Get-AppxPackage\").Invoke();\n foreach (var result in results)\n {\n packages.Add(\n new AppxPackageInfo\n {\n Name = result.Properties[\"Name\"]?.Value?.ToString(),\n PackageFullName = result\n .Properties[\"PackageFullName\"]\n ?.Value?.ToString(),\n Version = result.Properties[\"Version\"]?.Value?.ToString(),\n InstallLocation = result\n .Properties[\"InstallLocation\"]\n ?.Value?.ToString(),\n }\n );\n }\n }\n }\n catch\n {\n // Fall back to WMI if PowerShell fails\n try\n {\n var searcher = new ManagementObjectSearcher(\"SELECT * FROM Win32_Product\");\n foreach (var obj in searcher.Get().Cast())\n {\n packages.Add(\n new AppxPackageInfo\n {\n Name = obj[\"Name\"]?.ToString(),\n Version = obj[\"Version\"]?.ToString(),\n InstallLocation = obj[\"InstallLocation\"]?.ToString(),\n }\n );\n }\n }\n catch\n {\n // If both methods fail, return an empty list\n }\n }\n\n return packages;\n }\n }\n\n /// \n /// Represents information about an AppX package.\n /// \n public class AppxPackageInfo\n {\n /// \n /// Gets or sets the name of the package.\n /// \n public string Name { get; set; }\n\n /// \n /// Gets or sets the full name of the package.\n /// \n public string PackageFullName { get; set; }\n\n /// \n /// Gets or sets the version of the package.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets the installation location of the package.\n /// \n public string InstallLocation { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/CompositeInstallationVerifier.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification\n{\n /// \n /// Coordinates multiple verification methods to determine if a package is installed.\n /// \n public class CompositeInstallationVerifier : IInstallationVerifier\n {\n private readonly IEnumerable _verificationMethods;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The verification methods to use.\n public CompositeInstallationVerifier(IEnumerable verificationMethods)\n {\n _verificationMethods =\n verificationMethods?.OrderBy(m => m.Priority).ToList()\n ?? throw new ArgumentNullException(nameof(verificationMethods));\n }\n\n /// \n public async Task VerifyInstallationAsync(\n string packageId,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n // Add a short delay before verification to allow Windows to complete registration\n await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken).ConfigureAwait(false);\n\n var results = new List();\n VerificationResult successfulResult = null;\n\n // Try verification with up to 3 attempts with increasing delays\n for (int attempt = 1; attempt <= 3; attempt++)\n {\n // Clear previous results for each attempt\n results.Clear();\n successfulResult = null;\n \n foreach (var method in _verificationMethods)\n {\n try\n {\n var result = await method\n .VerifyAsync(packageId, cancellationToken: cancellationToken)\n .ConfigureAwait(false);\n\n results.Add(result);\n\n if (result.IsVerified)\n {\n successfulResult = result;\n break; // Stop at first successful verification\n }\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n results.Add(\n VerificationResult.Failure($\"Error in {method.Name}: {ex.Message}\")\n );\n }\n }\n\n // If we found a successful result, return it immediately\n if (successfulResult != null)\n return successfulResult;\n \n // If this isn't the last attempt, wait before trying again\n if (attempt < 3)\n {\n // Exponential backoff: 1s, then 2s\n await Task.Delay(TimeSpan.FromSeconds(attempt), cancellationToken).ConfigureAwait(false);\n }\n }\n\n // If we get here, all attempts failed\n var errorMessages = results\n .Where(r => !r.IsVerified && !string.IsNullOrEmpty(r.Message))\n .Select(r => r.Message)\n .ToList();\n\n return new VerificationResult\n {\n IsVerified = false,\n Message =\n $\"Package '{packageId}' not found after multiple attempts. Details: {string.Join(\"; \", errorMessages)}\",\n MethodUsed = \"Composite\",\n AdditionalInfo = new { PackageId = packageId, VerificationResults = results },\n };\n }\n\n /// \n public async Task VerifyInstallationAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n if (string.IsNullOrWhiteSpace(version))\n throw new ArgumentException(\n \"Version cannot be null or whitespace.\",\n nameof(version)\n );\n\n var results = new List();\n VerificationResult successfulResult = null;\n\n foreach (var method in _verificationMethods)\n {\n try\n {\n var result = await method\n .VerifyAsync(packageId, version, cancellationToken)\n .ConfigureAwait(false);\n\n results.Add(result);\n\n if (result.IsVerified)\n {\n successfulResult = result;\n // Don't break here, as we want to try all methods to find an exact version match\n }\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n results.Add(\n VerificationResult.Failure($\"Error in {method.Name}: {ex.Message}\")\n );\n }\n }\n\n // If we found a successful result, return it\n if (successfulResult != null)\n return successfulResult;\n\n // Check if any method found the package but with a different version\n var versionMismatch = results.FirstOrDefault(r =>\n r.IsVerified\n && r.AdditionalInfo is IDictionary info\n && info.ContainsKey(\"Version\")\n && info[\"Version\"]?.ToString() != version\n );\n\n if (versionMismatch != null)\n {\n var installedVersion =\n (versionMismatch.AdditionalInfo as IDictionary)?[\n \"Version\"\n ]?.ToString() ?? \"unknown\";\n return VerificationResult.Failure(\n $\"Version mismatch for '{packageId}'. Installed: {installedVersion}, Expected: {version}\",\n versionMismatch.MethodUsed\n );\n }\n\n // Otherwise, return a composite result with all the failures\n var errorMessages = results\n .Where(r => !r.IsVerified && !string.IsNullOrEmpty(r.Message))\n .Select(r => r.Message)\n .ToList();\n\n return new VerificationResult\n {\n IsVerified = false,\n Message =\n $\"Package '{packageId}' version '{version}' not found. Details: {string.Join(\"; \", errorMessages)}\",\n MethodUsed = \"Composite\",\n AdditionalInfo = new\n {\n PackageId = packageId,\n Version = version,\n VerificationResults = results,\n },\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Utilities/WindowSizeManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Interop;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Services;\nusing Winhance.WPF.Features.Common.Utilities;\n\nnamespace Winhance.WPF.Features.Common.Utilities\n{\n /// \n /// Manages window size and position, including dynamic sizing based on screen resolution\n /// and handling multiple monitors and DPI scaling.\n /// \n public class WindowSizeManager\n {\n private readonly Window _window;\n private readonly ILogService _logService;\n\n // Default window dimensions\n private const double DEFAULT_WIDTH = 1600;\n private const double DEFAULT_HEIGHT = 900;\n private const double MIN_WIDTH = 1024;\n private const double MIN_HEIGHT = 700; // Reduced minimum height to fit better on smaller screens\n private const double SCREEN_PERCENTAGE = 0.9; // Use 90% of screen size for better fit\n\n public WindowSizeManager(Window window, UserPreferencesService userPreferencesService, ILogService logService)\n {\n _window = window ?? throw new ArgumentNullException(nameof(window));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n \n // No events registered - we don't save window position anymore\n }\n\n /// \n /// Initializes the window size and position\n /// \n public void Initialize()\n {\n try\n {\n // Set dynamic window size based on screen resolution (75% of screen)\n SetDynamicWindowSize();\n \n // Always center the window on screen\n // This ensures consistent behavior regardless of WindowStartupLocation\n CenterWindowOnScreen();\n \n LogDebug($\"Window initialized with size: {_window.Width}x{_window.Height}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error initializing window size manager: {ex.Message}\", ex);\n }\n }\n \n /// \n /// Centers the window on the current screen\n /// \n private void CenterWindowOnScreen()\n {\n try\n {\n // Get the current screen's working area\n var workArea = GetCurrentScreenWorkArea();\n \n // Get DPI scaling factor\n double dpiScaleX = 1.0;\n double dpiScaleY = 1.0;\n \n try\n {\n var presentationSource = PresentationSource.FromVisual(_window);\n if (presentationSource?.CompositionTarget != null)\n {\n dpiScaleX = presentationSource.CompositionTarget.TransformToDevice.M11;\n dpiScaleY = presentationSource.CompositionTarget.TransformToDevice.M22;\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting DPI scale: {ex.Message}\", ex);\n }\n \n // Convert screen coordinates to account for DPI\n double screenWidth = workArea.Width / dpiScaleX;\n double screenHeight = workArea.Height / dpiScaleY;\n double screenLeft = workArea.X / dpiScaleX;\n double screenTop = workArea.Y / dpiScaleY;\n \n // Calculate center position\n double left = screenLeft + (screenWidth - _window.Width) / 2;\n double top = screenTop + (screenHeight - _window.Height) / 2;\n \n // Set window position\n _window.Left = left;\n _window.Top = top;\n \n LogDebug($\"Window explicitly centered at: Left={left}, Top={top}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error centering window: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Sets the window size dynamically based on the screen resolution\n /// \n private void SetDynamicWindowSize()\n {\n try\n {\n LogDebug(\"Setting dynamic window size\");\n \n // Get the current screen's working area (excludes taskbar)\n var workArea = GetCurrentScreenWorkArea();\n \n // Get DPI scaling factor for the current screen\n double dpiScaleX = 1.0;\n double dpiScaleY = 1.0;\n \n try\n {\n var presentationSource = PresentationSource.FromVisual(_window);\n if (presentationSource?.CompositionTarget != null)\n {\n dpiScaleX = presentationSource.CompositionTarget.TransformToDevice.M11;\n dpiScaleY = presentationSource.CompositionTarget.TransformToDevice.M22;\n LogDebug($\"DPI scale factors: X={dpiScaleX}, Y={dpiScaleY}\");\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting DPI scale: {ex.Message}\", ex);\n }\n \n // Calculate available screen space\n double screenWidth = workArea.Width / dpiScaleX;\n double screenHeight = workArea.Height / dpiScaleY;\n \n // Calculate window size (75% of screen size with minimum/maximum constraints)\n double windowWidth = Math.Min(DEFAULT_WIDTH, screenWidth * SCREEN_PERCENTAGE);\n double windowHeight = Math.Min(DEFAULT_HEIGHT, screenHeight * SCREEN_PERCENTAGE);\n \n // Ensure minimum size for usability\n windowWidth = Math.Max(windowWidth, MIN_WIDTH);\n windowHeight = Math.Max(windowHeight, MIN_HEIGHT);\n \n // Only set the window size, let WPF handle the centering via WindowStartupLocation=\"CenterScreen\"\n _window.Width = windowWidth;\n _window.Height = windowHeight;\n \n LogDebug($\"Dynamic window size set to: Width={windowWidth}, Height={windowHeight}\");\n LogDebug($\"Screen dimensions: Width={screenWidth}, Height={screenHeight}\");\n }\n catch (Exception ex)\n {\n LogDebug($\"Error setting dynamic window size: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Gets the working area of the screen that contains the window\n /// \n private Rect GetCurrentScreenWorkArea()\n {\n try\n {\n // Get the window handle\n var windowHandle = new WindowInteropHelper(_window).Handle;\n if (windowHandle != IntPtr.Zero)\n {\n // Get the monitor info for the monitor containing the window\n var monitorInfo = new MONITORINFO();\n monitorInfo.cbSize = Marshal.SizeOf(typeof(MONITORINFO));\n \n if (GetMonitorInfo(MonitorFromWindow(windowHandle, MONITOR_DEFAULTTONEAREST), ref monitorInfo))\n {\n // Convert the working area to a WPF Rect\n return new Rect(\n monitorInfo.rcWork.left,\n monitorInfo.rcWork.top,\n monitorInfo.rcWork.right - monitorInfo.rcWork.left,\n monitorInfo.rcWork.bottom - monitorInfo.rcWork.top);\n }\n }\n }\n catch (Exception ex)\n {\n LogDebug($\"Error getting current screen: {ex.Message}\", ex);\n }\n \n // Fallback to primary screen working area\n return SystemParameters.WorkArea;\n }\n\n // Event handlers for window state, location, and size changes have been removed\n // as we no longer save window position/size to preferences\n\n /// \n /// Logs a debug message\n /// \n private void LogDebug(string message, Exception ex = null)\n {\n try\n {\n _logService?.Log(LogLevel.Debug, message, ex);\n \n // Also log to file logger for troubleshooting\n FileLogger.Log(\"WindowSizeManager\", message + (ex != null ? $\" - Exception: {ex.Message}\" : \"\"));\n }\n catch\n {\n // Ignore logging errors\n }\n }\n\n #region Win32 API\n\n [DllImport(\"user32.dll\")]\n private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);\n \n [DllImport(\"user32.dll\")]\n private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);\n \n private const uint MONITOR_DEFAULTTONEAREST = 2;\n \n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int left;\n public int top;\n public int right;\n public int bottom;\n }\n \n [StructLayout(LayoutKind.Sequential)]\n private struct MONITORINFO\n {\n public int cbSize;\n public RECT rcMonitor;\n public RECT rcWork;\n public uint dwFlags;\n }\n\n #endregion\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Theme/FontLoader.cs", "using System;\nusing System.IO;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Media;\n\nnamespace Winhance.WPF.Theme\n{\n public static class FontLoader\n {\n [DllImport(\"gdi32.dll\")]\n private static extern int AddFontResource(string lpFilename);\n\n [DllImport(\"gdi32.dll\")]\n private static extern int RemoveFontResource(string lpFilename);\n\n private static string? _tempFontPath;\n\n public static bool LoadFont(string resourcePath)\n {\n try\n {\n // Extract the font to a temporary file\n var fontUri = new Uri(resourcePath);\n var streamResourceInfo = Application.GetResourceStream(fontUri);\n\n if (streamResourceInfo == null)\n {\n return false;\n }\n\n // Create a temporary file for the font\n _tempFontPath = Path.Combine(\n Path.GetTempPath(),\n $\"MaterialSymbols_{Guid.NewGuid()}.ttf\"\n );\n\n using (var fileStream = File.Create(_tempFontPath))\n using (var resourceStream = streamResourceInfo.Stream)\n {\n resourceStream.CopyTo(fileStream);\n }\n\n // Load the font using the Win32 API\n int result = AddFontResource(_tempFontPath);\n\n // Force a redraw of all text elements\n foreach (Window window in Application.Current.Windows)\n {\n window.InvalidateVisual();\n }\n\n return result > 0;\n }\n catch (Exception)\n {\n return false;\n }\n }\n\n public static void UnloadFont()\n {\n if (!string.IsNullOrEmpty(_tempFontPath) && File.Exists(_tempFontPath))\n {\n RemoveFontResource(_tempFontPath);\n try\n {\n File.Delete(_tempFontPath);\n }\n catch\n {\n // Ignore errors when deleting the temporary file\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Views/UpdateNotificationDialog.xaml.cs", "using System;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Views\n{\n /// \n /// Update notification dialog that shows when a new version is available\n /// \n public partial class UpdateNotificationDialog : Window\n {\n // Default text content for the update dialog\n private static readonly string DefaultTitle = \"Update Available\";\n private static readonly string DefaultUpdateMessage = \"A new version of Winhance is available.\";\n \n public UpdateNotificationDialog(UpdateNotificationViewModel viewModel)\n {\n InitializeComponent();\n DataContext = viewModel;\n }\n \n private void PrimaryButton_Click(object sender, RoutedEventArgs e)\n {\n // Download and install\n if (DataContext is UpdateNotificationViewModel viewModel)\n {\n viewModel.DownloadAndInstallUpdateCommand.Execute(null);\n }\n }\n\n private void SecondaryButton_Click(object sender, RoutedEventArgs e)\n {\n // Remind later\n if (DataContext is UpdateNotificationViewModel viewModel)\n {\n viewModel.RemindLaterCommand.Execute(null);\n }\n DialogResult = false;\n Close();\n }\n \n private void CloseButton_Click(object sender, RoutedEventArgs e)\n {\n // Close without action\n DialogResult = false;\n Close();\n }\n \n /// \n /// Creates and shows an update notification dialog with the specified parameters.\n /// This method ensures the dialog is properly modal and blocks the main window.\n /// \n /// The view model containing update information\n /// The dialog title (optional - uses default if empty)\n /// The update message (optional - uses default if empty)\n /// The dialog instance with DialogResult set\n public static async Task ShowUpdateDialogAsync(\n UpdateNotificationViewModel viewModel,\n string title = \"\",\n string updateMessage = \"\")\n {\n try\n {\n var dialog = new UpdateNotificationDialog(viewModel)\n {\n Title = string.IsNullOrEmpty(title) ? DefaultTitle : title,\n WindowStartupLocation = WindowStartupLocation.CenterOwner,\n ShowInTaskbar = false,\n ResizeMode = ResizeMode.NoResize,\n WindowStyle = WindowStyle.None,\n AllowsTransparency = true\n };\n\n // Set the update message\n dialog.UpdateMessageText.Text = string.IsNullOrEmpty(updateMessage) ? DefaultUpdateMessage : updateMessage;\n \n // Set button content\n dialog.PrimaryButton.Content = \"Download and Install\";\n dialog.SecondaryButton.Content = \"Remind Later\";\n\n // Set the owner to the main window to ensure it appears on top\n if (Application.Current.MainWindow != null && Application.Current.MainWindow != dialog)\n {\n dialog.Owner = Application.Current.MainWindow;\n dialog.Topmost = true; // Ensure it stays on top\n }\n else\n {\n // Try to find the main window another way\n foreach (Window window in Application.Current.Windows)\n {\n if (window != dialog && window.IsVisible)\n {\n dialog.Owner = window;\n dialog.Topmost = true;\n break;\n }\n }\n }\n\n // Make the dialog visible and focused\n dialog.Visibility = Visibility.Visible;\n dialog.Activate();\n dialog.Focus();\n \n // Show the dialog and wait for it to complete\n dialog.ShowDialog();\n \n // Return the dialog\n return dialog;\n }\n catch (Exception ex)\n {\n // Show error message\n MessageBox.Show($\"Error showing update dialog: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n \n // Create a dummy dialog with error result\n var errorDialog = new UpdateNotificationDialog(viewModel);\n errorDialog.DialogResult = false;\n return errorDialog;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Services/ModelMapper.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\nnamespace Winhance.Core.Features.Common.Services\n{\n /// \n /// Interface for mapping between different model types.\n /// \n public interface IModelMapper\n {\n /// \n /// Maps a source object to a destination type.\n /// \n /// The source type.\n /// The destination type.\n /// The source object.\n /// The mapped destination object.\n TDestination Map(TSource source) where TDestination : new();\n\n /// \n /// Maps a collection of source objects to a collection of destination objects.\n /// \n /// The source type.\n /// The destination type.\n /// The collection of source objects.\n /// The collection of mapped destination objects.\n IEnumerable MapCollection(IEnumerable source) where TDestination : new();\n }\n\n /// \n /// Service for mapping between different model types.\n /// \n public class ModelMapper : IModelMapper\n {\n /// \n public TDestination Map(TSource source) where TDestination : new()\n {\n if (source == null)\n {\n throw new ArgumentNullException(nameof(source));\n }\n\n var destination = new TDestination();\n MapProperties(source, destination);\n return destination;\n }\n\n /// \n public IEnumerable MapCollection(IEnumerable source) where TDestination : new()\n {\n if (source == null)\n {\n throw new ArgumentNullException(nameof(source));\n }\n\n return source.Select(item => Map(item));\n }\n\n private static void MapProperties(TSource source, TDestination destination)\n {\n var sourceProperties = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);\n var destinationProperties = typeof(TDestination).GetProperties(BindingFlags.Public | BindingFlags.Instance)\n .ToDictionary(p => p.Name, p => p);\n\n foreach (var sourceProperty in sourceProperties)\n {\n if (destinationProperties.TryGetValue(sourceProperty.Name, out var destinationProperty))\n {\n if (destinationProperty.CanWrite && \n (destinationProperty.PropertyType == sourceProperty.PropertyType || \n IsAssignableOrConvertible(sourceProperty.PropertyType, destinationProperty.PropertyType)))\n {\n var value = sourceProperty.GetValue(source);\n \n if (value != null && sourceProperty.PropertyType != destinationProperty.PropertyType)\n {\n value = Convert.ChangeType(value, destinationProperty.PropertyType);\n }\n \n destinationProperty.SetValue(destination, value);\n }\n }\n }\n }\n\n private static bool IsAssignableOrConvertible(Type sourceType, Type destinationType)\n {\n return destinationType.IsAssignableFrom(sourceType) || \n (sourceType.IsPrimitive && destinationType.IsPrimitive) ||\n (sourceType == typeof(string) && destinationType.IsPrimitive) ||\n (destinationType == typeof(string) && sourceType.IsPrimitive);\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Customize/Interfaces/IWallpaperService.cs", "using System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.Customize.Interfaces\n{\n /// \n /// Interface for wallpaper operations.\n /// \n public interface IWallpaperService\n {\n /// \n /// Sets the desktop wallpaper.\n /// \n /// The path to the wallpaper image.\n /// A task representing the asynchronous operation.\n Task SetWallpaperAsync(string wallpaperPath);\n\n /// \n /// Sets the default wallpaper based on Windows version and theme.\n /// \n /// Whether the system is Windows 11.\n /// Whether dark mode is enabled.\n /// A task representing the asynchronous operation.\n Task SetDefaultWallpaperAsync(bool isWindows11, bool isDarkMode);\n\n /// \n /// Gets the default wallpaper path based on Windows version and theme.\n /// \n /// Whether the system is Windows 11.\n /// Whether dark mode is enabled.\n /// The path to the default wallpaper.\n string GetDefaultWallpaperPath(bool isWindows11, bool isDarkMode);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/TaskProgressControl.xaml.cs", "using System;\nusing System.Collections.ObjectModel;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Markup;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.WPF.Features.Common.Models;\n\n[assembly: XmlnsDefinition(\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\", \"Winhance.WPF.Features.Common.Controls\")]\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// Interaction logic for TaskProgressControl.xaml\n /// \n public partial class TaskProgressControl : UserControl\n {\n #region Dependency Properties\n\n /// \n /// Gets or sets the progress value (0-100).\n /// \n public double Progress\n {\n get { return (double)GetValue(ProgressProperty); }\n set { SetValue(ProgressProperty, value); }\n }\n\n /// \n /// Identifies the Progress dependency property.\n /// \n public static readonly DependencyProperty ProgressProperty =\n DependencyProperty.Register(nameof(Progress), typeof(double), typeof(TaskProgressControl), \n new PropertyMetadata(0.0, OnProgressChanged));\n\n /// \n /// Gets or sets the status text.\n /// \n public string StatusText\n {\n get { return (string)GetValue(StatusTextProperty); }\n set { SetValue(StatusTextProperty, value); }\n }\n\n /// \n /// Identifies the StatusText dependency property.\n /// \n public static readonly DependencyProperty StatusTextProperty =\n DependencyProperty.Register(nameof(StatusText), typeof(string), typeof(TaskProgressControl), \n new PropertyMetadata(string.Empty));\n\n /// \n /// Gets or sets whether the progress is indeterminate.\n /// \n public bool IsIndeterminate\n {\n get { return (bool)GetValue(IsIndeterminateProperty); }\n set { SetValue(IsIndeterminateProperty, value); }\n }\n\n /// \n /// Identifies the IsIndeterminate dependency property.\n /// \n public static readonly DependencyProperty IsIndeterminateProperty =\n DependencyProperty.Register(nameof(IsIndeterminate), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets whether the control is visible.\n /// \n public new bool IsVisible\n {\n get { return (bool)GetValue(IsVisibleProperty); }\n set { SetValue(IsVisibleProperty, value); }\n }\n\n /// \n /// Identifies the IsVisible dependency property.\n /// \n public new static readonly DependencyProperty IsVisibleProperty =\n DependencyProperty.Register(nameof(IsVisible), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets the progress text (e.g., \"50%\").\n /// \n public string ProgressText\n {\n get { return (string)GetValue(ProgressTextProperty); }\n private set { SetValue(ProgressTextProperty, value); }\n }\n\n /// \n /// Identifies the ProgressText dependency property.\n /// \n public static readonly DependencyProperty ProgressTextProperty =\n DependencyProperty.Register(nameof(ProgressText), typeof(string), typeof(TaskProgressControl), \n new PropertyMetadata(string.Empty));\n\n /// \n /// Gets or sets whether the details are expanded.\n /// \n public bool AreDetailsExpanded\n {\n get { return (bool)GetValue(AreDetailsExpandedProperty); }\n set { SetValue(AreDetailsExpandedProperty, value); }\n }\n\n /// \n /// Identifies the AreDetailsExpanded dependency property.\n /// \n public static readonly DependencyProperty AreDetailsExpandedProperty =\n DependencyProperty.Register(nameof(AreDetailsExpanded), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets whether there are log messages.\n /// \n public bool HasLogMessages\n {\n get { return (bool)GetValue(HasLogMessagesProperty); }\n private set { SetValue(HasLogMessagesProperty, value); }\n }\n\n /// \n /// Identifies the HasLogMessages dependency property.\n /// \n public static readonly DependencyProperty HasLogMessagesProperty =\n DependencyProperty.Register(nameof(HasLogMessages), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets the log messages.\n /// \n public ObservableCollection LogMessages\n {\n get { return (ObservableCollection)GetValue(LogMessagesProperty); }\n private set { SetValue(LogMessagesProperty, value); }\n }\n\n /// \n /// Identifies the LogMessages dependency property.\n /// \n public static readonly DependencyProperty LogMessagesProperty =\n DependencyProperty.Register(nameof(LogMessages), typeof(ObservableCollection), \n typeof(TaskProgressControl), new PropertyMetadata(null));\n\n /// \n /// Gets or sets whether the operation can be cancelled.\n /// \n public bool CanCancel\n {\n get { return (bool)GetValue(CanCancelProperty); }\n set { SetValue(CanCancelProperty, value); }\n }\n\n /// \n /// Identifies the CanCancel dependency property.\n /// \n public static readonly DependencyProperty CanCancelProperty =\n DependencyProperty.Register(nameof(CanCancel), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets whether a task is running.\n /// \n public bool IsTaskRunning\n {\n get { return (bool)GetValue(IsTaskRunningProperty); }\n set { SetValue(IsTaskRunningProperty, value); }\n }\n\n /// \n /// Identifies the IsTaskRunning dependency property.\n /// \n public static readonly DependencyProperty IsTaskRunningProperty =\n DependencyProperty.Register(nameof(IsTaskRunning), typeof(bool), typeof(TaskProgressControl), \n new PropertyMetadata(false));\n\n /// \n /// Gets or sets the command to execute when the cancel button is clicked.\n /// \n public ICommand CancelCommand\n {\n get { return (ICommand)GetValue(CancelCommandProperty); }\n set { SetValue(CancelCommandProperty, value); }\n }\n\n /// \n /// Identifies the CancelCommand dependency property.\n /// \n public static readonly DependencyProperty CancelCommandProperty =\n DependencyProperty.Register(nameof(CancelCommand), typeof(ICommand), typeof(TaskProgressControl), \n new PropertyMetadata(null));\n\n #endregion\n\n /// \n /// Initializes a new instance of the class.\n /// \n public TaskProgressControl()\n {\n LogMessages = new ObservableCollection();\n InitializeComponent();\n UpdateProgressText();\n }\n\n private static void OnProgressChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is TaskProgressControl control)\n {\n control.UpdateProgressText();\n }\n }\n\n private void UpdateProgressText()\n {\n if (IsIndeterminate)\n {\n ProgressText = string.Empty;\n }\n else\n {\n ProgressText = $\"{Progress:F0}%\";\n }\n }\n\n /// \n /// Adds a log message to the control.\n /// \n /// The message content.\n /// The log level.\n public void AddLogMessage(string message, LogLevel level)\n {\n if (string.IsNullOrEmpty(message)) return;\n\n Application.Current.Dispatcher.Invoke(() =>\n {\n LogMessages.Add(new LogMessageViewModel\n {\n Message = message,\n Level = level,\n Timestamp = DateTime.Now\n });\n\n HasLogMessages = LogMessages.Count > 0;\n\n // Auto-expand details on error or warning\n if (level == LogLevel.Error || level == LogLevel.Warning)\n {\n AreDetailsExpanded = true;\n }\n });\n }\n\n /// \n /// Clears all log messages.\n /// \n public void ClearLogMessages()\n {\n Application.Current.Dispatcher.Invoke(() =>\n {\n LogMessages.Clear();\n HasLogMessages = false;\n });\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/ExplorerCustomizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Enums;\n\nnamespace Winhance.Core.Features.Customize.Models;\n\npublic static class ExplorerCustomizations\n{\n public static CustomizationGroup GetExplorerCustomizations()\n {\n return new CustomizationGroup\n {\n Name = \"Explorer\",\n Category = CustomizationCategory.Explorer,\n Settings = new List\n {\n new CustomizationSetting\n {\n Id = \"explorer-3d-objects\",\n Name = \"3D Objects\",\n Description = \"Controls 3D Objects folder visibility in This PC\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\MyComputer\\\\NameSpace\",\n Name = \"{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}\",\n RecommendedValue = null,\n EnabledValue = null, // When toggle is ON, 3D Objects folder is shown (key exists)\n DisabledValue = null, // When toggle is OFF, 3D Objects folder is hidden (key removed)\n ValueType = RegistryValueKind.None,\n DefaultValue = null,\n Description = \"Controls 3D Objects folder visibility in This PC\",\n ActionType = RegistryActionType.Remove,\n },\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\MyComputer\\\\NameSpace\\\\WOW64\",\n Name = \"{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}\",\n RecommendedValue = null,\n EnabledValue = null, // When toggle is ON, 3D Objects folder is shown (key exists)\n DisabledValue = null, // When toggle is OFF, 3D Objects folder is hidden (key removed)\n ValueType = RegistryValueKind.None,\n DefaultValue = null,\n Description =\n \"Controls 3D Objects folder visibility in This PC (WOW64)\",\n ActionType = RegistryActionType.Remove,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new CustomizationSetting\n {\n Id = \"explorer-home-folder\",\n Name = \"Home Folder in Navigation Pane\",\n Description = \"Controls Home Folder visibility in Navigation Pane\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Desktop\\\\NameSpace\",\n Name = \"{f874310e-b6b7-47dc-bc84-b9e6b38f5903}\",\n RecommendedValue = null,\n EnabledValue = null, // When toggle is ON, Home Folder is shown (key exists)\n DisabledValue = null, // When toggle is OFF, Home Folder is hidden (key removed)\n ValueType = RegistryValueKind.None,\n DefaultValue = null,\n Description = \"Controls Home Folder visibility in Navigation Pane\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n ActionType = RegistryActionType.Remove,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-launch-to\",\n Name = \"Launch to This PC\",\n Description = \"Controls where File Explorer opens by default\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"LaunchTo\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, File Explorer opens to 'This PC'\n DisabledValue = 2, // When toggle is OFF, File Explorer opens to 'Quick access'\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls where File Explorer opens by default\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-show-file-ext\",\n Name = \"Show File Extensions\",\n Description = \"Controls visibility of file name extensions\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"HideFileExt\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, file extensions are shown\n DisabledValue = 1, // When toggle is OFF, file extensions are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls visibility of file name extensions\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-show-hidden-files\",\n Name = \"Show Hidden Files, Folders & Drives\",\n Description = \"Controls visibility of hidden files and folders\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"Hidden\",\n RecommendedValue = 1,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls visibility of hidden files, folders and drives\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-hide-protected-files\",\n Name = \"Hide Protected Operating System Files\",\n Description = \"Controls visibility of protected operating system files\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowSuperHidden\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls visibility of protected operating system files\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-folder-tips\",\n Name = \"Folder Tips\",\n Description = \"Controls file size information in folder tips\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"FolderContentsInfoTip\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, folder tips are enabled\n DisabledValue = 0, // When toggle is OFF, folder tips are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls file size information in folder tips\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-popup-descriptions\",\n Name = \"Pop-up Descriptions\",\n Description = \"Controls pop-up descriptions for folder and desktop items\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowInfoTip\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, pop-up descriptions are shown\n DisabledValue = 0, // When toggle is OFF, pop-up descriptions are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description =\n \"Controls pop-up descriptions for folder and desktop items\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-preview-handlers\",\n Name = \"Preview Handlers\",\n Description = \"Controls preview handlers in preview pane\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowPreviewHandlers\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, preview handlers are enabled\n DisabledValue = 0, // When toggle is OFF, preview handlers are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls preview handlers in preview pane\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-status-bar\",\n Name = \"Status Bar\",\n Description = \"Controls status bar visibility in File Explorer\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowStatusBar\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, status bar is shown\n DisabledValue = 0, // When toggle is OFF, status bar is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls status bar visibility in File Explorer\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-show-thumbnails\",\n Name = \"Show Thumbnails\",\n Description = \"Controls whether to show thumbnails or icons\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"IconsOnly\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, thumbnails are shown\n DisabledValue = 1, // When toggle is OFF, icons are shown\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls whether to show thumbnails or icons\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-translucent-selection\",\n Name = \"Translucent Selection\",\n Description = \"Controls translucent selection rectangle\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ListviewAlphaSelect\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, translucent selection is enabled\n DisabledValue = 0, // When toggle is OFF, translucent selection is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls translucent selection rectangle\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-drop-shadows\",\n Name = \"Drop Shadows\",\n Description = \"Controls drop shadows for icon labels\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ListviewShadow\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, drop shadows are enabled\n DisabledValue = 0, // When toggle is OFF, drop shadows are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls drop shadows for icon labels\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-full-path\",\n Name = \"Full Path in Title Bar\",\n Description = \"Controls full path display in the title bar\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\CabinetState\",\n Name = \"FullPath\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, full path is shown\n DisabledValue = 0, // When toggle is OFF, full path is hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls full path display in the title bar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-font-smoothing\",\n Name = \"Font Smoothing\",\n Description = \"Controls smooth edges of screen fonts\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"FontSmoothing\",\n RecommendedValue = \"2\",\n EnabledValue = \"2\", // When toggle is ON, font smoothing is enabled\n DisabledValue = \"0\", // When toggle is OFF, font smoothing is disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = \"0\", // Default value when registry key exists but no value is set\n Description = \"Controls smooth edges of screen fonts\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-dpi-scaling\",\n Name = \"DPI Scaling (100%)\",\n Description = \"Controls DPI scaling setting\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"LogPixels\",\n RecommendedValue = 96,\n EnabledValue = 96, // When toggle is ON, DPI scaling is set to 100%\n DisabledValue = 120, // When toggle is OFF, DPI scaling is set to 125%\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 120, // Default value when registry key exists but no value is set\n Description = \"Controls DPI scaling setting\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-per-process-dpi\",\n Name = \"Per-Process DPI\",\n Description = \"Controls per-process system DPI\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"EnablePerProcessSystemDPI\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, per-process DPI is enabled\n DisabledValue = 0, // When toggle is OFF, per-process DPI is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls per-process system DPI\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-lock-screen\",\n Name = \"Lock Screen\",\n Description = \"Controls lock screen visibility\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\Personalization\",\n Name = \"NoLockScreen\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls lock screen visibility\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-gallery\",\n Name = \"Gallery in Navigation Pane\",\n Description = \"Controls gallery visibility in navigation pane\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Desktop\\\\NameSpace\",\n Name = \"{e88865ea-0e1c-4e20-9aa6-edcd0212c87c}\",\n RecommendedValue = null,\n EnabledValue = null, // When toggle is ON, gallery is shown (key exists)\n DisabledValue = null, // When toggle is OFF, gallery is hidden (key removed)\n ValueType = RegistryValueKind.None,\n DefaultValue = null,\n Description = \"Controls gallery visibility in navigation pane\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n ActionType = RegistryActionType.Remove,\n },\n },\n },\n new CustomizationSetting\n {\n Id = \"explorer-context-menu\",\n Name = \"Classic Context Menu\",\n Description = \"Controls context menu style (classic or modern)\",\n Category = CustomizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Classes\\\\CLSID\\\\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\\\\InprocServer32\",\n Name = \"\",\n RecommendedValue = \"\",\n EnabledValue = null, // When toggle is ON, classic context menu is used (value is deleted)\n DisabledValue = \"\", // When toggle is OFF, modern context menu is used (empty value is set)\n ValueType = RegistryValueKind.String,\n DefaultValue = \"\", // Default value when registry key exists but no value is set\n Description = \"Controls context menu style (classic or modern)\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Views/ExternalAppsView.xaml.cs", "using System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Views\n{\n public partial class ExternalAppsView : UserControl\n {\n public ExternalAppsView()\n {\n InitializeComponent();\n Loaded += ExternalAppsView_Loaded;\n }\n\n private void ExternalAppsView_Loaded(object sender, RoutedEventArgs e)\n {\n // Find all category header borders and attach click handlers\n foreach (var border in FindVisualChildren(this))\n {\n if (border?.Tag != null && border.Tag is string)\n {\n // Add click handler to toggle category expansion\n border.MouseLeftButtonDown += CategoryHeader_MouseLeftButtonDown;\n }\n }\n }\n\n private void CategoryHeader_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n try\n {\n if (sender is Border border && border.DataContext is ExternalAppsCategoryViewModel category)\n {\n // Toggle the IsExpanded property\n category.IsExpanded = !category.IsExpanded;\n e.Handled = true;\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Error handling category click: {ex.Message}\", \"Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n }\n }\n\n // Helper method to find visual children of a specific type\n private System.Collections.Generic.IEnumerable FindVisualChildren(DependencyObject parent) where T : DependencyObject\n {\n int childrenCount = VisualTreeHelper.GetChildrenCount(parent);\n for (int i = 0; i < childrenCount; i++)\n {\n DependencyObject child = VisualTreeHelper.GetChild(parent, i);\n \n if (child is T childOfType)\n yield return childOfType;\n \n foreach (T childOfChild in FindVisualChildren(child))\n yield return childOfChild;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Resources/Theme/IThemeManager.cs", "using System;\n\nnamespace Winhance.WPF.Features.Common.Resources.Theme\n{\n public interface IThemeManager : IDisposable\n {\n bool IsDarkTheme { get; set; }\n void ToggleTheme();\n void ApplyTheme();\n void LoadThemePreference();\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppServiceAdapter.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Adapter class that implements IAppService by delegating to AppDiscoveryService\n /// and other services for the additional functionality required by IAppService.\n /// \n public class AppServiceAdapter : IAppService\n {\n private readonly AppDiscoveryService _appDiscoveryService;\n private readonly ILogService _logService;\n private Dictionary _installStatusCache = new Dictionary();\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The app discovery service to delegate to.\n /// The logging service.\n public AppServiceAdapter(AppDiscoveryService appDiscoveryService, ILogService logService)\n {\n _appDiscoveryService = appDiscoveryService ?? throw new ArgumentNullException(nameof(appDiscoveryService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public async Task> GetInstallableAppsAsync()\n {\n return await _appDiscoveryService.GetInstallableAppsAsync();\n }\n\n /// \n public async Task> GetStandardAppsAsync()\n {\n return await _appDiscoveryService.GetStandardAppsAsync();\n }\n\n /// \n public async Task> GetCapabilitiesAsync()\n {\n return await _appDiscoveryService.GetCapabilitiesAsync();\n }\n\n /// \n public async Task> GetOptionalFeaturesAsync()\n {\n return await _appDiscoveryService.GetOptionalFeaturesAsync();\n }\n\n /// \n public async Task IsAppInstalledAsync(string packageName, CancellationToken cancellationToken = default)\n {\n // Implement using the concrete AppDiscoveryService\n return await _appDiscoveryService.IsAppInstalledAsync(packageName, cancellationToken);\n }\n\n /// \n public async Task IsEdgeInstalledAsync()\n {\n return await _appDiscoveryService.IsEdgeInstalledAsync();\n }\n\n /// \n public async Task IsOneDriveInstalledAsync()\n {\n return await _appDiscoveryService.IsOneDriveInstalledAsync();\n }\n\n /// \n public async Task GetItemInstallStatusAsync(IInstallableItem item)\n {\n if (item == null)\n return false;\n\n return await IsAppInstalledAsync(item.PackageId);\n }\n\n /// \n public async Task> GetBatchInstallStatusAsync(IEnumerable packageIds)\n {\n var result = new Dictionary();\n \n // Check for special apps first\n foreach (var packageId in packageIds)\n {\n // Special handling for Edge and OneDrive\n if (packageId.Equals(\"Microsoft Edge\", StringComparison.OrdinalIgnoreCase) ||\n packageId.Equals(\"msedge\", StringComparison.OrdinalIgnoreCase) ||\n packageId.Equals(\"Edge\", StringComparison.OrdinalIgnoreCase))\n {\n result[packageId] = await _appDiscoveryService.IsEdgeInstalledAsync();\n }\n else if (packageId.Equals(\"OneDrive\", StringComparison.OrdinalIgnoreCase))\n {\n result[packageId] = await _appDiscoveryService.IsOneDriveInstalledAsync();\n }\n }\n \n // Get the remaining package IDs that aren't special apps\n var remainingPackageIds = packageIds.Where(id =>\n !result.ContainsKey(id) &&\n !id.Equals(\"Microsoft Edge\", StringComparison.OrdinalIgnoreCase) &&\n !id.Equals(\"msedge\", StringComparison.OrdinalIgnoreCase) &&\n !id.Equals(\"Edge\", StringComparison.OrdinalIgnoreCase) &&\n !id.Equals(\"OneDrive\", StringComparison.OrdinalIgnoreCase));\n \n // Use the concrete AppDiscoveryService's batch method for the remaining packages\n var batchResults = await _appDiscoveryService.GetInstallationStatusBatchAsync(remainingPackageIds);\n \n // Merge the results\n foreach (var pair in batchResults)\n {\n result[pair.Key] = pair.Value;\n }\n \n return result;\n }\n\n /// \n public async Task GetInstallStatusAsync(string appId)\n {\n if (string.IsNullOrEmpty(appId))\n return InstallStatus.Failed;\n\n // Check cache first\n if (_installStatusCache.TryGetValue(appId, out var cachedStatus))\n {\n return cachedStatus;\n }\n\n // Check if the app is installed\n bool isInstalled = await IsAppInstalledAsync(appId);\n var status = isInstalled ? InstallStatus.Success : InstallStatus.NotFound;\n\n // Cache the result\n _installStatusCache[appId] = status;\n\n return status;\n }\n\n /// \n public async Task RefreshInstallationStatusAsync(IEnumerable items)\n {\n // Clear the cache for the specified items\n foreach (var item in items)\n {\n if (_installStatusCache.ContainsKey(item.PackageId))\n {\n _installStatusCache.Remove(item.PackageId);\n }\n }\n\n // Refresh the status for each item\n foreach (var item in items)\n {\n await GetInstallStatusAsync(item.PackageId);\n }\n }\n\n /// \n public async Task SetInstallStatusAsync(string appId, InstallStatus status)\n {\n if (string.IsNullOrEmpty(appId))\n return false;\n\n // Update the cache\n _installStatusCache[appId] = status;\n return true;\n }\n\n /// \n public void ClearStatusCache()\n {\n _installStatusCache.Clear();\n\n // Clear the app discovery service's cache\n _appDiscoveryService.ClearInstallationStatusCache();\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Messaging/Messages.cs", "using System;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Messaging\n{\n /// \n /// Base class for all messages that will be sent through the messenger\n /// \n public abstract class MessageBase\n {\n public DateTime Timestamp { get; } = DateTime.Now;\n }\n\n /// \n /// Message sent when a log entry is created\n /// \n public class LogMessage : MessageBase\n {\n public string Message { get; set; }\n public LogLevel Level { get; set; }\n public Exception Exception { get; set; }\n }\n\n /// \n /// Message sent when progress changes\n /// \n public class ProgressMessage : MessageBase\n {\n public double Progress { get; set; }\n public string StatusText { get; set; }\n public bool IsIndeterminate { get; set; }\n public bool IsTaskRunning { get; set; }\n }\n\n /// \n /// Message sent when detailed task progress changes\n /// \n public class TaskProgressMessage : MessageBase\n {\n public string TaskName { get; set; }\n public double Progress { get; set; }\n public string StatusText { get; set; }\n public bool IsIndeterminate { get; set; }\n public bool IsTaskRunning { get; set; }\n public bool CanCancel { get; set; }\n }\n\n /// \n /// Message sent when window state changes\n /// \n public class WindowStateMessage : MessageBase\n {\n public enum WindowStateAction\n {\n Minimize,\n Maximize,\n Restore,\n Close\n }\n\n public WindowStateAction Action { get; set; }\n }\n\n /// \n /// Message sent to update the UI theme\n /// \n public class ThemeChangedMessage : MessageBase\n {\n public bool IsDarkTheme { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/PowerShellScriptFactory.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Factory for creating PowerShell script objects.\n /// \n public class PowerShellScriptFactory : IScriptFactory\n {\n private readonly IScriptBuilderService _scriptBuilder;\n private readonly ILogService _logService;\n private readonly IAppDiscoveryService _appDiscoveryService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The script builder service.\n /// The logging service.\n /// The app discovery service.\n public PowerShellScriptFactory(\n IScriptBuilderService scriptBuilder,\n ILogService logService,\n IAppDiscoveryService appDiscoveryService)\n {\n _scriptBuilder = scriptBuilder ?? throw new ArgumentNullException(nameof(scriptBuilder));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _appDiscoveryService = appDiscoveryService ?? throw new ArgumentNullException(nameof(appDiscoveryService));\n }\n\n /// \n public RemovalScript CreateBatchRemovalScript(\n List appNames,\n Dictionary> appsWithRegistry,\n Dictionary appSubPackages = null)\n {\n try\n {\n _logService.LogInformation($\"Creating batch removal script for {appNames.Count} apps\");\n\n // Categorize apps into packages, capabilities, and features\n var (packages, capabilities, features) = CategorizeApps(appNames);\n\n // Build the script content\n string scriptContent = _scriptBuilder.BuildCompleteRemovalScript(\n packages,\n capabilities,\n features,\n appsWithRegistry,\n appSubPackages);\n\n // Return the RemovalScript object\n return new RemovalScript\n {\n Name = \"BloatRemoval\",\n Content = scriptContent,\n TargetScheduledTaskName = \"Winhance\\\\BloatRemoval\",\n RunOnStartup = true\n };\n }\n catch (Exception ex)\n {\n _logService.LogError(\"Error creating batch removal script\", ex);\n throw;\n }\n }\n\n /// \n public RemovalScript CreateSingleAppRemovalScript(AppInfo app)\n {\n try\n {\n _logService.LogInformation($\"Creating single app removal script for {app.PackageName}\");\n\n // Build the script content\n string scriptContent = _scriptBuilder.BuildSingleAppRemovalScript(app);\n\n // Return the RemovalScript object\n return new RemovalScript\n {\n Name = $\"Remove_{app.PackageName.Replace(\".\", \"_\")}\",\n Content = scriptContent,\n TargetScheduledTaskName = $\"Winhance\\\\Remove_{app.PackageName.Replace(\".\", \"_\")}\",\n RunOnStartup = false\n };\n }\n catch (Exception ex)\n {\n _logService.LogError($\"Error creating single app removal script for {app.PackageName}\", ex);\n throw;\n }\n }\n\n /// \n /// Categorizes apps into packages, capabilities, and features.\n /// \n /// The app names to categorize.\n /// A tuple containing lists of packages, capabilities, and features.\n private (List, List, List) CategorizeApps(List appNames)\n {\n var packages = new List();\n var capabilities = new List();\n var features = new List();\n\n // Get all standard apps to check their types\n var allApps = _appDiscoveryService.GetStandardAppsAsync().GetAwaiter().GetResult();\n var appInfoDict = allApps.ToDictionary(a => a.PackageName, a => a);\n\n foreach (var appName in appNames)\n {\n if (appInfoDict.TryGetValue(appName, out var appInfo))\n {\n switch (appInfo.Type)\n {\n case AppType.StandardApp:\n packages.Add(appName);\n break;\n case AppType.Capability:\n capabilities.Add(appName);\n break;\n case AppType.OptionalFeature:\n features.Add(appName);\n break;\n default:\n // Default to package if type is unknown\n packages.Add(appName);\n break;\n }\n }\n else\n {\n // If app is not found in the dictionary, assume it's a package\n packages.Add(appName);\n }\n }\n\n return (packages, capabilities, features);\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Extensions/RegistrySettingExtensions.cs", "using Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Extensions\n{\n /// \n /// Extension methods for RegistrySetting.\n /// \n public static class RegistrySettingExtensions\n {\n /// \n /// Determines if the registry setting is for HttpAcceptLanguageOptOut.\n /// \n /// The registry setting to check.\n /// True if the setting is for HttpAcceptLanguageOptOut; otherwise, false.\n public static bool IsHttpAcceptLanguageOptOut(this RegistrySetting setting)\n {\n if (setting == null)\n return false;\n\n return setting.SubKey == \"Control Panel\\\\International\\\\User Profile\" &&\n setting.Name == \"HttpAcceptLanguageOptOut\";\n }\n\n /// \n /// Determines if the registry setting requires special handling.\n /// \n /// The registry setting to check.\n /// True if the setting requires special handling; otherwise, false.\n public static bool RequiresSpecialHandling(this RegistrySetting setting)\n {\n if (setting == null)\n return false;\n\n // Currently, only HttpAcceptLanguageOptOut requires special handling\n return IsHttpAcceptLanguageOptOut(setting);\n }\n\n /// \n /// Applies special handling for the registry setting.\n /// \n /// The registry setting to apply special handling for.\n /// The registry service to use.\n /// Whether the setting is being enabled or disabled.\n /// True if the special handling was applied successfully; otherwise, false.\n public static bool ApplySpecialHandling(this RegistrySetting setting, IRegistryService registryService, bool isEnabled)\n {\n if (setting == null || registryService == null)\n return false;\n\n if (IsHttpAcceptLanguageOptOut(setting) && isEnabled && setting.EnabledValue != null &&\n ((setting.EnabledValue is int intValue && intValue == 0) ||\n (setting.EnabledValue is string strValue && strValue == \"0\")))\n {\n // When enabling language list access, Windows deletes the key entirely\n string hiveString = GetRegistryHiveString(setting.Hive);\n return registryService.DeleteValue(\n $\"{hiveString}\\\\{setting.SubKey}\",\n setting.Name);\n }\n\n // No special handling needed or applicable\n return false;\n }\n\n /// \n /// Converts a RegistryHive enum to its string representation (HKCU, HKLM, etc.)\n /// \n /// The registry hive.\n /// The string representation of the registry hive.\n private static string GetRegistryHiveString(RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => throw new System.ArgumentException($\"Unsupported registry hive: {hive}\")\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/BaseInstallationService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Base class for installation services that provides common functionality.\n /// \n /// The type of item to install, which must implement IInstallableItem.\n public abstract class BaseInstallationService : IInstallationService where T : IInstallableItem\n {\n protected readonly ILogService _logService;\n protected readonly IPowerShellExecutionService _powerShellService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The PowerShell execution service.\n protected BaseInstallationService(\n ILogService logService,\n IPowerShellExecutionService powerShellService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _powerShellService = powerShellService ?? throw new ArgumentNullException(nameof(powerShellService));\n }\n\n /// \n public Task> InstallAsync(\n T item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n return InstallItemAsync(item, progress, cancellationToken);\n }\n\n /// \n public Task> CanInstallAsync(T item)\n {\n return CanInstallItemAsync(item);\n }\n\n /// \n /// Internal method to install an item.\n /// \n /// The item to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n protected async Task> InstallItemAsync(\n T item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n if (item == null)\n {\n throw new ArgumentNullException(nameof(item));\n }\n\n try\n {\n // Report initial progress\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Starting installation of {item.DisplayName}...\",\n DetailedMessage = $\"Preparing to install {item.DisplayName}\",\n }\n );\n\n _logService.LogInformation($\"Attempting to install {item.DisplayName} ({item.PackageId})\");\n\n // Perform the actual installation\n var result = await PerformInstallationAsync(item, progress, cancellationToken);\n\n if (result.Success)\n {\n // Report completion\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 100,\n StatusText = $\"{item.DisplayName} installed successfully!\",\n DetailedMessage = $\"Successfully installed {item.DisplayName}\",\n }\n );\n\n if (item.RequiresRestart)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n StatusText = \"A system restart is required to complete the installation\",\n DetailedMessage = \"Please restart your computer to complete the installation\",\n LogLevel = LogLevel.Warning,\n }\n );\n _logService.LogWarning($\"A system restart is required for {item.DisplayName}\");\n }\n\n _logService.LogSuccess($\"Successfully installed {item.DisplayName}\");\n }\n\n return result;\n }\n catch (OperationCanceledException)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Installation of {item.DisplayName} was cancelled\",\n DetailedMessage = \"The installation was cancelled by the user\",\n LogLevel = LogLevel.Warning,\n }\n );\n \n _logService.LogWarning($\"Operation cancelled when installing {item.DisplayName}\");\n return OperationResult.Failed(\"The installation was cancelled by the user\");\n }\n catch (Exception ex)\n {\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Error installing {item.DisplayName}: {ex.Message}\",\n DetailedMessage = $\"Exception during installation: {ex.Message}\",\n LogLevel = LogLevel.Error,\n }\n );\n _logService.LogError($\"Error installing {item.DisplayName}\", ex);\n return OperationResult.Failed($\"Error installing {item.DisplayName}: {ex.Message}\", ex);\n }\n }\n\n /// \n /// Checks if an item can be installed.\n /// \n /// The item to check.\n /// An operation result indicating if the item can be installed, with error details if not.\n protected Task> CanInstallItemAsync(T item)\n {\n if (item == null)\n {\n return Task.FromResult(OperationResult.Failed(\"Item information cannot be null\"));\n }\n\n // Basic implementation: Assume all items can be installed for now.\n // Derived classes can override this method to provide specific checks.\n return Task.FromResult(OperationResult.Succeeded(true));\n }\n\n /// \n /// Performs the actual installation of the item.\n /// \n /// The item to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n protected abstract Task> PerformInstallationAsync(\n T item,\n IProgress? progress,\n CancellationToken cancellationToken);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/LoadingWindowViewModel.cs", "using System;\nusing System.ComponentModel;\nusing System.Runtime.CompilerServices;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n public class LoadingWindowViewModel : INotifyPropertyChanged\n {\n private readonly ITaskProgressService _progressService;\n\n // INotifyPropertyChanged implementation\n public event PropertyChangedEventHandler? PropertyChanged;\n\n protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n\n protected bool SetProperty(ref T field, T value, [CallerMemberName] string? propertyName = null)\n {\n if (Equals(field, value)) return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n\n // Progress properties\n private double _progress;\n public double Progress\n {\n get => _progress;\n set => SetProperty(ref _progress, value);\n }\n\n private string _progressText = string.Empty;\n public string ProgressText\n {\n get => _progressText;\n set => SetProperty(ref _progressText, value);\n }\n\n private bool _isIndeterminate = true;\n public bool IsIndeterminate\n {\n get => _isIndeterminate;\n set => SetProperty(ref _isIndeterminate, value);\n }\n\n private bool _showProgressText;\n public bool ShowProgressText\n {\n get => _showProgressText;\n set => SetProperty(ref _showProgressText, value);\n }\n\n // Additional properties for more detailed loading information\n private string _statusMessage = \"Initializing...\";\n public string StatusMessage\n {\n get => _statusMessage;\n set => SetProperty(ref _statusMessage, value);\n }\n\n private string _detailMessage = \"Please wait while the application loads...\";\n public string DetailMessage\n {\n get => _detailMessage;\n set => SetProperty(ref _detailMessage, value);\n }\n\n public LoadingWindowViewModel(ITaskProgressService progressService)\n {\n _progressService = progressService ?? throw new ArgumentNullException(nameof(progressService));\n \n // Subscribe to progress events\n _progressService.ProgressUpdated += ProgressService_ProgressUpdated;\n }\n\n private void ProgressService_ProgressUpdated(object? sender, TaskProgressDetail detail)\n {\n // Update UI properties based on progress events\n IsIndeterminate = detail.IsIndeterminate;\n Progress = detail.Progress ?? 0;\n \n // Update progress text with percentage and status\n ProgressText = detail.IsIndeterminate ? string.Empty : $\"{detail.Progress:F0}% - {detail.StatusText}\";\n ShowProgressText = !detail.IsIndeterminate && _progressService.IsTaskRunning;\n \n // Update status message with the current operation\n if (!string.IsNullOrEmpty(detail.StatusText))\n {\n StatusMessage = detail.StatusText;\n \n // Update detail message based on the current operation\n if (detail.StatusText.Contains(\"Loading installable apps\"))\n {\n DetailMessage = \"Discovering available applications...\";\n }\n else if (detail.StatusText.Contains(\"Loading removable apps\"))\n {\n DetailMessage = \"Identifying Windows applications...\";\n }\n else if (detail.StatusText.Contains(\"Checking installation status\"))\n {\n DetailMessage = \"Verifying which applications are installed...\";\n }\n else if (detail.StatusText.Contains(\"Organizing apps\"))\n {\n DetailMessage = \"Sorting applications for display...\";\n }\n else\n {\n DetailMessage = \"Please wait while the application loads...\";\n }\n }\n }\n\n public void Cleanup()\n {\n // Unsubscribe from events to prevent memory leaks\n _progressService.ProgressUpdated -= ProgressService_ProgressUpdated;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/ResponsiveScrollViewer.cs", "using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// A custom ScrollViewer that handles mouse wheel events regardless of cursor position\n /// and provides enhanced scrolling speed\n /// \n public class ResponsiveScrollViewer : ScrollViewer\n {\n #region Dependency Properties\n\n /// \n /// Dependency property for ScrollSpeedMultiplier\n /// \n public static readonly DependencyProperty ScrollSpeedMultiplierProperty =\n DependencyProperty.RegisterAttached(\n \"ScrollSpeedMultiplier\",\n typeof(double),\n typeof(ResponsiveScrollViewer),\n new PropertyMetadata(10.0));\n\n /// \n /// Gets the scroll speed multiplier for a ScrollViewer\n /// \n public static double GetScrollSpeedMultiplier(DependencyObject obj)\n {\n return (double)obj.GetValue(ScrollSpeedMultiplierProperty);\n }\n\n /// \n /// Sets the scroll speed multiplier for a ScrollViewer\n /// \n public static void SetScrollSpeedMultiplier(DependencyObject obj, double value)\n {\n obj.SetValue(ScrollSpeedMultiplierProperty, value);\n }\n\n #endregion\n\n /// \n /// Static constructor to register event handlers for all ScrollViewers\n /// \n static ResponsiveScrollViewer()\n {\n // Register class handler for the PreviewMouseWheel event\n EventManager.RegisterClassHandler(\n typeof(ScrollViewer),\n UIElement.PreviewMouseWheelEvent,\n new MouseWheelEventHandler(OnPreviewMouseWheel),\n true);\n }\n\n /// \n /// Constructor\n /// \n public ResponsiveScrollViewer()\n {\n // No need to register for the event here anymore as we're using a class handler\n }\n\n /// \n /// Handles the PreviewMouseWheel event for all ScrollViewers\n /// \n private static void OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)\n {\n if (sender is ScrollViewer scrollViewer)\n {\n // Get the current vertical offset\n double currentOffset = scrollViewer.VerticalOffset;\n\n // Get the scroll speed multiplier (use default value if not set)\n double speedMultiplier = GetScrollSpeedMultiplier(scrollViewer);\n\n // Calculate the scroll amount based on the mouse wheel delta and speed multiplier\n double scrollAmount = (SystemParameters.WheelScrollLines * speedMultiplier);\n\n if (e.Delta < 0)\n {\n // Scroll down when the mouse wheel is rotated down\n scrollViewer.ScrollToVerticalOffset(currentOffset + scrollAmount);\n }\n else\n {\n // Scroll up when the mouse wheel is rotated up\n scrollViewer.ScrollToVerticalOffset(currentOffset - scrollAmount);\n }\n\n // Mark the event as handled to prevent it from bubbling up\n e.Handled = true;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Helpers/ValidationHelper.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Helpers\n{\n /// \n /// Helper class for common validation operations.\n /// \n public static class ValidationHelper\n {\n /// \n /// Validates that the specified object is not null.\n /// \n /// The object to validate.\n /// The name of the parameter being validated.\n /// Thrown if the value is null.\n public static void NotNull(object value, string paramName)\n {\n if (value == null)\n {\n throw new ArgumentNullException(paramName);\n }\n }\n\n /// \n /// Validates that the specified string is not null or empty.\n /// \n /// The string to validate.\n /// The name of the parameter being validated.\n /// Thrown if the value is null.\n /// Thrown if the value is empty.\n public static void NotNullOrEmpty(string value, string paramName)\n {\n if (value == null)\n {\n throw new ArgumentNullException(paramName);\n }\n\n if (string.IsNullOrEmpty(value))\n {\n throw new ArgumentException(\"Value cannot be empty.\", paramName);\n }\n }\n\n /// \n /// Validates that the specified string is not null, empty, or consists only of white-space characters.\n /// \n /// The string to validate.\n /// The name of the parameter being validated.\n /// Thrown if the value is null.\n /// Thrown if the value is empty or consists only of white-space characters.\n public static void NotNullOrWhiteSpace(string value, string paramName)\n {\n if (value == null)\n {\n throw new ArgumentNullException(paramName);\n }\n\n if (string.IsNullOrWhiteSpace(value))\n {\n throw new ArgumentException(\"Value cannot be empty or consist only of white-space characters.\", paramName);\n }\n }\n\n /// \n /// Validates that the specified value is greater than or equal to the minimum value.\n /// \n /// The value to validate.\n /// The minimum allowed value.\n /// The name of the parameter being validated.\n /// Thrown if the value is less than the minimum value.\n public static void GreaterThanOrEqualTo(int value, int minValue, string paramName)\n {\n if (value < minValue)\n {\n throw new ArgumentOutOfRangeException(paramName, value, $\"Value must be greater than or equal to {minValue}.\");\n }\n }\n\n /// \n /// Validates that the specified value is less than or equal to the maximum value.\n /// \n /// The value to validate.\n /// The maximum allowed value.\n /// The name of the parameter being validated.\n /// Thrown if the value is greater than the maximum value.\n public static void LessThanOrEqualTo(int value, int maxValue, string paramName)\n {\n if (value > maxValue)\n {\n throw new ArgumentOutOfRangeException(paramName, value, $\"Value must be less than or equal to {maxValue}.\");\n }\n }\n\n /// \n /// Validates that the specified value is in the specified range.\n /// \n /// The value to validate.\n /// The minimum allowed value.\n /// The maximum allowed value.\n /// The name of the parameter being validated.\n /// Thrown if the value is outside the specified range.\n public static void InRange(int value, int minValue, int maxValue, string paramName)\n {\n if (value < minValue || value > maxValue)\n {\n throw new ArgumentOutOfRangeException(paramName, value, $\"Value must be between {minValue} and {maxValue}.\");\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Behaviors/ResponsiveLayoutBehavior.cs", "using System.Windows;\nusing System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Common.Behaviors\n{\n /// \n /// Provides attached properties and behaviors for responsive layouts\n /// \n public static class ResponsiveLayoutBehavior\n {\n #region ItemWidth Attached Property\n\n /// \n /// Gets the ItemWidth value\n /// \n public static double GetItemWidth(DependencyObject obj)\n {\n return (double)obj.GetValue(ItemWidthProperty);\n }\n\n /// \n /// Sets the ItemWidth value\n /// \n public static void SetItemWidth(DependencyObject obj, double value)\n {\n obj.SetValue(ItemWidthProperty, value);\n }\n\n /// \n /// ItemWidth Attached Dependency Property\n /// \n public static readonly DependencyProperty ItemWidthProperty =\n DependencyProperty.RegisterAttached(\n \"ItemWidth\",\n typeof(double),\n typeof(ResponsiveLayoutBehavior),\n new PropertyMetadata(200.0, OnItemWidthChanged));\n\n /// \n /// Called when ItemWidth is changed\n /// \n private static void OnItemWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is FrameworkElement element)\n {\n element.Width = (double)e.NewValue;\n }\n }\n\n #endregion\n\n #region MinItemWidth Attached Property\n\n /// \n /// Gets the MinItemWidth value\n /// \n public static double GetMinItemWidth(DependencyObject obj)\n {\n return (double)obj.GetValue(MinItemWidthProperty);\n }\n\n /// \n /// Sets the MinItemWidth value\n /// \n public static void SetMinItemWidth(DependencyObject obj, double value)\n {\n obj.SetValue(MinItemWidthProperty, value);\n }\n\n /// \n /// MinItemWidth Attached Dependency Property\n /// \n public static readonly DependencyProperty MinItemWidthProperty =\n DependencyProperty.RegisterAttached(\n \"MinItemWidth\",\n typeof(double),\n typeof(ResponsiveLayoutBehavior),\n new PropertyMetadata(150.0, OnMinItemWidthChanged));\n\n /// \n /// Called when MinItemWidth is changed\n /// \n private static void OnMinItemWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is FrameworkElement element)\n {\n element.MinWidth = (double)e.NewValue;\n }\n }\n\n #endregion\n\n #region WrapPanelMaxWidth Attached Property\n\n /// \n /// Gets the WrapPanelMaxWidth value\n /// \n public static double GetWrapPanelMaxWidth(DependencyObject obj)\n {\n return (double)obj.GetValue(WrapPanelMaxWidthProperty);\n }\n\n /// \n /// Sets the WrapPanelMaxWidth value\n /// \n public static void SetWrapPanelMaxWidth(DependencyObject obj, double value)\n {\n obj.SetValue(WrapPanelMaxWidthProperty, value);\n }\n\n /// \n /// WrapPanelMaxWidth Attached Dependency Property\n /// \n public static readonly DependencyProperty WrapPanelMaxWidthProperty =\n DependencyProperty.RegisterAttached(\n \"WrapPanelMaxWidth\",\n typeof(double),\n typeof(ResponsiveLayoutBehavior),\n new PropertyMetadata(1000.0));\n\n #endregion\n\n #region MaxItemWidth Attached Property\n\n /// \n /// Gets the MaxItemWidth value\n /// \n public static double GetMaxItemWidth(DependencyObject obj)\n {\n return (double)obj.GetValue(MaxItemWidthProperty);\n }\n\n /// \n /// Sets the MaxItemWidth value\n /// \n public static void SetMaxItemWidth(DependencyObject obj, double value)\n {\n obj.SetValue(MaxItemWidthProperty, value);\n }\n\n /// \n /// MaxItemWidth Attached Dependency Property\n /// \n public static readonly DependencyProperty MaxItemWidthProperty =\n DependencyProperty.RegisterAttached(\n \"MaxItemWidth\",\n typeof(double),\n typeof(ResponsiveLayoutBehavior),\n new PropertyMetadata(400.0, OnMaxItemWidthChanged));\n\n /// \n /// Called when MaxItemWidth is changed\n /// \n private static void OnMaxItemWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is FrameworkElement element)\n {\n element.MaxWidth = (double)e.NewValue;\n }\n }\n\n #endregion\n\n #region UseWrapPanel Attached Property\n\n /// \n /// Gets the UseWrapPanel value\n /// \n public static bool GetUseWrapPanel(DependencyObject obj)\n {\n return (bool)obj.GetValue(UseWrapPanelProperty);\n }\n\n /// \n /// Sets the UseWrapPanel value\n /// \n public static void SetUseWrapPanel(DependencyObject obj, bool value)\n {\n obj.SetValue(UseWrapPanelProperty, value);\n }\n\n /// \n /// UseWrapPanel Attached Dependency Property\n /// \n public static readonly DependencyProperty UseWrapPanelProperty =\n DependencyProperty.RegisterAttached(\n \"UseWrapPanel\",\n typeof(bool),\n typeof(ResponsiveLayoutBehavior),\n new PropertyMetadata(false, OnUseWrapPanelChanged));\n\n /// \n /// Called when UseWrapPanel is changed\n /// \n private static void OnUseWrapPanelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is ItemsControl itemsControl && (bool)e.NewValue)\n {\n // Get the WrapPanelMaxWidth value or use the default\n double maxWidth = GetWrapPanelMaxWidth(itemsControl);\n\n // Create a WrapPanel for the ItemsPanel\n var wrapPanel = new WrapPanel\n {\n Orientation = Orientation.Horizontal,\n MaxWidth = maxWidth,\n HorizontalAlignment = HorizontalAlignment.Left\n };\n \n // Add resources to the WrapPanel\n var wrapPanelStyle = new Style(typeof(ContentPresenter));\n wrapPanelStyle.Setters.Add(new Setter(FrameworkElement.MarginProperty, new Thickness(0, 5, 10, 5)));\n wrapPanel.Resources.Add(typeof(ContentPresenter), wrapPanelStyle);\n\n // Set the ItemsPanel template\n var template = new ItemsPanelTemplate();\n template.VisualTree = new FrameworkElementFactory(typeof(WrapPanel));\n template.VisualTree.SetValue(WrapPanel.OrientationProperty, Orientation.Horizontal);\n template.VisualTree.SetValue(WrapPanel.MaxWidthProperty, maxWidth);\n template.VisualTree.SetValue(WrapPanel.HorizontalAlignmentProperty, HorizontalAlignment.Left);\n \n // Add resources to the template\n var resourceDictionary = new ResourceDictionary();\n var contentPresenterStyle = new Style(typeof(ContentPresenter));\n contentPresenterStyle.Setters.Add(new Setter(FrameworkElement.MarginProperty, new Thickness(0, 5, 10, 5)));\n resourceDictionary.Add(typeof(ContentPresenter), contentPresenterStyle);\n template.Resources = resourceDictionary;\n \n // Set item spacing through the ItemContainerStyle\n var style = new Style(typeof(ContentPresenter));\n style.Setters.Add(new Setter(FrameworkElement.MarginProperty, new Thickness(0, 5, 10, 5)));\n style.Setters.Add(new Setter(FrameworkElement.WidthProperty, 250.0));\n style.Setters.Add(new Setter(FrameworkElement.MinWidthProperty, 250.0));\n style.Setters.Add(new Setter(FrameworkElement.MaxWidthProperty, 250.0));\n \n if (itemsControl.ItemContainerStyle == null)\n {\n itemsControl.ItemContainerStyle = style;\n }\n\n itemsControl.ItemsPanel = template;\n }\n }\n\n #endregion\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/PowerOptimizations.cs", "using System;\nusing System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\n/// \n/// Represents a PowerCfg command setting.\n/// \npublic class PowerCfgSetting\n{\n /// \n /// Gets or sets the command to execute.\n /// \n public string Command { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description of the command.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the value to use when the setting is enabled.\n /// \n public string EnabledValue { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the value to use when the setting is disabled.\n /// \n public string DisabledValue { get; set; } = string.Empty;\n}\n\npublic static class PowerOptimizations\n{\n /// \n /// Gets all power optimizations as an OptimizationGroup.\n /// \n /// An OptimizationGroup containing all power settings.\n public static OptimizationGroup GetPowerOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Power\",\n Category = OptimizationCategory.Power,\n Settings = new List\n {\n // Hibernate Settings\n new OptimizationSetting\n {\n Id = \"power-hibernate-enabled\",\n Name = \"Hibernate\",\n Description = \"Controls whether hibernate is enabled\",\n Category = OptimizationCategory.Power,\n GroupName = \"Power Management\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Power\",\n Name = \"HibernateEnabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, hibernate is enabled\n DisabledValue = 0, // When toggle is OFF, hibernate is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls whether hibernate is enabled\",\n IsPrimary = true, // Mark as primary for linked settings\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Power\",\n Name = \"HibernateEnabledDefault\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, hibernate is enabled\n DisabledValue = 0, // When toggle is OFF, hibernate is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls whether hibernate is enabled by default\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.Primary,\n },\n // Video Settings\n new OptimizationSetting\n {\n Id = \"power-video-quality\",\n Name = \"High Video Quality on Battery\",\n Description = \"Controls video quality when running on battery power\",\n Category = OptimizationCategory.Power,\n GroupName = \"Display & Graphics\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\VideoSettings\",\n Name = \"VideoQualityOnBattery\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 1, // High quality (from Recommended)\n DisabledValue = 0, // Lower quality (from Default)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls video quality when running on battery power\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n // Performance Settings\n new OptimizationSetting\n {\n Id = \"power-fast-boot\",\n Name = \"Fast Boot\",\n Description = \"Controls whether fast boot (hybrid boot) is enabled\",\n Category = OptimizationCategory.Power,\n GroupName = \"Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Power\",\n Name = \"HiberbootEnabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // Enable fast boot\n DisabledValue = 0, // Disable fast boot\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls whether fast boot (hybrid boot) is enabled\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Sleep Settings\n new OptimizationSetting\n {\n Id = \"power-sleep-settings\",\n Name = \"Sleep & Hibernate\",\n Description =\n \"When enabled, prevents your computer from going to sleep or hibernating\",\n Category = OptimizationCategory.Power,\n GroupName = \"Sleep & Hibernate\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command = \"powercfg /hibernate off\",\n Description = \"Disable hibernate\",\n EnabledValue = \"/hibernate off\",\n DisabledValue = \"/hibernate on\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n Description = \"Set sleep timeout (AC) to never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n DisabledValue =\n \"/setactive 381b4222-f694-41f0-9685-ff5bb260df2e\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n Description = \"Set sleep timeout (DC) to never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n DisabledValue =\n \"/setactive 381b4222-f694-41f0-9685-ff5bb260df2e\",\n },\n }\n },\n },\n },\n // Display Settings\n new OptimizationSetting\n {\n Id = \"power-display-settings\",\n Name = \"Display Always On\",\n Description =\n \"When enabled, prevents your display from turning off and sets maximum brightness\",\n Category = OptimizationCategory.Power,\n GroupName = \"Display & Graphics\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\",\n Description = \"Set display timeout (AC) to never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000258\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\",\n Description = \"Set display timeout (DC) to never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000258\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 aded5e82-b909-4619-9949-f5d71dac0bcb 0x00000064\",\n Description = \"Set display brightness (AC) to 100%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 aded5e82-b909-4619-9949-f5d71dac0bcb 0x00000064\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 aded5e82-b909-4619-9949-f5d71dac0bcb 0x00000032\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\",\n Description = \"Disable adaptive brightness (AC)\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\",\n Description = \"Disable adaptive brightness (DC)\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 001\",\n },\n }\n },\n },\n },\n // Processor Settings\n new OptimizationSetting\n {\n Id = \"power-processor-settings\",\n Name = \"CPU Performance\",\n Description =\n \"When enabled, sets processor to run at 100% power with active cooling\",\n Category = OptimizationCategory.Power,\n GroupName = \"Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 893dee8e-2bef-41e0-89c6-b55d0929964c 0x00000064\",\n Description = \"Set processor minimum state (AC) to 100%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 893dee8e-2bef-41e0-89c6-b55d0929964c 0x00000064\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 893dee8e-2bef-41e0-89c6-b55d0929964c 0x00000005\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 bc5038f7-23e0-4960-96da-33abaf5935ec 0x00000064\",\n Description = \"Set processor maximum state (AC) to 100%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 bc5038f7-23e0-4960-96da-33abaf5935ec 0x00000064\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 bc5038f7-23e0-4960-96da-33abaf5935ec 0x00000064\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 94d3a615-a899-4ac5-ae2b-e4d8f634367f 001\",\n Description = \"Set cooling policy (AC) to active\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 94d3a615-a899-4ac5-ae2b-e4d8f634367f 001\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 54533251-82be-4824-96c1-47b60b740d00 94d3a615-a899-4ac5-ae2b-e4d8f634367f 000\",\n },\n }\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"power-cpu-unpark\",\n Name = \"CPU Core Unparking\",\n Description = \"Controls CPU core parking for better performance\",\n Category = OptimizationCategory.Power,\n GroupName = \"Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SYSTEM\\\\ControlSet001\\\\Control\\\\Power\\\\PowerSettings\\\\54533251-82be-4824-96c1-47b60b740d00\\\\0cc5b647-c1df-4637-891a-dec35c318583\",\n Name = \"ValueMax\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // Unpark CPU cores (from Recommended)\n DisabledValue = 1, // Allow CPU core parking (from Default)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls CPU core parking for better performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"power-throttling\",\n Name = \"Power Throttling\",\n Description = \"Controls power throttling for better performance\",\n Category = OptimizationCategory.Power,\n GroupName = \"Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Power\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Power\\\\PowerThrottling\",\n Name = \"PowerThrottlingOff\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 0, // Enable power throttling\n DisabledValue = 1, // Disable power throttling\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls power throttling for better performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Storage Settings\n new OptimizationSetting\n {\n Id = \"power-hard-disk-settings\",\n Name = \"Hard Disks Always On\",\n Description =\n \"When enabled, prevents hard disks from turning off to improve performance\",\n Category = OptimizationCategory.Power,\n GroupName = \"Storage\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\",\n Description = \"Set hard disk timeout (AC) to never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000258\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\",\n Description = \"Set hard disk timeout (DC) to never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000258\",\n },\n }\n },\n },\n },\n // Desktop & Display Settings\n new OptimizationSetting\n {\n Id = \"power-desktop-slideshow-settings\",\n Name = \"Desktop Slideshow\",\n Description =\n \"When enabled, allows desktop background slideshow to run even on battery power\",\n Category = OptimizationCategory.Power,\n GroupName = \"Desktop & Display\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 000\",\n Description =\n \"Desktop slideshow (AC) - Value 0 means Available\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 000\",\n Description =\n \"Desktop slideshow (DC) - Value 0 means Available\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 001\",\n },\n }\n },\n },\n },\n // Network Settings\n new OptimizationSetting\n {\n Id = \"power-wireless-adapter-settings\",\n Name = \"Wi-Fi Performance\",\n Description = \"When enabled, sets wireless adapter to maximum performance mode\",\n Category = OptimizationCategory.Power,\n GroupName = \"Network\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\",\n Description =\n \"Wireless adapter power saving mode (AC) - Maximum performance\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\",\n Description =\n \"Wireless adapter power saving mode (DC) - Maximum performance\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 001\",\n },\n }\n },\n },\n },\n // Sleep & Hibernate Settings\n new OptimizationSetting\n {\n Id = \"power-sleep-hibernate-settings\",\n Name = \"All Sleep Features\",\n Description =\n \"When enabled, disables sleep, hybrid sleep, hibernate, and wake timers\",\n Category = OptimizationCategory.Power,\n GroupName = \"Sleep & Hibernate\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n Description = \"Sleep timeout (AC) - Never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000384\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n Description = \"Sleep timeout (DC) - Never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000384\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\",\n Description = \"Hybrid sleep (AC) - Off\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\",\n Description = \"Hybrid sleep (DC) - Off\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\",\n Description = \"Hibernate timeout (AC) - Never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000384\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\",\n Description = \"Hibernate timeout (DC) - Never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000384\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\",\n Description = \"Wake timers (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\",\n Description = \"Wake timers (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 001\",\n },\n }\n },\n },\n },\n // USB Settings\n new OptimizationSetting\n {\n Id = \"power-usb-settings\",\n Name = \"USB Devices Always On\",\n Description =\n \"When enabled, prevents USB devices from being powered down to save energy\",\n Category = OptimizationCategory.Power,\n GroupName = \"USB\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\",\n Description = \"USB hub timeout (AC) - Never\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000258\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\",\n Description = \"USB hub timeout (DC) - Never\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000258\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\",\n Description = \"USB selective suspend (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\",\n Description = \"USB selective suspend (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\",\n Description = \"USB 3.0 link power management (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\",\n Description = \"USB 3.0 link power management (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 001\",\n },\n }\n },\n },\n },\n // Power Button Settings\n new OptimizationSetting\n {\n Id = \"power-button-settings\",\n Name = \"Power Button Shutdown\",\n Description =\n \"When enabled, sets power button to immediately shut down your computer\",\n Category = OptimizationCategory.Power,\n GroupName = \"Power Buttons\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\",\n Description = \"Power button action (AC) - Shut down\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\",\n Description = \"Power button action (DC) - Shut down\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 000\",\n },\n }\n },\n },\n },\n // PCI Express Settings\n new OptimizationSetting\n {\n Id = \"power-pci-express-settings\",\n Name = \"PCI Express Performance\",\n Description =\n \"When enabled, disables power saving features for PCI Express devices\",\n Category = OptimizationCategory.Power,\n GroupName = \"PCI Express\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\",\n Description = \"PCI Express power management (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\",\n Description = \"PCI Express power management (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 001\",\n },\n }\n },\n },\n },\n // Video Playback Settings\n new OptimizationSetting\n {\n Id = \"power-video-playback-settings\",\n Name = \"Video Playback Quality\",\n Description =\n \"When enabled, ensures maximum video quality even when on battery power\",\n Category = OptimizationCategory.Power,\n GroupName = \"Video Playback\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\",\n Description =\n \"Video playback quality (AC) - Optimized for performance\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\",\n Description =\n \"Video playback quality (DC) - Optimized for performance\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\",\n Description =\n \"Video quality reduction on battery (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\",\n Description =\n \"Video quality reduction on battery (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 001\",\n },\n }\n },\n },\n },\n // Graphics Settings\n new OptimizationSetting\n {\n Id = \"power-graphics-settings\",\n Name = \"GPU Performance\",\n Description = \"When enabled, sets graphics cards to run at maximum performance\",\n Category = OptimizationCategory.Power,\n GroupName = \"Graphics\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\",\n Description = \"Intel graphics power (AC) - Maximum performance\",\n EnabledValue =\n \"/setacvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\",\n DisabledValue =\n \"/setacvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\",\n Description = \"Intel graphics power (DC) - Maximum performance\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\",\n Description = \"AMD power slider (AC) - Maximum performance\",\n EnabledValue =\n \"/setacvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\",\n DisabledValue =\n \"/setacvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\",\n Description = \"AMD power slider (DC) - Maximum performance\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\",\n Description = \"ATI PowerPlay (AC) - Enabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\",\n DisabledValue =\n \"/setacvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\",\n Description = \"ATI PowerPlay (DC) - Enabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\",\n Description = \"Switchable graphics (AC) - Maximum performance\",\n EnabledValue =\n \"/setacvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\",\n DisabledValue =\n \"/setacvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 000\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\",\n Description = \"Switchable graphics (DC) - Maximum performance\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 000\",\n },\n }\n },\n },\n },\n // Battery Settings\n new OptimizationSetting\n {\n Id = \"power-battery-settings\",\n Name = \"Battery Notifications\",\n Description =\n \"When enabled, turns off low battery and critical battery notifications\",\n Category = OptimizationCategory.Power,\n GroupName = \"Battery\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\",\n Description = \"Critical battery notification (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\",\n Description = \"Critical battery notification (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\",\n Description = \"Critical battery action (AC) - Do nothing\",\n EnabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\",\n Description = \"Critical battery action (DC) - Do nothing\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\",\n Description = \"Low battery level (AC) - 0%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x0000000A\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\",\n Description = \"Low battery level (DC) - 0%\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x0000000A\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\",\n Description = \"Low battery notification (AC) - Disabled\",\n EnabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 001\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\",\n Description = \"Low battery notification (DC) - Disabled\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 001\",\n },\n }\n },\n },\n },\n // Battery Saver Settings\n new OptimizationSetting\n {\n Id = \"power-battery-saver-settings\",\n Name = \"Battery Saver\",\n Description =\n \"When enabled, prevents battery saver from activating at any battery level\",\n Category = OptimizationCategory.Power,\n GroupName = \"Battery Saver\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CustomProperties = new Dictionary\n {\n {\n \"PowerCfgSettings\",\n new List\n {\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\",\n Description = \"Battery saver brightness (AC) - 100%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\",\n DisabledValue =\n \"/setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000032\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\",\n Description = \"Battery saver brightness (DC) - 100%\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000032\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\",\n Description = \"Battery saver threshold (AC) - 0%\",\n EnabledValue =\n \"/setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\",\n DisabledValue =\n \"/setacvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000032\",\n },\n new PowerCfgSetting\n {\n Command =\n \"powercfg /setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\",\n Description = \"Battery saver threshold (DC) - 0%\",\n EnabledValue =\n \"/setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\",\n DisabledValue =\n \"/setdcvalueindex {active_guid} de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000032\",\n },\n }\n },\n },\n },\n },\n };\n }\n\n /// \n /// Contains all the powercfg commands for the Ultimate Performance Power Plan.\n /// \n public static class UltimatePerformancePowerPlan\n {\n public static readonly Dictionary PowerCfgCommands = new()\n {\n // Create and set the Ultimate Performance power plan\n {\n \"CreateUltimatePlan\",\n \"/duplicatescheme e9a42b02-d5df-448d-aa00-03f14749eb61 99999999-9999-9999-9999-999999999999\"\n },\n { \"SetActivePlan\", \"/SETACTIVE 99999999-9999-9999-9999-999999999999\" },\n // Hard disk settings\n {\n \"HardDiskTimeout_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\"\n },\n {\n \"HardDiskTimeout_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 0012ee47-9041-4b5d-9b77-535fba8b1442 6738e2c4-e8a5-4a42-b16a-e040e769756e 0x00000000\"\n },\n // Desktop background slideshow\n {\n \"DesktopSlideshow_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 001\"\n },\n {\n \"DesktopSlideshow_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 001\"\n },\n // Wireless adapter settings\n {\n \"WirelessAdapter_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\"\n },\n {\n \"WirelessAdapter_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 19cbb8fa-5279-450e-9fac-8a3d5fedd0c1 12bbebe6-58d6-4636-95bb-3217ef867c1a 000\"\n },\n // Sleep settings\n {\n \"SleepTimeout_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\"\n },\n {\n \"SleepTimeout_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0x00000000\"\n },\n {\n \"HybridSleep_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\"\n },\n {\n \"HybridSleep_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 94ac6d29-73ce-41a6-809f-6363ba21b47e 000\"\n },\n {\n \"HibernateTimeout_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\"\n },\n {\n \"HibernateTimeout_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 9d7815a6-7ee4-497e-8888-515a05f02364 0x00000000\"\n },\n {\n \"WakeTimers_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\"\n },\n {\n \"WakeTimers_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 238c9fa8-0aad-41ed-83f4-97be242c8f20 bd3b718a-0680-4d9d-8ab2-e1d2b4ac806d 000\"\n },\n // USB settings\n {\n \"UsbHubTimeout_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\"\n },\n {\n \"UsbHubTimeout_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 0853a681-27c8-4100-a2fd-82013e970683 0x00000000\"\n },\n {\n \"UsbSelectiveSuspend_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\"\n },\n {\n \"UsbSelectiveSuspend_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 000\"\n },\n {\n \"Usb3LinkPower_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\"\n },\n {\n \"Usb3LinkPower_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 2a737441-1930-4402-8d77-b2bebba308a3 d4e98f31-5ffe-4ce1-be31-1b38b384c009 000\"\n },\n // Power button action\n {\n \"PowerButtonAction_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\"\n },\n {\n \"PowerButtonAction_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 4f971e89-eebd-4455-a8de-9e59040e7347 a7066653-8d6c-40a8-910e-a1f54b84c7e5 002\"\n },\n // PCI Express\n {\n \"PciExpressPower_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\"\n },\n {\n \"PciExpressPower_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 501a4d13-42af-4429-9fd1-a8218c268e20 ee12f906-d277-404b-b6da-e5fa1a576df5 000\"\n },\n // Processor settings\n {\n \"ProcessorMinState_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 893dee8e-2bef-41e0-89c6-b55d0929964c 0x00000064\"\n },\n {\n \"ProcessorMinState_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 893dee8e-2bef-41e0-89c6-b55d0929964c 0x00000064\"\n },\n {\n \"CoolingPolicy_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 94d3a615-a899-4ac5-ae2b-e4d8f634367f 001\"\n },\n {\n \"CoolingPolicy_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 94d3a615-a899-4ac5-ae2b-e4d8f634367f 001\"\n },\n {\n \"ProcessorMaxState_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 bc5038f7-23e0-4960-96da-33abaf5935ec 0x00000064\"\n },\n {\n \"ProcessorMaxState_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 54533251-82be-4824-96c1-47b60b740d00 bc5038f7-23e0-4960-96da-33abaf5935ec 0x00000064\"\n },\n // Display settings\n {\n \"DisplayTimeout_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\"\n },\n {\n \"DisplayTimeout_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e 0x00000000\"\n },\n {\n \"DisplayBrightness_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 aded5e82-b909-4619-9949-f5d71dac0bcb 0x00000064\"\n },\n {\n \"DisplayBrightness_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 aded5e82-b909-4619-9949-f5d71dac0bcb 0x00000064\"\n },\n {\n \"DimmedBrightness_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 f1fbfde2-a960-4165-9f88-50667911ce96 0x00000064\"\n },\n {\n \"DimmedBrightness_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 f1fbfde2-a960-4165-9f88-50667911ce96 0x00000064\"\n },\n {\n \"AdaptiveBrightness_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\"\n },\n {\n \"AdaptiveBrightness_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 7516b95f-f776-4464-8c53-06167f40cc99 fbd9aa66-9553-4097-ba44-ed6e9d65eab8 000\"\n },\n // Video playback settings\n {\n \"VideoPlaybackQuality_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\"\n },\n {\n \"VideoPlaybackQuality_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 10778347-1370-4ee0-8bbd-33bdacaade49 001\"\n },\n {\n \"VideoPlaybackQualityOnBattery_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\"\n },\n {\n \"VideoPlaybackQualityOnBattery_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 9596fb26-9850-41fd-ac3e-f7c3c00afd4b 34c7b99f-9a6d-4b3c-8dc7-b6693b78cef4 000\"\n },\n // Graphics settings\n {\n \"IntelGraphicsPower_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\"\n },\n {\n \"IntelGraphicsPower_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 44f3beca-a7c0-460e-9df2-bb8b99e0cba6 3619c3f2-afb2-4afc-b0e9-e7fef372de36 002\"\n },\n {\n \"AmdPowerSlider_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\"\n },\n {\n \"AmdPowerSlider_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 c763b4ec-0e50-4b6b-9bed-2b92a6ee884e 7ec1751b-60ed-4588-afb5-9819d3d77d90 003\"\n },\n {\n \"AtiPowerPlay_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\"\n },\n {\n \"AtiPowerPlay_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 f693fb01-e858-4f00-b20f-f30e12ac06d6 191f65b5-d45c-4a4f-8aae-1ab8bfd980e6 001\"\n },\n {\n \"SwitchableGraphics_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\"\n },\n {\n \"SwitchableGraphics_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e276e160-7cb0-43c6-b20b-73f5dce39954 a1662ab2-9d34-4e53-ba8b-2639b9e20857 003\"\n },\n // Battery settings\n {\n \"CriticalBatteryNotification_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\"\n },\n {\n \"CriticalBatteryNotification_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 5dbb7c9f-38e9-40d2-9749-4f8a0e9f640f 000\"\n },\n {\n \"CriticalBatteryAction_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\"\n },\n {\n \"CriticalBatteryAction_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 637ea02f-bbcb-4015-8e2c-a1c7b9c0b546 000\"\n },\n {\n \"LowBatteryLevel_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\"\n },\n {\n \"LowBatteryLevel_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 8183ba9a-e910-48da-8769-14ae6dc1170a 0x00000000\"\n },\n {\n \"CriticalBatteryLevel_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 9a66d8d7-4ff7-4ef9-b5a2-5a326ca2a469 0x00000000\"\n },\n {\n \"CriticalBatteryLevel_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f 9a66d8d7-4ff7-4ef9-b5a2-5a326ca2a469 0x00000000\"\n },\n {\n \"LowBatteryNotification_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\"\n },\n {\n \"LowBatteryNotification_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f bcded951-187b-4d05-bccc-f7e51960c258 000\"\n },\n {\n \"LowBatteryAction_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f d8742dcb-3e6a-4b3c-b3fe-374623cdcf06 000\"\n },\n {\n \"LowBatteryAction_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f d8742dcb-3e6a-4b3c-b3fe-374623cdcf06 000\"\n },\n {\n \"ReserveBatteryLevel_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f f3c5027d-cd16-4930-aa6b-90db844a8f00 0x00000000\"\n },\n {\n \"ReserveBatteryLevel_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 e73a048d-bf27-4f12-9731-8b2076e8891f f3c5027d-cd16-4930-aa6b-90db844a8f00 0x00000000\"\n },\n // Battery Saver settings\n {\n \"BatterySaverBrightness_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\"\n },\n {\n \"BatterySaverBrightness_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 de830923-a562-41af-a086-e3a2c6bad2da 13d09884-f74e-474a-a852-b6bde8ad03a8 0x00000064\"\n },\n {\n \"BatterySaverThreshold_AC\",\n \"/setacvalueindex 99999999-9999-9999-9999-999999999999 de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\"\n },\n {\n \"BatterySaverThreshold_DC\",\n \"/setdcvalueindex 99999999-9999-9999-9999-999999999999 de830923-a562-41af-a086-e3a2c6bad2da e69653ca-cf7f-4f05-aa73-cb833fa90ad4 0x00000000\"\n },\n };\n }\n\n /// \n /// Provides access to all available power plans.\n /// \n public static class PowerPlans\n {\n /// \n /// The Balanced power plan.\n /// \n public static readonly PowerPlan Balanced = new PowerPlan\n {\n Name = \"Balanced\",\n Guid = \"381b4222-f694-41f0-9685-ff5bb260df2e\",\n Description =\n \"Automatically balances performance with energy consumption on capable hardware.\",\n };\n\n /// \n /// The High Performance power plan.\n /// \n public static readonly PowerPlan HighPerformance = new PowerPlan\n {\n Name = \"High Performance\",\n Guid = \"8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c\",\n Description = \"Favors performance, but may use more energy.\",\n };\n\n /// \n /// The Ultimate Performance power plan.\n /// \n public static readonly PowerPlan UltimatePerformance = new PowerPlan\n {\n Name = \"Ultimate Performance\",\n // This GUID is a placeholder and will be updated at runtime by PowerPlanService\n Guid = \"e9a42b02-d5df-448d-aa00-03f14749eb61\",\n Description = \"Provides ultimate performance on Windows.\",\n };\n\n /// \n /// Gets a list of all available power plans.\n /// \n /// A list of all power plans.\n public static List GetAllPowerPlans()\n {\n return new List { Balanced, HighPerformance, UltimatePerformance };\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/UnifiedConfigurationDialogViewModel.cs", "using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n /// \n /// ViewModel for the UnifiedConfigurationDialog.\n /// \n public class UnifiedConfigurationDialogViewModel : ObservableObject\n {\n private string _title;\n private string _description;\n private bool _isSaveDialog;\n\n /// \n /// Gets or sets the title of the dialog.\n /// \n public string Title\n {\n get => _title;\n set => SetProperty(ref _title, value);\n }\n\n /// \n /// Gets or sets the description of the dialog.\n /// \n public string Description\n {\n get => _description;\n set => SetProperty(ref _description, value);\n }\n\n /// \n /// Gets a value indicating whether this is a save dialog.\n /// \n public bool IsSaveDialog => _isSaveDialog;\n\n /// \n /// Gets the collection of configuration sections.\n /// \n public ObservableCollection Sections { get; } = new ObservableCollection();\n\n /// \n /// Gets or sets the command to confirm the selection.\n /// \n public ICommand OkCommand { get; set; }\n\n /// \n /// Gets or sets the command to cancel the selection.\n /// \n public ICommand CancelCommand { get; set; }\n\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The title of the dialog.\n /// The description of the dialog.\n /// The dictionary of section names, their availability, and item counts.\n /// Whether this is a save dialog (true) or an import dialog (false).\n public UnifiedConfigurationDialogViewModel(\n string title, \n string description, \n Dictionary sections,\n bool isSaveDialog)\n {\n Title = title;\n Description = description;\n _isSaveDialog = isSaveDialog;\n\n // Create section view models\n foreach (var section in sections)\n {\n Sections.Add(new UnifiedConfigurationSectionViewModel\n {\n Name = GetSectionDisplayName(section.Key),\n Description = GetSectionDescription(section.Key),\n IsSelected = section.Value.IsSelected,\n IsAvailable = section.Value.IsAvailable,\n ItemCount = section.Value.ItemCount,\n SectionKey = section.Key\n });\n }\n\n // Commands will be set by the dialog\n OkCommand = null;\n CancelCommand = null;\n }\n\n /// \n /// Gets the result of the dialog as a dictionary of section names and their selection state.\n /// \n /// A dictionary of section names and their selection state.\n public Dictionary GetResult()\n {\n var result = new Dictionary();\n\n foreach (var section in Sections)\n {\n result[section.SectionKey] = section.IsSelected;\n }\n\n return result;\n }\n\n\n private string GetSectionDisplayName(string sectionKey)\n {\n return sectionKey switch\n {\n \"WindowsApps\" => \"Windows Apps\",\n \"ExternalApps\" => \"External Apps\",\n \"Customize\" => \"Customization Settings\",\n \"Optimize\" => \"Optimization Settings\",\n _ => sectionKey\n };\n }\n\n private string GetSectionDescription(string sectionKey)\n {\n return sectionKey switch\n {\n \"WindowsApps\" => \"Settings for Windows built-in applications\",\n \"ExternalApps\" => \"Settings for third-party applications\",\n \"Customize\" => \"Windows UI customization settings\",\n \"Optimize\" => \"Windows optimization settings\",\n _ => string.Empty\n };\n }\n }\n\n /// \n /// ViewModel for a unified configuration section.\n /// \n public class UnifiedConfigurationSectionViewModel : ObservableObject\n {\n private string _name;\n private string _description;\n private bool _isSelected;\n private bool _isAvailable;\n private int _itemCount;\n private string _sectionKey;\n\n /// \n /// Gets or sets the name of the section.\n /// \n public string Name\n {\n get => _name;\n set => SetProperty(ref _name, value);\n }\n\n /// \n /// Gets or sets the description of the section.\n /// \n public string Description\n {\n get => _description;\n set => SetProperty(ref _description, value);\n }\n\n /// \n /// Gets or sets a value indicating whether the section is selected.\n /// \n public bool IsSelected\n {\n get => _isSelected;\n set => SetProperty(ref _isSelected, value);\n }\n\n /// \n /// Gets or sets a value indicating whether the section is available.\n /// \n public bool IsAvailable\n {\n get => _isAvailable;\n set => SetProperty(ref _isAvailable, value);\n }\n\n /// \n /// Gets or sets the number of items in the section.\n /// \n public int ItemCount\n {\n get => _itemCount;\n set => SetProperty(ref _itemCount, value);\n }\n\n /// \n /// Gets or sets the section key.\n /// \n public string SectionKey\n {\n get => _sectionKey;\n set => SetProperty(ref _sectionKey, value);\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Services/DependencyManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Services\n{\n /// \n /// Manages dependencies between settings, ensuring that dependent settings are properly handled\n /// when their required settings change state.\n /// \n public class DependencyManager : IDependencyManager\n {\n private readonly ILogService _logService;\n \n public DependencyManager(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n \n /// \n /// Handles the enabling of a setting by automatically enabling any required settings.\n /// \n /// The ID of the setting that is being enabled.\n /// All available settings that might be required by the enabled setting.\n /// True if all required settings were enabled successfully; otherwise, false.\n public bool HandleSettingEnabled(string settingId, IEnumerable allSettings)\n {\n if (string.IsNullOrEmpty(settingId))\n {\n _logService.Log(LogLevel.Warning, \"Cannot handle dependencies for null or empty setting ID\");\n return false;\n }\n \n var setting = allSettings.FirstOrDefault(s => s.Id == settingId);\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, $\"Setting with ID '{settingId}' not found\");\n return false;\n }\n \n if (setting.Dependencies == null || !setting.Dependencies.Any())\n {\n return true; // No dependencies, so nothing to enable\n }\n \n // Get unsatisfied dependencies\n var unsatisfiedDependencies = GetUnsatisfiedDependencies(settingId, allSettings);\n \n // Enable all dependencies\n return EnableDependencies(unsatisfiedDependencies);\n }\n \n /// \n /// Gets a list of unsatisfied dependencies for a setting.\n /// \n /// The ID of the setting to check.\n /// All available settings that might be dependencies.\n /// A list of settings that are required by the specified setting but are not enabled.\n public List GetUnsatisfiedDependencies(string settingId, IEnumerable allSettings)\n {\n var unsatisfiedDependencies = new List();\n \n if (string.IsNullOrEmpty(settingId))\n {\n _logService.Log(LogLevel.Warning, \"Cannot get dependencies for null or empty setting ID\");\n return unsatisfiedDependencies;\n }\n \n var setting = allSettings.FirstOrDefault(s => s.Id == settingId);\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, $\"Setting with ID '{settingId}' not found\");\n return unsatisfiedDependencies;\n }\n \n if (setting.Dependencies == null || !setting.Dependencies.Any())\n {\n return unsatisfiedDependencies; // No dependencies\n }\n \n // Find all settings that this setting depends on\n foreach (var dependency in setting.Dependencies)\n {\n if (dependency.DependencyType == SettingDependencyType.RequiresEnabled)\n {\n var requiredSetting = allSettings.FirstOrDefault(s => s.Id == dependency.RequiredSettingId);\n if (requiredSetting != null && !requiredSetting.IsSelected)\n {\n unsatisfiedDependencies.Add(requiredSetting);\n }\n }\n }\n \n return unsatisfiedDependencies;\n }\n \n /// \n /// Enables all dependencies in the provided list.\n /// \n /// The dependencies to enable.\n /// True if all dependencies were enabled successfully; otherwise, false.\n public bool EnableDependencies(IEnumerable dependencies)\n {\n bool allSucceeded = true;\n \n foreach (var dependency in dependencies)\n {\n _logService.Log(LogLevel.Info, $\"Automatically enabling dependency: {dependency.Name}\");\n \n // Enable the dependency\n dependency.IsUpdatingFromCode = true;\n try\n {\n dependency.IsSelected = true;\n }\n finally\n {\n dependency.IsUpdatingFromCode = false;\n }\n \n // Apply the setting\n dependency.ApplySettingCommand?.Execute(null);\n \n // Check if the setting was successfully enabled\n if (!dependency.IsSelected)\n {\n _logService.Log(LogLevel.Warning, $\"Failed to enable required setting '{dependency.Name}'\");\n allSucceeded = false;\n }\n }\n \n return allSucceeded;\n }\n \n /// \n /// Determines if a setting can be enabled based on its dependencies.\n /// \n /// The ID of the setting to check.\n /// All available settings that might be dependencies.\n /// True if the setting can be enabled; otherwise, false.\n public bool CanEnableSetting(string settingId, IEnumerable allSettings)\n {\n if (string.IsNullOrEmpty(settingId))\n {\n _logService.Log(LogLevel.Warning, \"Cannot check dependencies for null or empty setting ID\");\n return false;\n }\n \n var setting = allSettings.FirstOrDefault(s => s.Id == settingId);\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, $\"Setting with ID '{settingId}' not found\");\n return false;\n }\n \n if (setting.Dependencies == null || !setting.Dependencies.Any())\n {\n return true; // No dependencies, so it can be enabled\n }\n \n foreach (var dependency in setting.Dependencies)\n {\n if (dependency.DependencyType == SettingDependencyType.RequiresEnabled)\n {\n var requiredSetting = allSettings.FirstOrDefault(s => s.Id == dependency.RequiredSettingId);\n if (requiredSetting != null && !requiredSetting.IsSelected)\n {\n _logService.Log(LogLevel.Warning, $\"Cannot enable '{setting.Name}' because '{requiredSetting.Name}' is disabled\");\n return false;\n }\n }\n else if (dependency.DependencyType == SettingDependencyType.RequiresDisabled)\n {\n var requiredSetting = allSettings.FirstOrDefault(s => s.Id == dependency.RequiredSettingId);\n if (requiredSetting != null && requiredSetting.IsSelected)\n {\n _logService.Log(LogLevel.Warning, $\"Cannot enable '{setting.Name}' because '{requiredSetting.Name}' is enabled\");\n return false;\n }\n }\n }\n \n return true;\n }\n \n /// \n /// Handles the disabling of a setting by automatically disabling any dependent settings.\n /// \n /// The ID of the setting that was disabled.\n /// All available settings that might depend on the disabled setting.\n public void HandleSettingDisabled(string settingId, IEnumerable allSettings)\n {\n if (string.IsNullOrEmpty(settingId))\n {\n _logService.Log(LogLevel.Warning, \"Cannot handle dependencies for null or empty setting ID\");\n return;\n }\n \n // Find all settings that depend on this setting\n var dependentSettings = allSettings.Where(s => \n s.Dependencies != null && \n s.Dependencies.Any(d => d.RequiredSettingId == settingId && \n d.DependencyType == SettingDependencyType.RequiresEnabled));\n \n foreach (var dependentSetting in dependentSettings)\n {\n if (dependentSetting.IsSelected)\n {\n _logService.Log(LogLevel.Info, $\"Automatically disabling '{dependentSetting.Name}' as '{settingId}' was disabled\");\n \n // Disable the dependent setting\n dependentSetting.IsUpdatingFromCode = true;\n try\n {\n dependentSetting.IsSelected = false;\n }\n finally\n {\n dependentSetting.IsUpdatingFromCode = false;\n }\n \n // Apply the change\n dependentSetting.ApplySettingCommand?.Execute(null);\n \n // Recursively handle any settings that depend on this one\n HandleSettingDisabled(dependentSetting.Id, allSettings);\n }\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/SoftwareAppsViewModel.cs", "using System;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n /// \n /// ViewModel for the SoftwareAppsView that coordinates WindowsApps and ExternalApps sections.\n /// \n public partial class SoftwareAppsViewModel : BaseViewModel\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly IPackageManager _packageManager;\n\n [ObservableProperty]\n private string _statusText =\n \"Manage Windows Apps, Capabilities & Features and Install External Software\";\n\n [ObservableProperty]\n private WindowsAppsViewModel _windowsAppsViewModel;\n\n [ObservableProperty]\n private ExternalAppsViewModel _externalAppsViewModel;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The task progress service.\n /// The package manager.\n /// The service provider for dependency resolution.\n public SoftwareAppsViewModel(\n ITaskProgressService progressService,\n IPackageManager packageManager,\n IServiceProvider serviceProvider\n )\n : base(progressService)\n {\n _packageManager =\n packageManager ?? throw new ArgumentNullException(nameof(packageManager));\n _serviceProvider =\n serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n\n // Resolve the dependencies via DI container\n WindowsAppsViewModel = _serviceProvider.GetRequiredService();\n ExternalAppsViewModel = _serviceProvider.GetRequiredService();\n }\n\n /// \n /// Initializes child view models and prepares the view.\n /// \n [RelayCommand]\n public async Task Initialize()\n {\n StatusText = \"Initializing Software Apps...\";\n IsLoading = true;\n\n try\n {\n // Initialize WindowsAppsViewModel if not already initialized\n if (!WindowsAppsViewModel.IsInitialized)\n {\n await WindowsAppsViewModel.LoadAppsAndCheckInstallationStatusAsync();\n }\n\n // Initialize ExternalAppsViewModel if not already initialized\n if (!ExternalAppsViewModel.IsInitialized)\n {\n await ExternalAppsViewModel.LoadAppsAndCheckInstallationStatusAsync();\n }\n\n StatusText =\n \"Manage Windows Apps, Capabilities & Features and Install External Software\";\n }\n catch (Exception ex)\n {\n StatusText = $\"Error initializing: {ex.Message}\";\n }\n finally\n {\n IsLoading = false;\n }\n }\n\n /// \n /// Called when the view is navigated to.\n /// \n /// Navigation parameter.\n public override async void OnNavigatedTo(object parameter)\n {\n try\n {\n // Initialize when navigated to this view\n await Initialize();\n }\n catch (Exception ex)\n {\n StatusText = $\"Error during navigation: {ex.Message}\";\n // Log the error or handle it appropriately\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/MessengerService.cs", "using System;\nusing System.Collections.Generic;\nusing CommunityToolkit.Mvvm.Messaging;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Messaging;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Implementation of IMessengerService that uses CommunityToolkit.Mvvm.Messenger\n /// \n public class MessengerService : IMessengerService\n {\n private readonly IMessenger _messenger;\n private readonly Dictionary> _recipientTokens;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public MessengerService()\n {\n _messenger = WeakReferenceMessenger.Default;\n _recipientTokens = new Dictionary>();\n }\n\n /// \n /// Initializes a new instance of the class with a specific messenger.\n /// \n /// The messenger to use.\n public MessengerService(IMessenger messenger)\n {\n _messenger = messenger ?? throw new ArgumentNullException(nameof(messenger));\n _recipientTokens = new Dictionary>();\n }\n\n /// \n void IMessengerService.Send(TMessage message)\n {\n // Only MessageBase objects can be sent with the messenger\n if (message is MessageBase msgBase)\n {\n _messenger.Send(msgBase);\n }\n }\n\n /// \n void IMessengerService.Register(object recipient, Action action)\n {\n // Only reference types can be registered with the messenger\n if (typeof(TMessage).IsClass && typeof(TMessage).IsAssignableTo(typeof(MessageBase)))\n {\n // We need to use dynamic here to handle the generic type constraints\n dynamic typedRecipient = recipient;\n dynamic typedAction = action;\n RegisterInternal(typedRecipient, typedAction);\n }\n }\n\n private void RegisterInternal(object recipient, Action action) \n where TMessage : MessageBase\n {\n // Register the recipient with the messenger\n _messenger.Register(recipient, (r, m) => action(m));\n \n // Create a token that will unregister the recipient when disposed\n var token = new RegistrationToken(() => _messenger.Unregister(recipient));\n\n // Keep track of the token for later cleanup\n if (!_recipientTokens.TryGetValue(recipient, out var tokens))\n {\n tokens = new List();\n _recipientTokens[recipient] = tokens;\n }\n\n tokens.Add(token);\n }\n\n /// \n /// A token that unregisters a recipient when disposed\n /// \n private class RegistrationToken : IDisposable\n {\n private readonly Action _unregisterAction;\n private bool _isDisposed;\n\n public RegistrationToken(Action unregisterAction)\n {\n _unregisterAction = unregisterAction;\n }\n\n public void Dispose()\n {\n if (!_isDisposed)\n {\n _unregisterAction();\n _isDisposed = true;\n }\n }\n }\n\n /// \n void IMessengerService.Unregister(object recipient)\n {\n if (_recipientTokens.TryGetValue(recipient, out var tokens))\n {\n foreach (var token in tokens)\n {\n token.Dispose();\n }\n\n _recipientTokens.Remove(recipient);\n }\n\n _messenger.UnregisterAll(recipient);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/FileSystemService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading.Tasks;\nusing Winhance.Core.Interfaces.Services;\n\nnamespace Winhance.Infrastructure.FileSystem\n{\n /// \n /// Implementation of IFileSystem that wraps the System.IO operations.\n /// \n public class FileSystemService : IFileSystemService\n {\n /// \n /// Determines whether the specified file exists.\n /// \n /// The file to check.\n /// True if the file exists; otherwise, false.\n public bool FileExists(string path)\n {\n return File.Exists(path);\n }\n\n /// \n /// Determines whether the specified directory exists.\n /// \n /// The directory to check.\n /// True if the directory exists; otherwise, false.\n public bool DirectoryExists(string path)\n {\n return Directory.Exists(path);\n }\n\n /// \n /// Creates a directory if it doesn't exist.\n /// \n /// The directory to create.\n /// True if the directory was created or already exists; otherwise, false.\n public bool CreateDirectory(string path)\n {\n try\n {\n if (!Directory.Exists(path))\n {\n Directory.CreateDirectory(path);\n }\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n /// Reads all text from a file.\n /// \n /// The file to read from.\n /// The text read from the file.\n public string ReadAllText(string path)\n {\n return File.ReadAllText(path);\n }\n\n /// \n /// Reads all text from a file asynchronously.\n /// \n /// The file to read from.\n /// A task that represents the asynchronous read operation and wraps the text read from the file.\n public async Task ReadAllTextAsync(string path)\n {\n using var reader = new StreamReader(path);\n return await reader.ReadToEndAsync();\n }\n\n /// \n /// Reads all bytes from a file.\n /// \n /// The file to read from.\n /// The bytes read from the file.\n public byte[] ReadAllBytes(string path)\n {\n return File.ReadAllBytes(path);\n }\n\n /// \n /// Reads all bytes from a file asynchronously.\n /// \n /// The file to read from.\n /// A task that represents the asynchronous read operation and wraps the bytes read from the file.\n public async Task ReadAllBytesAsync(string path)\n {\n return await File.ReadAllBytesAsync(path);\n }\n\n /// \n /// Writes text to a file.\n /// \n /// The file to write to.\n /// The text to write to the file.\n /// True if the text was written successfully; otherwise, false.\n public bool WriteAllText(string path, string contents)\n {\n try\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n File.WriteAllText(path, contents);\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n /// Writes text to a file asynchronously.\n /// \n /// The file to write to.\n /// The text to write to the file.\n /// A task that represents the asynchronous write operation.\n public async Task WriteAllTextAsync(string path, string contents)\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n await File.WriteAllTextAsync(path, contents);\n }\n \n /// \n /// Appends text to a file.\n /// \n /// The file to append to.\n /// The text to append to the file.\n public void AppendAllText(string path, string contents)\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n File.AppendAllText(path, contents);\n }\n \n /// \n /// Appends text to a file asynchronously.\n /// \n /// The file to append to.\n /// The text to append to the file.\n /// A task that represents the asynchronous append operation.\n public async Task AppendAllTextAsync(string path, string contents)\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n await File.AppendAllTextAsync(path, contents);\n }\n\n /// \n /// Writes bytes to a file.\n /// \n /// The file to write to.\n /// The bytes to write to the file.\n public void WriteAllBytes(string path, byte[] bytes)\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n File.WriteAllBytes(path, bytes);\n }\n\n /// \n /// Writes bytes to a file asynchronously.\n /// \n /// The file to write to.\n /// The bytes to write to the file.\n /// A task that represents the asynchronous write operation.\n public async Task WriteAllBytesAsync(string path, byte[] bytes)\n {\n // Ensure the directory exists\n var directory = Path.GetDirectoryName(path);\n if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))\n {\n Directory.CreateDirectory(directory);\n }\n\n await File.WriteAllBytesAsync(path, bytes);\n }\n\n /// \n /// Deletes a file.\n /// \n /// The file to delete.\n /// True if the file was deleted or didn't exist; otherwise, false.\n public bool DeleteFile(string path)\n {\n try\n {\n if (File.Exists(path))\n {\n File.Delete(path);\n }\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n /// \n /// Deletes a directory.\n /// \n /// The directory to delete.\n /// True to delete subdirectories and files; otherwise, false.\n public void DeleteDirectory(string path, bool recursive)\n {\n if (Directory.Exists(path))\n {\n Directory.Delete(path, recursive);\n }\n }\n\n /// \n /// Gets all files in a directory that match the specified pattern.\n /// \n /// The directory to search.\n /// The search pattern.\n /// Whether to search subdirectories.\n /// A collection of file paths.\n public IEnumerable GetFiles(string path, string pattern, bool recursive)\n {\n return Directory.GetFiles(path, pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);\n }\n\n /// \n /// Gets all directories in a directory that match the specified pattern.\n /// \n /// The directory to search.\n /// The search pattern.\n /// Whether to search subdirectories.\n /// A collection of directory paths.\n public IEnumerable GetDirectories(string path, string pattern, bool recursive)\n {\n return Directory.GetDirectories(path, pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);\n }\n \n /// \n /// Gets the path to a special folder, such as AppData, ProgramFiles, etc.\n /// \n /// The name of the special folder.\n /// The path to the special folder.\n public string GetSpecialFolderPath(string specialFolder)\n {\n if (Enum.TryParse(specialFolder, out var folder))\n {\n return Environment.GetFolderPath(folder);\n }\n return string.Empty;\n }\n \n /// \n /// Combines multiple paths into a single path.\n /// \n /// The paths to combine.\n /// The combined path.\n public string CombinePaths(params string[] paths)\n {\n return Path.Combine(paths);\n }\n \n /// \n /// Gets the current directory of the application.\n /// \n /// The current directory path.\n public string GetCurrentDirectory()\n {\n return Directory.GetCurrentDirectory();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/CustomAppInstallationService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Enums;\nusing Winhance.Core.Features.SoftwareApps.Exceptions;\nusing Winhance.Core.Features.SoftwareApps.Helpers;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services;\n\n/// \n/// Service that handles custom application installations.\n/// \npublic class CustomAppInstallationService : ICustomAppInstallationService\n{\n private readonly ILogService _logService;\n private readonly IOneDriveInstallationService _oneDriveInstallationService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n /// The OneDrive installation service.\n public CustomAppInstallationService(\n ILogService logService,\n IOneDriveInstallationService oneDriveInstallationService)\n {\n _logService = logService;\n _oneDriveInstallationService = oneDriveInstallationService;\n }\n\n /// \n public async Task InstallCustomAppAsync(\n AppInfo appInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n try\n {\n // Handle different custom app installations based on package name\n switch (appInfo.PackageName.ToLowerInvariant())\n {\n case \"onedrive\":\n return await _oneDriveInstallationService.InstallOneDriveAsync(progress, cancellationToken);\n\n // Add other custom app installation cases here\n // case \"some-app\":\n // return await InstallSomeAppAsync(progress, cancellationToken);\n\n default:\n throw new NotSupportedException(\n $\"Custom installation for '{appInfo.PackageName}' is not supported.\"\n );\n }\n }\n catch (Exception ex)\n {\n var errorType = InstallationErrorHelper.DetermineErrorType(ex.Message);\n var errorMessage = InstallationErrorHelper.GetUserFriendlyErrorMessage(errorType);\n\n progress?.Report(\n new TaskProgressDetail\n {\n Progress = 0,\n StatusText = $\"Error in custom installation for {appInfo.Name}: {errorMessage}\",\n DetailedMessage = $\"Exception during custom installation: {ex.Message}\",\n LogLevel = LogLevel.Error,\n AdditionalInfo = new Dictionary\n {\n { \"ErrorType\", errorType.ToString() },\n { \"PackageName\", appInfo.PackageName },\n { \"AppName\", appInfo.Name },\n { \"IsCustomInstall\", \"True\" },\n { \"OriginalError\", ex.Message }\n }\n }\n );\n\n return false;\n }\n }\n\n /// \n public async Task CheckInternetConnectionAsync()\n {\n try\n {\n // Try to reach a reliable site to check for internet connectivity\n using var client = new HttpClient();\n client.Timeout = TimeSpan.FromSeconds(5);\n var response = await client.GetAsync(\"https://www.google.com\");\n return response.IsSuccessStatusCode;\n }\n catch\n {\n return false;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/WindowsAppsConfigurationApplier.cs", "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for applying configuration to the WindowsApps section.\n /// \n public class WindowsAppsConfigurationApplier : ISectionConfigurationApplier\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n private readonly IViewModelRefresher _viewModelRefresher;\n private readonly IConfigurationPropertyUpdater _propertyUpdater;\n\n /// \n /// Gets the section name that this applier handles.\n /// \n public string SectionName => \"WindowsApps\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n /// The view model refresher.\n /// The property updater.\n public WindowsAppsConfigurationApplier(\n IServiceProvider serviceProvider,\n ILogService logService,\n IViewModelRefresher viewModelRefresher,\n IConfigurationPropertyUpdater propertyUpdater)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _viewModelRefresher = viewModelRefresher ?? throw new ArgumentNullException(nameof(viewModelRefresher));\n _propertyUpdater = propertyUpdater ?? throw new ArgumentNullException(nameof(propertyUpdater));\n }\n\n /// \n /// Applies the configuration to the WindowsApps section.\n /// \n /// The configuration file to apply.\n /// True if any items were updated, false otherwise.\n public async Task ApplyConfigAsync(ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Applying configuration to WindowsAppsViewModel\");\n \n var viewModel = _serviceProvider.GetService();\n if (viewModel == null)\n {\n _logService.Log(LogLevel.Warning, \"WindowsAppsViewModel not available\");\n return false;\n }\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, \"WindowsAppsViewModel not initialized, initializing now\");\n await viewModel.LoadItemsAsync();\n }\n \n // Apply the configuration directly to the view model's items\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Items, configFile);\n \n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in WindowsAppsViewModel\");\n \n // Refresh the UI\n await _viewModelRefresher.RefreshViewModelAsync(viewModel);\n \n return updatedCount > 0;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying WindowsApps configuration: {ex.Message}\");\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ExternalAppsConfigurationApplier.cs", "using System;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.SoftwareApps.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Service for applying configuration to the ExternalApps section.\n /// \n public class ExternalAppsConfigurationApplier : ISectionConfigurationApplier\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly ILogService _logService;\n private readonly IViewModelRefresher _viewModelRefresher;\n private readonly IConfigurationPropertyUpdater _propertyUpdater;\n\n /// \n /// Gets the section name that this applier handles.\n /// \n public string SectionName => \"ExternalApps\";\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service provider.\n /// The log service.\n /// The view model refresher.\n /// The property updater.\n public ExternalAppsConfigurationApplier(\n IServiceProvider serviceProvider,\n ILogService logService,\n IViewModelRefresher viewModelRefresher,\n IConfigurationPropertyUpdater propertyUpdater)\n {\n _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n _viewModelRefresher = viewModelRefresher ?? throw new ArgumentNullException(nameof(viewModelRefresher));\n _propertyUpdater = propertyUpdater ?? throw new ArgumentNullException(nameof(propertyUpdater));\n }\n\n /// \n /// Applies the configuration to the ExternalApps section.\n /// \n /// The configuration file to apply.\n /// True if any items were updated, false otherwise.\n public async Task ApplyConfigAsync(ConfigurationFile configFile)\n {\n try\n {\n _logService.Log(LogLevel.Info, \"Applying configuration to ExternalAppsViewModel\");\n \n var viewModel = _serviceProvider.GetService();\n if (viewModel == null)\n {\n _logService.Log(LogLevel.Warning, \"ExternalAppsViewModel not available\");\n return false;\n }\n \n // Ensure the view model is initialized\n if (!viewModel.IsInitialized)\n {\n _logService.Log(LogLevel.Info, \"ExternalAppsViewModel not initialized, initializing now\");\n await viewModel.LoadItemsAsync();\n }\n \n // Apply the configuration directly to the view model's items\n int updatedCount = await _propertyUpdater.UpdateItemsAsync(viewModel.Items, configFile);\n \n _logService.Log(LogLevel.Info, $\"Updated {updatedCount} items in ExternalAppsViewModel\");\n \n // Refresh the UI\n await _viewModelRefresher.RefreshViewModelAsync(viewModel);\n \n return updatedCount > 0;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error applying ExternalApps configuration: {ex.Message}\");\n return false;\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IRegistryService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides access to the Windows registry.\n /// \n public interface IRegistryService\n {\n /// \n /// Sets a value in the registry.\n /// \n /// The registry key path.\n /// The name of the value to set.\n /// The value to set.\n /// The type of the value.\n /// True if the operation succeeded; otherwise, false.\n bool SetValue(string keyPath, string valueName, object value, Microsoft.Win32.RegistryValueKind valueKind);\n\n /// \n /// Gets a value from the registry.\n /// \n /// The registry key path.\n /// The name of the value to get.\n /// The value from the registry, or null if it doesn't exist.\n object? GetValue(string keyPath, string valueName);\n\n /// \n /// Deletes a value from the registry.\n /// \n /// The registry key path.\n /// The name of the value to delete.\n /// True if the operation succeeded; otherwise, false.\n bool DeleteValue(string keyPath, string valueName);\n\n /// \n /// Deletes a value from the registry using hive and subkey.\n /// \n /// The registry hive.\n /// The registry subkey.\n /// The name of the value to delete.\n /// True if the operation succeeded; otherwise, false.\n Task DeleteValue(RegistryHive hive, string subKey, string valueName);\n\n /// \n /// Exports a registry key to a string.\n /// \n /// The registry key path to export.\n /// Whether to include subkeys in the export.\n /// The exported registry key as a string.\n Task ExportKey(string keyPath, bool includeSubKeys);\n\n /// \n /// Gets the status of a registry setting.\n /// \n /// The registry setting to check.\n /// The status of the registry setting.\n Task GetSettingStatusAsync(RegistrySetting setting);\n\n /// \n /// Gets the current value of a registry setting.\n /// \n /// The registry setting to check.\n /// The current value of the registry setting, or null if it doesn't exist.\n Task GetCurrentValueAsync(RegistrySetting setting);\n\n /// \n /// Determines whether a registry key exists.\n /// \n /// The registry key path.\n /// True if the key exists; otherwise, false.\n bool KeyExists(string keyPath);\n\n /// \n /// Creates a registry key.\n /// \n /// The registry key path.\n /// True if the operation succeeded; otherwise, false.\n bool CreateKey(string keyPath);\n\n /// \n /// Creates a registry key if it doesn't exist.\n /// \n /// The full path to the registry key.\n /// True if the key exists or was created successfully; otherwise, false.\n bool CreateKeyIfNotExists(string keyPath);\n\n /// \n /// Determines whether a registry value exists.\n /// \n /// The registry key path.\n /// The name of the value to check.\n /// True if the value exists; otherwise, false.\n bool ValueExists(string keyPath, string valueName);\n\n /// \n /// Deletes a registry key and all its values.\n /// \n /// The full path to the registry key to delete.\n /// True if the key was successfully deleted, false otherwise.\n bool DeleteKey(string keyPath);\n\n /// \n /// Deletes a registry key and all its values.\n /// \n /// The registry hive.\n /// The subkey path.\n /// True if the key was successfully deleted, false otherwise.\n Task DeleteKey(RegistryHive hive, string subKey);\n\n /// \n /// Tests a registry setting.\n /// \n /// The registry key path.\n /// The name of the value to test.\n /// The desired value.\n /// The status of the registry setting.\n RegistrySettingStatus TestRegistrySetting(string keyPath, string valueName, object desiredValue);\n\n /// \n /// Backs up the Windows registry.\n /// \n /// The path where the backup should be stored.\n /// True if the operation succeeded; otherwise, false.\n Task BackupRegistry(string backupPath);\n\n /// \n /// Restores the Windows registry from a backup.\n /// \n /// The path to the backup file.\n /// True if the operation succeeded; otherwise, false.\n Task RestoreRegistry(string backupPath);\n\n /// \n /// Applies customization settings to the registry.\n /// \n /// The settings to apply.\n /// True if all settings were applied successfully; otherwise, false.\n Task ApplyCustomizations(List settings);\n\n /// \n /// Restores customization settings to their default values.\n /// \n /// The settings to restore.\n /// True if all settings were restored successfully; otherwise, false.\n Task RestoreCustomizationDefaults(List settings);\n\n /// \n /// Applies power plan settings to the registry.\n /// \n /// The settings to apply.\n /// True if all settings were applied successfully; otherwise, false.\n Task ApplyPowerPlanSettings(List settings);\n\n /// \n /// Restores power plan settings to their default values.\n /// \n /// True if all settings were restored successfully; otherwise, false.\n Task RestoreDefaultPowerSettings();\n\n /// \n /// Gets the status of linked registry settings.\n /// \n /// The linked registry settings to check.\n /// The combined status of the linked registry settings.\n Task GetLinkedSettingsStatusAsync(LinkedRegistrySettings linkedSettings);\n\n /// \n /// Applies linked registry settings.\n /// \n /// The linked registry settings to apply.\n /// Whether to enable or disable the settings.\n /// True if all settings were applied successfully; otherwise, false.\n Task ApplyLinkedSettingsAsync(LinkedRegistrySettings linkedSettings, bool enable);\n\n /// \n /// Clears all registry caches to ensure fresh reads\n /// \n void ClearRegistryCaches();\n\n /// \n /// Gets the status of an optimization setting that may contain multiple registry settings.\n /// \n /// The optimization setting to check.\n /// The combined status of the optimization setting.\n Task GetOptimizationSettingStatusAsync(Winhance.Core.Features.Optimize.Models.OptimizationSetting setting);\n\n /// \n /// Applies an optimization setting that may contain multiple registry settings.\n /// \n /// The optimization setting to apply.\n /// Whether to enable or disable the setting.\n /// True if the setting was applied successfully; otherwise, false.\n Task ApplyOptimizationSettingAsync(Winhance.Core.Features.Optimize.Models.OptimizationSetting setting, bool enable);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/ViewModels/UpdateNotificationViewModel.cs", "using System;\nusing System.Threading.Tasks;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.ViewModels\n{\n public partial class UpdateNotificationViewModel : ObservableObject\n {\n private readonly IVersionService _versionService;\n private readonly ILogService _logService;\n private readonly IDialogService _dialogService;\n \n [ObservableProperty]\n private string _currentVersion = string.Empty;\n \n [ObservableProperty]\n private string _latestVersion = string.Empty;\n \n [ObservableProperty]\n private bool _isUpdateAvailable;\n \n [ObservableProperty]\n private bool _isDownloading;\n \n [ObservableProperty]\n private string _statusMessage = string.Empty;\n \n public UpdateNotificationViewModel(\n IVersionService versionService,\n ILogService logService,\n IDialogService dialogService)\n {\n _versionService = versionService;\n _logService = logService;\n _dialogService = dialogService;\n \n VersionInfo currentVersion = _versionService.GetCurrentVersion();\n CurrentVersion = currentVersion.Version;\n }\n \n [RelayCommand]\n private async Task CheckForUpdateAsync()\n {\n try\n {\n StatusMessage = \"Checking for updates...\";\n \n VersionInfo latestVersion = await _versionService.CheckForUpdateAsync();\n LatestVersion = latestVersion.Version;\n IsUpdateAvailable = latestVersion.IsUpdateAvailable;\n \n StatusMessage = IsUpdateAvailable \n ? $\"Update available: {LatestVersion}\" \n : \"You have the latest version.\";\n \n return;\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error checking for updates: {ex.Message}\", ex);\n StatusMessage = \"Error checking for updates.\";\n }\n }\n \n [RelayCommand]\n private async Task DownloadAndInstallUpdateAsync()\n {\n if (!IsUpdateAvailable)\n return;\n \n try\n {\n IsDownloading = true;\n StatusMessage = \"Downloading update...\";\n \n await _versionService.DownloadAndInstallUpdateAsync();\n \n StatusMessage = \"Update downloaded. Installing...\";\n \n // Notify the user that the application will close\n await _dialogService.ShowInformationAsync(\n \"The installer has been launched. The application will now close.\",\n \"Update\");\n \n // Close the application\n System.Windows.Application.Current.Shutdown();\n }\n catch (Exception ex)\n {\n _logService.Log(LogLevel.Error, $\"Error downloading update: {ex.Message}\", ex);\n StatusMessage = \"Error downloading update.\";\n IsDownloading = false;\n }\n }\n \n [RelayCommand]\n private void RemindLater()\n {\n // Just close the dialog, will check again next time\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/INavigationService.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for navigating between views in the application.\n /// \n public interface INavigationService\n {\n /// \n /// Navigates to a view.\n /// \n /// The name of the view to navigate to.\n /// True if navigation was successful; otherwise, false.\n bool NavigateTo(string viewName);\n\n /// \n /// Navigates to a view with parameters.\n /// \n /// The name of the view to navigate to.\n /// The navigation parameter.\n /// True if navigation was successful; otherwise, false.\n bool NavigateTo(string viewName, object parameter);\n\n /// \n /// Navigates back to the previous view.\n /// \n /// True if navigation was successful; otherwise, false.\n bool NavigateBack();\n\n /// \n /// Gets the current view name.\n /// \n string CurrentView { get; }\n\n /// \n /// Event raised when navigation occurs.\n /// \n event EventHandler? Navigated;\n\n /// \n /// Event raised before navigation occurs.\n /// \n event EventHandler? Navigating;\n\n /// \n /// Event raised when navigation fails.\n /// \n event EventHandler? NavigationFailed;\n }\n\n /// \n /// Event arguments for navigation events.\n /// \n public class NavigationEventArgs : EventArgs\n {\n /// \n /// Gets the source view name.\n /// \n public string SourceView { get; }\n\n /// \n /// Gets the target view name.\n /// \n public string TargetView { get; }\n\n /// \n /// Gets the navigation route (same as TargetView).\n /// \n public string Route => TargetView;\n\n /// \n /// Gets the view model type associated with the navigation.\n /// \n public Type? ViewModelType => Parameter?.GetType();\n\n /// \n /// Gets the navigation parameter.\n /// \n public object? Parameter { get; }\n\n /// \n /// Gets a value indicating whether the navigation can be canceled.\n /// \n public bool CanCancel { get; }\n\n /// \n /// Gets or sets a value indicating whether the navigation should be canceled.\n /// \n public bool Cancel { get; set; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The source view name.\n /// The target view name.\n /// The navigation parameter.\n /// Whether the navigation can be canceled.\n public NavigationEventArgs(\n string sourceView,\n string targetView,\n object? parameter = null,\n bool canCancel = false\n )\n {\n SourceView = sourceView;\n TargetView = targetView;\n Parameter = parameter;\n CanCancel = canCancel;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Controls/SearchBox.xaml.cs", "using System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\n\nnamespace Winhance.WPF.Features.Common.Controls\n{\n /// \n /// Interaction logic for SearchBox.xaml\n /// \n public partial class SearchBox : UserControl\n {\n /// \n /// Dependency property for the SearchText property.\n /// \n public static readonly DependencyProperty SearchTextProperty =\n DependencyProperty.Register(\n nameof(SearchText),\n typeof(string),\n typeof(SearchBox),\n new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSearchTextChanged));\n\n /// \n /// Dependency property for the Placeholder property.\n /// \n public static readonly DependencyProperty PlaceholderProperty =\n DependencyProperty.Register(\n nameof(Placeholder),\n typeof(string),\n typeof(SearchBox),\n new PropertyMetadata(\"Search...\"));\n\n /// \n /// Dependency property for the HasText property.\n /// \n public static readonly DependencyProperty HasTextProperty =\n DependencyProperty.Register(\n nameof(HasText),\n typeof(bool),\n typeof(SearchBox),\n new PropertyMetadata(false));\n\n /// \n /// Initializes a new instance of the class.\n /// \n public SearchBox()\n {\n InitializeComponent();\n }\n\n /// \n /// Gets or sets the search text.\n /// \n public string SearchText\n {\n get => (string)GetValue(SearchTextProperty);\n set => SetValue(SearchTextProperty, value);\n }\n\n /// \n /// Gets or sets the placeholder text.\n /// \n public string Placeholder\n {\n get => (string)GetValue(PlaceholderProperty);\n set => SetValue(PlaceholderProperty, value);\n }\n\n /// \n /// Gets a value indicating whether the search box has text.\n /// \n public bool HasText\n {\n get => (bool)GetValue(HasTextProperty);\n private set => SetValue(HasTextProperty, value);\n }\n\n /// \n /// Called when the search text changes.\n /// \n /// The dependency object.\n /// The event arguments.\n private static void OnSearchTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (d is SearchBox searchBox)\n {\n searchBox.HasText = !string.IsNullOrEmpty((string)e.NewValue);\n }\n }\n\n /// \n /// Handles the click event of the clear button.\n /// \n /// The sender.\n /// The event arguments.\n private void ClearButton_Click(object sender, RoutedEventArgs e)\n {\n SearchText = string.Empty;\n SearchTextBox.Focus();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/PowerShellScriptTemplateProvider.cs", "using System;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Provides PowerShell script templates with OS-specific adjustments.\n /// \n public class PowerShellScriptTemplateProvider : IScriptTemplateProvider\n {\n private readonly ISystemServices _systemService;\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The system service.\n /// The logging service.\n public PowerShellScriptTemplateProvider(\n ISystemServices systemService,\n ILogService logService)\n {\n _systemService = systemService ?? throw new ArgumentNullException(nameof(systemService));\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n public string GetPackageRemovalTemplate()\n {\n // Windows 10 compatibility: Don't use -AllUsers with Remove-AppxPackage\n return @\"Get-AppxPackage -Name \"\"{0}\"\" | Remove-AppxPackage -ErrorAction SilentlyContinue\nGet-AppxProvisionedPackage -Online | Where-Object {{ $_.DisplayName -eq \"\"{0}\"\" }} | Remove-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue\";\n }\n\n /// \n public string GetCapabilityRemovalTemplate()\n {\n return @\"Get-WindowsCapability -Online | Where-Object {{ $_.Name -like \"\"{0}*\"\" }} | Remove-WindowsCapability -Online\";\n }\n\n /// \n public string GetFeatureRemovalTemplate()\n {\n return @\"Write-Host \"\"Disabling optional feature: {0}\"\" -ForegroundColor Yellow\nDisable-WindowsOptionalFeature -Online -FeatureName \"\"{0}\"\" -NoRestart | Out-Null\";\n }\n\n /// \n public string GetRegistrySettingTemplate(bool isDelete)\n {\n if (isDelete)\n {\n return @\"reg delete \"\"{0}\"\" /v {1} /f | Out-Null\";\n }\n else\n {\n return @\"reg add \"\"{0}\"\" /v {1} /t REG_{2} /d {3} /f | Out-Null\";\n }\n }\n\n /// \n public string GetScriptHeader(string scriptName)\n {\n return $@\"# {scriptName}.ps1\n# This script removes Windows bloatware apps and prevents them from reinstalling\n# Source: Winhance (https://github.com/memstechtips/Winhance)\n# Generated by Winhance on {DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\")}\n\n\";\n }\n\n /// \n public string GetScriptFooter()\n {\n return @\"\n# Prevent apps from reinstalling\nreg add \"\"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\CloudContent\"\" /v DisableWindowsConsumerFeatures /t REG_DWORD /d 1 /f | Out-Null\n\nWrite-Host \"\"=== Script Completed ===\"\" -ForegroundColor Green\n\";\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ISystemServices.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Models.Enums;\nusing Winhance.Core.Features.Customize.Enums;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for system-level services that interact with the Windows operating system.\n /// \n public interface ISystemServices\n {\n /// \n /// Gets the registry service.\n /// \n IRegistryService RegistryService { get; }\n\n /// \n /// Restarts the Windows Explorer process.\n /// \n void RestartExplorer();\n\n /// \n /// Checks if the current user is an administrator.\n /// \n /// True if the current user is an administrator; otherwise, false.\n bool IsAdministrator();\n\n /// \n /// Gets the Windows version.\n /// \n /// A string representing the Windows version.\n string GetWindowsVersion();\n\n /// \n /// Refreshes the desktop.\n /// \n void RefreshDesktop();\n\n /// \n /// Checks if a process is running.\n /// \n /// The name of the process to check.\n /// True if the process is running; otherwise, false.\n bool IsProcessRunning(string processName);\n\n /// \n /// Kills a process.\n /// \n /// The name of the process to kill.\n void KillProcess(string processName);\n\n /// \n /// Checks if the operating system is Windows 11.\n /// \n /// True if the operating system is Windows 11; otherwise, false.\n bool IsWindows11();\n\n /// \n /// Requires administrator privileges.\n /// \n /// True if the application is running with administrator privileges; otherwise, false.\n bool RequireAdministrator();\n\n /// \n /// Checks if dark mode is enabled.\n /// \n /// True if dark mode is enabled; otherwise, false.\n bool IsDarkModeEnabled();\n\n /// \n /// Sets dark mode.\n /// \n /// True to enable dark mode; false to disable it.\n void SetDarkMode(bool enabled);\n\n /// \n /// Sets the UAC level.\n /// \n /// The UAC level to set.\n void SetUacLevel(Winhance.Core.Models.Enums.UacLevel level);\n\n /// \n /// Gets the UAC level.\n /// \n /// The current UAC level.\n Winhance.Core.Models.Enums.UacLevel GetUacLevel();\n\n /// \n /// Refreshes the Windows GUI.\n /// \n /// A task that represents the asynchronous operation. The task result contains a value indicating whether the operation succeeded.\n Task RefreshWindowsGUI();\n\n /// \n /// Refreshes the Windows GUI.\n /// \n /// True to kill the Explorer process; otherwise, false.\n /// A task that represents the asynchronous operation. The task result contains a value indicating whether the operation succeeded.\n Task RefreshWindowsGUI(bool killExplorer);\n\n /// \n /// Checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// True if internet is connected, false otherwise.\n bool IsInternetConnected(bool forceCheck = false);\n\n /// \n /// Asynchronously checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// Cancellation token for the operation.\n /// True if internet is connected, false otherwise.\n Task IsInternetConnectedAsync(bool forceCheck = false, CancellationToken cancellationToken = default, bool userInitiatedCancellation = false);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/VersionInfo.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n public class VersionInfo\n {\n public string Version { get; set; } = string.Empty;\n public DateTime ReleaseDate { get; set; }\n public string DownloadUrl { get; set; } = string.Empty;\n public bool IsUpdateAvailable { get; set; }\n \n public static VersionInfo FromTag(string tag)\n {\n // Parse version tag in format v25.05.02\n if (string.IsNullOrEmpty(tag) || !tag.StartsWith(\"v\"))\n return new VersionInfo();\n \n string versionString = tag.Substring(1); // Remove 'v' prefix\n string[] parts = versionString.Split('.');\n \n if (parts.Length != 3)\n return new VersionInfo();\n \n if (!int.TryParse(parts[0], out int year) || \n !int.TryParse(parts[1], out int month) || \n !int.TryParse(parts[2], out int day))\n return new VersionInfo();\n \n // Construct a date from the version components\n DateTime releaseDate;\n try\n {\n releaseDate = new DateTime(2000 + year, month, day);\n }\n catch\n {\n // Invalid date components\n return new VersionInfo();\n }\n \n return new VersionInfo\n {\n Version = tag,\n ReleaseDate = releaseDate\n };\n }\n \n public bool IsNewerThan(VersionInfo other)\n {\n if (other == null)\n return true;\n \n return ReleaseDate > other.ReleaseDate;\n }\n \n public override string ToString()\n {\n return Version;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/GamingandPerformanceOptimizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class GamingandPerformanceOptimizations\n{\n public static OptimizationGroup GetGamingandPerformanceOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Gaming and Performance\",\n Category = OptimizationCategory.GamingandPerformance,\n Settings = new List\n {\n new OptimizationSetting\n {\n Id = \"gaming-xbox-game-dvr\",\n Name = \"Xbox Game DVR\",\n Description = \"Controls Xbox Game DVR functionality\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Game Recording\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"System\\\\GameConfigStore\",\n Name = \"GameDVR_Enabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Game DVR is enabled\n DisabledValue = 0, // When toggle is OFF, Game DVR is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Game Bar and Game DVR functionality\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\GameConfigStore\",\n Name = \"AllowGameDVR\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Xbox Game DVR is enabled\n DisabledValue = 0, // When toggle is OFF, Xbox Game DVR is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Xbox GameDVR functionality\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"gaming-game-bar-controller\",\n Name = \"Game Bar Controller Access\",\n Description = \"Allow your controller to open Game Bar\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Game Bar\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\GameBar\",\n Name = \"UseNexusForGameBarEnabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, controller access is enabled\n DisabledValue = 0, // When toggle is OFF, controller access is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Xbox Game Bar access via game controller\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-game-mode\",\n Name = \"Game Mode\",\n Description = \"Controls Game Mode for optimized gaming performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Game Mode\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\GameBar\",\n Name = \"AutoGameModeEnabled\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Game Mode is enabled\n DisabledValue = 0, // When toggle is OFF, Game Mode is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Game Mode for optimized gaming performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-directx-optimizations\",\n Name = \"DirectX Optimizations\",\n Description = \"Changes DirectX settings for optimal gaming performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"DirectX\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\DirectX\\\\UserGpuPreferences\",\n Name = \"DirectXUserGlobalSettings\",\n RecommendedValue = \"SwapEffectUpgradeEnable=1;VRROptimizeEnable=0;\", // For backward compatibility\n EnabledValue = \"SwapEffectUpgradeEnable=1;VRROptimizeEnable=0;\", // When toggle is ON, optimizations are enabled\n DisabledValue = \"\", // When toggle is OFF, use default settings\n ValueType = RegistryValueKind.String,\n DefaultValue = \"SwapEffectUpgradeEnable=1;VRROptimizeEnable=0;\", // Default value when registry key exists but no value is set\n Description =\n \"Controls DirectX settings for optimal gaming performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-nvidia-sharpening\",\n Name = \"Old Nvidia Sharpening\",\n Description = \"Controls Nvidia sharpening for image quality\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Nvidia\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"Software\\\\NVIDIA Corporation\\\\Global\\\\FTS\",\n Name = \"EnableGR535\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, old Nvidia sharpening is enabled (0 = enabled for this setting)\n DisabledValue = 1, // When toggle is OFF, old Nvidia sharpening is disabled (1 = disabled for this setting)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Nvidia sharpening for image quality\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-high-precision-event-timer\",\n Name = \"High Precision Event Timer\",\n Description = \"Controls the High Precision Event Timer (HPET) for improved system performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n CommandSettings = new List\n {\n new CommandSetting\n {\n Id = \"hpet-platform-clock\",\n Category = \"Gaming\",\n Description = \"Controls the platform clock setting for HPET\",\n EnabledCommand = \"bcdedit /set useplatformclock true\",\n DisabledCommand = \"bcdedit /deletevalue useplatformclock\",\n RequiresElevation = true,\n IsPrimary = true\n },\n new CommandSetting\n {\n Id = \"hpet-dynamic-tick\",\n Category = \"Gaming\",\n Description = \"Controls the dynamic tick setting for HPET\",\n EnabledCommand = \"bcdedit /set disabledynamictick no\",\n DisabledCommand = \"bcdedit /set disabledynamictick yes\",\n RequiresElevation = true,\n IsPrimary = false\n }\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"gaming-system-responsiveness\",\n Name = \"System Responsiveness for Games\",\n Description = \"Controls system responsiveness for multimedia applications\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Multimedia\\\\SystemProfile\",\n Name = \"SystemResponsiveness\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, system responsiveness is optimized for games (0 = prioritize foreground)\n DisabledValue = 10, // When toggle is OFF, system responsiveness is balanced (10 = default Windows value)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 10, // Default value when registry key exists but no value is set\n Description =\n \"Controls system responsiveness for multimedia applications\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-network-throttling\",\n Name = \"Network Throttling for Gaming\",\n Description = \"Controls network throttling for optimal gaming performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Multimedia\\\\SystemProfile\",\n Name = \"NetworkThrottlingIndex\",\n RecommendedValue = 10, // For backward compatibility\n EnabledValue = 10, // When toggle is ON, network throttling is disabled (10 = disabled)\n DisabledValue = 5, // When toggle is OFF, network throttling is enabled (default Windows value)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 5, // Default value when registry key exists but no value is set\n Description =\n \"Controls network throttling for optimal gaming performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-gpu-priority\",\n Name = \"GPU Priority for Gaming\",\n Description = \"Controls GPU priority for gaming performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Multimedia\\\\SystemProfile\\\\Tasks\\\\Games\",\n Name = \"GPU Priority\",\n RecommendedValue = 8, // For backward compatibility\n EnabledValue = 8, // When toggle is ON, GPU priority is high (8 = high priority)\n DisabledValue = 2, // When toggle is OFF, GPU priority is normal (default Windows value)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls GPU priority for gaming performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-cpu-priority\",\n Name = \"CPU Priority for Gaming\",\n Description = \"Controls CPU priority for gaming performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Multimedia\\\\SystemProfile\\\\Tasks\\\\Games\",\n Name = \"Priority\",\n RecommendedValue = 6, // For backward compatibility\n EnabledValue = 6, // When toggle is ON, CPU priority is high (6 = high priority)\n DisabledValue = 2, // When toggle is OFF, CPU priority is normal (default Windows value)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls CPU priority for gaming performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-scheduling-category\",\n Name = \"High Scheduling Category for Gaming\",\n Description = \"Controls scheduling category for games\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Multimedia\\\\SystemProfile\\\\Tasks\\\\Games\",\n Name = \"Scheduling Category\",\n RecommendedValue = \"High\", // For backward compatibility\n EnabledValue = \"High\", // When toggle is ON, scheduling category is high\n DisabledValue = \"Medium\", // When toggle is OFF, scheduling category is medium (default Windows value)\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Medium\", // Default value when registry key exists but no value is set\n Description = \"Controls scheduling category for games\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-gpu-scheduling\",\n Name = \"Hardware-Accelerated GPU Scheduling\",\n Description = \"Controls hardware-accelerated GPU scheduling\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"System\\\\CurrentControlSet\\\\Control\\\\GraphicsDrivers\",\n Name = \"HwSchMode\",\n RecommendedValue = 2, // For backward compatibility\n EnabledValue = 2, // When toggle is ON, hardware-accelerated GPU scheduling is enabled\n DisabledValue = 1, // When toggle is OFF, hardware-accelerated GPU scheduling is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls hardware-accelerated GPU scheduling\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-win32-priority\",\n Name = \"Win32 Priority Separation\",\n Description = \"Controls Win32 priority separation for program performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"System\\\\CurrentControlSet\\\\Control\\\\PriorityControl\",\n Name = \"Win32PrioritySeparation\",\n RecommendedValue = 38, // For backward compatibility\n EnabledValue = 38, // When toggle is ON, priority is set for best performance of programs\n DisabledValue = 2, // When toggle is OFF, priority is set to default Windows value\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description =\n \"Controls Win32 priority separation for program performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"gaming-storage-sense\",\n Name = \"Storage Sense\",\n Description = \"Controls Storage Sense functionality\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Gaming\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\StorageSense\",\n Name = \"AllowStorageSenseGlobal\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, Storage Sense is enabled\n DisabledValue = 0, // When toggle is OFF, Storage Sense is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Storage Sense functionality\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-animations\",\n Name = \"UI Animations\",\n Description = \"Controls UI animations for improved performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Visual Effects\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\\\\WindowMetrics\",\n Name = \"MinAnimate\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, animations are enabled\n DisabledValue = 0, // When toggle is OFF, animations are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls UI animations for improved performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-autostart-delay\",\n Name = \"Startup Delay for Apps\",\n Description = \"Controls startup delay for applications\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Startup\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Serialize\",\n Name = \"StartupDelayInMSec\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 10000, // When toggle is ON, startup delay is enabled (10 seconds)\n DisabledValue = 0, // When toggle is OFF, startup delay is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls startup delay for applications\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-background-services\",\n Name = \"Optimize Background Services\",\n Description = \"Controls background services for better performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Services\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\",\n Name = \"ServicesPipeTimeout\",\n RecommendedValue = 60000, // For backward compatibility\n EnabledValue = 30000, // When toggle is ON, services timeout is reduced (30 seconds)\n DisabledValue = 60000, // When toggle is OFF, services timeout is default (60 seconds)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 60000, // Default value when registry key exists but no value is set\n Description = \"Controls background services for better performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-desktop-composition\",\n Name = \"Desktop Composition Effects\",\n Description = \"Controls desktop composition effects\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Visual Effects\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\DWM\",\n Name = \"CompositionPolicy\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, desktop composition is enabled\n DisabledValue = 0, // When toggle is OFF, desktop composition is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls desktop composition effects\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-fast-startup\",\n Name = \"Fast Startup\",\n Description = \"Controls fast startup feature\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Startup\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Power\",\n Name = \"HiberbootEnabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, fast startup is enabled\n DisabledValue = 0, // When toggle is OFF, fast startup is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls fast startup feature\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-explorer-search\",\n Name = \"Optimize File Explorer Search\",\n Description = \"Controls file explorer search indexing\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Search\\\\Preferences\",\n Name = \"WholeFileSystem\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, search includes whole file system\n DisabledValue = 0, // When toggle is OFF, search is limited to indexed locations\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls file explorer search indexing\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-menu-animations\",\n Name = \"Menu Animations\",\n Description = \"Controls menu animations\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Visual Effects\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"MenuShowDelay\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 400, // When toggle is ON, menu animations are enabled (default delay)\n DisabledValue = 0, // When toggle is OFF, menu animations are disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = 400, // Default value when registry key exists but no value is set\n Description = \"Controls menu animations\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-prefetch\",\n Name = \"Prefetch Feature\",\n Description = \"Controls Windows prefetch feature\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Memory Management\\\\PrefetchParameters\",\n Name = \"EnablePrefetcher\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 3, // When toggle is ON, prefetch is enabled (3 = both application and boot prefetching)\n DisabledValue = 0, // When toggle is OFF, prefetch is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls Windows prefetch feature\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-remote-assistance\",\n Name = \"Remote Assistance\",\n Description = \"Controls remote assistance feature\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Services\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Remote Assistance\",\n Name = \"fAllowToGetHelp\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, remote assistance is enabled\n DisabledValue = 0, // When toggle is OFF, remote assistance is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls remote assistance feature\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-superfetch\",\n Name = \"Superfetch Service\",\n Description = \"Controls superfetch/SysMain service\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"System Performance\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\Session Manager\\\\Memory Management\\\\PrefetchParameters\",\n Name = \"EnableSuperfetch\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 3, // When toggle is ON, superfetch is enabled (3 = full functionality)\n DisabledValue = 0, // When toggle is OFF, superfetch is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls superfetch/SysMain service\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"performance-visual-effects\",\n Name = \"Optimize Visual Effects\",\n Description = \"Controls visual effects for best performance\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Visual Effects\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\VisualEffects\",\n Name = \"VisualFXSetting\",\n RecommendedValue = 2, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, visual effects are set to \"best appearance\" (1)\n DisabledValue = 2, // When toggle is OFF, visual effects are set to \"best performance\" (2)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls visual effects for best performance\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-mouse-precision\",\n Name = \"Enhanced Pointer Precision\",\n Description = \"Controls enhanced pointer precision (mouse acceleration)\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Mouse Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"MouseSpeed\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, enhanced pointer precision is enabled\n DisabledValue = 0, // When toggle is OFF, enhanced pointer precision is disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Controls enhanced pointer precision (mouse acceleration)\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-mouse-threshold1\",\n Name = \"Mouse Acceleration Threshold 1\",\n Description = \"Controls mouse acceleration threshold 1\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Mouse Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"MouseThreshold1\",\n RecommendedValue = 0,\n EnabledValue = 6, // When toggle is ON, mouse threshold 1 is enabled (default value)\n DisabledValue = 0, // When toggle is OFF, mouse threshold 1 is disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls mouse acceleration threshold 1\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-mouse-threshold2\",\n Name = \"Mouse Acceleration Threshold 2\",\n Description = \"Controls mouse acceleration threshold 2\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Mouse Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"MouseThreshold2\",\n RecommendedValue = 0,\n EnabledValue = 10, // When toggle is ON, mouse threshold 2 is enabled (default value)\n DisabledValue = 0, // When toggle is OFF, mouse threshold 2 is disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls mouse acceleration threshold 2\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-set-mouse-sensitivity\",\n Name = \"Set Mouse Sensitivity\",\n Description = \"Sets mouse sensitivity to 10\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"MouseSensitivity\",\n RecommendedValue = 10,\n EnabledValue = 10,\n DisabledValue = \"\", // Sets to default\n ValueType = RegistryValueKind.String,\n DefaultValue = \"\", // Default value when registry key exists but no value is set\n Description = \"Sets mouse sensitivity to 10\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-set-smooth-mouse-x-curve\",\n Name = \"Set Smooth Mouse X Curve\",\n Description = \"Sets SmoothMouseXCurve\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"SmoothMouseXCurve\",\n RecommendedValue = new byte[]\n {\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xC0,\n 0xCC,\n 0x0C,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x80,\n 0x99,\n 0x19,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x40,\n 0x66,\n 0x26,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x33,\n 0x33,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n },\n ValueType = RegistryValueKind.Binary,\n DefaultValue = new byte[]\n {\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xC0,\n 0xCC,\n 0x0C,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x80,\n 0x99,\n 0x19,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x40,\n 0x66,\n 0x26,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x33,\n 0x33,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n },\n Description = \"Sets SmoothMouseXCurve\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-set-smooth-mouse-y-curve\",\n Name = \"Set Smooth Mouse Y Curve\",\n Description = \"Sets SmoothMouseYCurve\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Mouse\",\n Name = \"SmoothMouseYCurve\",\n RecommendedValue = new byte[]\n {\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x38,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x70,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xA8,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xE0,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n },\n ValueType = RegistryValueKind.Binary,\n DefaultValue = new byte[]\n {\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x38,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x70,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xA8,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0xE0,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n },\n Description = \"Sets SmoothMouseYCurve\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-animations\",\n Name = \"System Animations\",\n Description = \"Controls animations and visual effects\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"UserPreferencesMask\",\n RecommendedValue = new byte[]\n {\n 0x90,\n 0x12,\n 0x03,\n 0x80,\n 0x10,\n 0x00,\n 0x00,\n 0x00,\n },\n EnabledValue = new byte[]\n {\n 0x9E,\n 0x3E,\n 0x07,\n 0x80,\n 0x12,\n 0x00,\n 0x00,\n 0x00,\n }, // When toggle is ON, animations are enabled\n DisabledValue = new byte[]\n {\n 0x90,\n 0x12,\n 0x03,\n 0x80,\n 0x10,\n 0x00,\n 0x00,\n 0x00,\n }, // When toggle is OFF, animations are disabled\n ValueType = RegistryValueKind.Binary,\n DefaultValue = new byte[]\n {\n 0x90,\n 0x12,\n 0x03,\n 0x80,\n 0x10,\n 0x00,\n 0x00,\n 0x00,\n },\n Description = \"Controls animations and visual effects\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-menu-show-delay\",\n Name = \"Menu Show Delay\",\n Description = \"Controls menu show delay\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"MenuShowDelay\",\n RecommendedValue = 0,\n EnabledValue = 400, // When toggle is ON, menu show delay is enabled (default value)\n DisabledValue = 0, // When toggle is OFF, menu show delay is disabled\n ValueType = RegistryValueKind.String,\n DefaultValue = 400, // Default value when registry key exists but no value is set\n Description = \"Controls menu show delay\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-set-visual-effects\",\n Name = \"Set Visual Effects\",\n Description = \"Sets appearance options to custom\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\VisualEffects\",\n Name = \"VisualFXSetting\",\n RecommendedValue = 3,\n EnabledValue = 3,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Sets appearance options to custom\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-taskbar-animations\",\n Name = \"Taskbar Animations\",\n Description = \"Controls taskbar animations\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"TaskbarAnimations\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, taskbar animations are enabled\n DisabledValue = 0, // When toggle is OFF, taskbar animations are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls taskbar animations\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"background-apps\",\n Name = \"Let Apps Run in Background\",\n Description = \"Controls whether apps can run in the background\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"Background Apps\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Performance\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\AppPrivacy\",\n Name = \"LetAppsRunInBackground\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, background apps are enabled\n DisabledValue = 0, // When toggle is OFF, background apps are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls whether apps can run in the background\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-alt-tab-filter\",\n Name = \"Alt+Tab Filter\",\n Description = \"Sets Alt+Tab to show open windows only\",\n Category = OptimizationCategory.GamingandPerformance,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"MultiTaskingAltTabFilter\",\n RecommendedValue = 3,\n EnabledValue = 3,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Sets Alt+Tab to show open windows only\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/OptimizationModels.cs", "using Microsoft.Win32;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Core.Features.Common.Models;\n\n// This class is deprecated. Use Winhance.Core.Features.Optimize.Models.OptimizationSetting instead.\n[System.Obsolete(\"This class is deprecated. Use Winhance.Core.Features.Optimize.Models.OptimizationSetting instead.\")]\npublic record OptimizationSetting\n{\n public required string Id { get; init; } // Unique identifier\n public required string Name { get; init; } // User-friendly name\n public required string Description { get; init; }\n public required OptimizationCategory Category { get; init; }\n public required string GroupName { get; init; } // Sub-group within category\n\n // Single registry setting (for backward compatibility)\n public RegistrySetting? RegistrySetting { get; init; }\n\n // Multiple registry settings (new approach)\n private LinkedRegistrySettings? _linkedRegistrySettings;\n public LinkedRegistrySettings LinkedRegistrySettings\n {\n get\n {\n // If LinkedRegistrySettings is null but RegistrySetting is not, create a new LinkedRegistrySettings with the single RegistrySetting\n if (_linkedRegistrySettings == null && RegistrySetting != null)\n {\n _linkedRegistrySettings = new LinkedRegistrySettings(RegistrySetting);\n }\n return _linkedRegistrySettings ?? new LinkedRegistrySettings();\n }\n init { _linkedRegistrySettings = value; }\n }\n\n // New approach: Use a collection of registry settings directly\n public List RegistrySettings { get; init; } = new List();\n \n // Linked settings configuration\n public LinkedSettingsLogic LinkedSettingsLogic { get; init; } = LinkedSettingsLogic.Any;\n\n // Dependencies between settings\n public List Dependencies { get; init; } = new List();\n\n public ControlType ControlType { get; init; } = ControlType.BinaryToggle; // Default to binary toggle\n public int? SliderSteps { get; init; } // For discrete sliders (null for binary toggles)\n public bool IsEnabled { get; init; } // Current state\n}\n\npublic record OptimizationGroup\n{\n public required string Name { get; init; }\n public required OptimizationCategory Category { get; init; }\n public required IReadOnlyList Settings { get; init; }\n}\n\n/// \n/// Represents a dependency between two settings.\n/// \n/// \n/// For example, \"Improve Inking and Typing\" requires \"Send Diagnostic Data\" to be enabled.\n/// \n/// \n/// new SettingDependency\n/// {\n/// DependencyType = SettingDependencyType.RequiresEnabled,\n/// DependentSettingId = \"privacy-improve-inking-typing-user\",\n/// RequiredSettingId = \"privacy-diagnostics-policy\"\n/// }\n/// \npublic record SettingDependency\n{\n /// \n /// The type of dependency.\n /// \n public SettingDependencyType DependencyType { get; init; }\n\n /// \n /// The ID of the setting that depends on another setting.\n /// \n public required string DependentSettingId { get; init; }\n\n /// \n /// The ID of the setting that is required by the dependent setting.\n /// \n public required string RequiredSettingId { get; init; }\n}\n\n/// \n/// The type of dependency between two settings.\n/// \npublic enum SettingDependencyType\n{\n /// \n /// The dependent setting requires the required setting to be enabled.\n /// \n RequiresEnabled,\n\n /// \n /// The dependent setting requires the required setting to be disabled.\n /// \n RequiresDisabled\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryExtensions.cs", "using System;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Extension methods for registry operations.\n /// \n public static class RegistryExtensions\n {\n /// \n /// Converts a RegistryHive enum to its string representation (HKCU, HKLM, etc.)\n /// \n /// The registry hive.\n /// The string representation of the registry hive.\n public static string GetRegistryHiveString(this RegistryHive hive)\n {\n return hive switch\n {\n RegistryHive.LocalMachine => \"HKLM\",\n RegistryHive.CurrentUser => \"HKCU\",\n RegistryHive.ClassesRoot => \"HKCR\",\n RegistryHive.Users => \"HKU\",\n RegistryHive.CurrentConfig => \"HKCC\",\n _ => throw new ArgumentException($\"Unsupported registry hive: {hive}\")\n };\n }\n\n /// \n /// Gets the full registry path by combining the hive and subkey.\n /// \n /// The registry hive.\n /// The registry subkey.\n /// The full registry path.\n public static string GetFullRegistryPath(this RegistryHive hive, string subKey)\n {\n return $\"{hive.GetRegistryHiveString()}\\\\{subKey}\";\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Services/SettingsRegistry.cs", "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Core.Features.Common.Services\n{\n /// \n /// Registry for settings.\n /// \n public class SettingsRegistry : ISettingsRegistry\n {\n private readonly ILogService _logService;\n private readonly List _settings = new List();\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public SettingsRegistry(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Registers a setting in the registry.\n /// \n /// The setting to register.\n public void RegisterSetting(ISettingItem setting)\n {\n if (setting == null)\n {\n _logService.Log(LogLevel.Warning, \"Cannot register null setting\");\n return;\n }\n\n if (string.IsNullOrEmpty(setting.Id))\n {\n _logService.Log(LogLevel.Warning, \"Cannot register setting with null or empty ID\");\n return;\n }\n\n lock (_settings)\n {\n // Check if the setting is already registered\n if (_settings.Any(s => s.Id == setting.Id))\n {\n _logService.Log(LogLevel.Info, $\"Setting with ID '{setting.Id}' is already registered\");\n return;\n }\n\n _settings.Add(setting);\n _logService.Log(LogLevel.Info, $\"Registered setting {setting.Id} in global settings collection\");\n }\n }\n\n /// \n /// Gets a setting by its ID.\n /// \n /// The ID of the setting to get.\n /// The setting if found, otherwise null.\n public ISettingItem? GetSettingById(string id)\n {\n if (string.IsNullOrEmpty(id))\n {\n _logService.Log(LogLevel.Warning, \"Cannot get setting with null or empty ID\");\n return null;\n }\n\n lock (_settings)\n {\n return _settings.FirstOrDefault(s => s.Id == id);\n }\n }\n\n /// \n /// Gets all settings in the registry.\n /// \n /// A list of all settings.\n public List GetAllSettings()\n {\n lock (_settings)\n {\n return new List(_settings);\n }\n }\n\n /// \n /// Gets all settings of a specific type.\n /// \n /// The type of settings to get.\n /// A list of settings of the specified type.\n public List GetSettingsByType() where T : ISettingItem\n {\n lock (_settings)\n {\n return _settings.OfType().Cast().ToList();\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/SoundOptimizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class SoundOptimizations\n{\n public static OptimizationGroup GetSoundOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Sound\",\n Category = OptimizationCategory.Sound,\n Settings = new List\n {\n new OptimizationSetting\n {\n Id = \"sound-startup\",\n Name = \"Startup Sound During Boot\",\n Description = \"Controls the startup sound during boot and for the user\",\n Category = OptimizationCategory.Sound,\n GroupName = \"System Sounds\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Authentication\\\\LogonUI\\\\BootAnimation\",\n Name = \"DisableStartupSound\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, startup sound is enabled\n DisabledValue = 1, // When toggle is OFF, startup sound is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls the startup sound during boot\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\EditionOverrides\",\n Name = \"UserSetting_DisableStartupSound\",\n RecommendedValue = 1, // For backward compatibility\n EnabledValue = 0, // When toggle is ON, user startup sound is enabled\n DisabledValue = 1, // When toggle is OFF, user startup sound is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls the startup sound for the user\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"sound-communication-ducking\",\n Name = \"Sound Ducking Preference\",\n Description = \"Controls sound behavior by reducing the volume of other sounds\",\n Category = OptimizationCategory.Sound,\n GroupName = \"System Sounds\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Multimedia\\\\Audio\",\n Name = \"UserDuckingPreference\",\n RecommendedValue = 3, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, sound ducking is enabled (1 = reduce other sounds by 80%)\n DisabledValue = 3, // When toggle is OFF, sound ducking is disabled (3 = do nothing)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls sound communications behavior\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"sound-voice-activation\",\n Name = \"Voice Activation for Apps\",\n Description = \"Controls voice activation for all apps\",\n Category = OptimizationCategory.Sound,\n GroupName = \"System Sounds\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\SpeechOneCore\\\\Settings\",\n Name = \"AgentActivationEnabled\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, voice activation is enabled\n DisabledValue = 0, // When toggle is OFF, voice activation is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls voice activation for all apps\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"sound-voice-activation-last-used\",\n Name = \"Last Used Voice Activation Setting\",\n Description = \"Controls the last used voice activation setting\",\n Category = OptimizationCategory.Sound,\n GroupName = \"System Sounds\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\SpeechOneCore\\\\Settings\",\n Name = \"AgentActivationLastUsed\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, last used voice activation is enabled\n DisabledValue = 0, // When toggle is OFF, last used voice activation is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls the last used voice activation setting\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"sound-effects-enhancements\",\n Name = \"Sound Effects and Enhancements\",\n Description = \"Controls audio enhancements for playback devices\",\n Category = OptimizationCategory.Sound,\n GroupName = \"Audio Enhancements\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Multimedia\\\\Audio\\\\DeviceFx\",\n Name = \"EnableDeviceEffects\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, audio enhancements are enabled\n DisabledValue = 0, // When toggle is OFF, audio enhancements are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls audio enhancements for playback devices\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"sound-spatial-audio\",\n Name = \"Spatial Sound Settings\",\n Description = \"Controls Windows Sonic and spatial sound features\",\n Category = OptimizationCategory.Sound,\n GroupName = \"Audio Enhancements\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Sound\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Audio\",\n Name = \"EnableSpatialSound\",\n RecommendedValue = 0, // For backward compatibility\n EnabledValue = 1, // When toggle is ON, spatial sound is enabled\n DisabledValue = 0, // When toggle is OFF, spatial sound is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls Windows Sonic and spatial sound features\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/UpdateOptimizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class UpdateOptimizations\n{\n public static OptimizationGroup GetUpdateOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Windows Updates\",\n Category = OptimizationCategory.Updates,\n Settings = new List\n {\n new OptimizationSetting\n {\n Id = \"updates-auto-update\",\n Name = \"Automatic Windows Updates\",\n Description = \"Controls automatic Windows updates behavior\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Windows Update Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\\\\AU\",\n Name = \"NoAutoUpdate\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, automatic updates are enabled\n DisabledValue = 1, // When toggle is OFF, automatic updates are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls automatic Windows updates\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\\\\AU\",\n Name = \"AUOptions\",\n RecommendedValue = 2,\n EnabledValue = 4, // When toggle is ON, auto download and schedule install (4)\n DisabledValue = 2, // When toggle is OFF, notify before download (2)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls automatic update behavior\",\n },\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\\\\AU\",\n Name = \"AutoInstallMinorUpdates\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, minor updates are installed automatically\n DisabledValue = 0, // When toggle is OFF, minor updates are not installed automatically\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls automatic installation of minor updates\",\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"updates-defer-feature-updates\",\n Name = \"Delay Feature Updates for 365 Days\",\n Description = \"Delays major Windows feature updates for 365 days\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Windows Update Policies\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"DeferFeatureUpdates\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, feature updates are deferred\n DisabledValue = 0, // When toggle is OFF, feature updates are not deferred\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Enables deferral of feature updates\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"DeferFeatureUpdatesPeriodInDays\",\n RecommendedValue = 365,\n EnabledValue = 365, // When toggle is ON, feature updates are deferred for 365 days\n DisabledValue = 0, // When toggle is OFF, feature updates are not deferred\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Sets the deferral period for feature updates to 365 days\",\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"updates-defer-quality-updates\",\n Name = \"Delay Security Updates for 7 Days\",\n Description = \"Delays Windows security and quality updates for 7 days\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Windows Update Policies\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"DeferQualityUpdates\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, quality updates are deferred\n DisabledValue = 0, // When toggle is OFF, quality updates are not deferred\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Enables deferral of security and quality updates\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"DeferQualityUpdatesPeriodInDays\",\n RecommendedValue = 7,\n EnabledValue = 7, // When toggle is ON, quality updates are deferred for 7 days\n DisabledValue = 0, // When toggle is OFF, quality updates are not deferred\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Sets the deferral period for security and quality updates to 7 days\",\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n new OptimizationSetting\n {\n Id = \"updates-delivery-optimization\",\n Name = \"Delivery Optimization (LAN)\",\n Description = \"Controls peer-to-peer update distribution\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Delivery Optimization\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\DeliveryOptimization\",\n Name = \"DODownloadMode\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, peer-to-peer update distribution is enabled (LAN only)\n DisabledValue = 0, // When toggle is OFF, peer-to-peer update distribution is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls peer-to-peer update distribution\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-store-auto-download\",\n Name = \"Auto Update Microsoft Store Apps\",\n Description = \"Controls automatic updates for Microsoft Store apps\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Microsoft Store\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\WindowsStore\",\n Name = \"AutoDownload\",\n RecommendedValue = 2,\n EnabledValue = 4, // When toggle is ON, automatic updates for Microsoft Store apps are enabled\n DisabledValue = 2, // When toggle is OFF, automatic updates for Microsoft Store apps are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls automatic updates for Microsoft Store apps\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-app-archiving\",\n Name = \"Automatic Archiving of Unused Apps\",\n Description = \"Controls automatic archiving of unused apps\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Microsoft Store\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\Appx\",\n Name = \"AllowAutomaticAppArchiving\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, automatic archiving of unused apps is enabled\n DisabledValue = 0, // When toggle is OFF, automatic archiving of unused apps is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls automatic archiving of unused apps\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-restart-options\",\n Name = \"Prevent Automatic Restarts\",\n Description =\n \"Prevents automatic restarts after installing updates when users are logged on\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Update Behavior\",\n IsEnabled = true,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\\\\AU\",\n Name = \"NoAutoRebootWithLoggedOnUsers\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, automatic restarts are prevented\n DisabledValue = 1, // When toggle is OFF, automatic restarts are allowed\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls automatic restart behavior after updates\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-driver-controls\",\n Name = \"Do Not Include Drivers with Updates\",\n Description = \"Does not include driver updates with Windows quality updates\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Update Content\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"ExcludeWUDriversInQualityUpdate\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, driver updates are included\n DisabledValue = 1, // When toggle is OFF, driver updates are excluded\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Controls whether driver updates are included in Windows quality updates\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-notification-level\",\n Name = \"Update Notifications\",\n Description = \"Controls the visibility of update notifications\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Update Behavior\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\WindowsUpdate\",\n Name = \"SetUpdateNotificationLevel\",\n RecommendedValue = 1,\n EnabledValue = 2, // When toggle is ON, show all notifications (2 = default)\n DisabledValue = 1, // When toggle is OFF, show only restart required notifications (1 = reduced)\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 2, // Default value when registry key exists but no value is set\n Description = \"Controls the visibility level of update notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"updates-metered-connection\",\n Name = \"Updates on Metered Connections\",\n Description =\n \"Controls whether updates are downloaded over metered connections\",\n Category = OptimizationCategory.Updates,\n GroupName = \"Update Behavior\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Updates\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\WindowsUpdate\\\\UX\\\\Settings\",\n Name = \"AllowAutoWindowsUpdateDownloadOverMeteredNetwork\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, updates are downloaded over metered connections\n DisabledValue = 0, // When toggle is OFF, updates are not downloaded over metered connections\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description =\n \"Controls update download behavior on metered connections\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/ExplorerOptimizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class ExplorerOptimizations\n{\n public static OptimizationGroup GetExplorerOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Explorer\",\n Category = OptimizationCategory.Explorer,\n Settings = new List\n {\n new OptimizationSetting\n {\n Id = \"explorer-long-paths-enabled\",\n Name = \"Long Paths Enabled\",\n Description = \"Controls support for long file paths (up to 32,767 characters)\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SYSTEM\\\\CurrentControlSet\\\\Control\\\\FileSystem\",\n Name = \"LongPathsEnabled\",\n RecommendedValue = 1,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description =\n \"Controls support for long file paths (up to 32,767 characters)\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-block-aad-workplace-join\",\n Name = \"Block AAD Workplace Join\",\n Description = \"Controls 'Allow my organization to manage my device' pop-up\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\System\",\n Name = \"BlockAADWorkplaceJoin\",\n RecommendedValue = 1,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description =\n \"Controls 'Allow my organization to manage my device' pop-up\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-disable-sync-provider-notifications\",\n Name = \"Sync Provider Notifications\",\n Description = \"Controls sync provider notifications visibility\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"ShowSyncProviderNotifications\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls sync provider notifications visibility\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-tablet-mode\",\n Name = \"Tablet Mode\",\n Description = \"Controls Tablet Mode\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"System Interface\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ImmersiveShell\",\n Name = \"TabletMode\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, tablet mode is enabled\n DisabledValue = 0, // When toggle is OFF, tablet mode is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls Tablet Mode\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-desktop-mode-signin\",\n Name = \"Desktop Mode on Sign-in\",\n Description = \"Controls whether the system goes to desktop mode on sign-in\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"System Interface\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ImmersiveShell\",\n Name = \"SignInMode\",\n RecommendedValue = 1,\n EnabledValue = 1, // When toggle is ON, system goes to desktop mode on sign-in\n DisabledValue = 0, // When toggle is OFF, system uses default behavior\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description =\n \"Controls whether the system goes to desktop mode on sign-in\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-voice-typing\",\n Name = \"Voice Typing Button\",\n Description = \"Controls voice typing microphone button\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"Input Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\InputSettings\",\n Name = \"IsVoiceTypingKeyEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, voice typing is enabled\n DisabledValue = 0, // When toggle is OFF, voice typing is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls voice typing microphone button\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-typing-insights\",\n Name = \"Typing Insights\",\n Description = \"Controls typing insights and suggestions\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"Input Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\InputSettings\",\n Name = \"InsightsEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, typing insights are enabled\n DisabledValue = 0, // When toggle is OFF, typing insights are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls typing insights and suggestions\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-suggested-actions\",\n Name = \"Clipboard Suggested Actions\",\n Description = \"Controls suggested actions for clipboard content\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"System Interface\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\SmartActionPlatform\\\\SmartClipboard\",\n Name = \"Disabled\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, suggested actions are enabled\n DisabledValue = 1, // When toggle is OFF, suggested actions are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls suggested actions for clipboard content\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-windows-manage-printer\",\n Name = \"Default Printer Management\",\n Description = \"Controls Windows managing default printer\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"Printer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Windows\",\n Name = \"LegacyDefaultPrinterMode\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, Windows manages default printer\n DisabledValue = 1, // When toggle is OFF, Windows does not manage default printer\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls Windows managing default printer\",\n IsPrimary = true,\n AbsenceMeansEnabled = false,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-disable-snap-assist\",\n Name = \"Snap Assist\",\n Description = \"Controls Snap Assist feature\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"SnapAssist\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls Snap Assist feature\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-frequent-folders\",\n Name = \"Frequent Folders in Quick Access\",\n Description = \"Controls display of frequent folders in Quick Access\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\",\n Name = \"ShowFrequent\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, frequent folders are shown\n DisabledValue = 0, // When toggle is OFF, frequent folders are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls display of frequent folders in Quick Access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"compress-desktop-wallpaper\",\n Name = \"Compress Desktop Wallpaper\",\n Description = \"Controls compression of desktop wallpaper\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"Desktop Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"JPEGImportQuality\",\n RecommendedValue = 100,\n EnabledValue = 0,\n DisabledValue = 100,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls compression of desktop wallpaper\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n new OptimizationSetting\n {\n Id = \"explorer-office-files\",\n Name = \"Office Files in Quick Access\",\n Description = \"Controls display of files from Office.com in Quick Access\",\n Category = OptimizationCategory.Explorer,\n GroupName = \"File Explorer Settings\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Explorer\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\",\n Name = \"ShowCloudFilesInQuickAccess\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, Office.com files are shown\n DisabledValue = 0, // When toggle is OFF, Office.com files are hidden\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description =\n \"Controls display of files from Office.com in Quick Access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Services/LoggingService.cs", "using Microsoft.Extensions.Hosting;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System;\n\nnamespace Winhance.Core.Features.Common.Services\n{\n public class LoggingService : ILogService, IHostedService, IDisposable\n {\n private readonly ILogService _logService;\n \n public event EventHandler? LogMessageGenerated;\n\n public LoggingService(ILogService logService)\n {\n _logService = logService;\n \n // Subscribe to the inner log service events and forward them\n _logService.LogMessageGenerated += (sender, args) => \n {\n LogMessageGenerated?.Invoke(this, args);\n };\n }\n\n public void StartLog()\n {\n _logService.StartLog();\n }\n\n public void StopLog()\n {\n _logService.StopLog();\n }\n\n public Task StartAsync(CancellationToken cancellationToken)\n {\n _logService.StartLog();\n return Task.CompletedTask;\n }\n\n public Task StopAsync(CancellationToken cancellationToken)\n {\n _logService.StopLog();\n return Task.CompletedTask;\n }\n\n public void LogInformation(string message)\n {\n _logService.LogInformation(message);\n }\n\n public void LogWarning(string message)\n {\n _logService.LogWarning(message);\n }\n\n public void LogError(string message, Exception? exception)\n {\n _logService.LogError(message, exception);\n }\n\n public void LogSuccess(string message)\n {\n _logService.LogSuccess(message);\n }\n\n public void Log(LogLevel level, string message, Exception? exception = null)\n {\n _logService.Log(level, message, exception);\n }\n \n // Removed the incorrectly ordered Log method to fix the parameter order error\n // This was causing CS1503 errors with parameter type mismatches\n\n public string GetLogPath()\n {\n return _logService.GetLogPath();\n }\n\n public void Dispose()\n {\n if (_logService is IDisposable disposable)\n {\n disposable.Dispose();\n }\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/ExternalAppCatalog.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a catalog of external applications that can be installed.\n/// \npublic class ExternalAppCatalog\n{\n /// \n /// Gets or sets the collection of installable external applications.\n /// \n public IReadOnlyList ExternalApps { get; init; } = new List();\n\n /// \n /// Creates a default external app catalog with predefined installable apps.\n /// \n /// A new ExternalAppCatalog instance with default apps.\n public static ExternalAppCatalog CreateDefault()\n {\n return new ExternalAppCatalog { ExternalApps = CreateDefaultExternalApps() };\n }\n\n private static IReadOnlyList CreateDefaultExternalApps()\n {\n return new List\n {\n // Browsers\n new AppInfo\n {\n Name = \"Microsoft Edge WebView\",\n Description = \"WebView2 runtime for Windows applications\",\n PackageName = \"Microsoft.EdgeWebView2Runtime\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Thorium\",\n Description = \"Chromium-based browser with enhanced privacy features\",\n PackageName = \"Alex313031.Thorium\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Thorium AVX2\",\n Description = \"Chromium-based browser with enhanced privacy features\",\n PackageName = \"Alex313031.Thorium.AVX2\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Mercury\",\n Description = \"Compiler optimized, private Firefox fork\",\n PackageName = \"Alex313031.Mercury\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Firefox\",\n Description = \"Popular web browser known for privacy and customization\",\n PackageName = \"Mozilla.Firefox\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Chrome\",\n Description = \"Google's web browser with sync and extension support\",\n PackageName = \"Google.Chrome\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Ungoogled Chromium\",\n Description = \"Chromium-based browser with privacy enhancements\",\n PackageName = \"Eloston.Ungoogled-Chromium\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Brave\",\n Description = \"Privacy-focused browser with built-in ad blocking\",\n PackageName = \"Brave.Brave\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Opera\",\n Description = \"Feature-rich web browser with built-in VPN and ad blocker\",\n PackageName = \"Opera.Opera\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Opera GX\",\n Description = \"Gaming-oriented version of Opera with unique features\",\n PackageName = \"Opera.OperaGX\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Arc Browser\",\n Description = \"Innovative browser with a focus on design and user experience\",\n PackageName = \"TheBrowserCompany.Arc\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Tor Browser\",\n Description = \"Privacy-focused browser that routes traffic through the Tor network\",\n PackageName = \"TorProject.TorBrowser\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Vivaldi\",\n Description = \"Highly customizable browser with a focus on user control\",\n PackageName = \"Vivaldi.Vivaldi\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Waterfox\",\n Description = \"Firefox-based browser with a focus on privacy and customization\",\n PackageName = \"Waterfox.Waterfox\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Zen Browser\",\n Description = \"Privacy-focused browser with built-in ad blocking\",\n PackageName = \"Zen-Team.Zen-Browser\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Mullvad Browser\",\n Description =\n \"Privacy-focused browser designed to minimize tracking and fingerprints\",\n PackageName = \"MullvadVPN.MullvadBrowser\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Pale Moon Browser\",\n Description =\n \"Open Source, Goanna-based web browser focusing on efficiency and customization\",\n PackageName = \"MoonchildProductions.PaleMoon\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Maxthon Browser\",\n Description = \"Privacy focused browser with built-in ad blocking and VPN\",\n PackageName = \"Maxthon.Maxthon\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Floorp\",\n Description = \"Privacy focused browser with strong tracking protection\",\n PackageName = \"Ablaze.Floorp\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"DuckDuckGo\",\n Description = \"Privacy-focused search engine with a browser extension\",\n PackageName = \"DuckDuckGo.DesktopBrowser\",\n Category = \"Browsers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Document Viewers\n new AppInfo\n {\n Name = \"LibreOffice\",\n Description = \"Free and open-source office suite\",\n PackageName = \"TheDocumentFoundation.LibreOffice\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"ONLYOFFICE Desktop Editors\",\n Description = \"100% open-source free alternative to Microsoft Office\",\n PackageName = \"ONLYOFFICE.DesktopEditors\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Foxit Reader\",\n Description = \"Lightweight PDF reader with advanced features\",\n PackageName = \"Foxit.FoxitReader\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"SumatraPDF\",\n Description =\n \"PDF, eBook (epub, mobi), comic book (cbz/cbr), DjVu, XPS, CHM, image viewer for Windows\",\n PackageName = \"SumatraPDF.SumatraPDF\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"OpenOffice\",\n Description =\n \"Discontinued open-source office suite. Active successor projects is LibreOffice\",\n PackageName = \"Apache.OpenOffice\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Adobe Acrobat Reader DC\",\n Description = \"PDF reader and editor\",\n PackageName = \"XPDP273C0XHQH2\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Evernote\",\n Description = \"Note-taking app\",\n PackageName = \"Evernote.Evernote\",\n Category = \"Document Viewers\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Online Storage\n new AppInfo\n {\n Name = \"Google Drive\",\n Description = \"Cloud storage and file synchronization service\",\n PackageName = \"Google.GoogleDrive\",\n Category = \"Online Storage\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Dropbox\",\n Description =\n \"File hosting service that offers cloud storage, file synchronization, personal cloud\",\n PackageName = \"Dropbox.Dropbox\",\n Category = \"Online Storage\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"SugarSync\",\n Description =\n \"Automatically access and share your photos, videos, and files in any folder\",\n PackageName = \"IPVanish.SugarSync\",\n Category = \"Online Storage\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"NextCloud\",\n Description =\n \"Access, share and protect your files, calendars, contacts, communication & more at home and in your organization\",\n PackageName = \"Nextcloud.NextcloudDesktop\",\n Category = \"Online Storage\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Proton Drive\",\n Description = \"Secure cloud storage with end-to-end encryption\",\n PackageName = \"Proton.ProtonDrive\",\n Category = \"Online Storage\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Development Apps\n new AppInfo\n {\n Name = \"Python 3.13\",\n Description = \"Python programming language\",\n PackageName = \"Python.Python.3.13\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Notepad++\",\n Description = \"Free source code editor and Notepad replacement\",\n PackageName = \"Notepad++.Notepad++\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"WinSCP\",\n Description = \"Free SFTP, SCP, Amazon S3, WebDAV, and FTP client\",\n PackageName = \"WinSCP.WinSCP\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"PuTTY\",\n Description = \"Free SSH and telnet client\",\n PackageName = \"PuTTY.PuTTY\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"WinMerge\",\n Description = \"Open source differencing and merging tool\",\n PackageName = \"WinMerge.WinMerge\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Eclipse\",\n Description = \"Java IDE and development platform\",\n PackageName = \"EclipseFoundation.EclipseIDEforJavaDevelopers\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Visual Studio Code\",\n Description = \"Code editor with support for development operations\",\n PackageName = \"Microsoft.VisualStudioCode\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Git\",\n Description = \"Distributed version control system\",\n PackageName = \"Git.Git\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"GitHub Desktop\",\n Description = \"GitHub desktop client\",\n PackageName = \"GitHub.GitHubDesktop\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"AutoHotkey\",\n Description = \"Scripting language for desktop automation\",\n PackageName = \"AutoHotkey.AutoHotkey\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Windsurf\",\n Description = \"AI Code Editor\",\n PackageName = \"Codeium.Windsurf\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Cursor\",\n Description = \"AI Code Editor\",\n PackageName = \"Anysphere.Cursor\",\n Category = \"Development Apps\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Multimedia (Audio & Video)\n new AppInfo\n {\n Name = \"VLC\",\n Description = \"Open-source multimedia player and framework\",\n PackageName = \"VideoLAN.VLC\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"iTunes\",\n Description = \"Media player and library\",\n PackageName = \"Apple.iTunes\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"AIMP\",\n Description = \"Audio player with support for various formats\",\n PackageName = \"AIMP.AIMP\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"foobar2000\",\n Description = \"Advanced audio player for Windows\",\n PackageName = \"PeterPawlowski.foobar2000\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"MusicBee\",\n Description = \"Music manager and player\",\n PackageName = \"9P4CLT2RJ1RS\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Audacity\",\n Description = \"Audio editor and recorder\",\n PackageName = \"Audacity.Audacity\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"GOM\",\n Description = \"Media player for Windows\",\n PackageName = \"GOMLab.GOMPlayer\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Spotify\",\n Description = \"Music streaming service\",\n PackageName = \"Spotify.Spotify\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"MediaMonkey\",\n Description = \"Media manager and player\",\n PackageName = \"VentisMedia.MediaMonkey.5\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"HandBrake\",\n Description = \"Open-source video transcoder\",\n PackageName = \"HandBrake.HandBrake\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"OBS Studio\",\n Description =\n \"Free and open source software for video recording and live streaming\",\n PackageName = \"OBSProject.OBSStudio\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Streamlabs OBS\",\n Description = \"Streaming software built on OBS with additional features for streamers\",\n PackageName = \"Streamlabs.StreamlabsOBS\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"MPC-BE\",\n Description = \"Media Player Classic - Black Edition\",\n PackageName = \"MPC-BE.MPC-BE\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"K-Lite Codec Pack (Mega)\",\n Description = \"Collection of codecs and related tools\",\n PackageName = \"CodecGuide.K-LiteCodecPack.Mega\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"CapCut\",\n Description = \"Video editor\",\n PackageName = \"ByteDance.CapCut\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"PotPlayer\",\n Description = \"Comprehensive multimedia player for Windows\",\n PackageName = \"Daum.PotPlayer\",\n Category = \"Multimedia (Audio & Video)\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Imaging\n new AppInfo\n {\n Name = \"IrfanView\",\n Description = \"Fast and compact image viewer and converter\",\n PackageName = \"IrfanSkiljan.IrfanView\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Krita\",\n Description = \"Digital painting and illustration software\",\n PackageName = \"KDE.Krita\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Blender\",\n Description = \"3D creation suite\",\n PackageName = \"BlenderFoundation.Blender\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Paint.NET\",\n Description = \"Image and photo editing software\",\n PackageName = \"dotPDN.PaintDotNet\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"GIMP\",\n Description = \"GNU Image Manipulation Program\",\n PackageName = \"GIMP.GIMP.3\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"XnViewMP\",\n Description = \"Image viewer, browser and converter\",\n PackageName = \"XnSoft.XnViewMP\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"XnView Classic\",\n Description = \"Image viewer, browser and converter (Classic Version)\",\n PackageName = \"XnSoft.XnView.Classic\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Inkscape\",\n Description = \"Vector graphics editor\",\n PackageName = \"Inkscape.Inkscape\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Greenshot\",\n Description = \"Screenshot tool with annotation features\",\n PackageName = \"Greenshot.Greenshot\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"ShareX\",\n Description = \"Screen capture, file sharing and productivity tool\",\n PackageName = \"ShareX.ShareX\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Flameshot\",\n Description = \"Powerful yet simple to use screenshot software\",\n PackageName = \"Flameshot.Flameshot\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"FastStone\",\n Description = \"Image browser, converter and editor\",\n PackageName = \"FastStone.Viewer\",\n Category = \"Imaging\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Compression\n new AppInfo\n {\n Name = \"7-Zip\",\n Description = \"Open-source file archiver with a high compression ratio\",\n PackageName = \"7zip.7zip\",\n Category = \"Compression\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"WinRAR\",\n Description = \"File archiver with a high compression ratio\",\n PackageName = \"RARLab.WinRAR\",\n Category = \"Compression\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"PeaZip\",\n Description =\n \"Free file archiver utility. Open and extract RAR, TAR, ZIP files and more\",\n PackageName = \"Giorgiotani.Peazip\",\n Category = \"Compression\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"NanaZip\",\n Description =\n \"Open source fork of 7-zip intended for the modern Windows experience\",\n PackageName = \"M2Team.NanaZip\",\n Category = \"Compression\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Messaging, Email & Calendar\n new AppInfo\n {\n Name = \"Telegram\",\n Description = \"Instant messaging and voice calling app\",\n PackageName = \"Telegram.TelegramDesktop\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Whatsapp\",\n Description = \"Instant messaging and voice calling app\",\n PackageName = \"9NKSQGP7F2NH\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Zoom\",\n Description = \"Video conferencing and messaging platform\",\n PackageName = \"Zoom.Zoom\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Discord\",\n Description = \"Voice, video and text communication service\",\n PackageName = \"Discord.Discord\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Pidgin\",\n Description = \"Multi-protocol instant messaging client\",\n PackageName = \"Pidgin.Pidgin\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Thunderbird\",\n Description = \"Free email application\",\n PackageName = \"Mozilla.Thunderbird\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"eMClient\",\n Description = \"Email client with calendar, tasks, and chat\",\n PackageName = \"eMClient.eMClient\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Proton Mail\",\n Description = \"Secure email service with end-to-end encryption\",\n PackageName = \"Proton.ProtonMail\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Trillian\",\n Description = \"Instant messaging application\",\n PackageName = \"CeruleanStudios.Trillian\",\n Category = \"Messaging, Email & Calendar\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // File & Disk Management\n new AppInfo\n {\n Name = \"WinDirStat\",\n Description = \"Disk usage statistics viewer and cleanup tool\",\n PackageName = \"WinDirStat.WinDirStat\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"WizTree\",\n Description = \"Disk space analyzer with extremely fast scanning\",\n PackageName = \"AntibodySoftware.WizTree\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"TreeSize Free\",\n Description = \"Disk space manager\",\n PackageName = \"JAMSoftware.TreeSize.Free\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Everything\",\n Description = \"Locate files and folders by name instantly\",\n PackageName = \"voidtools.Everything\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"TeraCopy\",\n Description = \"Copy files faster and more securely\",\n PackageName = \"CodeSector.TeraCopy\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"File Converter\",\n Description = \"Batch file converter for Windows\",\n PackageName = \"AdrienAllard.FileConverter\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Crystal Disk Info\",\n Description = \"Hard drive health monitoring utility\",\n PackageName = \"WsSolInfor.CrystalDiskInfo\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Bulk Rename Utility\",\n Description = \"File renaming software for Windows\",\n PackageName = \"TGRMNSoftware.BulkRenameUtility\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"IObit Unlocker\",\n Description = \"Tool to unlock files that are in use by other processes\",\n PackageName = \"IObit.IObitUnlocker\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Ventoy\",\n Description = \"Open source tool to create bootable USB drive for ISO files\",\n PackageName = \"Ventoy.Ventoy\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Volume2\",\n Description = \"Advanced Windows volume control\",\n PackageName = \"irzyxa.Volume2Portable\",\n Category = \"File & Disk Management\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Remote Access\n new AppInfo\n {\n Name = \"RustDesk\",\n Description = \"Fast Open-Source Remote Access and Support Software\",\n PackageName = \"RustDesk.RustDesk\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Input Leap\",\n Description = \"Open-source KVM software for sharing mouse and keyboard between computers\",\n PackageName = \"input-leap.input-leap\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"AnyDesk\",\n Description = \"Remote desktop software for remote access and support\",\n PackageName = \"AnyDesk.AnyDesk\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"TeamViewer 15\",\n Description =\n \"Remote control, desktop sharing, online meetings, web conferencing and file transfer\",\n PackageName = \"TeamViewer.TeamViewer\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"RealVNC Server\",\n Description = \"Remote access software\",\n PackageName = \"RealVNC.VNCServer\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"RealVNC Viewer\",\n Description = \"Remote access software\",\n PackageName = \"RealVNC.VNCViewer\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Chrome Remote Desktop Host\",\n Description = \"Remote access to your computer through Chrome browser\",\n PackageName = \"Google.ChromeRemoteDesktopHost\",\n Category = \"Remote Access\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Optical Disc Tools\n new AppInfo\n {\n Name = \"CDBurnerXP\",\n Description = \"Application to burn CDs and DVDs\",\n PackageName = \"\",\n Category = \"Optical Disc Tools\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"ImgBurn\",\n Description = \"Lightweight CD / DVD / HD DVD / Blu-ray burning application\",\n PackageName = \"LIGHTNINGUK.ImgBurn\",\n Category = \"Optical Disc Tools\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"AnyBurn\",\n Description = \"Lightweight CD/DVD/Blu-ray burning software\",\n PackageName = \"PowerSoftware.AnyBurn\",\n Category = \"Optical Disc Tools\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Other Utilities\n new AppInfo\n {\n Name = \"Snappy Driver Installer Origin\",\n Description = \"Driver installer and updater\",\n PackageName = \"GlennDelahoy.SnappyDriverInstallerOrigin\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Wise Registry Cleaner\",\n Description = \"Registry cleaning and optimization tool\",\n PackageName = \"XPDLS1XBTXVPP4\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"UniGetUI\",\n Description =\n \"Universal package manager interface supporting WinGet, Chocolatey, and more\",\n PackageName = \"MartiCliment.UniGetUI\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Google Earth\",\n Description = \"3D representation of Earth based on satellite imagery\",\n PackageName = \"Google.GoogleEarthPro\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"NV Access\",\n Description = \"Screen reader for blind and vision impaired users\",\n PackageName = \"NVAccess.NVDA\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Revo Uninstaller\",\n Description = \"Uninstaller with advanced features\",\n PackageName = \"RevoUninstaller.RevoUninstaller\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Bulk Crap Uninstaller\",\n Description = \"Free and open-source program uninstaller with advanced features\",\n PackageName = \"Klocman.BulkCrapUninstaller\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Text Grab\",\n Description = \"Tool for extracting text from images and screenshots\",\n PackageName = \"JosephFinney.Text-Grab\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Glary Utilities\",\n Description = \"All-in-one PC care utility\",\n PackageName = \"Glarysoft.GlaryUtilities\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Buzz\",\n Description = \"AI video & audio transcription tool\",\n PackageName = \"ChidiWilliams.Buzz\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"PowerToys\",\n Description = \"Windows system utilities to maximize productivity\",\n PackageName = \"Microsoft.PowerToys\",\n Category = \"Other Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Customization Utilities\n new AppInfo\n {\n Name = \"Nilesoft Shell\",\n Description = \"Windows context menu customization tool\",\n PackageName = \"Nilesoft.Shell\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"StartAllBack\",\n Description = \"Windows 11 Start menu and taskbar customization\",\n PackageName = \"StartIsBack.StartAllBack\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Open-Shell\",\n Description = \"Classic style Start Menu for Windows\",\n PackageName = \"Open-Shell.Open-Shell-Menu\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Windhawk\",\n Description = \"Customization platform for Windows\",\n PackageName = \"RamenSoftware.Windhawk\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Lively Wallpaper\",\n Description = \"Free and open-source animated desktop wallpaper application\",\n PackageName = \"rocksdanister.LivelyWallpaper\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Sucrose Wallpaper Engine\",\n Description = \"Free and open-source animated desktop wallpaper application\",\n PackageName = \"Taiizor.SucroseWallpaperEngine\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Rainmeter\",\n Description = \"Desktop customization tool for Windows\",\n PackageName = \"Rainmeter.Rainmeter\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"ExplorerPatcher\",\n Description = \"Utility that enhances the Windows Explorer experience\",\n PackageName = \"valinet.ExplorerPatcher\",\n Category = \"Customization Utilities\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Gaming\n new AppInfo\n {\n Name = \"Steam\",\n Description = \"Digital distribution platform for PC gaming\",\n PackageName = \"Valve.Steam\",\n Category = \"Gaming\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Epic Games Launcher\",\n Description = \"Digital distribution platform for PC gaming\",\n PackageName = \"EpicGames.EpicGamesLauncher\",\n Category = \"Gaming\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"EA Desktop App\",\n Description = \"Digital distribution platform for PC gaming\",\n PackageName = \"ElectronicArts.EADesktop\",\n Category = \"Gaming\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Ubisoft Connect\",\n Description = \"Digital distribution platform for PC gaming\",\n PackageName = \"Ubisoft.Connect\",\n Category = \"Gaming\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Battle.net\",\n Description = \"Digital distribution platform for PC gaming\",\n PackageName = \"Blizzard.BattleNet\",\n Category = \"Gaming\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n // Privacy & Security\n new AppInfo\n {\n Name = \"Malwarebytes\",\n Description = \"Anti-malware software for Windows\",\n PackageName = \"Malwarebytes.Malwarebytes\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Malwarebytes AdwCleaner\",\n Description = \"Adware removal tool for Windows\",\n PackageName = \"Malwarebytes.AdwCleaner\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"SUPERAntiSpyware\",\n Description = \"Anti-spyware software for Windows\",\n PackageName = \"SUPERAntiSpyware.SUPERAntiSpyware\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"ProtonVPN\",\n Description = \"Secure and private VPN service\",\n PackageName = \"Proton.ProtonVPN\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"KeePass 2\",\n Description = \"Free, open source, light-weight password manager\",\n PackageName = \"DominikReichl.KeePass\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Proton Pass\",\n Description = \"Secure password manager with end-to-end encryption\",\n PackageName = \"Proton.ProtonPass\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Bitwarden\",\n Description = \"Open source password manager\",\n PackageName = \"Bitwarden.Bitwarden\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"KeePassXC\",\n Description = \"Cross-platform secure password manager\",\n PackageName = \"KeePassXCTeam.KeePassXC\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Tailscale\",\n Description = \"Zero config VPN for building secure networks\",\n PackageName = \"Tailscale.Tailscale\",\n Category = \"Privacy & Security\",\n IsCustomInstall = true,\n Type = AppType.StandardApp,\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/WindowsAppCatalog.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a catalog of Windows built-in applications that can be removed.\n/// \npublic class WindowsAppCatalog\n{\n /// \n /// Gets or sets the collection of removable Windows applications.\n /// \n public IReadOnlyList WindowsApps { get; init; } = new List();\n\n /// \n /// Creates a default Windows app catalog with predefined removable apps.\n /// \n /// A new WindowsAppCatalog instance with default apps.\n public static WindowsAppCatalog CreateDefault()\n {\n return new WindowsAppCatalog { WindowsApps = CreateDefaultWindowsApps() };\n }\n\n private static List CreateDefaultWindowsApps()\n {\n return new List\n {\n // 3D/Mixed Reality\n new AppInfo\n {\n Name = \"3D Viewer\",\n Description = \"View 3D models and animations\",\n PackageName = \"Microsoft.Microsoft3DViewer\",\n PackageID = \"9NBLGGH42THS\",\n Category = \"3D/Mixed Reality\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Mixed Reality Portal\",\n Description = \"Portal for Windows Mixed Reality experiences\",\n PackageName = \"Microsoft.MixedReality.Portal\",\n PackageID = \"9NG1H8B3ZC7M\",\n Category = \"3D/Mixed Reality\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Bing/Search\n new AppInfo\n {\n Name = \"Bing Search\",\n Description = \"Bing search integration for Windows\",\n PackageName = \"Microsoft.BingSearch\",\n PackageID = \"9NZBF4GT040C\",\n Category = \"Bing\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Microsoft News\",\n Description = \"Microsoft News app\",\n PackageName = \"Microsoft.BingNews\",\n PackageID = \"9WZDNCRFHVFW\",\n Category = \"Bing\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"MSN Weather\",\n Description = \"Weather forecasts and information\",\n PackageName = \"Microsoft.BingWeather\",\n PackageID = \"9WZDNCRFJ3Q2\",\n Category = \"Bing/Search\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Camera/Media\n new AppInfo\n {\n Name = \"Camera\",\n Description = \"Windows Camera app\",\n PackageName = \"Microsoft.WindowsCamera\",\n PackageID = \"9WZDNCRFJBBG\",\n Category = \"Camera/Media\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Clipchamp\",\n Description = \"Video editor app\",\n PackageName = \"Clipchamp.Clipchamp\",\n PackageID = \"9P1J8S7CCWWT\",\n Category = \"Camera/Media\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // System Utilities\n new AppInfo\n {\n Name = \"Alarms & Clock\",\n Description = \"Clock, alarms, timer, and stopwatch app\",\n PackageName = \"Microsoft.WindowsAlarms\",\n PackageID = \"9WZDNCRFJ3PR\",\n Category = \"System Utilities\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Cortana\",\n Description = \"Microsoft's virtual assistant\",\n PackageName = \"Microsoft.549981C3F5F10\",\n PackageID = \"9NFFX4SZZ23L\",\n Category = \"System Utilities\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Get Help\",\n Description = \"Microsoft support app\",\n PackageName = \"Microsoft.GetHelp\",\n PackageID = \"9PKDZBMV1H3T\",\n Category = \"System Utilities\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Calculator\",\n Description = \"Calculator app with standard, scientific, and programmer modes\",\n PackageName = \"Microsoft.WindowsCalculator\",\n PackageID = \"9WZDNCRFHVN5\",\n Category = \"System Utilities\",\n IsSystemProtected = true,\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Development\n new AppInfo\n {\n Name = \"Dev Home\",\n Description = \"Development environment for Windows\",\n PackageName = \"Microsoft.Windows.DevHome\",\n PackageID = \"9WZDNCRFHVN5\",\n Category = \"Development\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Communication & Family\n new AppInfo\n {\n Name = \"Microsoft Family Safety\",\n Description = \"Family safety and screen time management\",\n PackageName = \"MicrosoftCorporationII.MicrosoftFamily\",\n PackageID = \"9PDJDJS743XF\",\n Category = \"Communication\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Mail and Calendar\",\n Description = \"Microsoft Mail and Calendar apps\",\n PackageName = \"microsoft.windowscommunicationsapps\",\n PackageID = \"9WZDNCRFHVQM\",\n Category = \"Communication\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Skype\",\n Description = \"Video calling and messaging app\",\n PackageName = \"Microsoft.SkypeApp\",\n PackageID = \"9WZDNCRFJ364\",\n Category = \"Communication\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Microsoft Teams\",\n Description = \"Team collaboration and communication app\",\n PackageName = \"MSTeams\",\n PackageID = \"XP8BT8DW290MPQ\",\n Category = \"Communication\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // System Tools\n new AppInfo\n {\n Name = \"Feedback Hub\",\n Description = \"App for sending feedback to Microsoft\",\n PackageName = \"Microsoft.WindowsFeedbackHub\",\n PackageID = \"9NBLGGH4R32N\",\n Category = \"System Tools\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Maps\",\n Description = \"Microsoft Maps app\",\n PackageName = \"Microsoft.WindowsMaps\",\n PackageID = \"9WZDNCRDTBVB\",\n Category = \"System Tools\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Terminal\",\n Description = \"Modern terminal application for Windows\",\n PackageName = \"Microsoft.WindowsTerminal\",\n PackageID = \"9N0DX20HK701\",\n Category = \"System Tools\",\n IsSystemProtected = true,\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Office & Productivity\n new AppInfo\n {\n Name = \"Office Hub\",\n Description = \"Microsoft Office app hub\",\n PackageName = \"Microsoft.MicrosoftOfficeHub\",\n Category = \"Office\",\n CanBeReinstalled = false,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"OneNote\",\n Description = \"Microsoft note-taking app\",\n PackageName = \"Microsoft.Office.OneNote\",\n PackageID = \"XPFFZHVGQWWLHB\",\n Category = \"Office\",\n CanBeReinstalled = true,\n RequiresSpecialHandling = true,\n SpecialHandlerType = \"OneNote\",\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Outlook for Windows\",\n Description = \"Reimagined Outlook app for Windows\",\n PackageName = \"Microsoft.OutlookForWindows\",\n PackageID = \"9NRX63209R7B\",\n Category = \"Office\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Graphics & Images\n new AppInfo\n {\n Name = \"Paint 3D\",\n Description = \"3D modeling and editing app\",\n PackageName = \"Microsoft.MSPaint\",\n Category = \"Graphics\",\n CanBeReinstalled = false,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Paint\",\n Description = \"Traditional image editing app\",\n PackageName = \"Microsoft.Paint\",\n PackageID = \"9PCFS5B6T72H\",\n Category = \"Graphics\",\n IsSystemProtected = true,\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Photos\",\n Description = \"Photo viewing and editing app\",\n PackageName = \"Microsoft.Windows.Photos\",\n PackageID = \"9WZDNCRFJBH4\",\n Category = \"Graphics\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Snipping Tool\",\n Description = \"Screen capture and annotation tool\",\n PackageName = \"Microsoft.ScreenSketch\",\n PackageID = \"9MZ95KL8MR0L\",\n Category = \"Graphics\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Social & People\n new AppInfo\n {\n Name = \"People\",\n Description = \"Contact management app\",\n PackageName = \"Microsoft.People\",\n PackageID = \"9NBLGGH10PG8\",\n Category = \"Social\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Automation\n new AppInfo\n {\n Name = \"Power Automate\",\n Description = \"Desktop automation tool\",\n PackageName = \"Microsoft.PowerAutomateDesktop\",\n PackageID = \"9NFTCH6J7FHV\",\n Category = \"Automation\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Support Tools\n new AppInfo\n {\n Name = \"Quick Assist\",\n Description = \"Remote assistance tool\",\n PackageName = \"MicrosoftCorporationII.QuickAssist\",\n PackageID = \"9P7BP5VNWKX5\",\n Category = \"Support\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Games & Entertainment\n new AppInfo\n {\n Name = \"Solitaire Collection\",\n Description = \"Microsoft Solitaire Collection games\",\n PackageName = \"Microsoft.MicrosoftSolitaireCollection\",\n PackageID = \"9WZDNCRFHWD2\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Xbox\",\n Description = \"Xbox App for Windows\",\n PackageName = \"Microsoft.GamingApp\", // New Xbox Package Name (Windows 11)\n PackageID = \"9MV0B5HZVK9Z\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n SubPackages = new string[]\n {\n \"Microsoft.XboxApp\", // Microsoft.XboxApp is deprecated but still on Windows 10 22H2 ISO's\n },\n RegistrySettings = new AppRegistrySetting[]\n {\n new AppRegistrySetting\n {\n Path = @\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\GameDVR\",\n Name = \"AppCaptureEnabled\",\n Value = 0,\n ValueKind = Microsoft.Win32.RegistryValueKind.DWord,\n Description =\n \"Disables the Get an app to open this 'ms-gamingoverlay' popup\",\n },\n },\n },\n new AppInfo\n {\n Name = \"Xbox Identity Provider\",\n Description =\n \"Authentication service for Xbox Live and related Microsoft gaming services\",\n PackageName = \"Microsoft.XboxIdentityProvider\",\n PackageID = \"9WZDNCRD1HKW\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Xbox Game Bar Plugin\",\n Description =\n \"Extension component for Xbox Game Bar providing additional functionality\",\n PackageName = \"Microsoft.XboxGameOverlay\",\n PackageID = \"9NBLGGH537C2\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Xbox Live In-Game Experience\",\n Description = \"Core component for Xbox Live services within games\",\n PackageName = \"Microsoft.Xbox.TCUI\",\n PackageID = \"9NKNC0LD5NN6\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Xbox Game Bar\",\n Description =\n \"Gaming overlay with screen capture, performance monitoring, and social features\",\n PackageName = \"Microsoft.XboxGamingOverlay\",\n PackageID = \"9NZKPSTSNW4P\",\n Category = \"Games\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Windows Store\n new AppInfo\n {\n Name = \"Microsoft Store\",\n Description = \"App store for Windows\",\n PackageName = \"Microsoft.WindowsStore\",\n PackageID = \"9WZDNCRFJBMP\",\n Category = \"Store\",\n IsSystemProtected = true,\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Media Players\n new AppInfo\n {\n Name = \"Media Player\",\n Description = \"Music player app\",\n PackageName = \"Microsoft.ZuneMusic\",\n PackageID = \"9WZDNCRFJ3PT\",\n Category = \"Media\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Movies & TV\",\n Description = \"Video player app\",\n PackageName = \"Microsoft.ZuneVideo\",\n PackageID = \"9WZDNCRFJ3P2\",\n Category = \"Media\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Sound Recorder\",\n Description = \"Audio recording app\",\n PackageName = \"Microsoft.WindowsSoundRecorder\",\n PackageID = \"9WZDNCRFHWKN\",\n Category = \"Media\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Productivity Tools\n new AppInfo\n {\n Name = \"Sticky Notes\",\n Description = \"Note-taking app\",\n PackageName = \"Microsoft.MicrosoftStickyNotes\",\n PackageID = \"9NBLGGH4QGHW\",\n Category = \"Productivity\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Tips\",\n Description = \"Windows tutorial app\",\n PackageName = \"Microsoft.Getstarted\",\n Category = \"Productivity\",\n CanBeReinstalled = false,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"To Do\",\n Description = \"Task management app\",\n PackageName = \"Microsoft.Todos\",\n PackageID = \"9NBLGGH5R558\",\n Category = \"Productivity\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"Notepad\",\n Description = \"Text editing app\",\n PackageName = \"Microsoft.WindowsNotepad\",\n PackageID = \"9MSMLRH6LZF3\",\n Category = \"Productivity\",\n IsSystemProtected = true,\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // Phone Integration\n new AppInfo\n {\n Name = \"Phone Link\",\n Description = \"Connect your Android or iOS device to Windows\",\n PackageName = \"Microsoft.YourPhone\",\n PackageID = \"9NMPJ99VJBWV\",\n Category = \"Phone\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n },\n // AI & Copilot\n new AppInfo\n {\n Name = \"Copilot\",\n Description =\n \"AI assistant for Windows, includes Copilot provider and Store components\",\n PackageName = \"Microsoft.Copilot\",\n PackageID = \"9NHT9RB2F4HD\",\n Category = \"AI\",\n CanBeReinstalled = true,\n Type = AppType.StandardApp,\n SubPackages = new string[]\n {\n \"Microsoft.Windows.Ai.Copilot.Provider\",\n \"Microsoft.Copilot_8wekyb3d8bbwe\",\n },\n RegistrySettings = new AppRegistrySetting[]\n {\n new AppRegistrySetting\n {\n Path = @\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced\",\n Name = \"ShowCopilotButton\",\n Value = 0,\n ValueKind = Microsoft.Win32.RegistryValueKind.DWord,\n Description = \"Hide Copilot button from taskbar\",\n },\n new AppRegistrySetting\n {\n Path = @\"HKLM\\Software\\Policies\\Microsoft\\Windows\\CloudContent\",\n Name = \"TurnOffWindowsCopilot\",\n Value = 1,\n ValueKind = Microsoft.Win32.RegistryValueKind.DWord,\n Description = \"Disable Windows Copilot system-wide\",\n },\n },\n },\n // Special Items that require special handling\n new AppInfo\n {\n Name = \"Microsoft Edge\",\n Description = \"Microsoft's web browser (requires special removal process)\",\n PackageName = \"Edge\",\n PackageID = \"XPFFTQ037JWMHS\",\n Category = \"Browsers\",\n CanBeReinstalled = true,\n RequiresSpecialHandling = true,\n SpecialHandlerType = \"Edge\",\n Type = AppType.StandardApp,\n },\n new AppInfo\n {\n Name = \"OneDrive\",\n Description =\n \"Microsoft's cloud storage service (requires special removal process)\",\n PackageName = \"OneDrive\",\n PackageID = \"Microsoft.OneDrive\",\n Category = \"System\",\n CanBeReinstalled = true,\n RequiresSpecialHandling = true,\n SpecialHandlerType = \"OneDrive\",\n Type = AppType.StandardApp,\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/PrivacyOptimizations.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class PrivacyOptimizations\n{\n public static OptimizationGroup GetPrivacyOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Privacy\",\n Category = OptimizationCategory.Privacy,\n Settings = new List\n {\n // Activity History\n new OptimizationSetting\n {\n Id = \"privacy-activity-history\",\n Name = \"Activity History\",\n Description = \"Controls activity history tracking\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Activity History\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\System\",\n Name = \"PublishUserActivities\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, Activity History is enabled\n DisabledValue = 0, // When toggle is OFF, Activity History is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls activity history tracking\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Personalized Ads (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-advertising-id\",\n Name = \"Personalized Ads\",\n Description = \"Controls personalized ads using advertising ID\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Advertising\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\AdvertisingInfo\",\n Name = \"Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, advertising ID is enabled\n DisabledValue = 0, // When toggle is OFF, advertising ID is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls advertising ID for personalized ads\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\AdvertisingInfo\",\n Name = \"DisabledByGroupPolicy\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, advertising is NOT disabled by policy\n DisabledValue = 1, // When toggle is OFF, advertising is disabled by policy\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls advertising ID for personalized ads\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Language List Access\n new OptimizationSetting\n {\n Id = \"privacy-language-list\",\n Name = \"Allow Websites Access to Language List\",\n Description =\n \"Let websites show me locally relevant content by accessing my language list\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"General\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\International\\\\User Profile\",\n Name = \"HttpAcceptLanguageOptOut\",\n RecommendedValue = 0,\n EnabledValue = 0, // When toggle is ON, language list access is enabled\n DisabledValue = 1, // When toggle is OFF, language list access is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls language list access for websites\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // App Launch Tracking\n new OptimizationSetting\n {\n Id = \"privacy-app-launch-tracking\",\n Name = \"App Launch Tracking\",\n Description =\n \"Let Windows improve Start and search results by tracking app launches\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"General\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\Advanced\",\n Name = \"Start_TrackProgs\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, app launch tracking is enabled\n DisabledValue = 0, // When toggle is OFF, app launch tracking is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description =\n \"Controls app launch tracking for improved Start and search results\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Show Suggested Content in Settings (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-settings-content\",\n Name = \"Show Suggested Content in Settings\",\n Description = \"Controls suggested content in the Settings app\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Settings App\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ContentDeliveryManager\",\n Name = \"SubscribedContent-338393Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, suggested content is enabled\n DisabledValue = 0, // When toggle is OFF, suggested content is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls suggested content in the Settings app\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ContentDeliveryManager\",\n Name = \"SubscribedContent-353694Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, suggested content is enabled\n DisabledValue = 0, // When toggle is OFF, suggested content is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls suggested content in the Settings app\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ContentDeliveryManager\",\n Name = \"SubscribedContent-353696Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, suggested content is enabled\n DisabledValue = 0, // When toggle is OFF, suggested content is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls suggested content in the Settings app\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Settings App Notifications\n new OptimizationSetting\n {\n Id = \"privacy-settings-notifications\",\n Name = \"Settings App Notifications\",\n Description =\n \"Controls notifications in the Settings app and immersive control panel\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Settings App\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\SystemSettings\\\\AccountNotifications\",\n Name = \"EnableAccountNotifications\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, account notifications are enabled\n DisabledValue = 0, // When toggle is OFF, account notifications are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description =\n \"Controls notifications in the Settings app and immersive control panel\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Online Speech Recognition (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-speech-recognition\",\n Name = \"Online Speech Recognition\",\n Description = \"Controls online speech recognition\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Speech\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Speech_OneCore\\\\Settings\\\\OnlineSpeechPrivacy\",\n Name = \"HasAccepted\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, online speech recognition is enabled\n DisabledValue = 0, // When toggle is OFF, online speech recognition is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls online speech recognition\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\InputPersonalization\",\n Name = \"AllowInputPersonalization\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, input personalization is allowed\n DisabledValue = 0, // When toggle is OFF, input personalization is not allowed\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls input personalization for speech recognition\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Custom Inking and Typing Dictionary (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-inking-typing-dictionary\",\n Name = \"Custom Inking and Typing Dictionary\",\n Description =\n \"Controls custom inking and typing dictionary (turning off will clear all words in your custom dictionary)\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Inking and Typing\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CPSS\\\\Store\\\\InkingAndTypingPersonalization\",\n Name = \"Value\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, custom dictionary is enabled\n DisabledValue = 0, // When toggle is OFF, custom dictionary is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls custom inking and typing dictionary\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Personalization\\\\Settings\",\n Name = \"AcceptedPrivacyPolicy\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, privacy policy is accepted\n DisabledValue = 0, // When toggle is OFF, privacy policy is not accepted\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls custom inking and typing dictionary\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\InputPersonalization\",\n Name = \"RestrictImplicitTextCollection\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, text collection is not restricted\n DisabledValue = 1, // When toggle is OFF, text collection is restricted\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls custom inking and typing dictionary\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\InputPersonalization\\\\TrainedDataStore\",\n Name = \"HarvestContacts\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, contacts harvesting is enabled\n DisabledValue = 0, // When toggle is OFF, contacts harvesting is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls custom inking and typing dictionary\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Send Diagnostic Data (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-diagnostics\",\n Name = \"Send Diagnostic Data\",\n Description = \"Controls diagnostic data collection level\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Diagnostics & Feedback\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Diagnostics\\\\DiagTrack\",\n Name = \"ShowedToastAtLevel\",\n RecommendedValue = 1,\n EnabledValue = 3, // When toggle is ON, full diagnostic data is enabled\n DisabledValue = 1, // When toggle is OFF, basic diagnostic data is enabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls diagnostic data collection level\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\DataCollection\",\n Name = \"AllowTelemetry\",\n RecommendedValue = 1,\n EnabledValue = 3, // When toggle is ON, full telemetry is allowed\n DisabledValue = 1, // When toggle is OFF, basic telemetry is allowed\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls telemetry data collection\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\DataCollection\",\n Name = \"MaxTelemetryAllowed\",\n RecommendedValue = 1,\n EnabledValue = 3, // When toggle is ON, full telemetry is allowed\n DisabledValue = 1, // When toggle is OFF, basic telemetry is allowed\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls telemetry data collection\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\DataCollection\",\n Name = \"AllowTelemetry\",\n RecommendedValue = 1,\n EnabledValue = 3, // When toggle is ON, telemetry is allowed by policy\n DisabledValue = 0, // When toggle is OFF, telemetry is not allowed by policy\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 3, // Default value when registry key exists but no value is set\n Description = \"Controls telemetry data collection\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Improve Inking and Typing (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-improve-inking-typing\",\n Name = \"Improve Inking and Typing\",\n Description = \"Controls inking and typing data collection\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Diagnostics & Feedback\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n Dependencies = new List\n {\n new SettingDependency\n {\n DependencyType = SettingDependencyType.RequiresEnabled,\n DependentSettingId = \"privacy-improve-inking-typing\",\n RequiredSettingId = \"privacy-diagnostics\",\n },\n },\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Input\\\\TIPC\",\n Name = \"Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, inking and typing improvement is enabled\n DisabledValue = 0, // When toggle is OFF, inking and typing improvement is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls inking and typing data collection\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey =\n \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CPSS\\\\Store\\\\ImproveInkingAndTyping\",\n Name = \"Value\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, linguistic data collection is allowed\n DisabledValue = 0, // When toggle is OFF, linguistic data collection is not allowed\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls inking and typing data collection\",\n IsPrimary = false,\n AbsenceMeansEnabled = true,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Tailored Experiences (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-tailored-experiences\",\n Name = \"Tailored Experiences\",\n Description = \"Controls personalized experiences with diagnostic data\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Diagnostics & Feedback\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Privacy\",\n Name = \"TailoredExperiencesWithDiagnosticDataEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, tailored experiences are enabled\n DisabledValue = 0, // When toggle is OFF, tailored experiences are disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls personalized experiences with diagnostic data\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Policies\\\\Microsoft\\\\Windows\\\\CloudContent\",\n Name = \"DisableTailoredExperiencesWithDiagnosticData\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, tailored experiences are not disabled by policy\n DisabledValue = 1, // When toggle is OFF, tailored experiences are disabled by policy\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls personalized experiences with diagnostic data\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Location Services (combined setting)\n new OptimizationSetting\n {\n Id = \"privacy-location-services\",\n Name = \"Location Services\",\n Description = \"Controls location services\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"App Permissions\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\location\",\n Name = \"Value\",\n RecommendedValue = \"Deny\",\n EnabledValue = \"Allow\", // When toggle is ON, location services are allowed\n DisabledValue = \"Deny\", // When toggle is OFF, location services are denied\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Allow\", // Default value when registry key exists but no value is set\n Description = \"Controls location services\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows\\\\LocationAndSensors\",\n Name = \"DisableLocation\",\n RecommendedValue = 1,\n EnabledValue = 0, // When toggle is ON, location is not disabled by policy\n DisabledValue = 1, // When toggle is OFF, location is disabled by policy\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0, // Default value when registry key exists but no value is set\n Description = \"Controls location services\",\n IsPrimary = false,\n AbsenceMeansEnabled = false,\n },\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All,\n },\n // Camera Access\n new OptimizationSetting\n {\n Id = \"privacy-camera-access\",\n Name = \"Camera Access\",\n Description = \"Controls camera access\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"App Permissions\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\webcam\",\n Name = \"Value\",\n RecommendedValue = \"Deny\",\n EnabledValue = \"Allow\", // When toggle is ON, camera access is allowed\n DisabledValue = \"Deny\", // When toggle is OFF, camera access is denied\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Allow\", // Default value when registry key exists but no value is set\n Description = \"Controls camera access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Microphone Access\n new OptimizationSetting\n {\n Id = \"privacy-microphone-access\",\n Name = \"Microphone Access\",\n Description = \"Controls microphone access\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"App Permissions\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\microphone\",\n Name = \"Value\",\n RecommendedValue = \"Deny\",\n EnabledValue = \"Allow\", // When toggle is ON, microphone access is allowed\n DisabledValue = \"Deny\", // When toggle is OFF, microphone access is denied\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Allow\", // Default value when registry key exists but no value is set\n Description = \"Controls microphone access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Account Info Access\n new OptimizationSetting\n {\n Id = \"privacy-account-info-access\",\n Name = \"Account Info Access\",\n Description = \"Controls account information access\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"App Permissions\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\userAccountInformation\",\n Name = \"Value\",\n RecommendedValue = \"Deny\",\n EnabledValue = \"Allow\", // When toggle is ON, account info access is allowed\n DisabledValue = \"Deny\", // When toggle is OFF, account info access is denied\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Allow\", // Default value when registry key exists but no value is set\n Description = \"Controls account information access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // App Diagnostic Access\n new OptimizationSetting\n {\n Id = \"privacy-app-diagnostic-access\",\n Name = \"App Diagnostic Access\",\n Description = \"Controls app diagnostic access\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"App Permissions\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.LocalMachine,\n SubKey =\n \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\appDiagnostics\",\n Name = \"Value\",\n RecommendedValue = \"Deny\",\n EnabledValue = \"Allow\", // When toggle is ON, app diagnostic access is allowed\n DisabledValue = \"Deny\", // When toggle is OFF, app diagnostic access is denied\n ValueType = RegistryValueKind.String,\n DefaultValue = \"Allow\", // Default value when registry key exists but no value is set\n Description = \"Controls app diagnostic access\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Cloud Content Search for Microsoft Account\n new OptimizationSetting\n {\n Id = \"privacy-search-msa-cloud\",\n Name = \"Cloud Content Search (Microsoft Account)\",\n Description = \"Controls cloud content search for Microsoft account\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Search\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\SearchSettings\",\n Name = \"IsMSACloudSearchEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, cloud search is enabled\n DisabledValue = 0, // When toggle is OFF, cloud search is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls cloud content search for Microsoft account\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Cloud Content Search for Work or School Account\n new OptimizationSetting\n {\n Id = \"privacy-search-aad-cloud\",\n Name = \"Cloud Content Search (Work/School Acc)\",\n Description = \"Controls cloud content search for work or school account\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Search\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\SearchSettings\",\n Name = \"IsAADCloudSearchEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, cloud search is enabled\n DisabledValue = 0, // When toggle is OFF, cloud search is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description =\n \"Controls cloud content search for work or school account\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n // Web Search\n new OptimizationSetting\n {\n Id = \"privacy-web-search\",\n Name = \"Web Search\",\n Description = \"Controls web search in Start menu and taskbar\",\n Category = OptimizationCategory.Privacy,\n GroupName = \"Search\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Privacy\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Search\",\n Name = \"BingSearchEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1, // When toggle is ON, web search is enabled\n DisabledValue = 0, // When toggle is OFF, web search is disabled\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1, // Default value when registry key exists but no value is set\n Description = \"Controls web search in Start menu and taskbar\",\n IsPrimary = true,\n AbsenceMeansEnabled = true,\n },\n },\n },\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Verification/VerificationMethodBase.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Verification\n{\n /// \n /// Base class for verification methods that provides common functionality.\n /// \n public abstract class VerificationMethodBase : IVerificationMethod\n {\n /// \n /// Initializes a new instance of the class.\n /// \n /// The name of the verification method.\n /// The priority of the verification method. Lower numbers indicate higher priority.\n protected VerificationMethodBase(string name, int priority)\n {\n if (string.IsNullOrWhiteSpace(name))\n throw new ArgumentException(\n \"Verification method name cannot be null or whitespace.\",\n nameof(name)\n );\n\n Name = name;\n Priority = priority;\n }\n\n /// \n public string Name { get; }\n\n /// \n public int Priority { get; }\n\n /// \n public async Task VerifyAsync(\n string packageId,\n string version = null,\n CancellationToken cancellationToken = default\n )\n {\n if (string.IsNullOrWhiteSpace(packageId))\n throw new ArgumentException(\n \"Package ID cannot be null or whitespace.\",\n nameof(packageId)\n );\n\n try\n {\n if (version == null)\n {\n return await VerifyPresenceAsync(packageId, cancellationToken)\n .ConfigureAwait(false);\n }\n\n return await VerifyVersionAsync(packageId, version, cancellationToken)\n .ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n throw;\n }\n catch (Exception ex)\n {\n return new VerificationResult\n {\n IsVerified = false,\n Message = $\"Error during verification using {Name}: {ex.Message}\",\n MethodUsed = Name,\n };\n }\n }\n\n /// \n /// Verifies if a package is present (without version check).\n /// \n /// The ID of the package to verify.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the verification result.\n protected abstract Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken\n );\n\n /// \n /// Verifies if a package is present with the specified version.\n /// \n /// The ID of the package to verify.\n /// The expected version of the package.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the verification result.\n protected abstract Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken\n );\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Extensions/WinGetProgressExtensions.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.Extensions\n{\n /// \n /// Extension methods for specific to WinGet operations.\n /// \n public static class WinGetProgressExtensions\n {\n /// \n /// Tracks the progress of a WinGet installation operation.\n /// \n /// The progress service.\n /// The asynchronous operation to track.\n /// The display name of the application.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the result.\n public static async Task TrackWinGetInstallationAsync(\n this ITaskProgressService progressService,\n Func, Task> operation,\n string displayName,\n CancellationToken cancellationToken = default\n )\n {\n if (progressService == null)\n throw new ArgumentNullException(nameof(progressService));\n if (operation == null)\n throw new ArgumentNullException(nameof(operation));\n\n var progress = new Progress(p =>\n {\n progressService.UpdateDetailedProgress(\n new TaskProgressDetail\n {\n Progress = p.Percentage,\n StatusText = $\"Installing {displayName}: {p.Status}\",\n IsIndeterminate = p.IsIndeterminate,\n }\n );\n });\n\n try\n {\n return await operation(progress).ConfigureAwait(false);\n }\n catch (Exception ex)\n {\n progressService.UpdateProgress(0, $\"Failed to install {displayName}: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Tracks the progress of a WinGet upgrade operation.\n /// \n /// The progress service.\n /// The asynchronous operation to track.\n /// The display name of the application.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the result.\n public static async Task TrackWinGetUpgradeAsync(\n this ITaskProgressService progressService,\n Func, Task> operation,\n string displayName,\n CancellationToken cancellationToken = default\n )\n {\n if (progressService == null)\n throw new ArgumentNullException(nameof(progressService));\n if (operation == null)\n throw new ArgumentNullException(nameof(operation));\n\n var progress = new Progress(p =>\n {\n progressService.UpdateDetailedProgress(\n new TaskProgressDetail\n {\n Progress = p.Percentage,\n StatusText = $\"Upgrading {displayName}: {p.Status}\",\n IsIndeterminate = p.IsIndeterminate,\n }\n );\n });\n\n try\n {\n return await operation(progress).ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n progressService.UpdateProgress(0, $\"Upgrade of {displayName} was cancelled\");\n return new UpgradeResult\n {\n Success = false,\n Message = $\"Upgrade of {displayName} was cancelled by user\",\n PackageId = displayName\n };\n }\n catch (Exception ex)\n {\n progressService.UpdateProgress(0, $\"Failed to upgrade {displayName}: {ex.Message}\");\n throw;\n }\n }\n\n /// \n /// Tracks the progress of a WinGet uninstallation operation.\n /// \n /// The progress service.\n /// The asynchronous operation to track.\n /// The display name of the application.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the result.\n public static async Task TrackWinGetUninstallationAsync(\n this ITaskProgressService progressService,\n Func, Task> operation,\n string displayName,\n CancellationToken cancellationToken = default\n )\n {\n if (progressService == null)\n throw new ArgumentNullException(nameof(progressService));\n if (operation == null)\n throw new ArgumentNullException(nameof(operation));\n\n var progress = new Progress(p =>\n {\n progressService.UpdateDetailedProgress(\n new TaskProgressDetail\n {\n Progress = p.Percentage,\n StatusText = $\"Uninstalling {displayName}: {p.Status}\",\n IsIndeterminate = p.IsIndeterminate,\n }\n );\n });\n\n try\n {\n return await operation(progress).ConfigureAwait(false);\n }\n catch (Exception ex)\n {\n progressService.UpdateProgress(0, $\"Failed to uninstall {displayName}: {ex.Message}\");\n throw;\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/RegistryModels.cs", "using Microsoft.Win32;\nusing System;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models;\n\npublic record RegistrySetting\n{\n public required string Category { get; init; }\n public required RegistryHive Hive { get; init; }\n public required string SubKey { get; init; }\n public required string Name { get; init; }\n\n /// \n /// The value shown in the tooltip to indicate the recommended value.\n /// \n public required object RecommendedValue { get; init; }\n\n /// \n /// The value shown in the tooltip to indicate the default value. (or null to delete the registry key).\n /// \n public object? DefaultValue { get; init; }\n\n /// \n /// The value to set when the toggle is ON (enabled).\n /// \n public object? EnabledValue { get; init; }\n\n /// \n /// The value to set when the toggle is OFF (disabled), or null to delete the registry key.\n /// \n public object? DisabledValue { get; init; }\n\n public required RegistryValueKind ValueType { get; init; }\n /// \n /// Description of the registry setting. This is optional as the parent OptimizationSetting\n /// typically already has a Description property that serves the same purpose.\n /// \n public string Description { get; init; } = string.Empty;\n\n /// \n /// Specifies the intended action for this registry setting.\n /// Default is Set for backward compatibility.\n /// \n public RegistryActionType ActionType { get; init; } = RegistryActionType.Set;\n\n /// \n /// Specifies whether the absence of the registry key/value means the feature is enabled.\n /// Default is false, meaning absence = not applied.\n /// When true, absence of the key/value means the feature is enabled (Applied).\n /// \n public bool AbsenceMeansEnabled { get; init; } = false;\n\n /// \n /// Specifies whether this setting is a primary setting when used in linked settings.\n /// For settings with LinkedSettingsLogic.Primary, only the primary setting's status is used.\n /// \n public bool IsPrimary { get; init; } = false;\n\n /// \n /// Specifies whether this setting is a Group Policy registry key.\n /// When true, the entire key will be deleted when disabling the setting instead of just changing the value.\n /// This is necessary for Windows to recognize that the policy is no longer applied.\n /// \n public bool IsGroupPolicy { get; init; } = false;\n \n /// \n /// Dictionary to store custom properties for specific control types like ComboBox.\n /// This allows storing additional information that doesn't fit into the standard registry setting model.\n /// \n public Dictionary? CustomProperties { get; set; }\n}\n\npublic enum RegistryAction\n{\n Apply,\n Test,\n Rollback\n}\n\npublic record ValuePair\n{\n public required object Value { get; init; }\n public required RegistryValueKind Type { get; init; }\n\n public ValuePair(object value, RegistryValueKind type)\n {\n Value = value;\n Type = type;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/TaskProgressEventArgs.cs", "using System;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Event arguments for task progress events.\n /// \n public class TaskProgressEventArgs : EventArgs\n {\n /// \n /// Gets the progress value (0-100), or null if not applicable.\n /// \n public double Progress { get; }\n \n /// \n /// Gets the status text.\n /// \n public string StatusText { get; }\n \n /// \n /// Gets a detailed message about the current operation.\n /// \n public string DetailedMessage { get; }\n \n /// \n /// Gets the log level for the detailed message.\n /// \n public LogLevel LogLevel { get; }\n \n /// \n /// Gets whether the progress is indeterminate.\n /// \n public bool IsIndeterminate { get; }\n \n /// \n /// Gets whether a task is currently running.\n /// \n public bool IsTaskRunning { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The progress value.\n /// The status text.\n /// The detailed message.\n /// The log level.\n /// Whether the progress is indeterminate.\n /// Whether a task is running.\n public TaskProgressEventArgs(double progress, string statusText, string detailedMessage = \"\", LogLevel logLevel = LogLevel.Info, bool isIndeterminate = false, bool isTaskRunning = true)\n {\n Progress = progress;\n StatusText = statusText;\n DetailedMessage = detailedMessage;\n LogLevel = logLevel;\n IsIndeterminate = isIndeterminate;\n IsTaskRunning = isTaskRunning;\n }\n\n /// \n /// Creates a TaskProgressEventArgs instance from a TaskProgressDetail.\n /// \n /// The progress detail.\n /// Whether a task is running.\n /// A new TaskProgressEventArgs instance.\n public static TaskProgressEventArgs FromTaskProgressDetail(TaskProgressDetail detail, bool isTaskRunning = true)\n {\n return new TaskProgressEventArgs(\n detail.Progress ?? 0,\n detail.StatusText ?? string.Empty,\n detail.DetailedMessage ?? string.Empty,\n detail.LogLevel,\n detail.IsIndeterminate,\n isTaskRunning);\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Models/ExternalApp.cs", "using System;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Models\n{\n public partial class ExternalApp : ObservableObject, ISearchable\n {\n public string Name { get; set; }\n public string Description { get; set; }\n public string PackageName { get; set; }\n public string Version { get; set; } = string.Empty;\n \n [ObservableProperty]\n private bool _isInstalled;\n \n public bool CanBeReinstalled { get; set; }\n \n [ObservableProperty]\n private bool _isSelected;\n \n [ObservableProperty]\n private string _lastOperationError;\n\n public static ExternalApp FromAppInfo(AppInfo appInfo)\n {\n if (appInfo == null)\n throw new ArgumentNullException(nameof(appInfo));\n\n var app = new ExternalApp\n {\n Name = appInfo.Name,\n Description = appInfo.Description,\n PackageName = appInfo.PackageName,\n Version = appInfo.Version,\n CanBeReinstalled = appInfo.CanBeReinstalled,\n Category = appInfo.Category,\n LastOperationError = appInfo.LastOperationError\n };\n \n app.IsInstalled = appInfo.IsInstalled;\n \n return app;\n }\n\n public AppInfo ToAppInfo()\n {\n return new AppInfo\n {\n Name = Name,\n Description = Description,\n PackageName = PackageName,\n Version = Version,\n IsInstalled = IsInstalled,\n CanBeReinstalled = CanBeReinstalled,\n Category = Category,\n LastOperationError = LastOperationError\n };\n }\n\n /// \n /// Gets the category of the app.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Determines if the app matches the given search term.\n /// \n /// The search term to match against.\n /// True if the app matches the search term, false otherwise.\n public bool MatchesSearch(string searchTerm)\n {\n if (string.IsNullOrWhiteSpace(searchTerm))\n {\n return true;\n }\n\n searchTerm = searchTerm.ToLowerInvariant();\n \n // Check if the search term matches any of the searchable properties\n return Name.ToLowerInvariant().Contains(searchTerm) ||\n (!string.IsNullOrEmpty(Description) && Description.ToLowerInvariant().Contains(searchTerm)) ||\n (!string.IsNullOrEmpty(PackageName) && PackageName.ToLowerInvariant().Contains(searchTerm)) ||\n (!string.IsNullOrEmpty(Category) && Category.ToLowerInvariant().Contains(searchTerm));\n }\n\n /// \n /// Gets the searchable properties of the app.\n /// \n /// An array of property names that should be searched.\n public string[] GetSearchableProperties()\n {\n return new[] { nameof(Name), nameof(Description), nameof(PackageName), nameof(Category) };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/AppInfo.cs", "// This contains the model for standard application information\n\nusing System;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models\n{\n /// \n /// Defines the type of application.\n /// \n public enum AppType\n {\n /// \n /// Standard application.\n /// \n StandardApp,\n\n /// \n /// Windows capability.\n /// \n Capability,\n\n /// \n /// Windows optional feature.\n /// \n OptionalFeature,\n }\n\n /// \n /// Represents information about a standard application.\n /// \n public class AppInfo : IInstallableItem\n {\n string IInstallableItem.PackageId => PackageID;\n string IInstallableItem.DisplayName => Name;\n InstallItemType IInstallableItem.ItemType =>\n Type switch\n {\n AppType.Capability => InstallItemType.Capability,\n AppType.OptionalFeature => InstallItemType.Feature,\n _ => InstallItemType.WindowsApp,\n };\n bool IInstallableItem.RequiresRestart => false;\n\n /// \n /// Gets or sets the name of the application.\n /// \n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description of the application.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the package name of the application.\n /// \n public string PackageName { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the package ID of the application.\n /// \n public string PackageID { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the category of the application.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether the application is installed.\n /// \n public bool IsInstalled { get; set; }\n\n /// \n /// Gets or sets the type of application.\n /// \n public AppType Type { get; set; } = AppType.StandardApp;\n\n /// \n /// Gets or sets a value indicating whether the application requires a custom installation process.\n /// \n public bool IsCustomInstall { get; set; }\n\n /// \n /// Gets or sets the sub-packages associated with this application.\n /// \n public string[]? SubPackages { get; set; }\n\n /// \n /// Gets or sets the registry settings associated with this application.\n /// \n public AppRegistrySetting[]? RegistrySettings { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the application requires special handling.\n /// \n public bool RequiresSpecialHandling { get; set; }\n\n /// \n /// Gets or sets the special handler type for this application.\n /// \n public string? SpecialHandlerType { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the application is protected by the system.\n /// \n public bool IsSystemProtected { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the application can be reinstalled after removal.\n /// \n public bool CanBeReinstalled { get; set; } = true;\n\n /// \n /// Gets or sets the version of the application.\n /// \n public string Version { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the last operation error message, if any.\n /// \n public string? LastOperationError { get; set; }\n }\n\n /// \n /// Represents a registry setting for an application.\n /// \n public class AppRegistrySetting\n {\n /// \n /// Gets or sets the registry path.\n /// \n public string Path { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the registry value name.\n /// \n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the registry value.\n /// \n public object? Value { get; set; }\n\n /// \n /// Gets or sets the registry value kind.\n /// \n public Microsoft.Win32.RegistryValueKind ValueKind { get; set; }\n\n /// \n /// Gets or sets the description of the registry setting.\n /// \n public string? Description { get; set; }\n }\n\n /// \n /// Represents a package removal script.\n /// \n public class PackageRemovalScript\n {\n /// \n /// Gets or sets the name of the script.\n /// \n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the content of the script.\n /// \n public string Content { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the target scheduled task name.\n /// \n public string? TargetScheduledTaskName { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the script should run on startup.\n /// \n public bool RunOnStartup { get; set; }\n }\n\n /// \n /// Defines the types of special app handlers.\n /// \n public enum AppHandlerType\n {\n /// \n /// No special handling required.\n /// \n None,\n\n /// \n /// Microsoft Edge browser.\n /// \n Edge,\n\n /// \n /// Microsoft OneDrive.\n /// \n OneDrive,\n\n /// \n /// Microsoft Copilot.\n /// \n Copilot,\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/RegistryTestResult.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents the result of a registry value test.\n /// \n public class RegistryTestResult\n {\n /// \n /// Gets or sets the registry key path.\n /// \n public string KeyPath { get; set; }\n\n /// \n /// Gets or sets the registry value name.\n /// \n public string ValueName { get; set; }\n\n /// \n /// Gets or sets the expected value.\n /// \n public object ExpectedValue { get; set; }\n\n /// \n /// Gets or sets the actual value.\n /// \n public object ActualValue { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the test was successful.\n /// \n public bool IsSuccess { get; set; }\n\n /// \n /// Gets or sets the test result message.\n /// \n public string Message { get; set; }\n\n /// \n /// Gets or sets the category of the registry setting.\n /// \n public string Category { get; set; }\n\n /// \n /// Gets or sets the description of the registry setting.\n /// \n public string Description { get; set; }\n\n /// \n /// Gets a formatted string representation of the test result.\n /// \n /// A formatted string representation of the test result.\n public override string ToString()\n {\n return $\"{(IsSuccess ? \"✓\" : \"✗\")} {KeyPath}\\\\{ValueName}: {Message}\";\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/ApplicationSetting.cs", "using Microsoft.Win32;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Base class for all application settings that can modify registry values.\n /// \n public abstract record ApplicationSetting\n {\n /// \n /// Gets or sets the unique identifier for this setting.\n /// \n public required string Id { get; init; }\n\n /// \n /// Gets or sets the user-friendly name for this setting.\n /// \n public required string Name { get; init; }\n\n /// \n /// Gets or sets the description for this setting.\n /// \n public required string Description { get; init; }\n\n /// \n /// Gets or sets the group name for this setting.\n /// \n public required string GroupName { get; init; }\n\n /// \n /// Gets or sets the collection of registry settings associated with this application setting.\n /// \n public List RegistrySettings { get; init; } = new List();\n\n /// \n /// Gets or sets the collection of command settings associated with this application setting.\n /// \n public List CommandSettings { get; init; } = new List();\n\n /// \n /// Gets or sets the logic to use when determining the status of linked registry settings.\n /// \n public LinkedSettingsLogic LinkedSettingsLogic { get; init; } = LinkedSettingsLogic.Any;\n\n /// \n /// Gets or sets the dependencies between settings.\n /// \n public List Dependencies { get; init; } = new List();\n\n /// \n /// Gets or sets the control type for the UI.\n /// \n public ControlType ControlType { get; init; } = ControlType.BinaryToggle;\n\n /// \n /// Gets or sets the number of steps for a slider control.\n /// \n public int? SliderSteps { get; init; }\n\n /// \n /// Gets or sets a value indicating whether this setting is enabled.\n /// \n public bool IsEnabled { get; init; }\n\n /// \n /// Creates a LinkedRegistrySettings object from the RegistrySettings collection.\n /// \n /// A LinkedRegistrySettings object.\n public LinkedRegistrySettings CreateLinkedRegistrySettings()\n {\n if (RegistrySettings.Count == 0)\n {\n return new LinkedRegistrySettings();\n }\n\n var linkedSettings = new LinkedRegistrySettings\n {\n Category = RegistrySettings[0].Category,\n Description = Description,\n Logic = LinkedSettingsLogic\n };\n\n foreach (var registrySetting in RegistrySettings)\n {\n linkedSettings.AddSetting(registrySetting);\n }\n\n return linkedSettings;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Services/ScriptDetectionService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.Services\n{\n /// \n /// Implementation of the IScriptDetectionService interface.\n /// \n public class ScriptDetectionService : IScriptDetectionService\n {\n private const string ScriptsDirectory = @\"C:\\Program Files\\Winhance\\Scripts\";\n \n private static readonly Dictionary ScriptDescriptions = new Dictionary(StringComparer.OrdinalIgnoreCase)\n {\n { \"BloatRemoval.ps1\", \"Multiple items removed via BloatRemoval.ps1\" },\n { \"EdgeRemoval.ps1\", \"Microsoft Edge Removed via EdgeRemoval.ps1\" },\n { \"OneDriveRemoval.ps1\", \"OneDrive Removed via OneDriveRemoval.ps1\" }\n };\n \n /// \n public bool AreRemovalScriptsPresent()\n {\n if (!Directory.Exists(ScriptsDirectory))\n {\n return false;\n }\n \n return GetScriptFiles().Any();\n }\n \n /// \n public IEnumerable GetActiveScripts()\n {\n if (!Directory.Exists(ScriptsDirectory))\n {\n return Enumerable.Empty();\n }\n \n var scriptFiles = GetScriptFiles();\n \n return scriptFiles.Select(file => new ScriptInfo\n {\n Name = Path.GetFileName(file),\n Description = GetScriptDescription(Path.GetFileName(file)),\n FilePath = file\n });\n }\n \n private IEnumerable GetScriptFiles()\n {\n if (!Directory.Exists(ScriptsDirectory))\n {\n return Enumerable.Empty();\n }\n \n return Directory.GetFiles(ScriptsDirectory, \"*.ps1\")\n .Where(file => ScriptDescriptions.ContainsKey(Path.GetFileName(file)));\n }\n \n private string GetScriptDescription(string fileName)\n {\n return ScriptDescriptions.TryGetValue(fileName, out var description)\n ? description\n : $\"Unknown script: {fileName}\";\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Extensions/SettingViewModelExtensions.cs", "using System;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.Interfaces;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.Common.Extensions\n{\n /// \n /// Extension methods for setting view models.\n /// \n public static class SettingViewModelExtensions\n {\n /// \n /// Safely converts an ApplicationSettingViewModel to an ApplicationSettingViewModel if possible.\n /// \n /// The setting to convert.\n /// The setting as an ApplicationSettingViewModel, or null if conversion is not possible.\n public static ApplicationSettingViewModel? AsApplicationSettingViewModel(this ApplicationSettingViewModel setting)\n {\n return setting;\n }\n \n /// \n /// Creates a new ApplicationSettingViewModel with properties copied from an ApplicationSettingViewModel.\n /// \n /// The setting to convert.\n /// The registry service.\n /// The dialog service.\n /// The log service.\n /// The dependency manager.\n /// The view model locator.\n /// The settings registry.\n /// A new ApplicationSettingViewModel with properties copied from the input setting.\n public static ApplicationSettingViewModel ToApplicationSettingViewModel(\n this ApplicationSettingViewModel setting,\n IRegistryService registryService,\n IDialogService? dialogService,\n ILogService logService,\n IDependencyManager? dependencyManager = null,\n IViewModelLocator? viewModelLocator = null,\n ISettingsRegistry? settingsRegistry = null)\n {\n if (setting is ApplicationSettingViewModel applicationSetting)\n {\n return applicationSetting;\n }\n \n var result = new ApplicationSettingViewModel(\n registryService, \n dialogService, \n logService, \n dependencyManager)\n {\n Id = setting.Id,\n Name = setting.Name,\n Description = setting.Description,\n IsSelected = setting.IsSelected,\n GroupName = setting.GroupName,\n IsGroupHeader = setting.IsGroupHeader,\n IsGroupedSetting = setting.IsGroupedSetting,\n ControlType = setting.ControlType,\n SliderSteps = setting.SliderSteps,\n SliderValue = setting.SliderValue,\n Status = setting.Status,\n CurrentValue = setting.CurrentValue,\n StatusMessage = setting.StatusMessage,\n RegistrySetting = setting.RegistrySetting,\n LinkedRegistrySettings = setting.LinkedRegistrySettings,\n Dependencies = setting.Dependencies\n };\n \n // Copy child settings if any\n foreach (var child in setting.ChildSettings)\n {\n result.ChildSettings.Add(child.ToApplicationSettingViewModel(\n registryService, \n dialogService, \n logService, \n dependencyManager, \n viewModelLocator, \n settingsRegistry));\n }\n \n return result;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/Views/WindowsThemeCustomizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Customize.Views\n{\n /// \n /// Interaction logic for WindowsThemeCustomizationsView.xaml\n /// \n public partial class WindowsThemeCustomizationsView : UserControl\n {\n public WindowsThemeCustomizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/CapabilitiesViewModel.cs", "using CommunityToolkit.Mvvm.Input;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Infrastructure.Features.SoftwareApps.Services;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n public partial class CapabilitiesViewModel : AppListViewModel\n {\n private readonly IAppLoadingService _appLoadingService;\n private readonly IInstallationOrchestrator _installationOrchestrator;\n\n public CapabilitiesViewModel(\n IAppLoadingService appLoadingService,\n IInstallationOrchestrator installationOrchestrator,\n ITaskProgressService taskProgressService,\n IPackageManager packageManager)\n : base(taskProgressService, packageManager)\n {\n _appLoadingService = appLoadingService;\n _installationOrchestrator = installationOrchestrator;\n }\n\n public override async Task LoadItemsAsync()\n {\n var capabilities = await _appLoadingService.LoadCapabilitiesAsync();\n Items.Clear();\n foreach (var item in capabilities)\n {\n Items.Add(item);\n }\n }\n\n public override async Task CheckInstallationStatusAsync()\n {\n await Task.Run(async () =>\n {\n foreach (var item in Items)\n {\n // Use the AppLoadingService to check installation status\n item.IsInstalled = await _appLoadingService.GetItemInstallStatusAsync(item);\n }\n });\n }\n\n [RelayCommand]\n private async Task InstallAsync()\n {\n var selected = Items.Where(item => item.IsSelected).ToList();\n if (!selected.Any())\n {\n return;\n }\n await _installationOrchestrator.InstallBatchAsync(selected);\n }\n\n [RelayCommand]\n private async Task RemoveAsync()\n {\n var selected = Items.Where(item => item.IsSelected).ToList();\n if (!selected.Any())\n {\n return;\n }\n await _installationOrchestrator.RemoveBatchAsync(selected);\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Helpers/InstallationErrorHelper.cs", "using System;\nusing Winhance.Core.Features.SoftwareApps.Enums;\n\nnamespace Winhance.Core.Features.SoftwareApps.Helpers\n{\n /// \n /// Helper class for installation error handling.\n /// \n public static class InstallationErrorHelper\n {\n /// \n /// Gets a user-friendly error message based on the error type.\n /// \n /// The type of installation error.\n /// A user-friendly error message.\n public static string GetUserFriendlyErrorMessage(InstallationErrorType errorType)\n {\n return errorType switch\n {\n InstallationErrorType.NetworkError => \n \"Network connection error. Please check your internet connection and try again.\",\n \n InstallationErrorType.PermissionError => \n \"Permission denied. Please run the application with administrator privileges.\",\n \n InstallationErrorType.PackageNotFoundError => \n \"Package not found. The requested package may not be available in the repositories.\",\n \n InstallationErrorType.WinGetNotInstalledError => \n \"WinGet is not installed and could not be installed automatically.\",\n \n InstallationErrorType.AlreadyInstalledError => \n \"The package is already installed.\",\n \n InstallationErrorType.CancelledByUserError => \n \"The installation was cancelled by the user.\",\n \n InstallationErrorType.SystemStateError => \n \"The system is in a state that prevents installation. Please restart your computer and try again.\",\n \n InstallationErrorType.PackageCorruptedError => \n \"The package is corrupted or invalid. Please try reinstalling or contact the package maintainer.\",\n \n InstallationErrorType.DependencyResolutionError => \n \"The package dependencies could not be resolved. Some required components may be missing.\",\n \n InstallationErrorType.UnknownError or _ => \n \"An unknown error occurred during installation. Please check the logs for more details.\"\n };\n }\n\n /// \n /// Determines the error type based on the exception message.\n /// \n /// The exception message.\n /// The determined error type.\n public static InstallationErrorType DetermineErrorType(string exceptionMessage)\n {\n if (string.IsNullOrEmpty(exceptionMessage))\n return InstallationErrorType.UnknownError;\n\n exceptionMessage = exceptionMessage.ToLowerInvariant();\n\n if (exceptionMessage.Contains(\"network\") || \n exceptionMessage.Contains(\"connection\") || \n exceptionMessage.Contains(\"internet\") ||\n exceptionMessage.Contains(\"timeout\") ||\n exceptionMessage.Contains(\"unreachable\"))\n {\n return InstallationErrorType.NetworkError;\n }\n \n if (exceptionMessage.Contains(\"permission\") || \n exceptionMessage.Contains(\"access\") || \n exceptionMessage.Contains(\"denied\") ||\n exceptionMessage.Contains(\"administrator\") ||\n exceptionMessage.Contains(\"elevation\"))\n {\n return InstallationErrorType.PermissionError;\n }\n \n if (exceptionMessage.Contains(\"not found\") || \n exceptionMessage.Contains(\"no package\") ||\n exceptionMessage.Contains(\"no such package\") ||\n exceptionMessage.Contains(\"could not find\"))\n {\n return InstallationErrorType.PackageNotFoundError;\n }\n \n if (exceptionMessage.Contains(\"winget\") && \n (exceptionMessage.Contains(\"not installed\") || \n exceptionMessage.Contains(\"could not be installed\")))\n {\n return InstallationErrorType.WinGetNotInstalledError;\n }\n \n if (exceptionMessage.Contains(\"already installed\") ||\n exceptionMessage.Contains(\"is installed\"))\n {\n return InstallationErrorType.AlreadyInstalledError;\n }\n \n if (exceptionMessage.Contains(\"cancelled\") || \n exceptionMessage.Contains(\"canceled\") ||\n exceptionMessage.Contains(\"aborted\"))\n {\n return InstallationErrorType.CancelledByUserError;\n }\n \n if (exceptionMessage.Contains(\"system state\") || \n exceptionMessage.Contains(\"restart\") ||\n exceptionMessage.Contains(\"reboot\"))\n {\n return InstallationErrorType.SystemStateError;\n }\n \n if (exceptionMessage.Contains(\"corrupt\") || \n exceptionMessage.Contains(\"invalid\") ||\n exceptionMessage.Contains(\"damaged\"))\n {\n return InstallationErrorType.PackageCorruptedError;\n }\n \n if (exceptionMessage.Contains(\"dependency\") || \n exceptionMessage.Contains(\"dependencies\") ||\n exceptionMessage.Contains(\"requires\"))\n {\n return InstallationErrorType.DependencyResolutionError;\n }\n \n return InstallationErrorType.UnknownError;\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/UI/Services/NotificationService.cs", "using System;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.UI.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.UI.Services\n{\n /// \n /// Implementation of the notification service that shows toast notifications.\n /// \n public class NotificationService : INotificationService\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public NotificationService(ILogService logService)\n {\n _logService = logService;\n }\n\n /// \n public void ShowToast(string title, string message, ToastType type)\n {\n // Log the notification\n switch (type)\n {\n case ToastType.Information:\n _logService.LogInformation($\"Toast Notification - {title}: {message}\");\n break;\n case ToastType.Success:\n _logService.LogSuccess($\"Toast Notification - {title}: {message}\");\n break;\n case ToastType.Warning:\n _logService.LogWarning($\"Toast Notification - {title}: {message}\");\n break;\n case ToastType.Error:\n _logService.LogError($\"Toast Notification - {title}: {message}\");\n break;\n default:\n _logService.LogInformation($\"Toast Notification - {title}: {message}\");\n break;\n }\n\n // In a real implementation, this would show a toast notification in the UI\n // For now, we're just logging the notification\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Verification/VerificationMethodBase.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Verification\n{\n /// \n /// Base class for verification methods that check if a package is installed.\n /// \n public abstract class VerificationMethodBase\n {\n /// \n /// Gets the name of the verification method.\n /// \n public string Name { get; }\n\n /// \n /// Gets the priority of this verification method. Lower values mean higher priority.\n /// \n public int Priority { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The name of the verification method.\n /// The priority of the verification method. Lower values mean higher priority.\n protected VerificationMethodBase(string name, int priority)\n {\n Name = name ?? throw new System.ArgumentNullException(nameof(name));\n Priority = priority;\n }\n\n /// \n /// Verifies if a package is installed.\n /// \n /// The ID of the package to verify.\n /// The version of the package to verify, or null to check for any version.\n /// A cancellation token that can be used to cancel the operation.\n /// A task that represents the asynchronous operation. The task result contains the verification result.\n public async Task VerifyAsync(\n string packageId,\n string version = null,\n CancellationToken cancellationToken = default)\n {\n if (string.IsNullOrWhiteSpace(packageId))\n {\n throw new System.ArgumentException(\"Package ID cannot be null or whitespace.\", nameof(packageId));\n }\n\n return version == null\n ? await VerifyPresenceAsync(packageId, cancellationToken).ConfigureAwait(false)\n : await VerifyVersionAsync(packageId, version, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// When overridden in a derived class, verifies if a package is installed, regardless of version.\n /// \n /// The ID of the package to verify.\n /// A cancellation token that can be used to cancel the operation.\n /// A task that represents the asynchronous operation. The task result contains the verification result.\n protected abstract Task VerifyPresenceAsync(\n string packageId,\n CancellationToken cancellationToken);\n\n /// \n /// When overridden in a derived class, verifies if a specific version of a package is installed.\n /// \n /// The ID of the package to verify.\n /// The version of the package to verify.\n /// A cancellation token that can be used to cancel the operation.\n /// A task that represents the asynchronous operation. The task result contains the verification result.\n protected abstract Task VerifyVersionAsync(\n string packageId,\n string version,\n CancellationToken cancellationToken);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Exceptions/InstallationException.cs", "using System;\nusing Winhance.Core.Features.SoftwareApps.Enums;\n\nnamespace Winhance.Core.Features.SoftwareApps.Exceptions\n{\n /// \n /// Exception thrown when there is an error with installation operations.\n /// \n public class InstallationException : Exception\n {\n /// \n /// Gets the type of installation error.\n /// \n public InstallationErrorType ErrorType { get; }\n \n /// \n /// Initializes a new instance of the class.\n /// \n public InstallationException() : base()\n {\n ErrorType = InstallationErrorType.UnknownError;\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message.\n /// \n /// The message that describes the error.\n public InstallationException(string message) : base(message)\n {\n ErrorType = InstallationErrorType.UnknownError;\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message\n /// and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception.\n public InstallationException(string message, Exception innerException) : base(message, innerException)\n {\n ErrorType = InstallationErrorType.UnknownError;\n }\n \n /// \n /// Initializes a new instance of the class with a specified error message,\n /// error type, and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception.\n /// The type of installation error.\n public InstallationException(string message, Exception innerException, InstallationErrorType errorType)\n : base(message, innerException)\n {\n ErrorType = errorType;\n }\n\n /// \n /// Initializes a new instance of the class with a specified item name, error message,\n /// a flag indicating whether the error is critical, and a reference to the inner exception that is the cause of this exception.\n /// \n /// The name of the item that failed to be installed.\n /// The error message.\n /// A flag indicating whether the error is critical.\n /// The exception that is the cause of the current exception.\n public InstallationException(string itemName, string errorMessage, bool isCritical, Exception innerException)\n : base($\"Failed to install {itemName}: {errorMessage}\", innerException)\n {\n ItemName = itemName;\n IsCritical = isCritical;\n ErrorType = InstallationErrorType.UnknownError;\n }\n \n /// \n /// Initializes a new instance of the class with a specified item name, error message,\n /// a flag indicating whether the error is critical, the error type, and a reference to the inner exception that is the cause of this exception.\n /// \n /// The name of the item that failed to be installed.\n /// The error message.\n /// A flag indicating whether the error is critical.\n /// The type of installation error.\n /// The exception that is the cause of the current exception.\n public InstallationException(string itemName, string errorMessage, bool isCritical, InstallationErrorType errorType, Exception innerException)\n : base($\"Failed to install {itemName}: {errorMessage}\", innerException)\n {\n ItemName = itemName;\n IsCritical = isCritical;\n ErrorType = errorType;\n }\n\n /// \n /// Gets the name of the item that failed to be installed.\n /// \n public string? ItemName { get; }\n\n /// \n /// Gets a value indicating whether the error is critical.\n /// \n public bool IsCritical { get; }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/DesignTimeDataService.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.WPF.Features.SoftwareApps.Models;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Implementation of the IDesignTimeDataService interface that provides\n /// realistic sample data for design-time visualization.\n /// \n public class DesignTimeDataService : IDesignTimeDataService\n {\n /// \n /// Gets a collection of sample third-party applications for design-time.\n /// \n /// A collection of ThirdPartyApp instances.\n public IEnumerable GetSampleThirdPartyApps()\n {\n return new List\n {\n new ThirdPartyApp\n {\n Name = \"Visual Studio Code\",\n Description = \"Lightweight code editor with powerful features\",\n PackageName = \"Microsoft.VisualStudioCode\",\n Category = \"Development\",\n IsInstalled = true,\n IsCustomInstall = false\n },\n new ThirdPartyApp\n {\n Name = \"Mozilla Firefox\",\n Description = \"Fast, private and secure web browser\",\n PackageName = \"Mozilla.Firefox\",\n Category = \"Web Browsers\",\n IsInstalled = false,\n IsCustomInstall = false\n },\n new ThirdPartyApp\n {\n Name = \"7-Zip\",\n Description = \"File archiver with high compression ratio\",\n PackageName = \"7zip.7zip\",\n Category = \"Utilities\",\n IsInstalled = true,\n IsCustomInstall = false\n },\n new ThirdPartyApp\n {\n Name = \"Adobe Photoshop\",\n Description = \"Professional image editing software\",\n PackageName = \"Adobe.Photoshop\",\n Category = \"Graphics & Design\",\n IsInstalled = false,\n IsCustomInstall = true\n }\n };\n }\n\n /// \n /// Gets a collection of sample Windows applications for design-time.\n /// \n /// A collection of WindowsApp instances.\n public IEnumerable GetSampleWindowsApps()\n {\n // Create sample AppInfo objects to use with the factory method\n var appInfos = new List\n {\n new AppInfo\n {\n Name = \"Microsoft Store\",\n Description = \"Microsoft's digital distribution platform\",\n PackageName = \"Microsoft.WindowsStore\",\n PackageID = \"9WZDNCRFJBMP\",\n Category = \"System\",\n IsInstalled = true,\n CanBeReinstalled = true,\n IsSystemProtected = false\n },\n new AppInfo\n {\n Name = \"Xbox\",\n Description = \"Xbox console companion app for Windows\",\n PackageName = \"Microsoft.XboxApp\",\n PackageID = \"9MV0B5HZVK9Z\",\n Category = \"Entertainment\",\n IsInstalled = true,\n CanBeReinstalled = true,\n IsSystemProtected = false\n },\n new AppInfo\n {\n Name = \"Microsoft Edge\",\n Description = \"Microsoft's web browser\",\n PackageName = \"Microsoft.MicrosoftEdge\",\n PackageID = \"9NBLGGH4M8RR\",\n Category = \"Web Browsers\",\n IsInstalled = true,\n RequiresSpecialHandling = true,\n SpecialHandlerType = \"Edge\",\n CanBeReinstalled = false,\n IsSystemProtected = true\n },\n new AppInfo\n {\n Name = \"OneDrive\",\n Description = \"Microsoft's cloud storage service\",\n PackageName = \"Microsoft.OneDrive\",\n PackageID = \"9WZDNCRFJ3PL\",\n Category = \"Cloud Storage\",\n IsInstalled = false,\n RequiresSpecialHandling = true,\n SpecialHandlerType = \"OneDrive\",\n CanBeReinstalled = true,\n IsSystemProtected = false\n }\n };\n\n // Use the factory method to create properly configured WindowsApp instances\n var windowsApps = new List();\n foreach (var appInfo in appInfos)\n {\n windowsApps.Add(WindowsApp.FromAppInfo(appInfo));\n }\n\n return windowsApps;\n }\n\n /// \n /// Gets a collection of sample Windows capabilities for design-time.\n /// \n /// A collection of WindowsApp instances configured as capabilities.\n public IEnumerable GetSampleWindowsCapabilities()\n {\n // Create sample CapabilityInfo objects to use with the factory method\n var capabilityInfos = new List\n {\n new CapabilityInfo\n {\n Name = \"Windows Media Player\",\n Description = \"Classic media player for Windows\",\n PackageName = \"Media.WindowsMediaPlayer\",\n Category = \"Media\",\n IsInstalled = true,\n CanBeReenabled = true,\n IsSystemProtected = false\n },\n new CapabilityInfo\n {\n Name = \"Internet Explorer\",\n Description = \"Legacy web browser\",\n PackageName = \"Browser.InternetExplorer\",\n Category = \"Web Browsers\",\n IsInstalled = false,\n CanBeReenabled = true,\n IsSystemProtected = false\n },\n new CapabilityInfo\n {\n Name = \"Windows Hello Face\",\n Description = \"Facial recognition authentication\",\n PackageName = \"Hello.Face\",\n Category = \"Security\",\n IsInstalled = true,\n CanBeReenabled = true,\n IsSystemProtected = true\n }\n };\n\n // Use the factory method to create properly configured WindowsApp instances\n var capabilities = new List();\n foreach (var capabilityInfo in capabilityInfos)\n {\n capabilities.Add(WindowsApp.FromCapabilityInfo(capabilityInfo));\n }\n\n return capabilities;\n }\n\n /// \n /// Gets a collection of sample Windows features for design-time.\n /// \n /// A collection of WindowsApp instances configured as features.\n public IEnumerable GetSampleWindowsFeatures()\n {\n // Create sample FeatureInfo objects to use with the factory method\n var featureInfos = new List\n {\n new FeatureInfo\n {\n Name = \"Windows Subsystem for Linux\",\n Description = \"Run Linux command-line tools on Windows\",\n PackageName = \"Microsoft-Windows-Subsystem-Linux\",\n Category = \"Development\",\n IsInstalled = true,\n CanBeReenabled = true,\n IsSystemProtected = false\n },\n new FeatureInfo\n {\n Name = \"Hyper-V\",\n Description = \"Windows virtualization platform\",\n PackageName = \"Microsoft-Hyper-V-All\",\n Category = \"Virtualization\",\n IsInstalled = false,\n CanBeReenabled = true,\n IsSystemProtected = false\n },\n new FeatureInfo\n {\n Name = \"Windows Sandbox\",\n Description = \"Isolated desktop environment for running applications\",\n PackageName = \"Containers-DisposableClientVM\",\n Category = \"Security\",\n IsInstalled = false,\n CanBeReenabled = true,\n IsSystemProtected = false\n }\n };\n\n // Use the factory method to create properly configured WindowsApp instances\n var features = new List();\n foreach (var featureInfo in featureInfos)\n {\n features.Add(WindowsApp.FromFeatureInfo(featureInfo));\n }\n\n return features;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceCompletion.cs", "using Microsoft.Win32;\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Security.AccessControl;\nusing System.Security.Principal;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.Common.Enums;\nusing LogLevel = Winhance.Core.Features.Common.Enums.LogLevel;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n [SupportedOSPlatform(\"windows\")]\n public partial class RegistryService\n {\n private RegistryKey? GetRootKey(string rootKeyName)\n {\n // Normalize the input by converting to uppercase\n rootKeyName = rootKeyName.ToUpper();\n \n // Check for full names first\n if (rootKeyName == \"HKEY_LOCAL_MACHINE\" || rootKeyName == \"LOCALMACHINE\")\n return Microsoft.Win32.Registry.LocalMachine;\n if (rootKeyName == \"HKEY_CURRENT_USER\" || rootKeyName == \"CURRENTUSER\")\n return Microsoft.Win32.Registry.CurrentUser;\n if (rootKeyName == \"HKEY_CLASSES_ROOT\")\n return Microsoft.Win32.Registry.ClassesRoot;\n if (rootKeyName == \"HKEY_USERS\")\n return Microsoft.Win32.Registry.Users;\n if (rootKeyName == \"HKEY_CURRENT_CONFIG\")\n return Microsoft.Win32.Registry.CurrentConfig;\n \n // Then check for abbreviated names using the extension method's constants\n if (rootKeyName == RegistryExtensions.GetRegistryHiveString(RegistryHive.LocalMachine))\n return Microsoft.Win32.Registry.LocalMachine;\n if (rootKeyName == RegistryExtensions.GetRegistryHiveString(RegistryHive.CurrentUser))\n return Microsoft.Win32.Registry.CurrentUser;\n if (rootKeyName == RegistryExtensions.GetRegistryHiveString(RegistryHive.ClassesRoot))\n return Microsoft.Win32.Registry.ClassesRoot;\n if (rootKeyName == RegistryExtensions.GetRegistryHiveString(RegistryHive.Users))\n return Microsoft.Win32.Registry.Users;\n if (rootKeyName == RegistryExtensions.GetRegistryHiveString(RegistryHive.CurrentConfig))\n return Microsoft.Win32.Registry.CurrentConfig;\n \n // If no match is found, return null\n return null;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/Registry/RegistryServiceCore.cs", "using Microsoft.Win32;\nusing System;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Infrastructure.Features.Common.Registry\n{\n /// \n /// Core implementation of the registry service.\n /// \n [SupportedOSPlatform(\"windows\")]\n public partial class RegistryService : IRegistryService\n {\n private readonly ILogService _logService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The log service.\n public RegistryService(ILogService logService)\n {\n _logService = logService ?? throw new ArgumentNullException(nameof(logService));\n }\n\n /// \n /// Checks if the current platform is Windows.\n /// \n /// True if the platform is Windows; otherwise, logs an error and returns false.\n private bool CheckWindowsPlatform()\n {\n if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n _logService.Log(LogLevel.Error, \"Registry operations are only supported on Windows\");\n return false;\n }\n return true;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Models/ExternalAppSettingItem.cs", "using System.Collections.Generic;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Models\n{\n /// \n /// Adapter class that wraps an ExternalApp and implements ISettingItem.\n /// \n public class ExternalAppSettingItem : ISettingItem\n {\n private readonly ExternalApp _externalApp;\n \n public ExternalAppSettingItem(ExternalApp externalApp)\n {\n _externalApp = externalApp;\n \n // Initialize properties required by ISettingItem\n Id = externalApp.PackageName;\n Name = externalApp.Name;\n Description = externalApp.Description;\n IsSelected = externalApp.IsSelected;\n GroupName = externalApp.Category;\n IsVisible = true;\n ControlType = ControlType.BinaryToggle;\n Dependencies = new List();\n \n // Create a command that does nothing (placeholder)\n ApplySettingCommand = new RelayCommand(() => { });\n }\n \n // ISettingItem implementation\n public string Id { get; set; }\n public string Name { get; set; }\n public string Description { get; set; }\n public bool IsSelected { get; set; }\n public string GroupName { get; set; }\n public bool IsVisible { get; set; }\n public ControlType ControlType { get; set; }\n public List Dependencies { get; set; }\n public bool IsUpdatingFromCode { get; set; }\n public ICommand ApplySettingCommand { get; }\n \n // Method to convert back to ExternalApp\n public ExternalApp ToExternalApp()\n {\n // Update the original ExternalApp with any changes\n _externalApp.IsSelected = IsSelected;\n return _externalApp;\n }\n \n // Static method to convert a collection of ExternalApps to ExternalAppSettingItems\n public static IEnumerable FromExternalApps(IEnumerable externalApps)\n {\n foreach (var app in externalApps)\n {\n yield return new ExternalAppSettingItem(app);\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Models/WindowsAppSettingItem.cs", "using System.Collections.Generic;\nusing System.Windows.Input;\nusing CommunityToolkit.Mvvm.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Models\n{\n /// \n /// Adapter class that wraps a WindowsApp and implements ISettingItem.\n /// \n public class WindowsAppSettingItem : ISettingItem\n {\n private readonly WindowsApp _windowsApp;\n \n public WindowsAppSettingItem(WindowsApp windowsApp)\n {\n _windowsApp = windowsApp;\n \n // Initialize properties required by ISettingItem\n Id = windowsApp.PackageId;\n Name = windowsApp.DisplayName;\n Description = windowsApp.Description;\n IsSelected = windowsApp.IsSelected;\n GroupName = windowsApp.Category;\n IsVisible = true;\n ControlType = ControlType.BinaryToggle;\n Dependencies = new List();\n \n // Create a command that does nothing (placeholder)\n ApplySettingCommand = new RelayCommand(() => { });\n }\n \n // ISettingItem implementation\n public string Id { get; set; }\n public string Name { get; set; }\n public string Description { get; set; }\n public bool IsSelected { get; set; }\n public string GroupName { get; set; }\n public bool IsVisible { get; set; }\n public ControlType ControlType { get; set; }\n public List Dependencies { get; set; }\n public bool IsUpdatingFromCode { get; set; }\n public ICommand ApplySettingCommand { get; }\n \n // Method to convert back to WindowsApp\n public WindowsApp ToWindowsApp()\n {\n // Update the original WindowsApp with any changes\n _windowsApp.IsSelected = IsSelected;\n return _windowsApp;\n }\n \n // Static method to convert a collection of WindowsApps to WindowsAppSettingItems\n public static IEnumerable FromWindowsApps(IEnumerable windowsApps)\n {\n foreach (var app in windowsApps)\n {\n yield return new WindowsAppSettingItem(app);\n }\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Models/ThirdPartyApp.cs", "using CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Models\n{\n /// \n /// Represents a third-party application that can be installed through package managers like winget.\n /// These are applications not built into Windows but available for installation.\n /// \n public partial class ThirdPartyApp : ObservableObject\n {\n [ObservableProperty]\n private string _name = string.Empty;\n\n [ObservableProperty]\n private string _description = string.Empty;\n\n [ObservableProperty]\n private string _packageName = string.Empty;\n \n [ObservableProperty]\n private string _category = string.Empty;\n\n [ObservableProperty]\n private bool _isInstalled;\n\n [ObservableProperty]\n private bool _isCustomInstall;\n\n /// \n /// Determines if the app has a description that should be displayed.\n /// \n public bool HasDescription => !string.IsNullOrEmpty(Description);\n\n public static ThirdPartyApp FromAppInfo(AppInfo appInfo)\n {\n return new ThirdPartyApp\n {\n Name = appInfo.Name,\n Description = appInfo.Description,\n PackageName = appInfo.PackageName,\n Category = appInfo.Category,\n IsInstalled = appInfo.IsInstalled,\n IsCustomInstall = appInfo.IsCustomInstall\n };\n }\n\n /// \n /// Converts this ThirdPartyApp to an AppInfo object.\n /// \n /// An AppInfo object representing this ThirdPartyApp.\n public AppInfo ToAppInfo()\n {\n return new AppInfo\n {\n Name = Name,\n Description = Description,\n PackageName = PackageName,\n Category = Category,\n IsInstalled = IsInstalled,\n IsCustomInstall = IsCustomInstall\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Exceptions/RemovalException.cs", "using System;\n\nnamespace Winhance.Core.Features.SoftwareApps.Exceptions\n{\n /// \n /// Exception thrown when there is an error with removal operations.\n /// \n public class RemovalException : Exception\n {\n /// \n /// Initializes a new instance of the class.\n /// \n public RemovalException() : base()\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message.\n /// \n /// The message that describes the error.\n public RemovalException(string message) : base(message)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message\n /// and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception.\n public RemovalException(string message, Exception innerException) : base(message, innerException)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified item name, error message,\n /// a flag indicating whether the error is critical, and a reference to the inner exception that is the cause of this exception.\n /// \n /// The name of the item that failed to be removed.\n /// The error message.\n /// A flag indicating whether the error is critical.\n /// The exception that is the cause of the current exception.\n public RemovalException(string itemName, string errorMessage, bool isCritical, Exception innerException)\n : base($\"Failed to remove {itemName}: {errorMessage}\", innerException)\n {\n ItemName = itemName;\n IsCritical = isCritical;\n }\n\n /// \n /// Gets the name of the item that failed to be removed.\n /// \n public string? ItemName { get; }\n\n /// \n /// Gets a value indicating whether the error is critical.\n /// \n public bool IsCritical { get; }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/VerificationResult.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents the result of a verification operation.\n /// \n public class VerificationResult\n {\n /// \n /// Gets or sets a value indicating whether the verification was successful.\n /// \n public bool IsVerified { get; set; }\n\n /// \n /// Gets or sets the version that was verified, if applicable.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets an optional message providing additional information about the verification.\n /// \n public string Message { get; set; }\n\n /// \n /// Gets or sets the name of the verification method that was used.\n /// \n public string MethodUsed { get; set; }\n\n /// \n /// Gets or sets additional information about the verification result.\n /// This can be any object containing relevant details.\n /// \n public object AdditionalInfo { get; set; }\n\n /// \n /// Creates a successful verification result.\n /// \n /// The version that was verified.\n /// The name of the verification method that was used.\n /// Additional information about the verification result.\n /// A successful verification result.\n public static VerificationResult Success(string version = null, string methodUsed = null, object additionalInfo = null)\n {\n return new VerificationResult\n {\n IsVerified = true,\n Version = version,\n MethodUsed = methodUsed,\n AdditionalInfo = additionalInfo\n };\n }\n\n /// \n /// Creates a failed verification result.\n /// \n /// An optional message explaining why the verification failed.\n /// The name of the verification method that was used.\n /// Additional information about the verification result.\n /// A failed verification result.\n public static VerificationResult Failure(string message = null, string methodUsed = null, object additionalInfo = null)\n {\n return new VerificationResult\n {\n IsVerified = false,\n Message = message,\n MethodUsed = methodUsed,\n AdditionalInfo = additionalInfo\n };\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Exceptions/InstallationException.cs", "using System;\n\nnamespace Winhance.Core.Models.Exceptions\n{\n public class InstallationException : Exception \n {\n public bool IsRecoverable { get; }\n public string ItemName { get; }\n \n public InstallationException(string itemName, string message, \n bool isRecoverable = false, Exception? inner = null)\n : base(message, inner)\n {\n ItemName = itemName;\n IsRecoverable = isRecoverable;\n }\n }\n\n public class InstallationCancelledException : InstallationException\n {\n public InstallationCancelledException(string itemName)\n : base(itemName, $\"Installation cancelled for {itemName}\", true) { }\n }\n\n public class DependencyInstallationException : InstallationException\n {\n public string DependencyName { get; }\n\n public DependencyInstallationException(string itemName, string dependencyName)\n : base(itemName, $\"Dependency {dependencyName} failed to install for {itemName}\", true)\n {\n DependencyName = dependencyName;\n }\n }\n\n public class ItemOperationException : InstallationException\n {\n public ItemOperationException(string itemName, string operation, string message, \n bool isRecoverable = false, Exception? inner = null)\n : base(itemName, $\"{operation} failed for {itemName}: {message}\", isRecoverable, inner) { }\n }\n\n public class RemovalException : ItemOperationException\n {\n public RemovalException(string itemName, string message, \n bool isRecoverable = false, Exception? inner = null)\n : base(itemName, \"removal\", message, isRecoverable, inner) { }\n }\n\n public class BatchOperationException : InstallationException\n {\n public int FailedCount { get; }\n public string OperationType { get; }\n\n public BatchOperationException(string operationType, int failedCount, int totalCount)\n : base(\"multiple items\", \n $\"{operationType} failed for {failedCount} of {totalCount} items\", \n true)\n {\n OperationType = operationType;\n FailedCount = failedCount;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppInstallationCoordinatorService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Coordinates the installation of applications, handling connectivity monitoring,\n /// user notifications, and installation state management.\n /// \n public interface IAppInstallationCoordinatorService\n {\n /// \n /// Installs an application with connectivity monitoring and proper cancellation handling.\n /// \n /// The application information.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the installation operation with the result.\n Task InstallAppAsync(\n AppInfo appInfo,\n IProgress progress,\n CancellationToken cancellationToken = default);\n \n /// \n /// Event that is raised when the installation status changes.\n /// \n event EventHandler InstallationStatusChanged;\n }\n \n /// \n /// Result of an installation coordination operation.\n /// \n public class InstallationCoordinationResult\n {\n /// \n /// Gets or sets a value indicating whether the installation was successful.\n /// \n public bool Success { get; set; }\n \n /// \n /// Gets or sets the error message if the installation failed.\n /// \n public string ErrorMessage { get; set; }\n \n /// \n /// Gets or sets a value indicating whether the installation was cancelled by the user.\n /// \n public bool WasCancelled { get; set; }\n \n /// \n /// Gets or sets a value indicating whether the installation failed due to connectivity issues.\n /// \n public bool WasConnectivityIssue { get; set; }\n \n /// \n /// Gets or sets the application information.\n /// \n public AppInfo AppInfo { get; set; }\n }\n \n /// \n /// Event arguments for installation status change events.\n /// \n public class InstallationStatusChangedEventArgs : EventArgs\n {\n /// \n /// Gets the application information.\n /// \n public AppInfo AppInfo { get; }\n \n /// \n /// Gets the status message.\n /// \n public string StatusMessage { get; }\n \n /// \n /// Gets a value indicating whether the installation is complete.\n /// \n public bool IsComplete { get; }\n \n /// \n /// Gets a value indicating whether the installation was successful.\n /// \n public bool IsSuccess { get; }\n \n /// \n /// Gets a value indicating whether the installation was cancelled by the user.\n /// \n public bool IsCancelled { get; }\n \n /// \n /// Gets a value indicating whether the installation failed due to connectivity issues.\n /// \n public bool IsConnectivityIssue { get; }\n \n /// \n /// Gets the timestamp when the status changed.\n /// \n public DateTime Timestamp { get; }\n \n /// \n /// Initializes a new instance of the class.\n /// \n /// The application information.\n /// The status message.\n /// Whether the installation is complete.\n /// Whether the installation was successful.\n /// Whether the installation was cancelled by the user.\n /// Whether the installation failed due to connectivity issues.\n public InstallationStatusChangedEventArgs(\n AppInfo appInfo,\n string statusMessage,\n bool isComplete = false,\n bool isSuccess = false,\n bool isCancelled = false,\n bool isConnectivityIssue = false)\n {\n AppInfo = appInfo;\n StatusMessage = statusMessage;\n IsComplete = isComplete;\n IsSuccess = isSuccess;\n IsCancelled = isCancelled;\n IsConnectivityIssue = isConnectivityIssue;\n Timestamp = DateTime.Now;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/OperationResult.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents the result of an operation, including success status, error details, and a result value.\n /// \n /// The type of the result value.\n public class OperationResult\n {\n /// \n /// Gets or sets a value indicating whether the operation was successful.\n /// \n public bool Success { get; set; }\n\n /// \n /// Gets or sets the result value of the operation.\n /// \n public T? Result { get; set; }\n\n /// \n /// Gets or sets the error message if the operation failed.\n /// \n public string? ErrorMessage { get; set; }\n\n /// \n /// Gets or sets the exception that occurred during the operation, if any.\n /// \n public Exception? Exception { get; set; }\n\n /// \n /// Gets or sets additional error details.\n /// \n public Dictionary? ErrorDetails { get; set; }\n\n /// \n /// Creates a successful operation result with the specified result value.\n /// \n /// The result value.\n /// A successful operation result.\n public static OperationResult CreateSuccess(T result)\n {\n return new OperationResult\n {\n Success = true,\n Result = result\n };\n }\n\n /// \n /// Creates a failed operation result with the specified error message.\n /// \n /// The error message.\n /// A failed operation result.\n public static OperationResult CreateFailure(string errorMessage)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = errorMessage\n };\n }\n\n /// \n /// Creates a failed operation result with the specified exception.\n /// \n /// The exception that occurred.\n /// A failed operation result.\n public static OperationResult CreateFailure(Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = exception.Message,\n Exception = exception\n };\n }\n\n /// \n /// Creates a failed operation result with the specified error message and exception.\n /// \n /// The error message.\n /// The exception that occurred.\n /// A failed operation result.\n public static OperationResult CreateFailure(string errorMessage, Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = errorMessage,\n Exception = exception\n };\n }\n\n /// \n /// Checks if the operation was successful.\n /// \n /// True if the operation was successful; otherwise, false.\n public bool Succeeded()\n {\n return Success;\n }\n\n /// \n /// Creates a successful operation result with the specified message.\n /// \n /// The message.\n /// A successful operation result.\n public static OperationResult Succeeded(string message)\n {\n return new OperationResult\n {\n Success = true,\n ErrorMessage = message\n };\n }\n\n /// \n /// Creates a successful operation result with the specified result value.\n /// \n /// The result value.\n /// A successful operation result.\n public static OperationResult Succeeded(T result)\n {\n return new OperationResult\n {\n Success = true,\n Result = result\n };\n }\n\n /// \n /// Checks if the operation failed.\n /// \n /// True if the operation failed; otherwise, false.\n public bool Failed()\n {\n return !Success;\n }\n\n /// \n /// Creates a failed operation result with the specified message.\n /// \n /// The message.\n /// A failed operation result.\n public static OperationResult Failed(string message)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = message\n };\n }\n\n /// \n /// Creates a failed operation result with the specified message and exception.\n /// \n /// The message.\n /// The exception.\n /// A failed operation result.\n public static OperationResult Failed(string message, Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = message,\n Exception = exception\n };\n }\n\n /// \n /// Creates a failed operation result with the specified message and result value.\n /// \n /// The error message.\n /// The result value to set even though the operation failed.\n /// A failed operation result with the specified result value.\n public static OperationResult Failed(string message, T result)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = message,\n Result = result\n };\n }\n }\n\n /// \n /// Represents the result of an operation, including success status and error details.\n /// \n public class OperationResult\n {\n /// \n /// Gets or sets a value indicating whether the operation was successful.\n /// \n public bool Success { get; set; }\n\n /// \n /// Gets or sets the error message if the operation failed.\n /// \n public string? ErrorMessage { get; set; }\n\n /// \n /// Gets or sets the exception that occurred during the operation, if any.\n /// \n public Exception? Exception { get; set; }\n\n /// \n /// Gets or sets additional error details.\n /// \n public Dictionary? ErrorDetails { get; set; }\n\n /// \n /// Creates a successful operation result.\n /// \n /// A successful operation result.\n public static OperationResult CreateSuccess()\n {\n return new OperationResult\n {\n Success = true\n };\n }\n\n /// \n /// Creates a failed operation result with the specified error message.\n /// \n /// The error message.\n /// A failed operation result.\n public static OperationResult CreateFailure(string errorMessage)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = errorMessage\n };\n }\n\n /// \n /// Creates a failed operation result with the specified exception.\n /// \n /// The exception that occurred.\n /// A failed operation result.\n public static OperationResult CreateFailure(Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = exception.Message,\n Exception = exception\n };\n }\n\n /// \n /// Creates a failed operation result with the specified error message and exception.\n /// \n /// The error message.\n /// The exception that occurred.\n /// A failed operation result.\n public static OperationResult CreateFailure(string errorMessage, Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = errorMessage,\n Exception = exception\n };\n }\n\n /// \n /// Checks if the operation was successful.\n /// \n /// True if the operation was successful; otherwise, false.\n public bool Succeeded()\n {\n return Success;\n }\n\n /// \n /// Creates a successful operation result with the specified message.\n /// \n /// The message.\n /// A successful operation result.\n public static OperationResult Succeeded(string message)\n {\n return new OperationResult\n {\n Success = true,\n ErrorMessage = message\n };\n }\n\n /// \n /// Checks if the operation failed.\n /// \n /// True if the operation failed; otherwise, false.\n public bool Failed()\n {\n return !Success;\n }\n\n /// \n /// Creates a failed operation result with the specified message.\n /// \n /// The message.\n /// A failed operation result.\n public static OperationResult Failed(string message)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = message\n };\n }\n\n /// \n /// Creates a failed operation result with the specified message and exception.\n /// \n /// The message.\n /// The exception.\n /// A failed operation result.\n public static OperationResult Failed(string message, Exception exception)\n {\n return new OperationResult\n {\n Success = false,\n ErrorMessage = message,\n Exception = exception\n };\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IScriptGenerationService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for generating scripts for application removal and management.\n /// \n public interface IScriptGenerationService\n {\n /// \n /// Creates a batch removal script for applications.\n /// \n /// The application names to generate a removal script for.\n /// Dictionary mapping app names to registry settings.\n /// A removal script object.\n Task CreateBatchRemovalScriptAsync(\n List appNames,\n Dictionary> appsWithRegistry);\n\n /// \n /// Creates a batch removal script for a single application.\n /// \n /// The path where the script should be saved.\n /// The application to generate a removal script for.\n /// True if the script was created successfully; otherwise, false.\n Task CreateBatchRemovalScriptAsync(string scriptPath, AppInfo app);\n\n /// \n /// Updates the bloat removal script for an installed application.\n /// \n /// The application to update the script for.\n /// True if the script was updated successfully; otherwise, false.\n Task UpdateBloatRemovalScriptForInstalledAppAsync(AppInfo app);\n\n /// \n /// Registers a removal task in the Windows Task Scheduler.\n /// \n /// The script to register.\n /// A task representing the asynchronous operation.\n Task RegisterRemovalTaskAsync(RemovalScript script);\n\n /// \n /// Registers a removal task in the Windows Task Scheduler.\n /// \n /// The name of the task.\n /// The path to the script.\n /// True if the task was registered successfully; otherwise, false.\n Task RegisterRemovalTaskAsync(string taskName, string scriptPath);\n\n /// \n /// Saves a script to a file.\n /// \n /// The script to save.\n /// A task representing the asynchronous operation.\n Task SaveScriptAsync(RemovalScript script);\n\n /// \n /// Saves a script to a file.\n /// \n /// The path where the script should be saved.\n /// The content of the script.\n /// True if the script was saved successfully; otherwise, false.\n Task SaveScriptAsync(string scriptPath, string scriptContent);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/LinkedRegistrySettings.cs", "using System.Collections.Generic;\nusing Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents a collection of registry settings that should be treated as a single logical setting.\n /// This allows multiple registry keys to be controlled by a single toggle in the UI.\n /// \n public class LinkedRegistrySettings\n {\n /// \n /// Gets or sets the list of registry settings that are linked together.\n /// \n public List Settings { get; set; } = new List();\n\n /// \n /// Gets or sets the category for all linked settings.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description for all linked settings.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the logic to use when determining the status of linked settings.\n /// Default is Any, which means if any setting is applied, the entire setting is considered applied.\n /// \n public LinkedSettingsLogic Logic { get; set; } = LinkedSettingsLogic.Any;\n\n /// \n /// Creates a new instance of the LinkedRegistrySettings class.\n /// \n public LinkedRegistrySettings()\n {\n }\n\n /// \n /// Creates a new instance of the LinkedRegistrySettings class with a single registry setting.\n /// \n /// The registry setting to include.\n public LinkedRegistrySettings(RegistrySetting registrySetting)\n {\n if (registrySetting != null)\n {\n Settings.Add(registrySetting);\n Category = registrySetting.Category;\n Description = registrySetting.Description;\n }\n }\n\n /// \n /// Creates a new instance of the LinkedRegistrySettings class with a specific logic type.\n /// \n /// The logic to use when determining the status of linked settings.\n public LinkedRegistrySettings(LinkedSettingsLogic logic)\n {\n Logic = logic;\n }\n\n /// \n /// Adds a registry setting to the linked collection.\n /// \n /// The registry setting to add.\n public void AddSetting(RegistrySetting registrySetting)\n {\n if (registrySetting != null)\n {\n Settings.Add(registrySetting);\n }\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/RemovalScript.cs", "using System;\nusing System.IO;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a script for removing applications and preventing their reinstallation.\n/// \npublic class RemovalScript\n{\n /// \n /// Gets or sets the name of the script.\n /// \n public string Name { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the content of the script.\n /// \n public string Content { get; init; } = string.Empty;\n\n /// \n /// Gets or sets the name of the scheduled task to create for running the script.\n /// \n public string TargetScheduledTaskName { get; init; } = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether the script should run on system startup.\n /// \n public bool RunOnStartup { get; init; }\n\n /// \n /// Gets the path where the script will be saved.\n /// \n public string ScriptPath => Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),\n \"Winhance\",\n \"Scripts\",\n $\"{Name}.ps1\");\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IInternetConnectivityService.cs", "using System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for services that check and monitor internet connectivity.\n /// \n public interface IInternetConnectivityService\n {\n /// \n /// Checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// True if internet is connected, false otherwise.\n bool IsInternetConnected(bool forceCheck = false);\n\n /// \n /// Asynchronously checks if the system has an active internet connection.\n /// \n /// If true, bypasses the cache and performs a fresh check.\n /// Cancellation token for the operation.\n /// True if internet is connected, false otherwise.\n Task IsInternetConnectedAsync(bool forceCheck = false, CancellationToken cancellationToken = default, bool userInitiatedCancellation = false);\n \n /// \n /// Event that is raised when the internet connectivity status changes.\n /// \n event EventHandler ConnectivityChanged;\n \n /// \n /// Starts monitoring internet connectivity at the specified interval.\n /// \n /// The interval in seconds between connectivity checks.\n /// Cancellation token to stop monitoring.\n /// A task representing the monitoring operation.\n Task StartMonitoringAsync(int intervalSeconds = 5, CancellationToken cancellationToken = default);\n \n /// \n /// Stops monitoring internet connectivity.\n /// \n void StopMonitoring();\n }\n \n /// \n /// Event arguments for connectivity change events.\n /// \n public class ConnectivityChangedEventArgs : EventArgs\n {\n /// \n /// Gets a value indicating whether the internet is connected.\n /// \n public bool IsConnected { get; }\n \n /// \n /// Gets a value indicating whether the connectivity change was due to user cancellation.\n /// \n public bool IsUserCancelled { get; }\n \n /// \n /// Gets the timestamp when the connectivity status changed.\n /// \n public DateTime Timestamp { get; }\n \n /// \n /// Initializes a new instance of the class.\n /// \n /// Whether the internet is connected.\n /// Whether the connectivity change was due to user cancellation.\n public ConnectivityChangedEventArgs(bool isConnected, bool isUserCancelled = false)\n {\n IsConnected = isConnected;\n IsUserCancelled = isUserCancelled;\n Timestamp = DateTime.Now;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/NotificationOptimizations.cs", "using Microsoft.Win32;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Optimize.Models;\n\npublic static class NotificationOptimizations\n{\n public static OptimizationGroup GetNotificationOptimizations()\n {\n return new OptimizationGroup\n {\n Name = \"Notifications\",\n Category = OptimizationCategory.Notifications,\n Settings = new List\n {\n new OptimizationSetting\n {\n Id = \"notifications-toast\",\n Name = \"Windows Notifications\",\n Description = \"Controls toast notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\PushNotifications\",\n Name = \"ToastEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls toast notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-sound\",\n Name = \"Notification Sounds\",\n Description = \"Controls notification sounds\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\",\n Name = \"NOC_GLOBAL_SETTING_ALLOW_NOTIFICATION_SOUND\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls notification sounds\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-toast-above-lock\",\n Name = \"Notifications On Lock Screen\",\n Description = \"Controls notifications above lock screen\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\",\n Name = \"NOC_GLOBAL_SETTING_ALLOW_TOASTS_ABOVE_LOCK\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls notifications on lock screen\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n },\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\PushNotifications\",\n Name = \"LockScreenToastEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls notifications on lock screen\",\n IsPrimary = false,\n AbsenceMeansEnabled = true\n }\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All\n },\n new OptimizationSetting\n {\n Id = \"notifications-critical-toast-above-lock\",\n Name = \"Show Reminders and VoIP Calls Notifications\",\n Description = \"Controls critical notifications above lock screen\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\",\n Name = \"NOC_GLOBAL_SETTING_ALLOW_CRITICAL_TOASTS_ABOVE_LOCK\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls critical notifications above lock screen\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-security-maintenance\",\n Name = \"Security and Maintenance Notifications\",\n Description = \"Controls security and maintenance notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\\\\Windows.SystemToast.SecurityAndMaintenance\",\n Name = \"Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls security and maintenance notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-capability-access\",\n Name = \"Capability Access Notifications\",\n Description = \"Controls capability access notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\\\\Windows.SystemToast.CapabilityAccess\",\n Name = \"Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls capability access notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-startup-app\",\n Name = \"Startup App Notifications\",\n Description = \"Controls startup app notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Notifications\\\\Settings\\\\Windows.SystemToast.StartupApp\",\n Name = \"Enabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls startup app notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-system-setting-engagement\",\n Name = \"System Setting Engagement Notifications\",\n Description = \"Controls system setting engagement notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\UserProfileEngagement\",\n Name = \"ScoobeSystemSettingEnabled\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls system setting engagement notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-app-location-request\",\n Name = \"Notify when apps request location\",\n Description = \"Controls wheter notifications are shown for location requests\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"Privacy Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\CapabilityAccessManager\\\\ConsentStore\\\\location\",\n Name = \"ShowGlobalPrompts\",\n RecommendedValue = 1,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls wheter notifications are shown for location requests\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n },\n new OptimizationSetting\n {\n Id = \"notifications-windows-security\",\n Name = \"Windows Security Notifications\",\n Description = \"Controls whether Windows Security notifications are shown\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"Security Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Microsoft\\\\Windows Defender Security Center\\\\Notifications\",\n Name = \"DisableNotifications\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls whether Windows Security Center notifications are shown\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n },\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows Defender Security Center\\\\Notifications\",\n Name = \"DisableNotifications\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls whether Windows Defender Security Center notifications are shown\",\n IsPrimary = false,\n AbsenceMeansEnabled = true\n },\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.LocalMachine,\n SubKey = \"SOFTWARE\\\\Policies\\\\Microsoft\\\\Windows Defender Security Center\\\\Notifications\",\n Name = \"DisableEnhancedNotifications\",\n RecommendedValue = 0,\n EnabledValue = 0,\n DisabledValue = 1,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 0,\n Description = \"Controls whether Windows Defender Security Center notifications are shown\",\n IsPrimary = false,\n AbsenceMeansEnabled = true\n }\n },\n LinkedSettingsLogic = LinkedSettingsLogic.All\n },\n new OptimizationSetting\n {\n Id = \"notifications-clock-change\",\n Name = \"Clock Change Notifications\",\n Description = \"Controls clock change notifications\",\n Category = OptimizationCategory.Notifications,\n GroupName = \"System Notifications\",\n IsEnabled = false,\n ControlType = ControlType.BinaryToggle,\n RegistrySettings = new List\n {\n new RegistrySetting\n {\n Category = \"Notifications\",\n Hive = RegistryHive.CurrentUser,\n SubKey = \"Control Panel\\\\Desktop\",\n Name = \"DstNotification\",\n RecommendedValue = 0,\n EnabledValue = 1,\n DisabledValue = 0,\n ValueType = RegistryValueKind.DWord,\n DefaultValue = 1,\n Description = \"Controls clock change notifications\",\n IsPrimary = true,\n AbsenceMeansEnabled = true\n }\n }\n }\n }\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IPowerShellExecutionService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides functionality for executing PowerShell scripts.\n /// \n public interface IPowerShellExecutionService\n {\n /// \n /// Executes a PowerShell script.\n /// \n /// The script to execute.\n /// The progress reporter.\n /// The cancellation token.\n /// The output of the script.\n Task ExecuteScriptAsync(\n string script,\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Executes a PowerShell script file.\n /// \n /// The path to the script file.\n /// The arguments to pass to the script.\n /// The progress reporter.\n /// The cancellation token.\n /// The output of the script.\n Task ExecuteScriptFileAsync(\n string scriptPath,\n string arguments = \"\",\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ITaskProgressService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides functionality for tracking task progress.\n /// \n public interface ITaskProgressService\n {\n /// \n /// Gets a value indicating whether a task is currently running.\n /// \n bool IsTaskRunning { get; }\n\n /// \n /// Gets the current progress value (0-100).\n /// \n int CurrentProgress { get; }\n\n /// \n /// Gets the current status text.\n /// \n string CurrentStatusText { get; }\n\n /// \n /// Gets a value indicating whether the current task progress is indeterminate.\n /// \n bool IsIndeterminate { get; }\n\n /// \n /// Gets the cancellation token source for the current task.\n /// \n CancellationTokenSource? CurrentTaskCancellationSource { get; }\n\n /// \n /// Starts a new task.\n /// \n /// The name of the task.\n /// Whether the task progress is indeterminate.\n /// A cancellation token source for the task.\n CancellationTokenSource StartTask(string taskName, bool isIndeterminate = false);\n\n /// \n /// Updates the progress of the current task.\n /// \n /// The progress percentage (0-100).\n /// The status text.\n void UpdateProgress(int progressPercentage, string? statusText = null);\n\n /// \n /// Updates the progress of the current task with detailed information.\n /// \n /// The detailed progress information.\n void UpdateDetailedProgress(TaskProgressDetail detail);\n\n /// \n /// Completes the current task.\n /// \n void CompleteTask();\n\n /// \n /// Adds a log message to the task progress.\n /// \n /// The log message.\n void AddLogMessage(string message);\n\n /// \n /// Cancels the current task.\n /// \n void CancelCurrentTask();\n\n /// \n /// Creates a progress reporter for detailed progress.\n /// \n /// The progress reporter.\n IProgress CreateDetailedProgress();\n\n /// \n /// Creates a progress reporter for PowerShell progress.\n /// \n /// The progress reporter.\n IProgress CreatePowerShellProgress();\n\n /// \n /// Event raised when progress is updated.\n /// \n event EventHandler? ProgressUpdated;\n \n /// \n /// Event raised when progress is updated (legacy compatibility).\n /// \n event EventHandler? ProgressChanged;\n\n /// \n /// Event raised when a log message is added.\n /// \n event EventHandler? LogMessageAdded;\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/AppModels.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\npublic enum AppInstallType\n{\n Store,\n WinGet,\n DirectDownload,\n Custom\n}\n\npublic enum TaskAction\n{\n Apply,\n Test,\n Rollback\n}\n\npublic record AppInstallConfig\n{\n public required string FriendlyName { get; init; }\n public required AppInstallType InstallType { get; init; }\n public string? PackageId { get; init; }\n public string? DownloadUrl { get; init; }\n public string? CustomInstallHandler { get; init; }\n public IDictionary? CustomProperties { get; init; }\n public bool IsInstalled { get; init; }\n}\n\npublic record InstallResult\n{\n public required bool Success { get; init; }\n public string? ErrorMessage { get; init; }\n public Exception? Exception { get; init; }\n}\n\npublic class RegistryTestResult\n{\n public string KeyPath { get; set; } = string.Empty;\n public string ValueName { get; set; } = string.Empty;\n public bool IsSuccess { get; set; }\n public object? ActualValue { get; set; }\n public object? ExpectedValue { get; set; }\n public string Message { get; set; } = string.Empty;\n public string Description { get; set; } = string.Empty;\n public string Category { get; set; } = string.Empty;\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IParameterSerializer.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for serializing and deserializing navigation parameters.\n /// \n public interface IParameterSerializer\n {\n /// \n /// Serializes an object to a string representation.\n /// \n /// The object to serialize.\n /// A string representation of the object.\n string Serialize(object parameter);\n\n /// \n /// Deserializes a string to an object of the specified type.\n /// \n /// The type to deserialize to.\n /// The string to deserialize.\n /// The deserialized object.\n object Deserialize(Type targetType, string value);\n\n /// \n /// Deserializes a string to an object of the specified type.\n /// \n /// The type to deserialize to.\n /// The string to deserialize.\n /// The deserialized object.\n T Deserialize(string serialized);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Optimize/Interfaces/IPowerPlanService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Optimize.Models;\n\nnamespace Winhance.Core.Features.Optimize.Interfaces\n{\n /// \n /// Provides functionality for managing Windows power plans.\n /// \n public interface IPowerPlanService\n {\n /// \n /// Gets the GUID of the currently active power plan.\n /// \n /// The GUID of the active power plan.\n Task GetActivePowerPlanGuidAsync();\n\n /// \n /// Sets the active power plan.\n /// \n /// The GUID of the power plan to set as active.\n /// True if the operation succeeded; otherwise, false.\n Task SetPowerPlanAsync(string planGuid);\n\n /// \n /// Ensures that a power plan with the specified GUID exists.\n /// If it doesn't exist, creates it from the source plan if specified.\n /// \n /// The GUID of the power plan to ensure exists.\n /// The GUID of the source plan to create from, if needed.\n /// True if the plan exists or was created successfully; otherwise, false.\n Task EnsurePowerPlanExistsAsync(string planGuid, string sourcePlanGuid = null);\n\n /// \n /// Gets a list of all available power plans.\n /// \n /// A list of available power plans.\n Task> GetAvailablePowerPlansAsync();\n \n /// \n /// Executes a PowerCfg command.\n /// \n /// The PowerCfg command to execute.\n /// True if the operation succeeded; otherwise, false.\n Task ExecutePowerCfgCommandAsync(string command);\n \n /// \n /// Applies a power setting using PowerCfg.\n /// \n /// The subgroup GUID.\n /// The setting GUID.\n /// The value to set.\n /// True if this is an AC (plugged in) setting; false for DC (battery) setting.\n /// True if the operation succeeded; otherwise, false.\n Task ApplyPowerSettingAsync(string subgroupGuid, string settingGuid, string value, bool isAcSetting);\n \n /// \n /// Applies a collection of PowerCfg settings.\n /// \n /// The collection of PowerCfg settings to apply.\n /// True if all operations succeeded; otherwise, false.\n Task ApplyPowerCfgSettingsAsync(List settings);\n \n /// \n /// Checks if a PowerCfg setting is currently applied.\n /// \n /// The PowerCfg setting to check.\n /// True if the setting is applied; otherwise, false.\n Task IsPowerCfgSettingAppliedAsync(PowerCfgSetting setting);\n \n /// \n /// Checks if all PowerCfg settings in a collection are currently applied.\n /// \n /// The collection of PowerCfg settings to check.\n /// True if all settings are applied; otherwise, false.\n Task AreAllPowerCfgSettingsAppliedAsync(List settings);\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/RegistryScriptHelper.cs", "using System;\nusing Microsoft.Win32;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\n/// \n/// Provides helper methods for working with registry scripts.\n/// \npublic static class RegistryScriptHelper\n{\n /// \n /// Converts a RegistryValueKind to the corresponding reg.exe type string.\n /// \n /// The registry value kind.\n /// The reg.exe type string.\n public static string GetRegTypeString(RegistryValueKind valueKind)\n {\n return valueKind switch\n {\n RegistryValueKind.String => \"REG_SZ\",\n RegistryValueKind.ExpandString => \"REG_EXPAND_SZ\",\n RegistryValueKind.Binary => \"REG_BINARY\",\n RegistryValueKind.DWord => \"REG_DWORD\",\n RegistryValueKind.MultiString => \"REG_MULTI_SZ\",\n RegistryValueKind.QWord => \"REG_QWORD\",\n _ => \"REG_SZ\"\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/UnifiedConfigurationFile.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents a unified configuration file that stores settings for multiple parts of the application.\n /// \n public class UnifiedConfigurationFile\n {\n /// \n /// Gets or sets the version of the configuration file format.\n /// \n public string Version { get; set; } = \"1.0\";\n\n /// \n /// Gets or sets the date and time when the configuration file was created.\n /// \n public DateTime CreatedAt { get; set; } = DateTime.UtcNow;\n\n /// \n /// Gets or sets the Windows Apps configuration section.\n /// \n public ConfigSection WindowsApps { get; set; } = new ConfigSection();\n\n /// \n /// Gets or sets the External Apps configuration section.\n /// \n public ConfigSection ExternalApps { get; set; } = new ConfigSection();\n\n /// \n /// Gets or sets the Customize configuration section.\n /// \n public ConfigSection Customize { get; set; } = new ConfigSection();\n\n /// \n /// Gets or sets the Optimize configuration section.\n /// \n public ConfigSection Optimize { get; set; } = new ConfigSection();\n }\n\n /// \n /// Represents a section in the unified configuration file.\n /// \n public class ConfigSection\n {\n /// \n /// Gets or sets a value indicating whether this section is included in the configuration.\n /// \n public bool IsIncluded { get; set; } = false;\n\n /// \n /// Gets or sets the collection of configuration items in this section.\n /// \n public List Items { get; set; } = new List();\n\n /// \n /// Gets or sets the description of this section.\n /// \n public string Description { get; set; }\n\n /// \n /// Gets or sets the icon for this section.\n /// \n public string Icon { get; set; }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/WinGetModels.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents the result of a package installation operation.\n /// \n public class InstallationResult\n {\n /// \n /// Gets or sets a value indicating whether the installation was successful.\n /// \n public bool Success { get; set; }\n\n /// \n /// Gets or sets an optional message providing additional information about the result.\n /// \n public string Message { get; set; }\n\n /// \n /// Gets or sets the package ID that was installed.\n /// \n public string PackageId { get; set; }\n\n /// \n /// Gets or sets the version of the package that was installed.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets the exit code from the installation process.\n /// \n public int ExitCode { get; set; }\n\n /// \n /// Gets or sets the standard output from the installation process.\n /// \n public string Output { get; set; }\n\n /// \n /// Gets or sets the error output from the installation process.\n /// \n public string Error { get; set; }\n }\n\n \n /// \n /// Represents options for package installation.\n /// \n public class InstallationOptions\n {\n /// \n /// Gets or sets the version of the package to install. If null, the latest version is installed.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets the source to install the package from.\n /// \n public string Source { get; set; }\n\n /// \n /// Gets or sets a value indicating whether to accept package agreements automatically.\n /// \n public bool AcceptPackageAgreements { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether to accept source agreements automatically.\n /// \n public bool AcceptSourceAgreements { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether to run the installation in silent mode.\n /// \n public bool Silent { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether to force the installation even if the package is already installed.\n /// \n public bool Force { get; set; }\n\n /// \n /// Gets or sets the installation scope (user or machine).\n /// \n public PackageInstallScope Scope { get; set; } = PackageInstallScope.User;\n\n /// \n /// Gets or sets the installation location.\n /// \n public string Location { get; set; }\n }\n\n\n /// \n /// Represents the result of a package upgrade operation.\n /// \n public class UpgradeResult : InstallationResult\n {\n /// \n /// Gets or sets the version that was upgraded from.\n /// \n public string PreviousVersion { get; set; }\n }\n\n /// \n /// Represents options for package upgrades.\n /// \n public class UpgradeOptions : InstallationOptions\n {\n // Inherits all properties from InstallationOptions\n }\n\n /// \n /// Represents the result of a package uninstallation operation.\n /// \n public class UninstallationResult\n {\n /// \n /// Gets or sets a value indicating whether the uninstallation was successful.\n /// \n public bool Success { get; set; }\n\n /// \n /// Gets or sets an optional message providing additional information about the result.\n /// \n public string Message { get; set; }\n\n /// \n /// Gets or sets the package ID that was uninstalled.\n /// \n public string PackageId { get; set; }\n\n /// \n /// Gets or sets the version of the package that was uninstalled.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets the exit code from the uninstallation process.\n /// \n public int ExitCode { get; set; }\n\n /// \n /// Gets or sets the standard output from the uninstallation process.\n /// \n public string Output { get; set; }\n\n /// \n /// Gets or sets the error output from the uninstallation process.\n /// \n public string Error { get; set; }\n }\n\n\n /// \n /// Represents options for package uninstallation.\n /// \n public class UninstallationOptions\n {\n /// \n /// Gets or sets a value indicating whether to run the uninstallation in silent mode.\n /// \n public bool Silent { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether to force the uninstallation.\n /// \n public bool Force { get; set; }\n\n /// \n /// Gets or sets the installation scope (user or machine) to uninstall from.\n /// \n public PackageInstallScope Scope { get; set; } = PackageInstallScope.User;\n }\n\n /// \n /// Represents information about a package.\n /// \n public class PackageInfo\n {\n /// \n /// Gets or sets the package ID.\n /// \n public string Id { get; set; }\n\n /// \n /// Gets or sets the package name.\n /// \n public string Name { get; set; }\n\n /// \n /// Gets or sets the package version.\n /// \n public string Version { get; set; }\n\n /// \n /// Gets or sets the package source.\n /// \n public string Source { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the package is installed.\n /// \n public bool IsInstalled { get; set; }\n\n /// \n /// Gets or sets the installed version if different from the available version.\n /// \n public string InstalledVersion { get; set; }\n }\n\n\n /// \n /// Represents options for package search.\n /// \n public class SearchOptions\n {\n /// \n /// Gets or sets the maximum number of results to return.\n /// \n public int? Count { get; set; }\n\n /// \n /// Gets or sets the source to search in.\n /// \n public string Source { get; set; }\n\n /// \n /// Gets or sets a value indicating whether to include packages that are already installed.\n /// \n public bool IncludeInstalled { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether to include packages that are not installed.\n /// \n public bool IncludeAvailable { get; set; } = true;\n }\n\n /// \n /// Represents the installation scope for a package.\n /// \n public enum PackageInstallScope\n {\n /// \n /// Install for the current user only.\n /// \n User,\n\n /// \n /// Install for all users (requires elevation).\n /// \n Machine\n }\n\n /// \n /// Represents the progress of a package installation.\n /// \n public class InstallationProgress\n {\n /// \n /// Gets or sets the current progress percentage (0-100).\n /// \n public int Percentage { get; set; }\n\n /// \n /// Gets or sets the current status message.\n /// \n public string Status { get; set; }\n\n /// \n /// Gets or sets the current operation being performed.\n /// \n public string Operation { get; set; }\n\n /// \n /// Gets or sets the package ID being processed.\n /// \n public string PackageId { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the progress is indeterminate.\n /// \n public bool IsIndeterminate { get; set; }\n \n /// \n /// Gets or sets a value indicating whether the operation was cancelled.\n /// \n public bool IsCancelled { get; set; }\n \n /// \n /// Gets or sets a value indicating whether an error occurred during the operation.\n /// \n public bool IsError { get; set; }\n \n /// \n /// Gets or sets a value indicating whether the operation failed due to connectivity issues.\n /// \n public bool IsConnectivityIssue { get; set; }\n }\n\n /// \n /// Represents the progress of a package upgrade operation.\n /// \n public class UpgradeProgress\n {\n /// \n /// Gets or sets the percentage of completion (0-100).\n /// \n public int Percentage { get; set; }\n\n /// \n /// Gets or sets the status message.\n /// \n public string Status { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the progress is indeterminate.\n /// \n public bool IsIndeterminate { get; set; }\n\n /// \n /// Gets or sets the package ID being processed.\n /// \n public string PackageId { get; set; }\n }\n\n /// \n /// Represents the progress of a package uninstallation operation.\n /// \n public class UninstallationProgress\n {\n /// \n /// Gets or sets the percentage of completion (0-100).\n /// \n public int Percentage { get; set; }\n\n /// \n /// Gets or sets the status message.\n /// \n public string Status { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the progress is indeterminate.\n /// \n public bool IsIndeterminate { get; set; }\n\n /// \n /// Gets or sets the package ID being processed.\n /// \n public string PackageId { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/CustomUacSettings.cs", "using System;\nusing Newtonsoft.Json;\n\nnamespace Winhance.Core.Features.Optimize.Models\n{\n /// \n /// Represents custom User Account Control (UAC) settings that don't match standard Windows GUI options.\n /// \n [Serializable]\n public class CustomUacSettings\n {\n /// \n /// Gets or sets the ConsentPromptBehaviorAdmin registry value.\n /// \n [JsonProperty(\"ConsentPromptValue\")]\n public int ConsentPromptValue { get; set; }\n\n /// \n /// Gets or sets the PromptOnSecureDesktop registry value.\n /// \n [JsonProperty(\"SecureDesktopValue\")]\n public int SecureDesktopValue { get; set; }\n\n /// \n /// Gets or sets a timestamp when these settings were last detected or saved.\n /// \n [JsonProperty(\"LastUpdated\")]\n public DateTime LastUpdated { get; set; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n public CustomUacSettings()\n {\n // Default constructor for serialization\n }\n\n /// \n /// Initializes a new instance of the class with specific values.\n /// \n /// The ConsentPromptBehaviorAdmin registry value.\n /// The PromptOnSecureDesktop registry value.\n public CustomUacSettings(int consentPromptValue, int secureDesktopValue)\n {\n ConsentPromptValue = consentPromptValue;\n SecureDesktopValue = secureDesktopValue;\n LastUpdated = DateTime.Now;\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Models/LinkedRegistrySettingWithValue.cs", "using System;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Models\n{\n /// \n /// Wrapper class for RegistrySetting that includes the current value.\n /// Used for displaying registry settings with their current values in tooltips.\n /// \n public class LinkedRegistrySettingWithValue\n {\n /// \n /// Gets the underlying registry setting.\n /// \n public RegistrySetting Setting { get; }\n\n /// \n /// Gets or sets the current value of the registry setting.\n /// \n public object? CurrentValue { get; set; }\n\n /// \n /// Creates a new instance of the LinkedRegistrySettingWithValue class.\n /// \n /// The registry setting.\n /// The current value of the registry setting.\n public LinkedRegistrySettingWithValue(RegistrySetting setting, object? currentValue)\n {\n Setting = setting ?? throw new ArgumentNullException(nameof(setting));\n CurrentValue = currentValue;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/AppRemovalServiceAdapter.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services\n{\n /// \n /// Adapter class that adapts IAppRemovalService to IInstallationService<AppInfo>.\n /// This is used to maintain backward compatibility with code that expects the AppRemovalService\n /// property of IPackageManager to return an IInstallationService<AppInfo>.\n /// \n public class AppRemovalServiceAdapter : IInstallationService\n {\n private readonly IAppRemovalService _appRemovalService;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The app removal service to adapt.\n public AppRemovalServiceAdapter(IAppRemovalService appRemovalService)\n {\n _appRemovalService = appRemovalService ?? throw new ArgumentNullException(nameof(appRemovalService));\n }\n\n /// \n public Task> InstallAsync(\n AppInfo item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default)\n {\n // This is an adapter for removal service, so \"install\" actually means \"remove\"\n return _appRemovalService.RemoveAppAsync(item, progress, cancellationToken);\n }\n\n /// \n public Task> CanInstallAsync(AppInfo item)\n {\n // Since this is an adapter for removal, we'll always return true\n // The actual validation will happen in the RemoveAppAsync method\n return Task.FromResult(OperationResult.Succeeded(true));\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/CapabilityInfo.cs", "// This contains the model for Windows capability information\n\nusing System;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models\n{\n /// \n /// Represents information about a Windows capability.\n /// \n public class CapabilityInfo : IInstallableItem\n {\n public string PackageId => PackageName;\n public string DisplayName => Name;\n public InstallItemType ItemType => InstallItemType.Capability;\n public bool RequiresRestart { get; set; }\n\n /// \n /// Gets or sets the name of the capability.\n /// \n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description of the capability.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the package name of the capability.\n /// This is the identifier used by Windows to reference the capability.\n /// \n public string PackageName { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the category of the capability.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether the capability is installed.\n /// \n public bool IsInstalled { get; set; }\n\n /// \n /// Gets or sets the registry settings associated with this capability.\n /// \n public AppRegistrySetting[]? RegistrySettings { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the capability is protected by the system.\n /// \n public bool IsSystemProtected { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the capability can be reenabled after disabling.\n /// \n public bool CanBeReenabled { get; set; } = true;\n\n /// \n /// Gets or sets a value indicating whether the capability is selected for installation or removal.\n /// \n public bool IsSelected { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ILogService.cs", "using System;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides logging functionality for the application.\n /// \n public interface ILogService\n {\n /// \n /// Starts logging to a file.\n /// \n void StartLog();\n\n /// \n /// Stops logging to a file.\n /// \n void StopLog();\n\n /// \n /// Logs an informational message.\n /// \n /// The message to log.\n void LogInformation(string message);\n\n /// \n /// Logs a warning message.\n /// \n /// The message to log.\n void LogWarning(string message);\n\n /// \n /// Logs an error message.\n /// \n /// The message to log.\n /// The exception associated with the error, if any.\n void LogError(string message, Exception? exception = null);\n\n /// \n /// Logs a success message.\n /// \n /// The message to log.\n void LogSuccess(string message);\n\n /// \n /// Gets the path to the current log file.\n /// \n /// The path to the log file.\n string GetLogPath();\n\n /// \n /// Logs a message with the specified level.\n /// \n /// The log level.\n /// The message to log.\n /// The exception associated with the message, if any.\n void Log(LogLevel level, string message, Exception? exception = null);\n\n /// \n /// Event raised when a log message is generated.\n /// \n event EventHandler? LogMessageGenerated;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/TaskProgressDetail.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents detailed progress information for a task.\n /// \n public class TaskProgressDetail\n {\n /// \n /// Gets or sets the progress value (0-100), or null if not applicable.\n /// \n public double? Progress { get; set; }\n \n /// \n /// Gets or sets the status text.\n /// \n public string StatusText { get; set; }\n \n /// \n /// Gets or sets a detailed message about the current operation.\n /// \n public string DetailedMessage { get; set; }\n \n /// \n /// Gets or sets the log level for the detailed message.\n /// \n public LogLevel LogLevel { get; set; } = LogLevel.Info;\n \n /// \n /// Gets or sets whether the progress is indeterminate.\n /// \n public bool IsIndeterminate { get; set; }\n \n /// \n /// Gets or sets additional information about the progress as key-value pairs.\n /// This can be used to provide more detailed information for logging or debugging.\n /// \n public Dictionary AdditionalInfo { get; set; } = new Dictionary();\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IPackageManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.UI.Interfaces;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Provides package management functionality across the application.\n /// \n public interface IPackageManager\n {\n /// \n /// Gets the logging service.\n /// \n ILogService LogService { get; }\n\n /// \n /// Gets the app discovery service.\n /// \n IAppService AppDiscoveryService { get; }\n\n /// \n /// Gets the app removal service.\n /// \n IInstallationService AppRemovalService { get; }\n\n /// \n /// Gets the special app handler service.\n /// \n ISpecialAppHandlerService SpecialAppHandlerService { get; }\n\n /// \n /// Gets the script generation service.\n /// \n IScriptGenerationService ScriptGenerationService { get; }\n\n /// \n /// Gets the system services.\n /// \n ISystemServices SystemServices { get; }\n\n /// \n /// Gets the notification service.\n /// \n INotificationService NotificationService { get; }\n\n /// \n /// Gets all installable applications.\n /// \n /// A collection of installable applications.\n Task> GetInstallableAppsAsync();\n\n /// \n /// Gets all standard (built-in) applications.\n /// \n /// A collection of standard applications.\n Task> GetStandardAppsAsync();\n\n /// \n /// Gets all available Windows capabilities.\n /// \n /// A collection of Windows capabilities.\n Task> GetCapabilitiesAsync();\n\n /// \n /// Gets all available Windows optional features.\n /// \n /// A collection of Windows optional features.\n Task> GetOptionalFeaturesAsync();\n\n /// \n /// Removes a specific application.\n /// \n /// The package name to remove.\n /// Whether the package is a capability.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task RemoveAppAsync(string packageName, bool isCapability = false);\n\n /// \n /// Checks if an application is installed.\n /// \n /// The package name to check.\n /// The cancellation token.\n /// True if the application is installed; otherwise, false.\n Task IsAppInstalledAsync(string packageName, CancellationToken cancellationToken = default);\n\n /// \n /// Removes Microsoft Edge.\n /// \n /// True if Edge was removed successfully; otherwise, false.\n Task RemoveEdgeAsync();\n\n /// \n /// Removes OneDrive.\n /// \n /// True if OneDrive was removed successfully; otherwise, false.\n Task RemoveOneDriveAsync();\n\n /// \n /// Removes OneNote.\n /// \n /// True if OneNote was removed successfully; otherwise, false.\n Task RemoveOneNoteAsync();\n\n /// \n /// Removes a special application.\n /// \n /// The type of special app handler to use.\n /// True if the application was removed successfully; otherwise, false.\n Task RemoveSpecialAppAsync(string appHandlerType);\n\n /// \n /// Removes multiple applications in a batch operation.\n /// \n /// A list of app information to remove.\n /// A list of results indicating success or failure for each application.\n Task> RemoveAppsInBatchAsync(\n List<(string PackageName, bool IsCapability, string? SpecialHandlerType)> apps);\n\n /// \n /// Registers a removal task.\n /// \n /// The removal script to register.\n /// A task representing the asynchronous operation.\n Task RegisterRemovalTaskAsync(RemovalScript script);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IDialogService.cs", "using System.Threading.Tasks;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides functionality for displaying dialog boxes to the user.\n /// \n public interface IDialogService\n {\n /// \n /// Displays a message to the user.\n /// \n /// The message to display.\n /// The title of the dialog box.\n void ShowMessage(string message, string title = \"\");\n\n /// \n /// Displays a confirmation dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// The text for the OK button.\n /// The text for the Cancel button.\n /// True if the user confirmed; otherwise, false.\n Task ShowConfirmationAsync(string message, string title = \"\", string okButtonText = \"OK\", string cancelButtonText = \"Cancel\");\n\n /// \n /// Displays an information dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// The text for the button.\n /// A task representing the asynchronous operation.\n Task ShowInformationAsync(string message, string title = \"Information\", string buttonText = \"OK\");\n\n /// \n /// Displays a warning dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// The text for the button.\n /// A task representing the asynchronous operation.\n Task ShowWarningAsync(string message, string title = \"Warning\", string buttonText = \"OK\");\n\n /// \n /// Displays an error dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// The text for the button.\n /// A task representing the asynchronous operation.\n Task ShowErrorAsync(string message, string title = \"Error\", string buttonText = \"OK\");\n\n /// \n /// Displays an input dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// The default value for the input.\n /// The value entered by the user, or null if the user canceled.\n Task ShowInputAsync(string message, string title = \"\", string defaultValue = \"\");\n\n /// \n /// Displays a Yes/No/Cancel dialog.\n /// \n /// The message to display.\n /// The title of the dialog box.\n /// True if the user clicked Yes, false if the user clicked No, null if the user clicked Cancel.\n Task ShowYesNoCancelAsync(string message, string title = \"\");\n\n /// \n /// Displays a unified configuration save dialog.\n /// \n /// The title of the dialog box.\n /// The description of the dialog.\n /// A dictionary of section names, their availability, and item counts.\n /// A dictionary of section names and their final selection state, or null if the user canceled.\n Task> ShowUnifiedConfigurationSaveDialogAsync(string title, string description, Dictionary sections);\n\n /// \n /// Displays a unified configuration import dialog.\n /// \n /// The title of the dialog box.\n /// The description of the dialog.\n /// A dictionary of section names, their availability, and item counts.\n /// A dictionary of section names and their final selection state, or null if the user canceled.\n Task> ShowUnifiedConfigurationImportDialogAsync(string title, string description, Dictionary sections);\n\n /// \n /// Displays a donation dialog.\n /// \n /// The title of the dialog box.\n /// The support message to display.\n /// The footer text.\n /// A task representing the asynchronous operation, with a tuple containing the dialog result (whether the user clicked Yes or No) and whether the \"Don't show again\" checkbox was checked.\n Task<(bool? Result, bool DontShowAgain)> ShowDonationDialogAsync(string title, string supportMessage, string footerText);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/FeatureInfo.cs", "// This contains the model for Windows optional feature information\n\nusing System;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models\n{\n /// \n /// Represents information about a Windows optional feature.\n /// \n public class FeatureInfo : IInstallableItem\n {\n public string PackageId => PackageName;\n public string DisplayName => Name;\n public InstallItemType ItemType => InstallItemType.Feature;\n public bool RequiresRestart => RequiresReboot;\n\n /// \n /// Gets or sets the name of the feature.\n /// \n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description of the feature.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the package name of the feature.\n /// This is the identifier used by Windows to reference the feature.\n /// \n public string PackageName { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the category of the feature.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Gets or sets a value indicating whether the feature is installed.\n /// \n public bool IsInstalled { get; set; }\n\n /// \n /// Gets or sets the registry settings associated with this feature.\n /// \n public AppRegistrySetting[]? RegistrySettings { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the feature is protected by the system.\n /// \n public bool IsSystemProtected { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the feature requires a reboot after installation or removal.\n /// \n public bool RequiresReboot { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the feature can be reenabled after disabling.\n /// \n public bool CanBeReenabled { get; set; } = true;\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/IScriptUpdateService.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\n/// \n/// Provides methods for updating script content.\n/// \npublic interface IScriptUpdateService\n{\n /// \n /// Updates an existing BloatRemoval script with new entries.\n /// \n /// The names of the applications to add or remove.\n /// Dictionary mapping app names to their registry settings.\n /// Dictionary mapping app names to their subpackages.\n /// True if this is an install operation (remove from script), false if it's a removal operation (add to script).\n /// The updated removal script.\n Task UpdateExistingBloatRemovalScriptAsync(\n List appNames,\n Dictionary> appsWithRegistry,\n Dictionary appSubPackages,\n bool isInstallOperation = false);\n\n /// \n /// Updates the capabilities array in the script by adding or removing capabilities.\n /// \n /// The script content.\n /// The capabilities to add or remove.\n /// True if this is an install operation (remove from script), false if it's a removal operation (add to script).\n /// The updated script content.\n string UpdateCapabilitiesArrayInScript(string scriptContent, List capabilities, bool isInstallOperation = false);\n\n /// \n /// Updates the packages array in the script by adding or removing packages.\n /// \n /// The script content.\n /// The packages to add or remove.\n /// True if this is an install operation (remove from script), false if it's a removal operation (add to script).\n /// The updated script content.\n string UpdatePackagesArrayInScript(string scriptContent, List packages, bool isInstallOperation = false);\n\n /// \n /// Updates the optional features in the script by adding or removing features.\n /// \n /// The script content.\n /// The features to add or remove.\n /// True if this is an install operation (remove from script), false if it's a removal operation (add to script).\n /// The updated script content.\n string UpdateOptionalFeaturesInScript(string scriptContent, List features, bool isInstallOperation = false);\n\n /// \n /// Updates the registry settings in the script by adding new settings.\n /// \n /// The script content.\n /// Dictionary mapping app names to their registry settings.\n /// The updated script content.\n string UpdateRegistrySettingsInScript(string scriptContent, Dictionary> appsWithRegistry);\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/CompositeScriptContentModifier.cs", "using System;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Implementation of IScriptContentModifier that delegates to specialized modifiers.\n /// \n public class CompositeScriptContentModifier : IScriptContentModifier\n {\n private readonly IPackageScriptModifier _packageModifier;\n private readonly ICapabilityScriptModifier _capabilityModifier;\n private readonly IFeatureScriptModifier _featureModifier;\n private readonly IRegistryScriptModifier _registryModifier;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The package script modifier.\n /// The capability script modifier.\n /// The feature script modifier.\n /// The registry script modifier.\n public CompositeScriptContentModifier(\n IPackageScriptModifier packageModifier,\n ICapabilityScriptModifier capabilityModifier,\n IFeatureScriptModifier featureModifier,\n IRegistryScriptModifier registryModifier)\n {\n _packageModifier = packageModifier ?? throw new ArgumentNullException(nameof(packageModifier));\n _capabilityModifier = capabilityModifier ?? throw new ArgumentNullException(nameof(capabilityModifier));\n _featureModifier = featureModifier ?? throw new ArgumentNullException(nameof(featureModifier));\n _registryModifier = registryModifier ?? throw new ArgumentNullException(nameof(registryModifier));\n }\n\n /// \n public string RemoveCapabilityFromScript(string scriptContent, string capabilityName)\n {\n return _capabilityModifier.RemoveCapabilityFromScript(scriptContent, capabilityName);\n }\n\n /// \n public string RemovePackageFromScript(string scriptContent, string packageName)\n {\n return _packageModifier.RemovePackageFromScript(scriptContent, packageName);\n }\n\n /// \n public string RemoveOptionalFeatureFromScript(string scriptContent, string featureName)\n {\n return _featureModifier.RemoveOptionalFeatureFromScript(scriptContent, featureName);\n }\n\n /// \n public string RemoveAppRegistrySettingsFromScript(string scriptContent, string appName)\n {\n return _registryModifier.RemoveAppRegistrySettingsFromScript(scriptContent, appName);\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/CapabilityCatalog.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a catalog of Windows capabilities that can be enabled or disabled.\n/// \npublic class CapabilityCatalog\n{\n /// \n /// Gets or sets the collection of Windows capabilities.\n /// \n public IReadOnlyList Capabilities { get; init; } = new List();\n\n /// \n /// Creates a default capability catalog with predefined Windows capabilities.\n /// \n /// A new CapabilityCatalog instance with default capabilities.\n public static CapabilityCatalog CreateDefault()\n {\n return new CapabilityCatalog { Capabilities = CreateDefaultCapabilities() };\n }\n\n private static IReadOnlyList CreateDefaultCapabilities()\n {\n return new List\n {\n // Browser capabilities\n new CapabilityInfo\n {\n Name = \"Internet Explorer\",\n Description = \"Legacy web browser\",\n PackageName = \"Browser.InternetExplorer\",\n Category = \"Browser\",\n CanBeReenabled = false,\n },\n // Development capabilities\n new CapabilityInfo\n {\n Name = \"PowerShell ISE\",\n Description = \"PowerShell Integrated Scripting Environment\",\n PackageName = \"Microsoft.Windows.PowerShell.ISE\",\n Category = \"Development\",\n CanBeReenabled = true,\n },\n // System capabilities\n new CapabilityInfo\n {\n Name = \"Quick Assist\",\n Description = \"Remote assistance app\",\n PackageName = \"App.Support.QuickAssist\",\n Category = \"System\",\n CanBeReenabled = false,\n },\n // Utilities capabilities\n new CapabilityInfo\n {\n Name = \"Steps Recorder\",\n Description = \"Screen recording tool\",\n PackageName = \"App.StepsRecorder\",\n Category = \"Utilities\",\n CanBeReenabled = true,\n },\n // Media capabilities\n new CapabilityInfo\n {\n Name = \"Windows Media Player\",\n Description = \"Classic media player\",\n PackageName = \"Media.WindowsMediaPlayer\",\n Category = \"Media\",\n CanBeReenabled = true,\n },\n // Productivity capabilities\n new CapabilityInfo\n {\n Name = \"WordPad\",\n Description = \"Rich text editor\",\n PackageName = \"Microsoft.Windows.WordPad\",\n Category = \"Productivity\",\n CanBeReenabled = false,\n },\n new CapabilityInfo\n {\n Name = \"Paint (Legacy)\",\n Description = \"Classic Paint app\",\n PackageName = \"Microsoft.Windows.MSPaint\",\n Category = \"Graphics\",\n CanBeReenabled = false,\n },\n // OpenSSH capabilities\n new CapabilityInfo\n {\n Name = \"OpenSSH Client\",\n Description = \"Secure Shell client for remote connections\",\n PackageName = \"OpenSSH.Client\",\n Category = \"Networking\",\n IsSystemProtected = false,\n CanBeReenabled = true,\n },\n new CapabilityInfo\n {\n Name = \"OpenSSH Server\",\n Description = \"Secure Shell server for remote connections\",\n PackageName = \"OpenSSH.Server\",\n Category = \"Networking\",\n IsSystemProtected = false,\n CanBeReenabled = true,\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/FeatureCatalog.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\n/// \n/// Represents a catalog of Windows optional features that can be enabled or disabled.\n/// \npublic class FeatureCatalog\n{\n /// \n /// Gets or sets the collection of Windows optional features.\n /// \n public IReadOnlyList Features { get; init; } = new List();\n\n /// \n /// Creates a default feature catalog with predefined Windows optional features.\n /// \n /// A new FeatureCatalog instance with default features.\n public static FeatureCatalog CreateDefault()\n {\n return new FeatureCatalog { Features = CreateDefaultFeatures() };\n }\n\n private static IReadOnlyList CreateDefaultFeatures()\n {\n return new List\n {\n // Windows Subsystems\n new FeatureInfo\n {\n Name = \"Subsystem for Linux\",\n Description = \"Allows running Linux binary executables natively on Windows\",\n PackageName = \"Microsoft-Windows-Subsystem-Linux\",\n Category = \"Development\",\n RequiresReboot = true,\n CanBeReenabled = true,\n },\n // Virtualization\n new FeatureInfo\n {\n Name = \"Windows Hypervisor Platform\",\n Description = \"Core virtualization platform without Hyper-V management tools\",\n PackageName = \"Microsoft-Hyper-V-Hypervisor\",\n Category = \"Virtualization\",\n RequiresReboot = true,\n CanBeReenabled = true,\n },\n // Hyper-V\n new FeatureInfo\n {\n Name = \"Hyper-V\",\n Description = \"Virtualization platform for running multiple operating systems\",\n PackageName = \"Microsoft-Hyper-V-All\",\n Category = \"Virtualization\",\n RequiresReboot = true,\n CanBeReenabled = true,\n },\n new FeatureInfo\n {\n Name = \"Hyper-V Management Tools\",\n Description = \"Tools for managing Hyper-V virtual machines\",\n PackageName = \"Microsoft-Hyper-V-Tools-All\",\n Category = \"Virtualization\",\n RequiresReboot = false,\n CanBeReenabled = true,\n },\n // .NET Framework\n new FeatureInfo\n {\n Name = \".NET Framework 3.5\",\n Description = \"Legacy .NET Framework for older applications\",\n PackageName = \"NetFx3\",\n Category = \"Development\",\n RequiresReboot = true,\n CanBeReenabled = true,\n },\n // Windows Features\n new FeatureInfo\n {\n Name = \"Windows Sandbox\",\n Description = \"Isolated desktop environment for running applications\",\n PackageName = \"Containers-DisposableClientVM\",\n Category = \"Security\",\n RequiresReboot = true,\n CanBeReenabled = true,\n },\n new FeatureInfo\n {\n Name = \"Recall\",\n Description = \"Windows 11 feature that records user activity\",\n PackageName = \"Recall\",\n Category = \"System\",\n RequiresReboot = false,\n CanBeReenabled = true,\n },\n };\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/LogMessageEventArgs.cs", "using System;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Event arguments for log message events.\n /// \n public class LogMessageEventArgs : EventArgs\n {\n /// \n /// Gets the message content.\n /// \n public string Message { get; }\n \n /// \n /// Gets the log level.\n /// \n public LogLevel Level { get; }\n \n /// \n /// Gets the timestamp when the message was created.\n /// \n public DateTime Timestamp { get; }\n \n /// \n /// Gets the exception associated with the log message, if any.\n /// \n public Exception? Exception { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The message content.\n /// The log level.\n public LogMessageEventArgs(string message, LogLevel level)\n {\n Message = message ?? throw new ArgumentNullException(nameof(message));\n Level = level;\n Timestamp = DateTime.Now;\n Exception = null;\n }\n \n /// \n /// Initializes a new instance of the class.\n /// \n /// The log level.\n /// The message content.\n /// The exception associated with the message, if any.\n public LogMessageEventArgs(LogLevel level, string message, Exception? exception)\n {\n Message = message ?? throw new ArgumentNullException(nameof(message));\n Level = level;\n Timestamp = DateTime.Now;\n Exception = exception;\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Exceptions/AppLoadingException.cs", "using System;\n\nnamespace Winhance.Core.Models.Exceptions\n{\n public enum AppLoadingErrorCode\n {\n Unknown,\n CacheFailure,\n Timeout,\n PackageManagerError,\n InvalidConfiguration,\n NetworkError\n }\n\n public class AppLoadingException : Exception\n {\n public AppLoadingErrorCode ErrorCode { get; }\n public Exception? OriginalException { get; }\n\n public AppLoadingException(AppLoadingErrorCode errorCode, string message, \n Exception? originalException = null)\n : base(message, originalException)\n {\n ErrorCode = errorCode;\n OriginalException = originalException;\n }\n }\n\n public class PackageManagerException : Exception\n {\n public string PackageId { get; }\n public string Operation { get; }\n public Exception? OriginalException { get; }\n\n public PackageManagerException(string packageId, string operation, string message,\n Exception? originalException = null)\n : base($\"Package {operation} failed for {packageId}: {message}\", originalException)\n {\n PackageId = packageId;\n Operation = operation;\n OriginalException = originalException;\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IUnifiedConfigurationService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for managing unified configuration operations across the application.\n /// \n public interface IUnifiedConfigurationService\n {\n /// \n /// Creates a unified configuration file containing settings from all view models.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file.\n Task CreateUnifiedConfigurationAsync();\n\n /// \n /// Saves a unified configuration file.\n /// \n /// The unified configuration to save.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile config);\n\n /// \n /// Loads a unified configuration file.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file if successful, null otherwise.\n Task LoadUnifiedConfigurationAsync();\n\n /// \n /// Shows the unified configuration dialog to let the user select which sections to include.\n /// \n /// The unified configuration file.\n /// Whether this is a save dialog (true) or an import dialog (false).\n /// A dictionary of section names and their selection state.\n Task> ShowUnifiedConfigurationDialogAsync(UnifiedConfigurationFile config, bool isSaveDialog);\n\n /// \n /// Applies a unified configuration to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task ApplyUnifiedConfigurationAsync(UnifiedConfigurationFile config, IEnumerable selectedSections);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ISettingItem.cs", "using System.Collections.Generic;\nusing System.Windows.Input;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Defines the common properties that all setting items should have.\n /// \n public interface ISettingItem\n {\n /// \n /// Gets or sets the unique identifier for the setting.\n /// \n string Id { get; set; }\n\n /// \n /// Gets or sets the name of the setting.\n /// \n string Name { get; set; }\n\n /// \n /// Gets or sets the description of the setting.\n /// \n string Description { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the setting is selected.\n /// \n bool IsSelected { get; set; }\n\n /// \n /// Gets or sets the group name that this setting belongs to.\n /// \n string GroupName { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the setting is visible in the UI.\n /// \n bool IsVisible { get; set; }\n\n /// \n /// Gets or sets the type of control used for this setting.\n /// \n ControlType ControlType { get; set; }\n\n /// \n /// Gets or sets the dependencies for this setting.\n /// \n List Dependencies { get; set; }\n\n /// \n /// Gets or sets a value indicating whether the setting is being updated from code.\n /// \n bool IsUpdatingFromCode { get; set; }\n\n /// \n /// Gets the command to apply the setting.\n /// \n ICommand ApplySettingCommand { get; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/ApplicationAction.cs", "using CommunityToolkit.Mvvm.ComponentModel;\nusing System;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Base class for application actions that can be performed in both Optimization and Customization features.\n /// \n public partial class ApplicationAction : ObservableObject\n {\n [ObservableProperty]\n private string _id = string.Empty;\n \n [ObservableProperty]\n private string _name = string.Empty;\n \n [ObservableProperty]\n private string _description = string.Empty;\n \n [ObservableProperty]\n private string _groupName = string.Empty;\n \n [ObservableProperty]\n private string _confirmationMessage = string.Empty;\n \n [ObservableProperty]\n private string _actionType = string.Empty;\n \n [ObservableProperty]\n private string _command = string.Empty;\n \n [ObservableProperty]\n private string _commandAction = string.Empty;\n \n /// \n /// Gets or sets the registry setting or other action to perform.\n /// \n public RegistrySetting? RegistrySetting { get; set; }\n \n /// \n /// Gets or sets optional additional actions to perform.\n /// \n public Func>? CustomAction { get; set; }\n \n /// \n /// Gets or sets a value indicating whether this action supports backup.\n /// \n public bool SupportsBackup { get; set; }\n \n /// \n /// Gets or sets optional backup action to perform.\n /// \n public Func>? BackupAction { get; set; }\n \n /// \n /// Gets or sets the parameters for this action.\n /// \n public Dictionary Parameters { get; set; } = new Dictionary();\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Interfaces/IVerificationMethod.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces\n{\n /// \n /// Defines the contract for different verification methods to check if a package is installed.\n /// \n public interface IVerificationMethod\n {\n /// \n /// Gets the name of the verification method.\n /// \n string Name { get; }\n\n /// \n /// Gets the priority of this verification method. Lower numbers indicate higher priority.\n /// \n int Priority { get; }\n\n /// \n /// Verifies if a package is installed using this verification method.\n /// \n /// The ID of the package to verify.\n /// Optional version to verify. If null, only the presence is checked.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the verification result.\n Task VerifyAsync(\n string packageId, \n string version = null, \n CancellationToken cancellationToken = default);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/ExternalAppsCategoryViewModel.cs", "using System.Collections.ObjectModel;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.WPF.Features.SoftwareApps.Models;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n public partial class ExternalAppsCategoryViewModel : ObservableObject\n {\n [ObservableProperty]\n private string _name;\n\n [ObservableProperty]\n private ObservableCollection _apps = new();\n\n [ObservableProperty]\n private bool _isExpanded = true;\n\n public ExternalAppsCategoryViewModel(string name, ObservableCollection apps)\n {\n _name = name;\n _apps = apps;\n }\n\n public int AppCount => Apps.Count;\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Theme/MaterialSymbols.cs", "namespace Winhance.WPF.Theme\n{\n /// \n /// Contains constants for Material Symbols icon names.\n /// \n public static class MaterialSymbols\n {\n // Sync icons\n public const string Sync = \"sync\";\n public const string SyncProblem = \"sync_problem\";\n\n // Other commonly used icons\n public const string Check = \"check\";\n public const string Close = \"close\";\n public const string Info = \"info\";\n public const string Warning = \"warning\";\n public const string Error = \"error\";\n public const string Settings = \"settings\";\n public const string Add = \"add\";\n public const string Remove = \"remove\";\n public const string Edit = \"edit\";\n public const string Delete = \"delete\";\n public const string Search = \"search\";\n public const string Download = \"download\";\n public const string Upload = \"upload\";\n public const string Refresh = \"refresh\";\n public const string Save = \"save\";\n public const string Menu = \"menu\";\n public const string Home = \"home\";\n public const string Person = \"person\";\n public const string Help = \"help\";\n public const string ArrowBack = \"arrow_back\";\n public const string ArrowForward = \"arrow_forward\";\n public const string ArrowUpward = \"arrow_upward\";\n public const string ArrowDownward = \"arrow_downward\";\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/CustomizationSetting.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.Customize.Enums;\n\nnamespace Winhance.Core.Features.Customize.Models\n{\n /// \n /// Represents a setting that customizes the system by modifying registry values.\n /// \n public record CustomizationSetting : ApplicationSetting\n {\n /// \n /// Gets or sets the customization category for this setting.\n /// \n public required CustomizationCategory Category { get; init; }\n\n /// \n /// Gets or sets the linked settings for this setting.\n /// This allows grouping multiple settings together under a parent setting.\n /// \n public List LinkedSettings { get; init; } = new List();\n\n /// \n /// Gets or sets a value indicating whether this setting is only applicable to Windows 11.\n /// \n public bool IsWindows11Only { get; init; }\n\n /// \n /// Gets or sets a value indicating whether this setting is only applicable to Windows 10.\n /// \n public bool IsWindows10Only { get; init; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IParameterSerializerService.cs", "namespace Winhance.Core.Interfaces.Services\n{\n /// \n /// Service for serializing and deserializing navigation parameters.\n /// \n public interface IParameterSerializerService\n {\n /// \n /// Serializes an object to a string.\n /// \n /// The object to serialize.\n /// The serialized string.\n string Serialize(object value);\n\n /// \n /// Deserializes a string to an object of the specified type.\n /// \n /// The type to deserialize to.\n /// The string to deserialize.\n /// The deserialized object.\n T Deserialize(string value);\n\n /// \n /// Deserializes a string to an object of the specified type.\n /// \n /// The type to deserialize to.\n /// The string to deserialize.\n /// The deserialized object.\n object Deserialize(System.Type type, string value);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IInstallationOrchestrator.cs", "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Orchestrates high-level installation and removal operations across different types of items.\n /// \n /// \n /// This is a higher-level service that coordinates operations across different specific services.\n /// \n public interface IInstallationOrchestrator\n {\n /// \n /// Installs an installable item based on its type.\n /// \n /// The item to install.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the asynchronous operation.\n Task InstallAsync(\n IInstallableItem item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Removes an installable item based on its type.\n /// \n /// The item to remove.\n /// A task representing the asynchronous operation.\n Task RemoveAsync(IInstallableItem item);\n\n /// \n /// Installs multiple items in batch.\n /// \n /// The items to install.\n /// The progress reporter.\n /// The cancellation token.\n /// A task representing the asynchronous operation.\n Task InstallBatchAsync(\n IEnumerable items,\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Removes multiple items in batch.\n /// \n /// The items to remove.\n /// A list of results indicating success or failure for each item.\n Task> RemoveBatchAsync(\n IEnumerable items);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/ViewModels/AppListViewModel.cs", "using System.Collections.ObjectModel;\nusing System.Threading.Tasks;\nusing CommunityToolkit.Mvvm.ComponentModel;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.WPF.Features.SoftwareApps.Models;\nusing Winhance.WPF.Features.Common.ViewModels;\n\nnamespace Winhance.WPF.Features.SoftwareApps.ViewModels\n{\n public abstract partial class AppListViewModel : BaseViewModel where T : class\n {\n protected readonly IPackageManager? _packageManager;\n protected readonly ITaskProgressService _progressService;\n \n [ObservableProperty]\n private bool _isLoading;\n\n public ObservableCollection Items { get; } = new();\n\n protected AppListViewModel(ITaskProgressService progressService, IPackageManager? packageManager) \n : base(progressService)\n {\n _packageManager = packageManager;\n _progressService = progressService;\n }\n\n public abstract Task LoadItemsAsync();\n public abstract Task CheckInstallationStatusAsync();\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Interfaces/IInstallationVerifier.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces\n{\n /// \n /// Defines the contract for verifying software installations.\n /// \n public interface IInstallationVerifier\n {\n /// \n /// Verifies if a package is installed.\n /// \n /// The ID of the package to verify.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the verification result.\n Task VerifyInstallationAsync(\n string packageId, \n CancellationToken cancellationToken = default);\n\n /// \n /// Verifies if a package is installed with the specified version.\n /// \n /// The ID of the package to verify.\n /// The expected version of the package.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the verification result.\n Task VerifyInstallationAsync(\n string packageId, \n string version, \n CancellationToken cancellationToken = default);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IFileSystemService.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Interfaces.Services\n{\n /// \n /// Provides access to the file system.\n /// \n public interface IFileSystemService\n {\n /// \n /// Determines whether the specified file exists.\n /// \n /// The file to check.\n /// True if the file exists; otherwise, false.\n bool FileExists(string path);\n\n /// \n /// Determines whether the specified directory exists.\n /// \n /// The directory to check.\n /// True if the directory exists; otherwise, false.\n bool DirectoryExists(string path);\n\n /// \n /// Creates a directory if it doesn't already exist.\n /// \n /// The directory to create.\n /// True if the directory was created or already exists; otherwise, false.\n bool CreateDirectory(string path);\n\n /// \n /// Deletes a file if it exists.\n /// \n /// The file to delete.\n /// True if the file was deleted or didn't exist; otherwise, false.\n bool DeleteFile(string path);\n\n /// \n /// Reads all text from a file.\n /// \n /// The file to read.\n /// The contents of the file.\n string ReadAllText(string path);\n\n /// \n /// Writes all text to a file.\n /// \n /// The file to write to.\n /// The text to write.\n /// True if the text was written successfully; otherwise, false.\n bool WriteAllText(string path, string contents);\n\n /// \n /// Gets all files in a directory that match the specified pattern.\n /// \n /// The directory to search.\n /// The search pattern.\n /// Whether to search subdirectories.\n /// A collection of file paths.\n IEnumerable GetFiles(string path, string pattern, bool recursive);\n\n /// \n /// Gets all directories in a directory that match the specified pattern.\n /// \n /// The directory to search.\n /// The search pattern.\n /// Whether to search subdirectories.\n /// A collection of directory paths.\n IEnumerable GetDirectories(string path, string pattern, bool recursive);\n\n /// \n /// Gets the path to a special folder, such as AppData, ProgramFiles, etc.\n /// \n /// The name of the special folder.\n /// The path to the special folder.\n string GetSpecialFolderPath(string specialFolder);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IViewModel.cs", "namespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Base interface for all view models.\n /// \n public interface IViewModel\n {\n /// \n /// Called when navigation to the view model has occurred.\n /// \n /// The navigation parameter.\n void OnNavigatedTo(object? parameter = null);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IUacSettingsService.cs", "using System.Threading.Tasks;\nusing Winhance.Core.Features.Optimize.Models;\nusing Winhance.Core.Models.Enums;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for a service that manages UAC settings persistence.\n /// \n public interface IUacSettingsService\n {\n /// \n /// Saves custom UAC settings.\n /// \n /// The ConsentPromptBehaviorAdmin registry value.\n /// The PromptOnSecureDesktop registry value.\n /// A task representing the asynchronous operation.\n Task SaveCustomUacSettingsAsync(int consentPromptValue, int secureDesktopValue);\n\n /// \n /// Loads custom UAC settings.\n /// \n /// A CustomUacSettings object if settings exist, null otherwise.\n Task LoadCustomUacSettingsAsync();\n\n /// \n /// Checks if custom UAC settings exist.\n /// \n /// True if custom settings exist, false otherwise.\n Task HasCustomUacSettingsAsync();\n\n /// \n /// Gets custom UAC settings if they exist.\n /// \n /// The ConsentPromptBehaviorAdmin registry value.\n /// The PromptOnSecureDesktop registry value.\n /// True if custom settings were retrieved, false otherwise.\n bool TryGetCustomUacValues(out int consentPromptValue, out int secureDesktopValue);\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Interfaces/IViewModelLocator.cs", "using System.Windows;\n\nnamespace Winhance.WPF.Features.Common.Interfaces\n{\n /// \n /// Interface for locating view models in the application.\n /// \n public interface IViewModelLocator\n {\n /// \n /// Finds a view model of the specified type in the application.\n /// \n /// The type of view model to find.\n /// The view model if found, otherwise null.\n T? FindViewModel() where T : class;\n\n /// \n /// Finds a view model of the specified type in the specified window.\n /// \n /// The type of view model to find.\n /// The window to search in.\n /// The view model if found, otherwise null.\n T? FindViewModelInWindow(Window window) where T : class;\n\n /// \n /// Finds a view model of the specified type in the visual tree starting from the specified element.\n /// \n /// The type of view model to find.\n /// The starting element.\n /// The view model if found, otherwise null.\n T? FindViewModelInVisualTree(DependencyObject element) where T : class;\n\n /// \n /// Finds a view model by its name.\n /// \n /// The name of the view model to find.\n /// The view model if found, otherwise null.\n object? FindViewModelByName(string viewModelName);\n\n /// \n /// Gets a property from a view model.\n /// \n /// The type of the property to get.\n /// The view model to get the property from.\n /// The name of the property to get.\n /// The property value if found, otherwise null.\n T? GetPropertyFromViewModel(object viewModel, string propertyName) where T : class;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IScriptFactory.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Factory for creating script objects.\n /// \n public interface IScriptFactory\n {\n /// \n /// Creates a batch removal script.\n /// \n /// The names of the applications to remove.\n /// Dictionary mapping app names to registry settings.\n /// Dictionary mapping app names to their subpackages.\n /// A removal script object.\n RemovalScript CreateBatchRemovalScript(\n List appNames,\n Dictionary> appsWithRegistry,\n Dictionary appSubPackages = null);\n\n /// \n /// Creates a single app removal script.\n /// \n /// The app to remove.\n /// A removal script object.\n RemovalScript CreateSingleAppRemovalScript(AppInfo app);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Models/ApplicationSettingGroup.cs", "using CommunityToolkit.Mvvm.ComponentModel;\nusing System.Collections.ObjectModel;\n\nnamespace Winhance.WPF.Features.Common.Models\n{\n /// \n /// Base class for application setting groups used in both Optimization and Customization features.\n /// \n public partial class ApplicationSettingGroup : ObservableObject\n {\n [ObservableProperty]\n private string _name = string.Empty;\n\n [ObservableProperty]\n private string _description = string.Empty;\n\n [ObservableProperty]\n private bool _isSelected;\n \n [ObservableProperty]\n private bool _isGroupHeader;\n \n [ObservableProperty]\n private string _groupName = string.Empty;\n \n [ObservableProperty]\n private bool _isVisible = true;\n \n /// \n /// Gets the collection of settings in this group.\n /// \n public ObservableCollection Settings { get; } = new();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/UacLevel.cs", "namespace Winhance.Core.Models.Enums\n{\n /// \n /// Represents User Account Control (UAC) levels in Windows.\n /// \n public enum UacLevel\n {\n /// \n /// Never notify the user when programs try to install software or make changes to the computer.\n /// \n NeverNotify = 0,\n\n /// \n /// Notify the user only when programs try to make changes to the computer, without dimming the desktop.\n /// \n NotifyNoDesktopDim = 1,\n\n /// \n /// Notify the user only when programs try to make changes to the computer (default).\n /// \n NotifyChangesOnly = 2,\n\n /// \n /// Always notify the user when programs try to install software or make changes to the computer\n /// or when the user makes changes to Windows settings.\n /// \n AlwaysNotify = 3,\n\n /// \n /// Custom UAC setting that doesn't match any of the standard Windows GUI options.\n /// This is used when the registry contains values that don't match the standard options.\n /// \n Custom = 99,\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ICommandService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for executing system commands related to optimizations.\n /// \n public interface ICommandService\n {\n /// \n /// Executes the specified command with elevated privileges if required.\n /// \n /// The command to execute.\n /// Whether the command requires elevation.\n /// The result of the command execution.\n Task<(bool Success, string Output, string Error)> ExecuteCommandAsync(string command, bool requiresElevation = true);\n \n /// \n /// Applies the command settings based on the enabled state.\n /// \n /// The command settings to apply.\n /// Whether the optimization is enabled.\n /// A result indicating success or failure with details.\n Task<(bool Success, string Message)> ApplyCommandSettingsAsync(IEnumerable settings, bool isEnabled);\n \n /// \n /// Gets the current state of a command setting.\n /// \n /// The command setting to check.\n /// True if the setting is in its enabled state, false otherwise.\n Task IsCommandSettingEnabledAsync(CommandSetting setting);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppService.cs", "using System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.SoftwareApps.Models;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Unified service interface for app discovery, loading, and status management.\n /// \n public interface IAppService\n {\n #region App Discovery & Loading\n\n /// \n /// Gets all installable applications.\n /// \n /// A collection of installable applications.\n Task> GetInstallableAppsAsync();\n\n /// \n /// Gets all standard (built-in) applications.\n /// \n /// A collection of standard applications.\n Task> GetStandardAppsAsync();\n\n /// \n /// Gets all available Windows capabilities.\n /// \n /// A collection of Windows capabilities.\n Task> GetCapabilitiesAsync();\n\n /// \n /// Gets all available Windows optional features.\n /// \n /// A collection of Windows optional features.\n Task> GetOptionalFeaturesAsync();\n\n #endregion\n\n #region Status Management\n\n /// \n /// Checks if an application is installed.\n /// \n /// The package name to check.\n /// The cancellation token.\n /// True if the application is installed; otherwise, false.\n Task IsAppInstalledAsync(string packageName, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if Microsoft Edge is installed.\n /// \n /// True if Edge is installed; otherwise, false.\n Task IsEdgeInstalledAsync();\n\n /// \n /// Checks if OneDrive is installed.\n /// \n /// True if OneDrive is installed; otherwise, false.\n Task IsOneDriveInstalledAsync();\n\n /// \n /// Gets the installation status of an item.\n /// \n /// The item to check.\n /// True if the item is installed; otherwise, false.\n Task GetItemInstallStatusAsync(IInstallableItem item);\n\n /// \n /// Gets the installation status of multiple items by package ID.\n /// \n /// The package IDs to check.\n /// A dictionary mapping package IDs to installation status.\n Task> GetBatchInstallStatusAsync(IEnumerable packageIds);\n\n /// \n /// Gets detailed installation status of an app.\n /// \n /// The app ID to check.\n /// The detailed installation status.\n Task GetInstallStatusAsync(string appId);\n\n /// \n /// Refreshes the installation status of multiple items.\n /// \n /// The items to refresh.\n /// A task representing the asynchronous operation.\n Task RefreshInstallationStatusAsync(IEnumerable items);\n\n /// \n /// Sets the installation status of an app.\n /// \n /// The app ID to update.\n /// The new installation status.\n /// True if the status was updated successfully; otherwise, false.\n Task SetInstallStatusAsync(string appId, InstallStatus status);\n\n /// \n /// Clears the status cache.\n /// \n void ClearStatusCache();\n\n #endregion\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/RefreshResult.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents the result of a refresh operation for installation statuses.\n /// \n public class RefreshResult\n {\n /// \n /// Gets or sets a value indicating whether the refresh operation was successful.\n /// \n public bool Success { get; set; }\n\n /// \n /// Gets or sets the error message if the refresh operation failed.\n /// \n public string? ErrorMessage { get; set; }\n\n /// \n /// Gets or sets the collection of app IDs that were successfully refreshed.\n /// \n public IEnumerable RefreshedAppIds { get; set; } = new List();\n\n /// \n /// Gets or sets the collection of app IDs that failed to refresh.\n /// \n public IEnumerable FailedAppIds { get; set; } = new List();\n\n /// \n /// Gets or sets the number of successfully refreshed apps.\n /// \n public int SuccessCount { get; set; }\n\n /// \n /// Gets or sets the number of failed refreshed apps.\n /// \n public int FailedCount { get; set; }\n\n /// \n /// Gets or sets the collection of errors.\n /// \n public Dictionary Errors { get; set; } = new Dictionary();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/CommandSetting.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents a command-based setting that can be executed to enable or disable an optimization.\n /// \n public class CommandSetting\n {\n /// \n /// Gets or sets the unique identifier for this command setting.\n /// \n public string Id { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the category this command belongs to.\n /// \n public string Category { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the description of what this command does.\n /// \n public string Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the command to execute when the setting is enabled.\n /// \n public string EnabledCommand { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the command to execute when the setting is disabled.\n /// \n public string DisabledCommand { get; set; } = string.Empty;\n\n /// \n /// Gets or sets whether this command requires elevation.\n /// \n public bool RequiresElevation { get; set; } = true;\n\n /// \n /// Gets or sets whether this is the primary command in a group.\n /// \n public bool IsPrimary { get; set; } = true;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/ConfigurationFile.cs", "using System;\nusing System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents a configuration file that stores application settings.\n /// \n public class ConfigurationFile\n {\n /// \n /// Gets or sets the type of configuration (e.g., \"ExternalApps\", \"WindowsApps\").\n /// \n public string ConfigType { get; set; }\n\n /// \n /// Gets or sets the version of the configuration file format.\n /// \n public string Version { get; set; } = \"1.0\";\n\n /// \n /// Gets or sets the date and time when the configuration file was created.\n /// \n public DateTime CreatedAt { get; set; } = DateTime.UtcNow;\n\n /// \n /// Gets or sets the collection of configuration items.\n /// \n public List Items { get; set; } = new List();\n }\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/SoftwareApps/Services/WinGet/Interfaces/IWinGetInstaller.cs", "using System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Infrastructure.Features.SoftwareApps.Services.WinGet.Interfaces\n{\n /// \n /// Defines the contract for WinGet package installation and management.\n /// \n public interface IWinGetInstaller\n {\n /// \n /// Installs a package using WinGet.\n /// \n /// The ID of the package to install.\n /// Optional installation options.\n /// The display name to use in progress reporting.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the installation result.\n Task InstallPackageAsync(\n string packageId, \n InstallationOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Upgrades a package using WinGet.\n /// \n /// The ID of the package to upgrade.\n /// Optional upgrade options.\n /// The display name to use in progress reporting.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the upgrade result.\n Task UpgradePackageAsync(\n string packageId, \n UpgradeOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Uninstalls a package using WinGet.\n /// \n /// The ID of the package to uninstall.\n /// Optional uninstallation options.\n /// The display name to use in progress reporting.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the uninstallation result.\n Task UninstallPackageAsync(\n string packageId, \n UninstallationOptions options = null,\n string displayName = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Gets information about an installed package.\n /// \n /// The ID of the package to get information about.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the package information.\n Task GetPackageInfoAsync(\n string packageId, \n CancellationToken cancellationToken = default);\n\n /// \n /// Searches for packages matching the given query.\n /// \n /// The search query.\n /// Optional search options.\n /// A cancellation token to cancel the operation.\n /// A task representing the asynchronous operation with the search results.\n Task> SearchPackagesAsync(\n string query, \n SearchOptions options = null, \n CancellationToken cancellationToken = default);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IWinGetInstallationService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces;\n\n/// \n/// Interface for services that handle WinGet-related installation operations.\n/// \npublic interface IWinGetInstallationService\n{\n /// \n /// Installs a package using WinGet.\n /// \n /// The package name or ID to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// The display name of the package for progress reporting.\n /// True if installation was successful; otherwise, false.\n Task InstallWithWingetAsync(\n string packageName,\n IProgress? progress = null,\n CancellationToken cancellationToken = default,\n string? displayName = null);\n\n /// \n /// Installs WinGet if not already installed.\n /// \n Task InstallWinGetAsync(IProgress? progress = null);\n\n /// \n /// Checks if WinGet is installed on the system.\n /// \n /// True if WinGet is installed, false otherwise\n Task IsWinGetInstalledAsync();\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IInstallationService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Generic interface for installation services.\n /// \n /// The type of item to install, which must implement IInstallableItem.\n public interface IInstallationService where T : IInstallableItem\n {\n /// \n /// Installs an item.\n /// \n /// The item to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n Task> InstallAsync(\n T item,\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Checks if an item can be installed.\n /// \n /// The item to check.\n /// An operation result indicating if the item can be installed, with error details if not.\n Task> CanInstallAsync(T item);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IScriptDetectionService.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for detecting the presence of script files used by Winhance to remove applications.\n /// \n public interface IScriptDetectionService\n {\n /// \n /// Checks if any removal scripts are present.\n /// \n /// True if any removal scripts are present, false otherwise.\n bool AreRemovalScriptsPresent();\n \n /// \n /// Gets information about all active removal scripts.\n /// \n /// A collection of script information objects.\n IEnumerable GetActiveScripts();\n }\n \n /// \n /// Represents information about a script file.\n /// \n public class ScriptInfo\n {\n /// \n /// Gets or sets the name of the script file.\n /// \n public string Name { get; set; }\n \n /// \n /// Gets or sets the description of what the script does.\n /// \n public string Description { get; set; }\n \n /// \n /// Gets or sets the full path to the script file.\n /// \n public string FilePath { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/PowerShellProgressData.cs", "using Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.Core.Features.Common.Models\n{\n /// \n /// Represents progress data from PowerShell operations.\n /// \n public class PowerShellProgressData\n {\n /// \n /// Gets or sets the percent complete value (0-100).\n /// \n public int? PercentComplete { get; set; }\n\n /// \n /// Gets or sets the activity description.\n /// \n public string Activity { get; set; }\n\n /// \n /// Gets or sets the status description.\n /// \n public string StatusDescription { get; set; }\n\n /// \n /// Gets or sets the current operation description.\n /// \n public string CurrentOperation { get; set; }\n\n /// \n /// Gets or sets the PowerShell stream type.\n /// \n public PowerShellStreamType StreamType { get; set; }\n\n /// \n /// Gets or sets the message content.\n /// \n public string Message { get; set; }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ISearchable.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for objects that can be searched.\n /// \n public interface ISearchable\n {\n /// \n /// Determines if the object matches the given search term.\n /// \n /// The search term to match against.\n /// True if the object matches the search term, false otherwise.\n bool MatchesSearch(string searchTerm);\n \n /// \n /// Gets the searchable properties of the object.\n /// \n /// An array of property names that should be searched.\n string[] GetSearchableProperties();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/PowerShellStreamType.cs", "namespace Winhance.Core.Features.Common.Enums\n{\n /// \n /// Defines the types of PowerShell streams.\n /// \n public enum PowerShellStreamType\n {\n /// \n /// The output stream.\n /// \n Output,\n \n /// \n /// The error stream.\n /// \n Error,\n \n /// \n /// The warning stream.\n /// \n Warning,\n \n /// \n /// The verbose stream.\n /// \n Verbose,\n \n /// \n /// The debug stream.\n /// \n Debug,\n \n /// \n /// The information stream.\n /// \n Information,\n \n /// \n /// The progress stream.\n /// \n Progress\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/OptimizationSetting.cs", "using Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Optimize.Models\n{\n /// \n /// Represents a setting that optimizes the system by modifying registry values.\n /// \n public record OptimizationSetting : ApplicationSetting\n {\n /// \n /// Gets or sets the optimization category for this setting.\n /// \n public required OptimizationCategory Category { get; init; }\n \n /// \n /// Gets or sets custom properties for this setting.\n /// This can be used to store additional data specific to certain optimization types,\n /// such as PowerCfg settings.\n /// \n public Dictionary CustomProperties { get; init; } = new Dictionary();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppDiscoveryService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for discovering and retrieving information about installed applications.\n /// \n public interface IAppDiscoveryService\n {\n /// \n /// Gets all standard (built-in) applications.\n /// \n /// A collection of standard applications.\n Task> GetStandardAppsAsync();\n\n /// \n /// Gets all installable third-party applications.\n /// \n /// A collection of installable applications.\n Task> GetInstallableAppsAsync();\n\n /// \n /// Gets all available Windows capabilities.\n /// \n /// A collection of Windows capabilities.\n Task> GetCapabilitiesAsync();\n\n /// \n /// Gets all available Windows optional features.\n /// \n /// A collection of Windows optional features.\n Task> GetOptionalFeaturesAsync();\n\n /// \n /// Checks if Microsoft Edge is installed.\n /// \n /// True if Edge is installed; otherwise, false.\n Task IsEdgeInstalledAsync();\n\n /// \n /// Checks if OneDrive is installed.\n /// \n /// True if OneDrive is installed; otherwise, false.\n Task IsOneDriveInstalledAsync();\n\n /// \n /// Checks if OneNote is installed.\n /// \n /// True if OneNote is installed; otherwise, false.\n Task IsOneNoteInstalledAsync();\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ConfigurationServiceExtensions.cs", "using Microsoft.Extensions.DependencyInjection;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Extension methods for registering configuration services with the dependency injection container.\n /// \n public static class ConfigurationServiceExtensions\n {\n /// \n /// Adds all configuration services to the service collection.\n /// \n /// The service collection.\n /// The service collection for chaining.\n public static IServiceCollection AddConfigurationServices(this IServiceCollection services)\n {\n // Register the main configuration applier service\n services.AddTransient();\n \n // Register the property updater and view model refresher\n services.AddTransient();\n services.AddTransient();\n \n // Register all section-specific appliers\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n \n return services;\n }\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/IConfigurationApplierService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Interface for the service that applies configuration settings to different view models.\n /// \n public interface IConfigurationApplierService\n {\n /// \n /// Applies configuration settings to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A dictionary of section names and their application result.\n Task> ApplySectionsAsync(UnifiedConfigurationFile config, IEnumerable selectedSections);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IScriptTemplateProvider.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides templates for PowerShell scripts used in the application.\n /// \n public interface IScriptTemplateProvider\n {\n /// \n /// Gets the template for removing a package.\n /// \n /// The template string for package removal.\n string GetPackageRemovalTemplate();\n\n /// \n /// Gets the template for removing a capability.\n /// \n /// The template string for capability removal.\n string GetCapabilityRemovalTemplate();\n\n /// \n /// Gets the template for removing an optional feature.\n /// \n /// The template string for optional feature removal.\n string GetFeatureRemovalTemplate();\n\n /// \n /// Gets the template for a registry setting operation.\n /// \n /// True if this is a delete operation; false if it's a set operation.\n /// The template string for registry operations.\n string GetRegistrySettingTemplate(bool isDelete);\n\n /// \n /// Gets the header for a script.\n /// \n /// The name of the script.\n /// The header string for the script.\n string GetScriptHeader(string scriptName);\n\n /// \n /// Gets the footer for a script.\n /// \n /// The footer string for the script.\n string GetScriptFooter();\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/ICustomAppInstallationService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces;\n\n/// \n/// Interface for services that handle custom application installations.\n/// \npublic interface ICustomAppInstallationService\n{\n /// \n /// Installs a custom application.\n /// \n /// Information about the application to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// True if installation was successful; otherwise, false.\n Task InstallCustomAppAsync(\n AppInfo appInfo,\n IProgress? progress = null,\n CancellationToken cancellationToken = default);\n\n /// \n /// Checks if internet connection is available.\n /// \n /// True if internet connection is available; otherwise, false.\n Task CheckInternetConnectionAsync();\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IConfigurationService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Defines methods for saving and loading application configuration files.\n /// \n public interface IConfigurationService\n {\n /// \n /// Saves a configuration file containing the selected items.\n /// \n /// The type of items to save.\n /// The collection of items to save.\n /// The type of configuration being saved.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task SaveConfigurationAsync(IEnumerable items, string configType);\n\n /// \n /// Loads a configuration file and returns the configuration file.\n /// \n /// The type of configuration being loaded.\n /// A task representing the asynchronous operation. Returns the configuration file if successful, null otherwise.\n Task LoadConfigurationAsync(string configType);\n\n /// \n /// Saves a unified configuration file containing settings for multiple parts of the application.\n /// \n /// The unified configuration to save.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task SaveUnifiedConfigurationAsync(UnifiedConfigurationFile unifiedConfig);\n\n /// \n /// Loads a unified configuration file.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file if successful, null otherwise.\n Task LoadUnifiedConfigurationAsync();\n\n /// \n /// Creates a unified configuration file from individual configuration sections.\n /// \n /// Dictionary of section names and their corresponding configuration items.\n /// List of section names to include in the unified configuration.\n /// A unified configuration file.\n UnifiedConfigurationFile CreateUnifiedConfiguration(Dictionary> sections, IEnumerable includedSections);\n\n /// \n /// Extracts a specific section from a unified configuration file.\n /// \n /// The unified configuration file.\n /// The name of the section to extract.\n /// A configuration file containing only the specified section.\n ConfigurationFile ExtractSectionFromUnifiedConfiguration(UnifiedConfigurationFile unifiedConfig, string sectionName);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/LogLevel.cs", "namespace Winhance.Core.Features.Common.Enums\n{\n public enum LogLevel\n {\n Info,\n Warning,\n Error,\n Success,\n Debug\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScriptModifierServiceExtensions.cs", "using Microsoft.Extensions.DependencyInjection;\nusing System;\nusing Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Extension methods for registering script modifier services with the dependency injection container.\n /// \n public static class ScriptModifierServiceExtensions\n {\n /// \n /// Adds script modifier services to the specified .\n /// \n /// The to add the services to.\n /// The so that additional calls can be chained.\n public static IServiceCollection AddScriptModifierServices(this IServiceCollection services)\n {\n // Register the specialized modifiers\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n services.AddTransient();\n\n // Register the composite modifier as the implementation of IScriptContentModifier\n services.AddTransient();\n\n return services;\n }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ScriptGenerationServiceExtensions.cs", "using Microsoft.Extensions.DependencyInjection;\nusing Winhance.Core.Features.Common.Interfaces;\nusing Winhance.Core.Features.SoftwareApps.Interfaces;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Extension methods for registering script generation services.\n /// \n public static class ScriptGenerationServiceExtensions\n {\n /// \n /// Adds script generation services to the service collection.\n /// \n /// The service collection.\n /// The service collection.\n public static IServiceCollection AddScriptGenerationServices(this IServiceCollection services)\n {\n // Register script template provider\n services.AddSingleton();\n \n // Register script builder service\n services.AddSingleton();\n \n // Register script factory\n services.AddSingleton();\n \n // Register script generation service\n services.AddSingleton();\n \n // Register script content modifier\n services.AddSingleton();\n \n // Register composite script content modifier\n services.AddSingleton();\n \n // Register specialized script modifiers\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n services.AddSingleton();\n \n // Register scheduled task service\n services.AddSingleton();\n \n // Register script update service\n services.AddSingleton();\n \n return services;\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Exceptions/InstallationStatusException.cs", "using System;\n\nnamespace Winhance.Core.Features.SoftwareApps.Exceptions\n{\n /// \n /// Exception thrown when there is an error with installation status operations.\n /// \n public class InstallationStatusException : Exception\n {\n /// \n /// Initializes a new instance of the class.\n /// \n public InstallationStatusException() : base()\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message.\n /// \n /// The message that describes the error.\n public InstallationStatusException(string message) : base(message)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message\n /// and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception.\n public InstallationStatusException(string message, Exception innerException) : base(message, innerException)\n {\n }\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IScriptBuilderService.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for building script content.\n /// \n public interface IScriptBuilderService\n {\n /// \n /// Builds a script for removing packages.\n /// \n /// The names of the packages to remove.\n /// The script content.\n string BuildPackageRemovalScript(IEnumerable packageNames);\n\n /// \n /// Builds a script for removing capabilities.\n /// \n /// The names of the capabilities to remove.\n /// The script content.\n string BuildCapabilityRemovalScript(IEnumerable capabilityNames);\n\n /// \n /// Builds a script for removing features.\n /// \n /// The names of the features to remove.\n /// The script content.\n string BuildFeatureRemovalScript(IEnumerable featureNames);\n\n /// \n /// Builds a script for registry operations.\n /// \n /// Dictionary mapping app names to registry settings.\n /// The script content.\n string BuildRegistryScript(Dictionary> registrySettings);\n\n /// \n /// Builds a complete removal script.\n /// \n /// The names of the packages to remove.\n /// The names of the capabilities to remove.\n /// The names of the features to remove.\n /// Dictionary mapping app names to registry settings.\n /// Dictionary mapping app names to their subpackages.\n /// The script content.\n string BuildCompleteRemovalScript(\n IEnumerable packageNames,\n IEnumerable capabilityNames,\n IEnumerable featureNames,\n Dictionary> registrySettings,\n Dictionary subPackages);\n\n /// \n /// Builds a script for removing a single app.\n /// \n /// The app to remove.\n /// The script content.\n string BuildSingleAppRemovalScript(AppInfo app);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/StartMenuLayouts.cs", "using System;\n\nnamespace Winhance.Core.Features.Customize.Models;\n\n/// \n/// Contains layout templates for Windows 10 and Windows 11 Start Menus.\n/// \npublic static class StartMenuLayouts\n{\n /// \n /// Gets the Windows 10 Start Menu layout XML template.\n /// \n public static string Windows10Layout => @\"\n\n \n \n \n \n \n \n\";\n\n /// \n /// Gets the Windows 11 Start Menu binary certificate template.\n /// This is a base64 encoded representation of the start2.bin file.\n /// \n public static string Windows11StartBinCertificate => @\"-----BEGIN CERTIFICATE-----\n4nrhSwH8TRucAIEL3m5RhU5aX0cAW7FJilySr5CE+V40mv9utV7aAZARAABc9u55\nLN8F4borYyXEGl8Q5+RZ+qERszeqUhhZXDvcjTF6rgdprauITLqPgMVMbSZbRsLN\n/O5uMjSLEr6nWYIwsMJkZMnZyZrhR3PugUhUKOYDqwySCY6/CPkL/Ooz/5j2R2hw\nWRGqc7ZsJxDFM1DWofjUiGjDUny+Y8UjowknQVaPYao0PC4bygKEbeZqCqRvSgPa\nlSc53OFqCh2FHydzl09fChaos385QvF40EDEgSO8U9/dntAeNULwuuZBi7BkWSIO\nmWN1l4e+TZbtSJXwn+EINAJhRHyCSNeku21dsw+cMoLorMKnRmhJMLvE+CCdgNKI\naPo/Krizva1+bMsI8bSkV/CxaCTLXodb/NuBYCsIHY1sTvbwSBRNMPvccw43RJCU\nKZRkBLkCVfW24ANbLfHXofHDMLxxFNUpBPSgzGHnueHknECcf6J4HCFBqzvSH1Tj\nQ3S6J8tq2yaQ+jFNkxGRMushdXNNiTNjDFYMJNvgRL2lu606PZeypEjvPg7SkGR2\n7a42GDSJ8n6HQJXFkOQPJ1mkU4qpA78U+ZAo9ccw8XQPPqE1eG7wzMGihTWfEMVs\nK1nsKyEZCLYFmKwYqdIF0somFBXaL/qmEHxwlPCjwRKpwLOue0Y8fgA06xk+DMti\nzWahOZNeZ54MN3N14S22D75riYEccVe3CtkDoL+4Oc2MhVdYEVtQcqtKqZ+DmmoI\n5BqkECeSHZ4OCguheFckK5Eq5Yf0CKRN+RY2OJ0ZCPUyxQnWdnOi9oBcZsz2NGzY\ng8ifO5s5UGscSDMQWUxPJQePDh8nPUittzJ+iplQqJYQ/9p5nKoDukzHHkSwfGms\n1GiSYMUZvaze7VSWOHrgZ6dp5qc1SQy0FSacBaEu4ziwx1H7w5NZj+zj2ZbxAZhr\n7Wfvt9K1xp58H66U4YT8Su7oq5JGDxuwOEbkltA7PzbFUtq65m4P4LvS4QUIBUqU\n0+JRyppVN5HPe11cCPaDdWhcr3LsibWXQ7f0mK8xTtPkOUb5pA2OUIkwNlzmwwS1\nNn69/13u7HmPSyofLck77zGjjqhSV22oHhBSGEr+KagMLZlvt9pnD/3I1R1BqItW\nKF3woyb/QizAqScEBsOKj7fmGA7f0KKQkpSpenF1Q/LNdyyOc77wbu2aywLGLN7H\nBCdwwjjMQ43FHSQPCA3+5mQDcfhmsFtORnRZWqVKwcKWuUJ7zLEIxlANZ7rDcC30\nFKmeUJuKk0Upvhsz7UXzDtNmqYmtg6vY/yPtG5Cc7XXGJxY2QJcbg1uqYI6gKtue\n00Mfpjw7XpUMQbIW9rXMA9PSWX6h2ln2TwlbrRikqdQXACZyhtuzSNLK7ifSqw4O\nJcZ8JrQ/xePmSd0z6O/MCTiUTFwG0E6WS1XBV1owOYi6jVif1zg75DTbXQGTNRvK\nKarodfnpYg3sgTe/8OAI1YSwProuGNNh4hxK+SmljqrYmEj8BNK3MNCyIskCcQ4u\ncyoJJHmsNaGFyiKp1543PktIgcs8kpF/SN86/SoB/oI7KECCCKtHNdFV8p9HO3t8\n5OsgGUYgvh7Z/Z+P7UGgN1iaYn7El9XopQ/XwK9zc9FBr73+xzE5Hh4aehNVIQdM\nMb+Rfm11R0Jc4WhqBLCC3/uBRzesyKUzPoRJ9IOxCwzeFwGQ202XVlPvklXQwgHx\nBfEAWZY1gaX6femNGDkRldzImxF87Sncnt9Y9uQty8u0IY3lLYNcAFoTobZmFkAQ\nvuNcXxObmHk3rZNAbRLFsXnWUKGjuK5oP2TyTNlm9fMmnf/E8deez3d8KOXW9YMZ\nDkA/iElnxcCKUFpwI+tWqHQ0FT96sgIP/EyhhCq6o/RnNtZvch9zW8sIGD7Lg0cq\nSzPYghZuNVYwr90qt7UDekEei4CHTzgWwlSWGGCrP6Oxjk1Fe+KvH4OYwEiDwyRc\nl7NRJseqpW1ODv8c3VLnTJJ4o3QPlAO6tOvon7vA1STKtXylbjWARNcWuxT41jtC\nCzrAroK2r9bCij4VbwHjmpQnhYbF/hCE1r71Z5eHdWXqpSgIWeS/1avQTStsehwD\n2+NGFRXI8mwLBLQN/qi8rqmKPi+fPVBjFoYDyDc35elpdzvqtN/mEp+xDrnAbwXU\nyfhkZvyo2+LXFMGFLdYtWTK/+T/4n03OJH1gr6j3zkoosewKTiZeClnK/qfc8YLw\nbCdwBm4uHsZ9I14OFCepfHzmXp9nN6a3u0sKi4GZpnAIjSreY4rMK8c+0FNNDLi5\nDKuck7+WuGkcRrB/1G9qSdpXqVe86uNojXk9P6TlpXyL/noudwmUhUNTZyOGcmhJ\nEBiaNbT2Awx5QNssAlZFuEfvPEAixBz476U8/UPb9ObHbsdcZjXNV89WhfYX04DM\n9qcMhCnGq25sJPc5VC6XnNHpFeWhvV/edYESdeEVwxEcExKEAwmEZlGJdxzoAH+K\nY+xAZdgWjPPL5FaYzpXc5erALUfyT+n0UTLcjaR4AKxLnpbRqlNzrWa6xqJN9NwA\n+xa38I6EXbQ5Q2kLcK6qbJAbkEL76WiFlkc5mXrGouukDvsjYdxG5Rx6OYxb41Ep\n1jEtinaNfXwt/JiDZxuXCMHdKHSH40aZCRlwdAI1C5fqoUkgiDdsxkEq+mGWxMVE\nZd0Ch9zgQLlA6gYlK3gt8+dr1+OSZ0dQdp3ABqb1+0oP8xpozFc2bK3OsJvucpYB\nOdmS+rfScY+N0PByGJoKbdNUHIeXv2xdhXnVjM5G3G6nxa3x8WFMJsJs2ma1xRT1\n8HKqjX9Ha072PD8Zviu/bWdf5c4RrphVqvzfr9wNRpfmnGOoOcbkRE4QrL5CqrPb\nVRujOBMPGAxNlvwq0w1XDOBDawZgK7660yd4MQFZk7iyZgUSXIo3ikleRSmBs+Mt\nr+3Og54Cg9QLPHbQQPmiMsu21IJUh0rTgxMVBxNUNbUaPJI1lmbkTcc7HeIk0Wtg\nRxwYc8aUn0f/V//c+2ZAlM6xmXmj6jIkOcfkSBd0B5z63N4trypD3m+w34bZkV1I\ncQ8h7SaUUqYO5RkjStZbvk2IDFSPUExvqhCstnJf7PZGilbsFPN8lYqcIvDZdaAU\nMunNh6f/RnhFwKHXoyWtNI6yK6dm1mhwy+DgPlA2nAevO+FC7Vv98Sl9zaVjaPPy\n3BRyQ6kISCL065AKVPEY0ULHqtIyfU5gMvBeUa5+xbU+tUx4ZeP/BdB48/LodyYV\nkkgqTafVxCvz4vgmPbnPjm/dlRbVGbyygN0Noq8vo2Ea8Z5zwO32coY2309AC7wv\nPp2wJZn6LKRmzoLWJMFm1A1Oa4RUIkEpA3AAL+5TauxfawpdtTjicoWGQ5gGNwum\n+evTnGEpDimE5kUU6uiJ0rotjNpB52I+8qmbgIPkY0Fwwal5Z5yvZJ8eepQjvdZ2\nUcdvlTS8oA5YayGi+ASmnJSbsr/v1OOcLmnpwPI+hRgPP+Hwu5rWkOT+SDomF1TO\nn/k7NkJ967X0kPx6XtxTPgcG1aKJwZBNQDKDP17/dlZ869W3o6JdgCEvt1nIOPty\nlGgvGERC0jCNRJpGml4/py7AtP0WOxrs+YS60sPKMATtiGzp34++dAmHyVEmelhK\napQBuxFl6LQN33+2NNn6L5twI4IQfnm6Cvly9r3VBO0Bi+rpjdftr60scRQM1qw+\n9dEz4xL9VEL6wrnyAERLY58wmS9Zp73xXQ1mdDB+yKkGOHeIiA7tCwnNZqClQ8Mf\nRnZIAeL1jcqrIsmkQNs4RTuE+ApcnE5DMcvJMgEd1fU3JDRJbaUv+w7kxj4/+G5b\nIU2bfh52jUQ5gOftGEFs1LOLj4Bny2XlCiP0L7XLJTKSf0t1zj2ohQWDT5BLo0EV\n5rye4hckB4QCiNyiZfavwB6ymStjwnuaS8qwjaRLw4JEeNDjSs/JC0G2ewulUyHt\nkEobZO/mQLlhso2lnEaRtK1LyoD1b4IEDbTYmjaWKLR7J64iHKUpiQYPSPxcWyei\no4kcyGw+QvgmxGaKsqSBVGogOV6YuEyoaM0jlfUmi2UmQkju2iY5tzCObNQ41nsL\ndKwraDrcjrn4CAKPMMfeUSvYWP559EFfDhDSK6Os6Sbo8R6Zoa7C2NdAicA1jPbt\n5ENSrVKf7TOrthvNH9vb1mZC1X2RBmriowa/iT+LEbmQnAkA6Y1tCbpzvrL+cX8K\npUTOAovaiPbab0xzFP7QXc1uK0XA+M1wQ9OF3XGp8PS5QRgSTwMpQXW2iMqihYPv\nHu6U1hhkyfzYZzoJCjVsY2xghJmjKiKEfX0w3RaxfrJkF8ePY9SexnVUNXJ1654/\nPQzDKsW58Au9QpIH9VSwKNpv003PksOpobM6G52ouCFOk6HFzSLfnlGZW0yyUQL3\nRRyEE2PP0LwQEuk2gxrW8eVy9elqn43S8CG2h2NUtmQULc/IeX63tmCOmOS0emW9\n66EljNdMk/e5dTo5XplTJRxRydXcQpgy9bQuntFwPPoo0fXfXlirKsav2rPSWayw\nKQK4NxinT+yQh//COeQDYkK01urc2G7SxZ6H0k6uo8xVp9tDCYqHk/lbvukoN0RF\ntUI4aLWuKet1O1s1uUAxjd50ELks5iwoqLJ/1bzSmTRMifehP07sbK/N1f4hLae+\njykYgzDWNfNvmPEiz0DwO/rCQTP6x69g+NJaFlmPFwGsKfxP8HqiNWQ6D3irZYcQ\nR5Mt2Iwzz2ZWA7B2WLYZWndRCosRVWyPdGhs7gkmLPZ+WWo/Yb7O1kIiWGfVuPNA\nMKmgPPjZy8DhZfq5kX20KF6uA0JOZOciXhc0PPAUEy/iQAtzSDYjmJ8HR7l4mYsT\nO3Mg3QibMK8MGGa4tEM8OPGktAV5B2J2QOe0f1r3vi3QmM+yukBaabwlJ+dUDQGm\n+Ll/1mO5TS+BlWMEAi13cB5bPRsxkzpabxq5kyQwh4vcMuLI0BOIfE2pDKny5jhW\n0C4zzv3avYaJh2ts6kvlvTKiSMeXcnK6onKHT89fWQ7Hzr/W8QbR/GnIWBbJMoTc\nWcgmW4fO3AC+YlnLVK4kBmnBmsLzLh6M2LOabhxKN8+0Oeoouww7g0HgHkDyt+MS\n97po6SETwrdqEFslylLo8+GifFI1bb68H79iEwjXojxQXcD5qqJPxdHsA32eWV0b\nqXAVojyAk7kQJfDIK+Y1q9T6KI4ew4t6iauJ8iVJyClnHt8z/4cXdMX37EvJ+2BS\nYKHv5OAfS7/9ZpKgILT8NxghgvguLB7G9sWNHntExPtuRLL4/asYFYSAJxUPm7U2\nxnp35Zx5jCXesd5OlKNdmhXq519cLl0RGZfH2ZIAEf1hNZqDuKesZ2enykjFlIec\nhZsLvEW/pJQnW0+LFz9N3x3vJwxbC7oDgd7A2u0I69Tkdzlc6FFJcfGabT5C3eF2\nEAC+toIobJY9hpxdkeukSuxVwin9zuBoUM4X9x/FvgfIE0dKLpzsFyMNlO4taCLc\nv1zbgUk2sR91JmbiCbqHglTzQaVMLhPwd8GU55AvYCGMOsSg3p952UkeoxRSeZRp\njQHr4bLN90cqNcrD3h5knmC61nDKf8e+vRZO8CVYR1eb3LsMz12vhTJGaQ4jd0Kz\nQyosjcB73wnE9b/rxfG1dRactg7zRU2BfBK/CHpIFJH+XztwMJxn27foSvCY6ktd\nuJorJvkGJOgwg0f+oHKDvOTWFO1GSqEZ5BwXKGH0t0udZyXQGgZWvF5s/ojZVcK3\nIXz4tKhwrI1ZKnZwL9R2zrpMJ4w6smQgipP0yzzi0ZvsOXRksQJNCn4UPLBhbu+C\neFBbpfe9wJFLD+8F9EY6GlY2W9AKD5/zNUCj6ws8lBn3aRfNPE+Cxy+IKC1NdKLw\neFdOGZr2y1K2IkdefmN9cLZQ/CVXkw8Qw2nOr/ntwuFV/tvJoPW2EOzRmF2XO8mQ\nDQv51k5/v4ZE2VL0dIIvj1M+KPw0nSs271QgJanYwK3CpFluK/1ilEi7JKDikT8X\nTSz1QZdkum5Y3uC7wc7paXh1rm11nwluCC7jiA==\n-----END CERTIFICATE-----\";\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/IConfigurationPropertyUpdater.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Interface for a service that updates properties of configuration items.\n /// \n public interface IConfigurationPropertyUpdater\n {\n /// \n /// Updates properties of items based on the configuration.\n /// \n /// The items to update.\n /// The configuration file containing the updates.\n /// The number of items that were updated.\n Task UpdateItemsAsync(IEnumerable items, ConfigurationFile configFile);\n\n /// \n /// Updates additional properties of an item based on the configuration.\n /// \n /// The item to update.\n /// The configuration item containing the updates.\n /// True if any properties were updated, false otherwise.\n bool UpdateAdditionalProperties(object item, ConfigurationItem configItem);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IConfigurationCoordinatorService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for coordinating configuration operations across multiple view models.\n /// \n public interface IConfigurationCoordinatorService\n {\n /// \n /// Creates a unified configuration file containing settings from all view models.\n /// \n /// A task representing the asynchronous operation. Returns the unified configuration file.\n Task CreateUnifiedConfigurationAsync();\n\n /// \n /// Applies a unified configuration to the selected sections.\n /// \n /// The unified configuration file.\n /// The sections to apply.\n /// A task representing the asynchronous operation. Returns true if successful, false otherwise.\n Task ApplyUnifiedConfigurationAsync(UnifiedConfigurationFile config, IEnumerable selectedSections);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/ISectionConfigurationApplier.cs", "using System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Interface for services that apply configuration to specific sections.\n /// \n public interface ISectionConfigurationApplier\n {\n /// \n /// Gets the section name that this applier handles.\n /// \n string SectionName { get; }\n\n /// \n /// Applies the configuration to the section.\n /// \n /// The configuration file to apply.\n /// True if any items were updated, false otherwise.\n Task ApplyConfigAsync(ConfigurationFile configFile);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IMessengerService.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Provides functionality for messaging between components.\n /// \n public interface IMessengerService\n {\n /// \n /// Sends a message of the specified type.\n /// \n /// The type of the message to send.\n /// The message to send.\n void Send(TMessage message);\n\n /// \n /// Registers a recipient for messages of the specified type.\n /// \n /// The type of message to register for.\n /// The recipient object.\n /// The action to perform when a message is received.\n void Register(object recipient, Action action);\n\n /// \n /// Unregisters a recipient from receiving messages.\n /// \n /// The recipient to unregister.\n void Unregister(object recipient);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Models/LogMessageViewModel.cs", "using System;\nusing Winhance.Core.Features.Common.Enums;\n\nnamespace Winhance.WPF.Features.Common.Models\n{\n /// \n /// View model for log messages displayed in the UI.\n /// \n public class LogMessageViewModel\n {\n /// \n /// Gets or sets the message content.\n /// \n public string Message { get; set; }\n \n /// \n /// Gets or sets the log level.\n /// \n public LogLevel Level { get; set; }\n \n /// \n /// Gets or sets the timestamp when the message was created.\n /// \n public DateTime Timestamp { get; set; }\n \n /// \n /// Gets the formatted message with timestamp.\n /// \n public string FormattedMessage => $\"[{Timestamp:HH:mm:ss}] {Message}\";\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppLoadingService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for loading application information and status.\n /// \n public interface IAppLoadingService\n {\n /// \n /// Loads applications and their installation status.\n /// \n /// An operation result containing a collection of applications with their installation status or error details.\n Task>> LoadAppsAsync();\n\n /// \n /// Refreshes the installation status of applications.\n /// \n /// The applications to refresh.\n /// An operation result indicating success or failure with error details.\n Task> RefreshInstallationStatusAsync(IEnumerable apps);\n\n /// \n /// Gets the installation status for an app by ID.\n /// \n /// The app ID.\n /// An operation result containing the installation status or error details.\n Task> GetInstallStatusAsync(string appId);\n\n /// \n /// Sets the installation status for an app.\n /// \n /// The app ID.\n /// The new status.\n /// An operation result indicating success or failure with error details.\n Task> SetInstallStatusAsync(string appId, InstallStatus status);\n\n /// \n /// Loads Windows capabilities.\n /// \n /// A collection of capability information.\n Task> LoadCapabilitiesAsync();\n\n /// \n /// Gets the installation status for an installable item.\n /// \n /// The installable item.\n /// True if the item is installed, false otherwise.\n Task GetItemInstallStatusAsync(IInstallableItem item);\n\n /// \n /// Gets the installation status for multiple package IDs.\n /// \n /// The package IDs to check.\n /// A dictionary mapping package IDs to their installation status.\n Task> GetBatchInstallStatusAsync(IEnumerable packageIds);\n\n /// \n /// Clears the status cache.\n /// \n void ClearStatusCache();\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IVisibleSettingItem.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for setting items that can be shown or hidden in the UI.\n /// \n public interface IVisibleSettingItem\n {\n /// \n /// Gets or sets a value indicating whether this setting item is visible in the UI.\n /// \n bool IsVisible { get; set; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IFeatureInstallationService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for installing Windows optional features.\n /// \n public interface IFeatureInstallationService : IInstallationService\n {\n /// \n /// Installs a feature.\n /// \n /// The feature to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n Task> InstallFeatureAsync(FeatureInfo feature, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if a feature can be installed.\n /// \n /// The feature to check.\n /// An operation result indicating if the feature can be installed, with error details if not.\n Task> CanInstallFeatureAsync(FeatureInfo feature);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/ICapabilityInstallationService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for installing Windows capabilities.\n /// \n public interface ICapabilityInstallationService : IInstallationService\n {\n /// \n /// Installs a capability.\n /// \n /// The capability to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n Task> InstallCapabilityAsync(CapabilityInfo capability, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if a capability can be installed.\n /// \n /// The capability to check.\n /// An operation result indicating if the capability can be installed, with error details if not.\n Task> CanInstallCapabilityAsync(CapabilityInfo capability);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppInstallationService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for installing Windows applications.\n /// \n public interface IAppInstallationService : IInstallationService\n {\n /// \n /// Installs an application.\n /// \n /// The application to install.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n Task> InstallAppAsync(AppInfo app, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if an application can be installed.\n /// \n /// The application to check.\n /// An operation result indicating if the application can be installed, with error details if not.\n Task> CanInstallAppAsync(AppInfo app);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IFeatureRemovalService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for removing Windows optional features.\n /// \n public interface IFeatureRemovalService\n {\n /// \n /// Removes a feature.\n /// \n /// The feature to remove.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// True if the removal was successful; otherwise, false.\n Task RemoveFeatureAsync(FeatureInfo feature, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if a feature can be removed.\n /// \n /// The feature to check.\n /// True if the feature can be removed; otherwise, false.\n Task CanRemoveFeatureAsync(FeatureInfo feature);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/ICapabilityRemovalService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for removing Windows capabilities.\n /// \n public interface ICapabilityRemovalService\n {\n /// \n /// Removes a capability.\n /// \n /// The capability to remove.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// True if the removal was successful; otherwise, false.\n Task RemoveCapabilityAsync(CapabilityInfo capability, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Checks if a capability can be removed.\n /// \n /// The capability to check.\n /// True if the capability can be removed; otherwise, false.\n Task CanRemoveCapabilityAsync(CapabilityInfo capability);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IApplicationCloseService.cs", "using System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Service for handling application close functionality\n /// \n public interface IApplicationCloseService\n {\n /// \n /// Shows the support dialog if needed and handles the application close process\n /// \n /// A task representing the asynchronous operation\n Task CloseApplicationWithSupportDialogAsync();\n \n /// \n /// Saves the \"Don't show support dialog\" preference\n /// \n /// Whether to show the support dialog in the future\n /// A task representing the asynchronous operation\n Task SaveDontShowSupportPreferenceAsync(bool dontShow);\n \n /// \n /// Checks if the support dialog should be shown based on user preferences\n /// \n /// True if the dialog should be shown, false otherwise\n Task ShouldShowSupportDialogAsync();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IScheduledTaskService.cs", "using System.Threading.Tasks;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for a service that manages scheduled tasks for script execution.\n /// \n public interface IScheduledTaskService\n {\n /// \n /// Registers a scheduled task to run the specified script.\n /// \n /// The script to register as a scheduled task.\n /// True if the task was registered successfully, false otherwise.\n Task RegisterScheduledTaskAsync(RemovalScript script);\n\n /// \n /// Unregisters a scheduled task with the specified name.\n /// \n /// The name of the task to unregister.\n /// True if the task was unregistered successfully, false otherwise.\n Task UnregisterScheduledTaskAsync(string taskName);\n\n /// \n /// Checks if a scheduled task with the specified name is registered.\n /// \n /// The name of the task to check.\n /// True if the task exists, false otherwise.\n Task IsTaskRegisteredAsync(string taskName);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IDependencyManager.cs", "using System.Collections.Generic;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Defines methods for managing dependencies between settings.\n /// \n public interface IDependencyManager\n {\n /// \n /// Determines if a setting can be enabled based on its dependencies.\n /// \n /// The ID of the setting to check.\n /// All available settings that might be dependencies.\n /// True if the setting can be enabled; otherwise, false.\n bool CanEnableSetting(string settingId, IEnumerable allSettings);\n \n /// \n /// Handles the disabling of a setting by automatically disabling any dependent settings.\n /// \n /// The ID of the setting that was disabled.\n /// All available settings that might depend on the disabled setting.\n void HandleSettingDisabled(string settingId, IEnumerable allSettings);\n \n /// \n /// Handles the enabling of a setting by automatically enabling any required settings.\n /// \n /// The ID of the setting that is being enabled.\n /// All available settings that might be required by the enabled setting.\n /// True if all required settings were enabled successfully; otherwise, false.\n bool HandleSettingEnabled(string settingId, IEnumerable allSettings);\n\n /// \n /// Gets a list of unsatisfied dependencies for a setting.\n /// \n /// The ID of the setting to check.\n /// All available settings that might be dependencies.\n /// A list of settings that are required by the specified setting but are not enabled.\n List GetUnsatisfiedDependencies(string settingId, IEnumerable allSettings);\n\n /// \n /// Enables all dependencies in the provided list.\n /// \n /// The dependencies to enable.\n /// True if all dependencies were enabled successfully; otherwise, false.\n bool EnableDependencies(IEnumerable dependencies);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/IVersionService.cs", "using System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n public interface IVersionService\n {\n /// \n /// Gets the current application version\n /// \n VersionInfo GetCurrentVersion();\n \n /// \n /// Checks if an update is available\n /// \n /// A task that resolves to true if an update is available, false otherwise\n Task CheckForUpdateAsync();\n \n /// \n /// Downloads and launches the installer for the latest version\n /// \n /// A task that completes when the download is initiated\n Task DownloadAndInstallUpdateAsync();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Models/WindowsPackageModels.cs", "using Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Models;\n\npublic record WindowsPackage\n{\n public required string Category { get; init; }\n public required string FriendlyName { get; init; }\n public required string PackageName { get; init; }\n public WindowsAppType AppType { get; init; }\n public IReadOnlyList? SubPackages { get; init; }\n public string? Description { get; init; }\n public IReadOnlyList? RegistrySettings { get; init; }\n public bool IsInstalled { get; init; }\n}\n\npublic record LegacyCapability\n{\n public required string FriendlyName { get; init; }\n public required string Name { get; init; }\n public bool IsInstalled { get; init; }\n}\n\npublic record WindowsService\n{\n public required string Name { get; init; }\n public required string DisplayName { get; init; }\n public required string Description { get; init; }\n public required ServiceStartupType RecommendedState { get; init; }\n public ServiceStartupType? CurrentState { get; init; }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Exceptions/InstallationStatusException.cs", "using System;\n\nnamespace Winhance.Core.Models.Exceptions\n{\n public class InstallationStatusException : Exception\n {\n public InstallationStatusException(string message) : base(message)\n {\n }\n\n public InstallationStatusException(string message, Exception innerException) \n : base(message, innerException)\n {\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/SoftwareApps/Views/WindowsAppsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.SoftwareApps.Views\n{\n /// \n /// Interaction logic for WindowsAppsView.xaml\n /// \n public partial class WindowsAppsView : UserControl\n {\n public WindowsAppsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/Views/ExplorerCustomizationsView.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Customize.Views\n{\n /// \n /// Interaction logic for ExplorerCustomizationsView.xaml\n /// \n public partial class ExplorerCustomizationsView : UserControl\n {\n public ExplorerCustomizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/Views/TaskbarCustomizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Customize.Views\n{\n /// \n /// Interaction logic for TaskbarCustomizationsView.xaml\n /// \n public partial class TaskbarCustomizationsView : UserControl\n {\n public TaskbarCustomizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Customize/Views/StartMenuCustomizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Customize.Views\n{\n /// \n /// Interaction logic for StartMenuCustomizationsView.xaml\n /// \n public partial class StartMenuCustomizationsView : UserControl\n {\n public StartMenuCustomizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/UpdateOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for UpdateOptimizationsView.xaml\n /// \n public partial class UpdateOptimizationsView : UserControl\n {\n public UpdateOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/SoundOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for SoundOptimizationsView.xaml\n /// \n public partial class SoundOptimizationsView : UserControl\n {\n public SoundOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/PrivacyOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for PrivacyOptimizationsView.xaml\n /// \n public partial class PrivacyOptimizationsView : UserControl\n {\n public PrivacyOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/NotificationOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for NotificationOptimizationsView.xaml\n /// \n public partial class NotificationOptimizationsView : UserControl\n {\n public NotificationOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/ExplorerOptimizationsView.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for ExplorerOptimizationsView.xaml\n /// \n public partial class ExplorerOptimizationsView : UserControl\n {\n public ExplorerOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/PowerOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for PowerOptimizationsView.xaml\n /// \n public partial class PowerOptimizationsView : UserControl\n {\n public PowerOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/RegistryActionType.cs", "namespace Winhance.Core.Features.Common.Enums;\n\n/// \n/// Defines the intended action for a registry setting.\n/// \npublic enum RegistryActionType\n{\n /// \n /// The setting is intended to set a specific value.\n /// \n Set,\n \n /// \n /// The setting is intended to remove a key or value.\n /// \n Remove,\n \n /// \n /// The setting is intended to modify an existing value.\n /// \n Modify\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/WindowsSecurityOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for WindowsSecurityOptimizationsView.xaml\n /// \n public partial class WindowsSecurityOptimizationsView : UserControl\n {\n public WindowsSecurityOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Optimize/Views/GamingandPerformanceOptimizationsView.xaml.cs", "using System.Windows.Controls;\n\nnamespace Winhance.WPF.Features.Optimize.Views\n{\n /// \n /// Interaction logic for GamingandPerformanceOptimizationsView.xaml\n /// \n public partial class GamingandPerformanceOptimizationsView : UserControl\n {\n public GamingandPerformanceOptimizationsView()\n {\n InitializeComponent();\n }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppRemovalService.cs", "using System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Service for removing Windows applications.\n /// \n public interface IAppRemovalService\n {\n /// \n /// Removes an application.\n /// \n /// The application to remove.\n /// Optional progress reporter.\n /// Optional cancellation token.\n /// An operation result indicating success or failure with error details.\n Task> RemoveAppAsync(AppInfo app, IProgress? progress = null, CancellationToken cancellationToken = default);\n\n /// \n /// Generates a removal script for an application.\n /// \n /// The application to generate a removal script for.\n /// An operation result containing the removal script or error details.\n Task> GenerateRemovalScriptAsync(AppInfo app);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/ISpecialAppHandlerService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n /// \n /// Provides functionality for handling special applications that require custom removal procedures.\n /// \n public interface ISpecialAppHandlerService\n {\n /// \n /// Gets all registered special app handlers.\n /// \n /// A collection of special app handlers.\n IEnumerable GetAllHandlers();\n\n /// \n /// Gets a special app handler by its type.\n /// \n /// The type of handler to retrieve.\n /// The requested special app handler, or null if not found.\n SpecialAppHandler? GetHandler(string handlerType);\n\n /// \n /// Removes Microsoft Edge.\n /// \n /// True if the operation succeeded; otherwise, false.\n Task RemoveEdgeAsync();\n\n /// \n /// Removes OneDrive.\n /// \n /// True if the operation succeeded; otherwise, false.\n Task RemoveOneDriveAsync();\n\n /// \n /// Removes OneNote.\n /// \n /// True if the operation succeeded; otherwise, false.\n Task RemoveOneNoteAsync();\n\n /// \n /// Removes a special application using its registered handler.\n /// \n /// The type of handler to use.\n /// True if the operation succeeded; otherwise, false.\n Task RemoveSpecialAppAsync(string handlerType);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/LinkedSettingsLogic.cs", "namespace Winhance.Core.Features.Common.Enums;\n\n/// \n/// Defines the logic to use when determining the status of linked registry settings.\n/// \npublic enum LinkedSettingsLogic\n{\n /// \n /// If any of the linked settings is applied, the entire setting is considered applied.\n /// \n Any,\n \n /// \n /// All linked settings must be applied for the entire setting to be considered applied.\n /// \n All,\n \n /// \n /// Only use the first (primary) setting to determine the status.\n /// \n Primary,\n \n /// \n /// Use a custom logic defined in the code.\n /// \n Custom\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ISearchService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for services that handle search operations.\n /// \n public interface ISearchService\n {\n /// \n /// Filters a collection of items based on a search term.\n /// \n /// The type of items to filter.\n /// The collection of items to filter.\n /// The search term to filter by.\n /// A filtered collection of items that match the search term.\n IEnumerable FilterItems(IEnumerable items, string searchTerm) where T : ISearchable;\n\n /// \n /// Asynchronously filters a collection of items based on a search term.\n /// \n /// The type of items to filter.\n /// The collection of items to filter.\n /// The search term to filter by.\n /// A task that represents the asynchronous operation. The task result contains a filtered collection of items that match the search term.\n Task> FilterItemsAsync(IEnumerable items, string searchTerm) where T : ISearchable;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IAppVerificationService.cs", "using System.Threading.Tasks;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces;\n\n/// \n/// Interface for services that handle verification of application installations.\n/// \npublic interface IAppVerificationService\n{\n /// \n /// Verifies if an app is installed.\n /// \n /// The package name to verify.\n /// True if the app is installed; otherwise, false.\n Task VerifyAppInstallationAsync(string packageName);\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Interfaces/ISettingsRegistry.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Interfaces;\n\nnamespace Winhance.Core.Features.Common.Interfaces\n{\n /// \n /// Interface for a registry of settings.\n /// \n public interface ISettingsRegistry\n {\n /// \n /// Registers a setting in the registry.\n /// \n /// The setting to register.\n void RegisterSetting(ISettingItem setting);\n\n /// \n /// Gets a setting by its ID.\n /// \n /// The ID of the setting to get.\n /// The setting if found, otherwise null.\n ISettingItem? GetSettingById(string id);\n\n /// \n /// Gets all settings in the registry.\n /// \n /// A list of all settings.\n List GetAllSettings();\n\n /// \n /// Gets all settings of a specific type.\n /// \n /// The type of settings to get.\n /// A list of settings of the specified type.\n List GetSettingsByType() where T : ISettingItem;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/CancellationReason.cs", "namespace Winhance.Core.Features.Common.Enums\n{\n /// \n /// Represents the reason for a cancellation operation.\n /// \n public enum CancellationReason\n {\n /// \n /// No cancellation occurred.\n /// \n None = 0,\n\n /// \n /// Cancellation was initiated by the user.\n /// \n UserCancelled = 1,\n\n /// \n /// Cancellation occurred due to internet connectivity issues.\n /// \n InternetConnectivityLost = 2,\n\n /// \n /// Cancellation occurred due to a system error.\n /// \n SystemError = 3\n }\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Messages/ResetExpansionStateMessage.cs", "using System;\n\nnamespace Winhance.WPF.Features.Common.Messages\n{\n /// \n /// Message to notify the view to reset the expansion state of collapsible sections.\n /// \n public class ResetExpansionStateMessage\n {\n /// \n /// Gets the timestamp when the message was created.\n /// \n public DateTime Timestamp { get; } = DateTime.Now;\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/RegistrySettingStatus.cs", "namespace Winhance.Core.Features.Common.Enums;\n\npublic enum RegistrySettingStatus\n{\n Unknown, // Status couldn't be determined\n NotApplied, // Registry key doesn't exist or has default value\n Applied, // Current value matches recommended value\n Modified, // Value exists but doesn't match recommended or default\n Error // Error occurred while checking status\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/IScriptContentModifier.cs", "using System;\nusing System.Collections.Generic;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration;\n\n/// \n/// Provides methods for modifying script content.\n/// \npublic interface IScriptContentModifier\n{\n /// \n /// Removes a capability from the script content.\n /// \n /// The script content.\n /// The name of the capability to remove.\n /// The updated script content.\n string RemoveCapabilityFromScript(string scriptContent, string capabilityName);\n\n /// \n /// Removes a package from the script content.\n /// \n /// The script content.\n /// The name of the package to remove.\n /// The updated script content.\n string RemovePackageFromScript(string scriptContent, string packageName);\n\n /// \n /// Removes an optional feature from the script content.\n /// \n /// The script content.\n /// The name of the optional feature to remove.\n /// The updated script content.\n string RemoveOptionalFeatureFromScript(string scriptContent, string featureName);\n\n /// \n /// Removes app-specific registry settings from the script content.\n /// \n /// The script content.\n /// The name of the app whose registry settings should be removed.\n /// The updated script content.\n string RemoveAppRegistrySettingsFromScript(string scriptContent, string appName);\n}\n"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/ICapabilityScriptModifier.cs", "using System;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Provides methods for modifying capability-related script content.\n /// \n public interface ICapabilityScriptModifier\n {\n /// \n /// Removes a capability from the script content.\n /// \n /// The script content.\n /// The name of the capability to remove.\n /// The updated script content.\n string RemoveCapabilityFromScript(string scriptContent, string capabilityName);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Models/IInstallableItem.cs", "namespace Winhance.Core.Features.Common.Models\n{\n public interface IInstallableItem\n {\n string PackageId { get; }\n string DisplayName { get; }\n InstallItemType ItemType { get; }\n bool IsInstalled { get; set; }\n bool RequiresRestart { get; }\n }\n\n public enum InstallItemType\n {\n WindowsApp,\n Capability,\n Feature,\n ThirdParty\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Optimize/Models/PowerPlan.cs", "using System;\n\nnamespace Winhance.Core.Features.Optimize.Models\n{\n /// \n /// Represents a Windows power plan.\n /// \n public class PowerPlan\n {\n /// \n /// Gets or sets the name of the power plan.\n /// \n public string Name { get; set; }\n\n /// \n /// Gets or sets the GUID of the power plan.\n /// \n public string Guid { get; set; }\n\n /// \n /// Gets or sets the source GUID for plans that need to be created from another plan.\n /// \n public string SourceGuid { get; set; }\n\n /// \n /// Gets or sets the description of the power plan.\n /// \n public string Description { get; set; }\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/IFeatureScriptModifier.cs", "using System;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Provides methods for modifying feature-related script content.\n /// \n public interface IFeatureScriptModifier\n {\n /// \n /// Removes an optional feature from the script content.\n /// \n /// The script content.\n /// The name of the optional feature to remove.\n /// The updated script content.\n string RemoveOptionalFeatureFromScript(string scriptContent, string featureName);\n }\n}"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/Configuration/IViewModelRefresher.cs", "using System.Threading.Tasks;\n\nnamespace Winhance.WPF.Features.Common.Services.Configuration\n{\n /// \n /// Interface for a service that refreshes view models after configuration changes.\n /// \n public interface IViewModelRefresher\n {\n /// \n /// Refreshes a view model after configuration changes.\n /// \n /// The view model to refresh.\n /// A task representing the asynchronous operation.\n Task RefreshViewModelAsync(object viewModel);\n\n /// \n /// Refreshes a child view model after configuration changes.\n /// \n /// The child view model to refresh.\n /// A task representing the asynchronous operation.\n Task RefreshChildViewModelAsync(object childViewModel);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Enums/InstallationErrorType.cs", "using System;\n\nnamespace Winhance.Core.Features.SoftwareApps.Enums\n{\n /// \n /// Defines the types of errors that can occur during installation operations.\n /// \n public enum InstallationErrorType\n {\n /// \n /// An unknown error occurred during installation.\n /// \n UnknownError,\n\n /// \n /// A network-related error occurred during installation.\n /// \n NetworkError,\n\n /// \n /// A permission-related error occurred during installation.\n /// \n PermissionError,\n\n /// \n /// The package was not found in the repositories.\n /// \n PackageNotFoundError,\n\n /// \n /// WinGet is not installed and could not be installed automatically.\n /// \n WinGetNotInstalledError,\n\n /// \n /// The package is already installed.\n /// \n AlreadyInstalledError,\n\n /// \n /// The installation was cancelled by the user.\n /// \n CancelledByUserError,\n\n /// \n /// The system is in a state that prevents installation.\n /// \n SystemStateError,\n\n /// \n /// The package is corrupted or invalid.\n /// \n PackageCorruptedError,\n\n /// \n /// The package dependencies could not be resolved.\n /// \n DependencyResolutionError\n }\n}"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/OptimizationEnums.cs", "namespace Winhance.Core.Features.Common.Enums;\n\npublic enum OptimizationCategory\n{\n Privacy,\n Gaming,\n Updates,\n Performance,\n GamingandPerformance,\n Personalization,\n Taskbar,\n StartMenu,\n Explorer,\n Notifications,\n Sound,\n Accessibility,\n Search,\n Services,\n Power\n}\n\npublic enum WindowsAppType\n{\n AppX,\n Capability,\n Special // For Edge, OneDrive, etc.\n}\n\npublic enum ServiceStartupType\n{\n Automatic = 2,\n Manual = 3,\n Disabled = 4\n}"], ["/Winhance/src/Winhance.Core/Features/Customize/Models/CustomizationGroup.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Customize.Enums;\n\nnamespace Winhance.Core.Features.Customize.Models\n{\n /// \n /// Represents a group of customization settings.\n /// \n public record CustomizationGroup\n {\n /// \n /// Gets or sets the name of the customization group.\n /// \n public required string Name { get; init; }\n\n /// \n /// Gets or sets the category of the customization group.\n /// \n public required CustomizationCategory Category { get; init; }\n\n /// \n /// Gets or sets the settings in the customization group.\n /// \n public required IReadOnlyList Settings { get; init; }\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Enums/ControlType.cs", "using System;\n\nnamespace Winhance.Core.Features.Common.Enums\n{\n /// \n /// Defines the type of control to use for a setting.\n /// \n public enum ControlType\n {\n /// \n /// A binary toggle (on/off) control.\n /// \n BinaryToggle,\n\n /// \n /// A three-state slider control.\n /// \n ThreeStateSlider,\n\n /// \n /// A combo box control for selecting from a list of options.\n /// \n ComboBox,\n\n /// \n /// A custom control.\n /// \n Custom,\n\n /// \n /// A slider control.\n /// \n Slider,\n\n /// \n /// A dropdown control.\n /// \n Dropdown,\n\n /// \n /// A color picker control.\n /// \n ColorPicker\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/IPackageScriptModifier.cs", "using System;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Provides methods for modifying package-related script content.\n /// \n public interface IPackageScriptModifier\n {\n /// \n /// Removes a package from the script content.\n /// \n /// The script content.\n /// The name of the package to remove.\n /// The updated script content.\n string RemovePackageFromScript(string scriptContent, string packageName);\n }\n}"], ["/Winhance/src/Winhance.Infrastructure/Features/Common/ScriptGeneration/IRegistryScriptModifier.cs", "using System;\n\nnamespace Winhance.Infrastructure.Features.Common.ScriptGeneration\n{\n /// \n /// Provides methods for modifying registry-related script content.\n /// \n public interface IRegistryScriptModifier\n {\n /// \n /// Removes app-specific registry settings from the script content.\n /// \n /// The script content.\n /// The name of the app whose registry settings should be removed.\n /// The updated script content.\n string RemoveAppRegistrySettingsFromScript(string scriptContent, string appName);\n }\n}"], ["/Winhance/src/Winhance.Core/Features/UI/Interfaces/INotificationService.cs", "using System;\n\nnamespace Winhance.Core.Features.UI.Interfaces\n{\n /// \n /// Interface for notification services that can display toast notifications and other alerts.\n /// \n public interface INotificationService\n {\n /// \n /// Shows a toast notification.\n /// \n /// The title of the notification.\n /// The message content of the notification.\n /// The type of notification.\n void ShowToast(string title, string message, ToastType type);\n }\n\n /// \n /// Defines the types of toast notifications.\n /// \n public enum ToastType\n {\n /// \n /// Information notification.\n /// \n Information,\n\n /// \n /// Success notification.\n /// \n Success,\n\n /// \n /// Warning notification.\n /// \n Warning,\n\n /// \n /// Error notification.\n /// \n Error\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IOneDriveInstallationService.cs", "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces;\n\n/// \n/// Interface for services that handle OneDrive installation.\n/// \npublic interface IOneDriveInstallationService\n{\n /// \n /// Installs OneDrive from the Microsoft download link.\n /// \n /// Optional progress reporter.\n /// Optional cancellation token.\n /// True if installation was successful; otherwise, false.\n Task InstallOneDriveAsync(\n IProgress? progress,\n CancellationToken cancellationToken);\n}\n"], ["/Winhance/src/Winhance.WPF/Features/Common/Services/IDesignTimeDataService.cs", "using System.Collections.Generic;\nusing Winhance.WPF.Features.SoftwareApps.Models;\n\nnamespace Winhance.WPF.Features.Common.Services\n{\n /// \n /// Interface for providing design-time data for the application.\n /// This allows for proper visualization in the designer without running the application.\n /// \n public interface IDesignTimeDataService\n {\n /// \n /// Gets a collection of sample third-party applications for design-time.\n /// \n /// A collection of ThirdPartyApp instances.\n IEnumerable GetSampleThirdPartyApps();\n\n /// \n /// Gets a collection of sample Windows applications for design-time.\n /// \n /// A collection of WindowsApp instances.\n IEnumerable GetSampleWindowsApps();\n\n /// \n /// Gets a collection of sample Windows capabilities for design-time.\n /// \n /// A collection of WindowsApp instances configured as capabilities.\n IEnumerable GetSampleWindowsCapabilities();\n\n /// \n /// Gets a collection of sample Windows features for design-time.\n /// \n /// A collection of WindowsApp instances configured as features.\n IEnumerable GetSampleWindowsFeatures();\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/OptimizationConfig.cs", "using System.Collections.Generic;\nusing Winhance.Core.Features.Common.Enums;\nusing Winhance.Core.Features.Common.Models;\nusing Winhance.Core.Features.SoftwareApps.Models;\n\nnamespace Winhance.Core.Features.Common.Models;\n\npublic class OptimizationConfig\n{\n public required IDictionary> RegistrySettings { get; init; }\n public required IReadOnlyList WindowsPackages { get; init; }\n public required IReadOnlyList LegacyCapabilities { get; init; }\n public required IReadOnlyList Services { get; init; }\n}"], ["/Winhance/src/Winhance.Core/Features/SoftwareApps/Interfaces/IInstallationStatusService.cs", "using System.Collections.Generic;\nusing System.Threading.Tasks;\nusing Winhance.Core.Features.Common.Models;\n\nnamespace Winhance.Core.Features.SoftwareApps.Interfaces\n{\n public interface IInstallationStatusService\n {\n Task GetInstallStatusAsync(string appId);\n Task RefreshStatusAsync(IEnumerable appIds);\n Task SetInstallStatusAsync(string appId, InstallStatus status);\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Enums/CustomizationSettingType.cs", "using System;\n\nnamespace Winhance.Core.Features.Customize.Enums\n{\n /// \n /// Defines the type of customization setting.\n /// \n public enum CustomizationSettingType\n {\n /// \n /// A standard setting.\n /// \n Standard,\n\n /// \n /// A slider setting.\n /// \n Slider,\n\n /// \n /// A dropdown setting.\n /// \n Dropdown,\n\n /// \n /// A color picker setting.\n /// \n ColorPicker\n }\n}\n"], ["/Winhance/src/Winhance.Core/Features/Customize/Enums/CustomizationCategory.cs", "namespace Winhance.Core.Features.Customize.Enums;\n\n/// \n/// Defines the categories for customization settings.\n/// \npublic enum CustomizationCategory\n{\n /// \n /// Theme-related customization settings.\n /// \n Theme,\n \n /// \n /// Taskbar-related customization settings.\n /// \n Taskbar,\n \n /// \n /// Start menu-related customization settings.\n /// \n StartMenu,\n \n /// \n /// Explorer-related customization settings.\n /// \n Explorer,\n \n /// \n /// Notification-related customization settings.\n /// \n Notifications,\n \n /// \n /// Sound-related customization settings.\n /// \n Sound,\n \n /// \n /// Accessibility-related customization settings.\n /// \n Accessibility\n}\n"], ["/Winhance/src/Winhance.Core/Features/Common/Models/InstallStatus.cs", "namespace Winhance.Core.Features.Common.Models\n{\n public enum InstallStatus\n {\n Success,\n NotFound,\n Failed,\n Pending\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 19:10:26", "created_task_model": "DeepSeek-R1", "function_skeleton": "public object Convert (object value, Type targetType, object parameter, CultureInfo culture) {}", "code_description": "This code segment functions to: Transform theme configuration data into visual resource paths by selecting appropriate assets based on light/dark mode states and converting string parameters into usable image references, with fallback handling for invalid input conditions."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isDarkTheme && parameter is string iconPaths)\n {\n var pathParts = iconPaths.Split(';');\n if (pathParts.Length == 2)\n {\n var selectedPath = isDarkTheme ? pathParts[1] : pathParts[0];\n return new BitmapImage(new Uri(selectedPath, UriKind.RelativeOrAbsolute));\n }\n }\n return null;\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 19-10-53"}, "editdistance_info": {"edit_distance": 24.1935, "calculate_time": "2025-08-20 19:10:53", "true_code_clean": "public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n bool isDarkTheme = false;\n if (value is bool boolValue)\n {\n isDarkTheme = boolValue;\n Debug.WriteLine($\"BooleanToThemeIconConverter: isDarkTheme = {isDarkTheme} (from bool)\");\n }\n else if (value is string stringValue)\n {\n isDarkTheme = stringValue.Equals(\"Dark\", StringComparison.OrdinalIgnoreCase);\n Debug.WriteLine($\"BooleanToThemeIconConverter: isDarkTheme = {isDarkTheme} (from string '{stringValue}')\");\n }\n else\n {\n Debug.WriteLine($\"BooleanToThemeIconConverter: value is {(value == null ? \"null\" : value.GetType().Name)}\");\n }\n if (parameter is string paramString)\n {\n string[] iconPaths = paramString.Split('|');\n if (iconPaths.Length >= 2)\n {\n string darkIconPath = iconPaths[0];\n string lightIconPath = iconPaths[1];\n string selectedPath = isDarkTheme ? darkIconPath : lightIconPath;\n Debug.WriteLine($\"BooleanToThemeIconConverter: Selected path = {selectedPath}\");\n if (targetType == typeof(BitmapImage))\n {\n return new BitmapImage(new Uri(selectedPath, UriKind.Relative));\n }\n return selectedPath;\n }\n }\n Debug.WriteLine(\"BooleanToThemeIconConverter: Using fallback icon path\");\n return \"/Resources/AppIcons/winhance-rocket.ico\";\n }", "predict_code_clean": "public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool isDarkTheme && parameter is string iconPaths)\n {\n var pathParts = iconPaths.Split(';');\n if (pathParts.Length == 2)\n {\n var selectedPath = isDarkTheme ? pathParts[1] : pathParts[0];\n return new BitmapImage(new Uri(selectedPath, UriKind.RelativeOrAbsolute));\n }\n }\n return null;\n }"}}