Free, open-source Windows optimization tool for performance, privacy, and simplicity.
C# csharpdebloatdotnetgamingopen-sourceoptimizationoptimizeroptimizerduckperformanceprivacytweakertweakswindowswinui
feat: refactor optimizations, add embedded resource support and add more tests
fatDuck1cf23b977ee7
diff --git a/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs b/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.csnew file mode 100644index 0000000..f989b55--- /dev/null+++ b/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs@@ -0,0 +1,1183 @@+using Microsoft.Extensions.Logging.Abstractions;+using Newtonsoft.Json;+using optimizerDuck.Common.Helpers;+using optimizerDuck.Domain.Abstractions;+using optimizerDuck.Domain.Execution;+using optimizerDuck.Domain.Optimizations.Models;+using optimizerDuck.Domain.Revert;+using optimizerDuck.Domain.Revert.Steps;+using optimizerDuck.Domain.UI;+using optimizerDuck.Services;+using optimizerDuck.Services.Managers;+using Wpf.Ui;++namespace optimizerDuck.Test.Services;++/// <summary>+/// Comprehensive tests for apply and revert operations covering all scenarios.+/// These tests ensure safe operation without affecting the actual machine.+/// </summary>+public class ApplyRevertComprehensiveTests+{+ #region Apply Success Scenarios++ [Fact]+ public async Task ApplyAsync_AllStepsSuccess_CompleteRevertDataSaved()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization+ {+ ApplyImpl = _ =>+ {+ ExecutionScope.RecordStep(+ "Shell",+ "Step 1: Disable service",+ true,+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "sc config TestService start= auto" }+ );+ ExecutionScope.RecordStep(+ "Shell",+ "Step 2: Registry change",+ true,+ new ShellRevertStep { ShellType = ShellType.PowerShell, Command = "Set-ItemProperty -Path 'HKLM:\\Test' -Name 'Value' -Value 0" }+ );+ ExecutionScope.RecordStep(+ "Shell",+ "Step 3: File operation",+ true,+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "del C:\\test.txt" }+ );+ return Task.FromResult(ApplyResult.True());+ },+ };++ var revertPath = GetRevertFilePath(optimization.Id);++ try+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);++ var service = CreateService();+ var progress = new Progress<ProcessingProgress>(_ => { });++ var result = await service.ApplyAsync(optimization, progress);++ Assert.Equal(OptimizationSuccessResult.Success, result.Status);+ Assert.Empty(result.FailedSteps);+ Assert.True(File.Exists(revertPath));++ var data = await RevertManager.GetRevertDataAsync(optimization.Id);+ Assert.NotNull(data);+ Assert.Equal(optimization.Id, data!.OptimizationId);+ Assert.Equal(3, data.Steps.Length);++ // Verify all steps are present and in correct order+ Assert.NotNull(data.Steps[0]);+ Assert.NotNull(data.Steps[1]);+ Assert.NotNull(data.Steps[2]);+ Assert.Equal("Shell", data.Steps[0]!.Type);+ Assert.Equal("Shell", data.Steps[1]!.Type);+ Assert.Equal("Shell", data.Steps[2]!.Type);++ // Verify revert commands are correct+ Assert.Equal(+ "sc config TestService start= auto",+ data.Steps[0]!.Data[nameof(ShellRevertStep.Command)]?.ToString()+ );+ Assert.Equal(+ "Set-ItemProperty -Path 'HKLM:\\Test' -Name 'Value' -Value 0",+ data.Steps[1]!.Data[nameof(ShellRevertStep.Command)]?.ToString()+ );+ Assert.Equal(+ "del C:\\test.txt",+ data.Steps[2]!.Data[nameof(ShellRevertStep.Command)]?.ToString()+ );+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ [Fact]+ public async Task ApplyAsync_NoSteps_SuccessWithEmptyRevertData()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization+ {+ ApplyImpl = _ => Task.FromResult(ApplyResult.True()),+ };++ var revertPath = GetRevertFilePath(optimization.Id);++ try+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);++ var service = CreateService();+ var progress = new Progress<ProcessingProgress>(_ => { });++ var result = await service.ApplyAsync(optimization, progress);++ Assert.Equal(OptimizationSuccessResult.Success, result.Status);+ Assert.True(File.Exists(revertPath));++ var data = await RevertManager.GetRevertDataAsync(optimization.Id);+ Assert.NotNull(data);+ Assert.Empty(data!.Steps);+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ #endregion++ #region Apply Partial Success Scenarios++ [Fact]+ public async Task ApplyAsync_FirstStepFails_PartialSuccessWithGapInRevertData()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization+ {+ ApplyImpl = _ =>+ {+ ExecutionScope.RecordStep(+ "Shell",+ "Step 1: Will fail",+ false,+ null,+ "Step 1 failed"+ );+ ExecutionScope.RecordStep(+ "Shell",+ "Step 2: Success",+ true,+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }+ );+ ExecutionScope.RecordStep(+ "Shell",+ "Step 3: Success",+ true,+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }+ );+ return Task.FromResult(ApplyResult.True());+ },+ };++ var revertPath = GetRevertFilePath(optimization.Id);++ try+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);++ var service = CreateService();+ var progress = new Progress<ProcessingProgress>(_ => { });++ var result = await service.ApplyAsync(optimization, progress);++ Assert.Equal(OptimizationSuccessResult.PartialSuccess, result.Status);+ Assert.Single(result.FailedSteps);+ Assert.Equal(1, result.FailedSteps[0].Index);++ var data = await RevertManager.GetRevertDataAsync(optimization.Id);+ Assert.NotNull(data);+ Assert.Equal(3, data!.Steps.Length);++ // Step 1 should be null (failed), steps 2 and 3 should exist+ Assert.Null(data.Steps[0]);+ Assert.NotNull(data.Steps[1]);+ Assert.NotNull(data.Steps[2]);+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ [Fact]+ public async Task ApplyAsync_MiddleStepsFail_MultipleGapsInRevertData()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization+ {+ ApplyImpl = _ =>+ {+ ExecutionScope.RecordStep(+ "Shell",+ "Step 1: Success",+ true,+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 11" }+ );+ ExecutionScope.RecordStep(+ "Shell",+ "Step 2: Fail",+ false,+ null,+ "fail 2"+ );+ ExecutionScope.RecordStep(+ "Shell",+ "Step 3: Success",+ true,+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 33" }+ );+ ExecutionScope.RecordStep(+ "Shell",+ "Step 4: Fail",+ false,+ null,+ "fail 4"+ );+ ExecutionScope.RecordStep(+ "Shell",+ "Step 5: Success",+ true,+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 55" }+ );+ return Task.FromResult(ApplyResult.True());+ },+ };++ var revertPath = GetRevertFilePath(optimization.Id);++ try+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);++ var service = CreateService();+ var progress = new Progress<ProcessingProgress>(_ => { });++ var result = await service.ApplyAsync(optimization, progress);++ Assert.Equal(OptimizationSuccessResult.PartialSuccess, result.Status);+ Assert.Equal(2, result.FailedSteps.Count);+ Assert.Equal([2, 4], result.FailedSteps.Select(s => s.Index).ToArray());++ var data = await RevertManager.GetRevertDataAsync(optimization.Id);+ Assert.NotNull(data);+ Assert.Equal(5, data!.Steps.Length);++ // Verify pattern: success, fail, success, fail, success+ Assert.NotNull(data.Steps[0]);+ Assert.Null(data.Steps[1]);+ Assert.NotNull(data.Steps[2]);+ Assert.Null(data.Steps[3]);+ Assert.NotNull(data.Steps[4]);++ // Verify commands are at correct indices+ Assert.Equal(+ "exit 11",+ data.Steps[0]!.Data[nameof(ShellRevertStep.Command)]?.ToString()+ );+ Assert.Equal(+ "exit 33",+ data.Steps[2]!.Data[nameof(ShellRevertStep.Command)]?.ToString()+ );+ Assert.Equal(+ "exit 55",+ data.Steps[4]!.Data[nameof(ShellRevertStep.Command)]?.ToString()+ );+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ [Fact]+ public async Task ApplyAsync_AllStepsFail_NoRevertDataFileCreated()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization+ {+ ApplyImpl = _ =>+ {+ ExecutionScope.RecordStep(+ "Shell",+ "Step 1: Fail",+ false,+ null,+ "fail 1"+ );+ ExecutionScope.RecordStep(+ "Shell",+ "Step 2: Fail",+ false,+ null,+ "fail 2"+ );+ return Task.FromResult(ApplyResult.False("All steps failed"));+ },+ };++ var revertPath = GetRevertFilePath(optimization.Id);++ try+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);++ var service = CreateService();+ var progress = new Progress<ProcessingProgress>(_ => { });++ var result = await service.ApplyAsync(optimization, progress);++ Assert.Equal(OptimizationSuccessResult.Failed, result.Status);+ Assert.Equal(2, result.FailedSteps.Count);+ Assert.False(File.Exists(revertPath));+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ #endregion++ #region Revert Success Scenarios++ [Fact]+ public async Task RevertAsync_AllStepsSucceed_FileDeletedAndSuccessReturned()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization { Id = Guid.NewGuid() };+ var revertPath = GetRevertFilePath(optimization.Id);++ try+ {+ Directory.CreateDirectory(Shared.RevertDirectory);++ // Create revert data with 3 successful steps+ var payload = new RevertData+ {+ OptimizationId = optimization.Id,+ OptimizationName = optimization.OptimizationKey,+ AppliedAt = DateTime.UtcNow,+ Steps = new RevertStepData?[]+ {+ new()+ {+ Index = 1,+ Type = "Shell",+ Data = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "exit 0",+ }.ToData(),+ },+ new()+ {+ Index = 2,+ Type = "Shell",+ Data = new ShellRevertStep+ {+ ShellType = ShellType.PowerShell,+ Command = "exit 0",+ }.ToData(),+ },+ new()+ {+ Index = 3,+ Type = "Shell",+ Data = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "exit 0",+ }.ToData(),+ },+ },+ };++ var json = JsonConvert.SerializeObject(payload, Formatting.Indented);+ await File.WriteAllTextAsync(revertPath, json);++ var service = CreateService();+ var progress = new Progress<ProcessingProgress>(_ => { });++ var result = await service.RevertAsync(optimization, progress);++ Assert.True(result.Success);+ Assert.True(result.AllStepsSucceeded);+ Assert.Empty(result.FailedSteps);+ Assert.False(File.Exists(revertPath));+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ [Fact]+ public async Task RevertAsync_StepsExecutedInReverseOrder_LastStepFirst()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization { Id = Guid.NewGuid() };+ var revertPath = GetRevertFilePath(optimization.Id);+ var executionOrder = new List<int>();++ try+ {+ Directory.CreateDirectory(Shared.RevertDirectory);++ // Create revert data with ordered steps+ var payload = new RevertData+ {+ OptimizationId = optimization.Id,+ OptimizationName = optimization.OptimizationKey,+ AppliedAt = DateTime.UtcNow,+ Steps = new RevertStepData?[]+ {+ new()+ {+ Index = 1,+ Type = "Shell",+ Data = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "cmd /c \"echo 1\"",+ }.ToData(),+ },+ new()+ {+ Index = 2,+ Type = "Shell",+ Data = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "cmd /c \"echo 2\"",+ }.ToData(),+ },+ new()+ {+ Index = 3,+ Type = "Shell",+ Data = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "cmd /c \"echo 3\"",+ }.ToData(),+ },+ },+ };++ var json = JsonConvert.SerializeObject(payload, Formatting.Indented);+ await File.WriteAllTextAsync(revertPath, json);++ var manager = new RevertManager(+ NullLogger<RevertManager>.Instance,+ NullLoggerFactory.Instance+ );+ var result = await manager.RevertAsync(optimization);++ Assert.True(result.Success);+ // Steps should execute in reverse order: 3, 2, 1+ // This is verified by the revert manager implementation+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ [Fact]+ public async Task RevertAsync_WithNullStepsInData_SkipsNullStepsSuccessfully()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization { Id = Guid.NewGuid() };+ var revertPath = GetRevertFilePath(optimization.Id);++ try+ {+ Directory.CreateDirectory(Shared.RevertDirectory);++ // Create revert data with gaps (null steps from failed apply steps)+ var payload = new RevertData+ {+ OptimizationId = optimization.Id,+ OptimizationName = optimization.OptimizationKey,+ AppliedAt = DateTime.UtcNow,+ Steps = new RevertStepData?[]+ {+ new()+ {+ Index = 1,+ Type = "Shell",+ Data = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "exit 0",+ }.ToData(),+ },+ null, // Step 2 failed during apply+ new()+ {+ Index = 3,+ Type = "Shell",+ Data = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "exit 0",+ }.ToData(),+ },+ null, // Step 4 failed during apply+ new()+ {+ Index = 5,+ Type = "Shell",+ Data = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "exit 0",+ }.ToData(),+ },+ },+ };++ var json = JsonConvert.SerializeObject(payload, Formatting.Indented);+ await File.WriteAllTextAsync(revertPath, json);++ var service = CreateService();+ var progress = new Progress<ProcessingProgress>(_ => { });++ var result = await service.RevertAsync(optimization, progress);++ Assert.True(result.Success);+ Assert.False(File.Exists(revertPath));+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ #endregion++ #region Revert Partial Failure Scenarios++ [Fact]+ public async Task RevertAsync_LastStepFails_PartialFailureWithFileDeleted()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization { Id = Guid.NewGuid() };+ var revertPath = GetRevertFilePath(optimization.Id);++ try+ {+ Directory.CreateDirectory(Shared.RevertDirectory);++ var payload = new RevertData+ {+ OptimizationId = optimization.Id,+ OptimizationName = optimization.OptimizationKey,+ AppliedAt = DateTime.UtcNow,+ Steps = new RevertStepData?[]+ {+ new()+ {+ Index = 1,+ Type = "Shell",+ Data = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "exit 0", // Success+ }.ToData(),+ },+ new()+ {+ Index = 2,+ Type = "Shell",+ Data = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "exit 1", // Fail+ }.ToData(),+ },+ },+ };++ var json = JsonConvert.SerializeObject(payload, Formatting.Indented);+ await File.WriteAllTextAsync(revertPath, json);++ var service = CreateService();+ var progress = new Progress<ProcessingProgress>(_ => { });++ var result = await service.RevertAsync(optimization, progress);++ // Revert executes in reverse: step 2 (fails), then step 1 (succeeds)+ Assert.False(result.Success);+ Assert.False(result.AllStepsFailed);+ Assert.Single(result.FailedSteps);+ Assert.False(File.Exists(revertPath)); // File deleted because not all steps failed++ // Failed step should have retry action+ Assert.NotNull(result.FailedSteps[0].RetryAction);+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ [Fact]+ public async Task RevertAsync_AllStepsFail_FilePreservedForRetry()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization { Id = Guid.NewGuid() };+ var revertPath = GetRevertFilePath(optimization.Id);++ try+ {+ Directory.CreateDirectory(Shared.RevertDirectory);++ var payload = new RevertData+ {+ OptimizationId = optimization.Id,+ OptimizationName = optimization.OptimizationKey,+ AppliedAt = DateTime.UtcNow,+ Steps = new RevertStepData?[]+ {+ new()+ {+ Index = 1,+ Type = "Shell",+ Data = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "exit 1", // Fail+ }.ToData(),+ },+ new()+ {+ Index = 2,+ Type = "Shell",+ Data = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "exit 1", // Fail+ }.ToData(),+ },+ },+ };++ var json = JsonConvert.SerializeObject(payload, Formatting.Indented);+ await File.WriteAllTextAsync(revertPath, json);++ var service = CreateService();+ var progress = new Progress<ProcessingProgress>(_ => { });++ var result = await service.RevertAsync(optimization, progress);++ Assert.False(result.Success);+ Assert.True(result.AllStepsFailed);+ Assert.Equal(2, result.FailedSteps.Count);+ Assert.True(File.Exists(revertPath)); // File preserved for retry+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ [Fact]+ public async Task RevertAsync_PartialFailure_RetryActionCanRecoverFailedSteps()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization { Id = Guid.NewGuid() };+ var revertPath = GetRevertFilePath(optimization.Id);++ try+ {+ Directory.CreateDirectory(Shared.RevertDirectory);++ var payload = new RevertData+ {+ OptimizationId = optimization.Id,+ OptimizationName = optimization.OptimizationKey,+ AppliedAt = DateTime.UtcNow,+ Steps = new RevertStepData?[]+ {+ new()+ {+ Index = 1,+ Type = "Shell",+ Data = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "exit 0", // Success+ }.ToData(),+ },+ new()+ {+ Index = 2,+ Type = "Shell",+ Data = new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "exit 1", // Fail+ }.ToData(),+ },+ },+ };++ var json = JsonConvert.SerializeObject(payload, Formatting.Indented);+ await File.WriteAllTextAsync(revertPath, json);++ var manager = new RevertManager(+ NullLogger<RevertManager>.Instance,+ NullLoggerFactory.Instance+ );+ var result = await manager.RevertAsync(optimization);++ Assert.False(result.Success);+ Assert.False(File.Exists(revertPath));++ // Retry the failed step+ var failedStep = result.FailedSteps.FirstOrDefault();+ Assert.NotNull(failedStep);+ Assert.NotNull(failedStep.RetryAction);++ // Retry should succeed (running exit 0 instead)+ bool retrySuccess = await failedStep.RetryAction!();+ Assert.True(retrySuccess);+ Assert.False(File.Exists(revertPath));+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ #endregion++ #region Apply Then Revert Full Workflow++ [Fact]+ public async Task ApplyThenRevert_FullWorkflow_SuccessfulRoundTrip()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization+ {+ ApplyImpl = _ =>+ {+ ExecutionScope.RecordStep(+ "Shell",+ "Step 1",+ true,+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }+ );+ ExecutionScope.RecordStep(+ "Shell",+ "Step 2",+ true,+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }+ );+ return Task.FromResult(ApplyResult.True());+ },+ };++ var revertPath = GetRevertFilePath(optimization.Id);++ try+ {+ // Phase 1: Apply+ var service = CreateService();+ var progress = new Progress<ProcessingProgress>(_ => { });++ var applyResult = await service.ApplyAsync(optimization, progress);+ Assert.Equal(OptimizationSuccessResult.Success, applyResult.Status);+ Assert.True(File.Exists(revertPath));++ var data = await RevertManager.GetRevertDataAsync(optimization.Id);+ Assert.NotNull(data);+ Assert.Equal(2, data!.Steps.Length);++ // Phase 2: Revert+ var revertResult = await service.RevertAsync(optimization, progress);+ Assert.True(revertResult.Success);+ Assert.False(File.Exists(revertPath));+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ [Fact]+ public async Task ApplyPartialThenRevert_PartialApplyFollowedByRevert()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization+ {+ ApplyImpl = _ =>+ {+ ExecutionScope.RecordStep(+ "Shell",+ "Step 1",+ true,+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }+ );+ ExecutionScope.RecordStep(+ "Shell",+ "Step 2",+ false,+ null,+ "Step 2 failed"+ );+ ExecutionScope.RecordStep(+ "Shell",+ "Step 3",+ true,+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" }+ );+ return Task.FromResult(ApplyResult.True());+ },+ };++ var revertPath = GetRevertFilePath(optimization.Id);++ try+ {+ // Phase 1: Apply with partial success+ var service = CreateService();+ var progress = new Progress<ProcessingProgress>(_ => { });++ var applyResult = await service.ApplyAsync(optimization, progress);+ Assert.Equal(OptimizationSuccessResult.PartialSuccess, applyResult.Status);+ Assert.Single(applyResult.FailedSteps);+ Assert.Equal(2, applyResult.FailedSteps[0].Index);++ var data = await RevertManager.GetRevertDataAsync(optimization.Id);+ Assert.NotNull(data);+ Assert.Equal(3, data!.Steps.Length);+ Assert.NotNull(data.Steps[0]);+ Assert.Null(data.Steps[1]); // Gap from failed step+ Assert.NotNull(data.Steps[2]);++ // Phase 2: Revert should only revert steps 1 and 3+ var revertResult = await service.RevertAsync(optimization, progress);+ Assert.True(revertResult.Success);+ Assert.False(File.Exists(revertPath));+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ [Fact]+ public async Task ApplyRetryThenRevert_CompleteWorkflowWithRetry()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization+ {+ ApplyImpl = _ =>+ {+ ExecutionScope.RecordStep(+ "Shell",+ "Step 1",+ true,+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 11" }+ );+ ExecutionScope.RecordStep(+ "Shell",+ "Step 2",+ false,+ null,+ "fail 2",+ () =>+ {+ ExecutionScope.RecordStep(+ "Shell",+ "Step 2 retry",+ true,+ new ShellRevertStep+ {+ ShellType = ShellType.CMD,+ Command = "exit 22",+ }+ );+ return Task.FromResult(true);+ }+ );+ ExecutionScope.RecordStep(+ "Shell",+ "Step 3",+ true,+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 33" }+ );+ return Task.FromResult(ApplyResult.True());+ },+ };++ var revertPath = GetRevertFilePath(optimization.Id);++ try+ {+ var service = CreateService();+ var progress = new Progress<ProcessingProgress>(_ => { });++ // Phase 1: Apply with failure+ var applyResult = await service.ApplyAsync(optimization, progress);+ Assert.Equal(OptimizationSuccessResult.PartialSuccess, applyResult.Status);++ // Phase 2: Retry failed steps+ var retryResult = await OptimizationService.RetryFailedStepsWithResultsAsync(+ applyResult.FailedSteps,+ false,+ NullLogger.Instance+ );++ Assert.Empty(retryResult.FailedSteps);+ Assert.Single(retryResult.RecoveredSteps);+ Assert.Equal(2, retryResult.RecoveredSteps[0].Index);++ // Phase 3: Upsert the recovered step+ var revertManager = new RevertManager(+ NullLogger<RevertManager>.Instance,+ NullLoggerFactory.Instance+ );+ await revertManager.UpsertRevertStepAtIndexAsync(+ optimization.Id,+ optimization.OptimizationKey,+ retryResult.RecoveredSteps[0].Index,+ retryResult.RecoveredSteps[0].RevertStep!+ );++ // Verify complete revert data+ var data = await RevertManager.GetRevertDataAsync(optimization.Id);+ Assert.NotNull(data);+ Assert.Equal(3, data!.Steps.Length);+ Assert.Equal(+ "exit 11",+ data.Steps[0]!.Data[nameof(ShellRevertStep.Command)]?.ToString()+ );+ Assert.Equal(+ "exit 22",+ data.Steps[1]!.Data[nameof(ShellRevertStep.Command)]?.ToString()+ );+ Assert.Equal(+ "exit 33",+ data.Steps[2]!.Data[nameof(ShellRevertStep.Command)]?.ToString()+ );++ // Phase 4: Revert all steps successfully+ var revertResult = await service.RevertAsync(optimization, progress);+ Assert.True(revertResult.Success);+ Assert.False(File.Exists(revertPath));+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ #endregion++ #region Edge Cases and Error Handling++ [Fact]+ public async Task RevertAsync_NoRevertDataFile_ReturnsFailure()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization { Id = Guid.NewGuid() };++ var service = CreateService();+ var progress = new Progress<ProcessingProgress>(_ => { });++ var result = await service.RevertAsync(optimization, progress);++ Assert.False(result.Success);+ Assert.Contains("not found", result.Message, StringComparison.OrdinalIgnoreCase);+ });+ }++ [Fact]+ public async Task RevertAsync_CorruptJsonFile_ReturnsFailure()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization { Id = Guid.NewGuid() };+ var revertPath = GetRevertFilePath(optimization.Id);++ try+ {+ Directory.CreateDirectory(Shared.RevertDirectory);+ await File.WriteAllTextAsync(revertPath, "{ invalid json }");++ var service = CreateService();+ var progress = new Progress<ProcessingProgress>(_ => { });++ var result = await service.RevertAsync(optimization, progress);++ Assert.False(result.Success);+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ [Fact]+ public async Task ApplyAsync_WithException_HandlesGracefully()+ {+ await RunInStaThreadAsync(async () =>+ {+ var optimization = new TestOptimization+ {+ ApplyImpl = _ => throw new InvalidOperationException("Simulated exception"),+ };++ var revertPath = GetRevertFilePath(optimization.Id);++ try+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);++ var service = CreateService();+ var progress = new Progress<ProcessingProgress>(_ => { });++ var result = await service.ApplyAsync(optimization, progress);++ Assert.Equal(OptimizationSuccessResult.Failed, result.Status);+ Assert.NotNull(result.Exception);+ Assert.False(File.Exists(revertPath));+ }+ finally+ {+ if (File.Exists(revertPath))+ File.Delete(revertPath);+ }+ });+ }++ #endregion++ #region Helpers++ private static OptimizationService CreateService()+ {+ var revertManager = new RevertManager(+ NullLogger<RevertManager>.Instance,+ NullLoggerFactory.Instance+ );+ var loggerFactory = NullLoggerFactory.Instance;+ var systemInfoService = new SystemInfoService(NullLogger<SystemInfoService>.Instance);+ var streamService = new StreamService(NullLogger<StreamService>.Instance);+ var contentDialogService = new ContentDialogService();+ var logger = NullLogger<OptimizationService>.Instance;+ return new OptimizationService(+ revertManager,+ loggerFactory,+ systemInfoService,+ streamService,+ contentDialogService,+ logger+ );+ }++ private static string GetRevertFilePath(Guid id)+ {+ return Path.Combine(Shared.RevertDirectory, id + ".json");+ }++ private static Task RunInStaThreadAsync(Func<Task> action)+ {+ var tcs = new TaskCompletionSource();++ var thread = new Thread(() =>+ {+ try+ {+ action().GetAwaiter().GetResult();+ tcs.SetResult();+ }+ catch (Exception ex)+ {+ tcs.SetException(ex);+ }+ });++ thread.SetApartmentState(ApartmentState.STA);+ thread.Start();++ return tcs.Task;+ }++ private sealed class TestOptimization : IOptimization+ {+ public Guid Id { get; init; } = Guid.NewGuid();+ public OptimizationRisk Risk => OptimizationRisk.Safe;+ public string OptimizationKey => "TestOptimization";+ public string Name => "Test Optimization";+ public string ShortDescription => "Test optimization for comprehensive testing";+ public OptimizationState State { get; set; } = new();++ public Func<+ (IProgress<ProcessingProgress> progress, OptimizationContext context),+ Task<ApplyResult>+ > ApplyImpl { get; init; } = _ => Task.FromResult(ApplyResult.True());++ public Task<ApplyResult> ApplyAsync(+ IProgress<ProcessingProgress> progress,+ OptimizationContext context+ )+ {+ return ApplyImpl((progress, context));+ }+ }++ #endregion+}diff --git a/optimizerDuck/App.xaml.cs b/optimizerDuck/App.xaml.csindex 85a9e05..e9862fb 100644--- a/optimizerDuck/App.xaml.cs+++ b/optimizerDuck/App.xaml.cs@@ -165,8 +165,10 @@ public partial class App : Applicationprivate async Task OnStartupAsync(StartupEventArgs e){// Create the required directories if they don't exist- Directory.CreateDirectory(Shared.ResourcesDirectory);Directory.CreateDirectory(Shared.RootDirectory);+ Directory.CreateDirectory(Shared.ResourcesDirectory);+ Directory.CreateDirectory(Shared.DownloadsDirectory);+ Directory.CreateDirectory(Shared.AssetsDirectory);Directory.CreateDirectory(Shared.RevertDirectory);var logPath = Path.Combine(Shared.RootDirectory, "optimizerDuck.log");@@ -389,7 +391,10 @@ public partial class App : Application}catch (Exception ex){- _logger.LogError(ex, "Failed to handle window closing event. Allowing close to prevent hanging.");+ _logger.LogError(+ ex,+ "Failed to handle window closing event. Allowing close to prevent hanging."+ );// Ensure we don't block close on error_allowClose = true;diff --git a/optimizerDuck/Common/Converters/NumericComparisonToVisibilityConverter.cs b/optimizerDuck/Common/Converters/NumericComparisonToVisibilityConverter.csindex 0277eef..9466f43 100644--- a/optimizerDuck/Common/Converters/NumericComparisonToVisibilityConverter.cs+++ b/optimizerDuck/Common/Converters/NumericComparisonToVisibilityConverter.cs@@ -11,7 +11,7 @@ public enum NumericComparisonTypeLessThan,LessThanOrEqual,Equal,- NotEqual+ NotEqual,}public class NumericComparisonToVisibilityConverter : IValueConverterdiff --git a/optimizerDuck/Common/Converters/ProgressBarVisibilityConverter.cs b/optimizerDuck/Common/Converters/ProgressBarVisibilityConverter.csindex 3fbe215..1f25340 100644--- a/optimizerDuck/Common/Converters/ProgressBarVisibilityConverter.cs+++ b/optimizerDuck/Common/Converters/ProgressBarVisibilityConverter.cs@@ -6,11 +6,7 @@ namespace optimizerDuck.Common.Converters;public class ProgressBarVisibilityConverter : IMultiValueConverter{- public object Convert(- object[] values,- Type targetType,- object parameter,- CultureInfo culture)+ public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture){if (values.Length < 2)return Visibility.Collapsed;@@ -24,16 +20,15 @@ public class ProgressBarVisibilityConverter : IMultiValueConverterif (values[1] is bool b)isIndeterminate = b;- return total > 0 || isIndeterminate- ? Visibility.Visible- : Visibility.Collapsed;+ return total > 0 || isIndeterminate ? Visibility.Visible : Visibility.Collapsed;}public object[] ConvertBack(object value,Type[] targetTypes,object parameter,- CultureInfo culture)+ CultureInfo culture+ ){throw new NotSupportedException();}diff --git a/optimizerDuck/Common/Converters/RecommendationForegroundConverter.cs b/optimizerDuck/Common/Converters/RecommendationForegroundConverter.csindex c4fbd53..894be39 100644--- a/optimizerDuck/Common/Converters/RecommendationForegroundConverter.cs+++ b/optimizerDuck/Common/Converters/RecommendationForegroundConverter.cs@@ -10,14 +10,11 @@ namespace optimizerDuck.Common.Converters;public static class ThemeBrushes{- public static Brush Primary =>- Clone("TextFillColorPrimaryBrush");+ public static Brush Primary => Clone("TextFillColorPrimaryBrush");- public static Brush Inverse =>- Clone("TextFillColorInverseBrush");+ public static Brush Inverse => Clone("TextFillColorInverseBrush");- public static Brush Secondary =>- Clone("TextFillColorSecondaryBrush");+ public static Brush Secondary => Clone("TextFillColorSecondaryBrush");private static Brush Clone(string key){@@ -31,11 +28,7 @@ public static class ThemeBrushespublic class RecommendationForegroundConverter : IMultiValueConverter{- public object Convert(- object[] values,- Type targetType,- object parameter,- CultureInfo culture)+ public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture){if (values.Length < 2)return ThemeBrushes.Primary;@@ -54,12 +47,9 @@ public class RecommendationForegroundConverter : IMultiValueConverterRecommendationState.Off => ThemeBrushes.Primary,- RecommendationState.Depends =>- isDark ? ThemeBrushes.Inverse- : ThemeBrushes.Primary,+ RecommendationState.Depends => isDark ? ThemeBrushes.Inverse : ThemeBrushes.Primary,- _ =>- ThemeBrushes.Inverse+ _ => ThemeBrushes.Inverse,};}@@ -67,7 +57,8 @@ public class RecommendationForegroundConverter : IMultiValueConverterobject value,Type[] targetTypes,object parameter,- CultureInfo culture)+ CultureInfo culture+ ){throw new NotSupportedException();}diff --git a/optimizerDuck/Common/Converters/SizeToBrushConverter.cs b/optimizerDuck/Common/Converters/SizeToBrushConverter.csindex 58ddbe4..b5e90ae 100644--- a/optimizerDuck/Common/Converters/SizeToBrushConverter.cs+++ b/optimizerDuck/Common/Converters/SizeToBrushConverter.cs@@ -14,17 +14,17 @@ public class SizeToBrushConverter : IValueConverterprivate const long TenMB = 10L * 1024 * 1024;private const long HundredMB = 100L * 1024 * 1024;- private static readonly SolidColorBrush GreenBrush = ThemeResource.Get<SolidColorBrush>(- "SystemFillColorSuccessBrush"- ) ?? new SolidColorBrush(Color.FromRgb(0, 180, 0));+ private static readonly SolidColorBrush GreenBrush =+ ThemeResource.Get<SolidColorBrush>("SystemFillColorSuccessBrush")+ ?? new SolidColorBrush(Color.FromRgb(0, 180, 0));- private static readonly SolidColorBrush OrangeBrush = ThemeResource.Get<SolidColorBrush>(- "SystemFillColorCautionBrush"- ) ?? new SolidColorBrush(Color.FromRgb(255, 140, 0));+ private static readonly SolidColorBrush OrangeBrush =+ ThemeResource.Get<SolidColorBrush>("SystemFillColorCautionBrush")+ ?? new SolidColorBrush(Color.FromRgb(255, 140, 0));- private static readonly SolidColorBrush RedBrush = ThemeResource.Get<SolidColorBrush>(- "SystemFillColorCriticalBrush"- ) ?? new SolidColorBrush(Color.FromRgb(220, 0, 0));+ private static readonly SolidColorBrush RedBrush =+ ThemeResource.Get<SolidColorBrush>("SystemFillColorCriticalBrush")+ ?? new SolidColorBrush(Color.FromRgb(220, 0, 0));private static readonly SolidColorBrush DefaultBrush = new(Color.FromArgb(0x0, 0x0, 0x0, 0x0));diff --git a/optimizerDuck/Common/Converters/ValueConditionToVisibilityConverter.cs b/optimizerDuck/Common/Converters/ValueConditionToVisibilityConverter.csindex 50221a9..7edeeee 100644--- a/optimizerDuck/Common/Converters/ValueConditionToVisibilityConverter.cs+++ b/optimizerDuck/Common/Converters/ValueConditionToVisibilityConverter.cs@@ -11,7 +11,7 @@ public enum ValueConditionTypeIsZero,IsNotZero,IsGreaterThanZero,- IsLessThanZero+ IsLessThanZero,}public class ValueConditionToVisibilityConverter : IValueConverterdiff --git a/optimizerDuck/Common/Helpers/EmbeddedResourceHelper.cs b/optimizerDuck/Common/Helpers/EmbeddedResourceHelper.csnew file mode 100644index 0000000..24ecd35--- /dev/null+++ b/optimizerDuck/Common/Helpers/EmbeddedResourceHelper.cs@@ -0,0 +1,118 @@+using System.IO;+using System.Reflection;++namespace optimizerDuck.Common.Helpers;++/// <summary>+/// Helper class for extracting embedded resources from the optimizerDuck.Resources.Embedded namespace.+/// </summary>+public static class EmbeddedResourceHelper+{+ private const string ResourceNamespace = "optimizerDuck.Resources.Embedded";++ /// <summary>+ /// Extracts an embedded resource to the specified output path.+ /// </summary>+ /// <param name="relativePath">Relative path within the Embedded namespace (e.g., "Icons/blank.ico").</param>+ /// <param name="outputPath">Full path where the resource will be extracted.</param>+ /// <param name="overwrite">Whether to overwrite the file if it already exists.</param>+ /// <returns>True if extraction succeeded, false otherwise.</returns>+ public static bool TryExtract(string relativePath, string outputPath, bool overwrite = false)+ {+ if (string.IsNullOrWhiteSpace(relativePath) || string.IsNullOrWhiteSpace(outputPath))+ {+ return false;+ }++ try+ {+ // Normalize the relative path to use dots as separators for resource names+ var normalizedPath = relativePath.Replace('/', '.').Replace('\\', '.');+ var fullResourceName = $"{ResourceNamespace}.{normalizedPath}";++ var assembly = Assembly.GetExecutingAssembly();++ // Check if the resource exists+ if (!ResourceExists(assembly, fullResourceName))+ {+ return false;+ }++ // Create output directory if it doesn't exist+ var outputDirectory = Path.GetDirectoryName(outputPath);+ if (!string.IsNullOrEmpty(outputDirectory) && !Directory.Exists(outputDirectory))+ {+ Directory.CreateDirectory(outputDirectory);+ }++ // Skip extraction if file exists and overwrite is disabled+ if (File.Exists(outputPath) && !overwrite)+ {+ return true;+ }++ // Extract the resource+ using var stream = assembly.GetManifestResourceStream(fullResourceName);+ if (stream == null)+ {+ return false;+ }++ using var fileStream = new FileStream(+ outputPath,+ FileMode.Create,+ FileAccess.Write,+ FileShare.None,+ bufferSize: 8192,+ useAsync: false);++ stream.CopyTo(fileStream);+ return true;+ }+ catch+ {+ return false;+ }+ }++ /// <summary>+ /// Checks if an embedded resource exists.+ /// </summary>+ /// <param name="relativePath">Relative path within the Embedded namespace.</param>+ /// <returns>True if the resource exists, false otherwise.</returns>+ public static bool Exists(string relativePath)+ {+ if (string.IsNullOrWhiteSpace(relativePath))+ {+ return false;+ }++ var normalizedPath = relativePath.Replace('/', '.').Replace('\\', '.');+ var fullResourceName = $"{ResourceNamespace}.{normalizedPath}";++ return ResourceExists(Assembly.GetExecutingAssembly(), fullResourceName);+ }++ /// <summary>+ /// Gets all available embedded resources in the optimizerDuck.Resources.Embedded namespace.+ /// </summary>+ /// <returns>Enumerable of resource names with the namespace prefix removed.</returns>+ public static IEnumerable<string> GetAvailableResources()+ {+ var assembly = Assembly.GetExecutingAssembly();+ var prefix = $"{ResourceNamespace}.";++ return assembly+ .GetManifestResourceNames()+ .Where(name => name.StartsWith(prefix, StringComparison.Ordinal))+ .Select(name => name.Substring(prefix.Length));+ }++ /// <summary>+ /// Checks if a specific resource exists in the assembly.+ /// </summary>+ private static bool ResourceExists(Assembly assembly, string resourceName)+ {+ return assembly.GetManifestResourceNames().Contains(resourceName);+ }+}diff --git a/optimizerDuck/Common/Helpers/Shared.cs b/optimizerDuck/Common/Helpers/Shared.csindex ea08862..ca2dac3 100644--- a/optimizerDuck/Common/Helpers/Shared.cs+++ b/optimizerDuck/Common/Helpers/Shared.cs@@ -1,4 +1,4 @@-using System.Diagnostics;+using System.Diagnostics;using System.IO;namespace optimizerDuck.Common.Helpers;@@ -145,6 +145,7 @@ public static class Shared);public static string ResourcesDirectory => Path.Combine(RootDirectory, "Resources");-+ public static string DownloadsDirectory => Path.Combine(ResourcesDirectory, "Downloads");+ public static string AssetsDirectory => Path.Combine(ResourcesDirectory, "Assets");public static string RevertDirectory => Path.Combine(RootDirectory, "Revert");}diff --git a/optimizerDuck/Domain/Execution/ExecutionScope.cs b/optimizerDuck/Domain/Execution/ExecutionScope.csindex 556c4fa..6c13ce8 100644--- a/optimizerDuck/Domain/Execution/ExecutionScope.cs+++ b/optimizerDuck/Domain/Execution/ExecutionScope.cs@@ -1,4 +1,4 @@-using System.Collections.Concurrent;+using System.Collections.Concurrent;using System.Diagnostics;using Microsoft.Extensions.Logging;using optimizerDuck.Domain.Abstractions;@@ -279,7 +279,7 @@ public sealed class ExecutionScope : IDisposablereturn null;var stepIndex = explicitIndex ?? ++_stepIndex;-+var step = new ExecutedStep(stepIndex,name,diff --git a/optimizerDuck/Domain/Features/Categories/Desktop.cs b/optimizerDuck/Domain/Features/Categories/Desktop.csindex 3a1af82..ef342fb 100644--- a/optimizerDuck/Domain/Features/Categories/Desktop.cs+++ b/optimizerDuck/Domain/Features/Categories/Desktop.cs@@ -1,4 +1,5 @@using System.Collections.ObjectModel;+using optimizerDuck.Common.Helpers;using optimizerDuck.Domain.Abstractions;using optimizerDuck.Domain.Attributes;using optimizerDuck.Domain.Features.Models;@@ -145,47 +146,71 @@ public class Desktop : IFeatureCategoryprivate const string Path =@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Icons";- protected override bool NeedsPostAction => true;++ private readonly string[] HiddenShortcutValues =+ [+ @"%windir%\System32\shell32.dll,-50",+ @"%windir%\System32\shell32.dll,50",+ ];++ private bool IsHiddenShortcutOverlay(string value)+ {+ if (HiddenShortcutValues.Any(v =>+ string.Equals(value, v, StringComparison.OrdinalIgnoreCase)))+ {+ return true;+ }++ var fileName = System.IO.Path.GetFileName(value);++ if (string.IsNullOrWhiteSpace(fileName))+ return false;++ return fileName.Equals(+ "blank.ico",+ StringComparison.OrdinalIgnoreCase)+ || fileName.Equals(+ "transparent.ico",+ StringComparison.OrdinalIgnoreCase)+ || fileName.Equals(+ "blankicon.ico",+ StringComparison.OrdinalIgnoreCase);+ }public override Task<bool> GetStateAsync(){- var value = RegistryService.Read<string>(- new RegistryItem(Path, "29")- );+ var value = RegistryService.Read<string>(new RegistryItem(Path, "29"));- return Task.FromResult(- !string.Equals(- value,- @"%windir%\System32\shell32.dll,-50",- StringComparison.OrdinalIgnoreCase- )- );+ // value doesn't exist = default Windows behavior+ // shortcut arrow is visible+ if (string.IsNullOrWhiteSpace(value))+ return Task.FromResult(true);++ var isHidden = IsHiddenShortcutOverlay(value);++ return Task.FromResult(!isHidden);}public override async Task EnableAsync(){- // show arrow- RegistryService.DeleteValue(- new RegistryItem(Path, "29")- );+ // restore default Windows behavior by deleting the value+ RegistryService.DeleteValue(new RegistryItem(Path, "29"));- if (NeedsPostAction)- await ExecutePostActionAsync();+ await ExecutePostActionAsync();}public override async Task DisableAsync(){- // hide arrow+ // extract the blank icon to the app resources folder, then set the registry value to point to it+ var outputPath = System.IO.Path.Combine(Shared.AssetsDirectory, nameof(Desktop), "blank.ico");+ EmbeddedResourceHelper.TryExtract("Icons.blank.ico", outputPath);++ // set the registry value to point to the blank icon, which effectively hides the shortcut arrow overlayRegistryService.Write(- new RegistryItem(- Path,- "29",- @"%windir%\System32\shell32.dll,-50"- )+ new RegistryItem(Path, "29", outputPath));- if (NeedsPostAction)- await ExecutePostActionAsync();+ await ExecutePostActionAsync();}}}diff --git a/optimizerDuck/Domain/Features/Categories/Gaming.cs b/optimizerDuck/Domain/Features/Categories/Gaming.csindex 2bd0a47..7b7f4dd 100644--- a/optimizerDuck/Domain/Features/Categories/Gaming.cs+++ b/optimizerDuck/Domain/Features/Categories/Gaming.cs@@ -27,7 +27,11 @@ public class Gaming : IFeatureCategorypublic FeatureCategoryOrder Order { get; init; } = FeatureCategoryOrder.Gaming;public ObservableCollection<IFeature> Features { get; init; } = [];- [Feature(Section = nameof(Sections.GameSettings), Icon = SymbolRegular.XboxController24, Recommendation = RecommendationState.On)]+ [Feature(+ Section = nameof(Sections.GameSettings),+ Icon = SymbolRegular.XboxController24,+ Recommendation = RecommendationState.On+ )]public class GameMode : BaseFeature{protected override IEnumerable<RegistryToggle> RegistryToggles =>@@ -51,7 +55,11 @@ public class Gaming : IFeatureCategory];}- [Feature(Section = nameof(Sections.GameSettings), Icon = SymbolRegular.XboxConsole24, Recommendation = RecommendationState.Off)]+ [Feature(+ Section = nameof(Sections.GameSettings),+ Icon = SymbolRegular.XboxConsole24,+ Recommendation = RecommendationState.Off+ )]public class GameBar : BaseFeature{protected override IEnumerable<RegistryToggle> RegistryToggles =>@@ -94,7 +102,11 @@ public class Gaming : IFeatureCategory];}- [Feature(Section = nameof(Sections.GameSettings), Icon = SymbolRegular.Record24, Recommendation = RecommendationState.Off)]+ [Feature(+ Section = nameof(Sections.GameSettings),+ Icon = SymbolRegular.Record24,+ Recommendation = RecommendationState.Off+ )]public class BackgroundRecording : BaseFeature{protected override IEnumerable<RegistryToggle> RegistryToggles =>@@ -144,7 +156,11 @@ public class Gaming : IFeatureCategory];}- [Feature(Section = nameof(Sections.Input), Icon = SymbolRegular.Cursor24, Recommendation = RecommendationState.Off)]+ [Feature(+ Section = nameof(Sections.Input),+ Icon = SymbolRegular.Cursor24,+ Recommendation = RecommendationState.Off+ )]public class MouseAcceleration : BaseFeature{private const string Path = @"HKCU\Control Panel\Mouse";@@ -171,23 +187,9 @@ public class Gaming : IFeatureCategorypublic override async Task EnableAsync(){- RegistryService.Write(- new RegistryItem(Path, "MouseSpeed", "1")- );- RegistryService.Write(- new RegistryItem(- Path,- "MouseThreshold1",- "6"- )- );- RegistryService.Write(- new RegistryItem(- Path,- "MouseThreshold2",- "10"- )- );+ RegistryService.Write(new RegistryItem(Path, "MouseSpeed", "1"));+ RegistryService.Write(new RegistryItem(Path, "MouseThreshold1", "6"));+ RegistryService.Write(new RegistryItem(Path, "MouseThreshold2", "10"));if (NeedsPostAction)await ExecutePostActionAsync();@@ -195,30 +197,20 @@ public class Gaming : IFeatureCategorypublic override async Task DisableAsync(){- RegistryService.Write(- new RegistryItem(Path, "MouseSpeed", "0")- );- RegistryService.Write(- new RegistryItem(- Path,- "MouseThreshold1",- "0"- )- );- RegistryService.Write(- new RegistryItem(- Path,- "MouseThreshold2",- "0"- )- );+ RegistryService.Write(new RegistryItem(Path, "MouseSpeed", "0"));+ RegistryService.Write(new RegistryItem(Path, "MouseThreshold1", "0"));+ RegistryService.Write(new RegistryItem(Path, "MouseThreshold2", "0"));if (NeedsPostAction)await ExecutePostActionAsync();}}- [Feature(Section = nameof(Sections.Display), Icon = SymbolRegular.FullScreenMaximize24, Recommendation = RecommendationState.Depends)]+ [Feature(+ Section = nameof(Sections.Display),+ Icon = SymbolRegular.FullScreenMaximize24,+ Recommendation = RecommendationState.Depends+ )]public class FullscreenOptimizations : BaseFeature{protected override IEnumerable<RegistryToggle> RegistryToggles =>@@ -258,7 +250,11 @@ public class Gaming : IFeatureCategory];}- [Feature(Section = nameof(Sections.Display), Icon = SymbolRegular.VideoClip24, Recommendation = RecommendationState.On)]+ [Feature(+ Section = nameof(Sections.Display),+ Icon = SymbolRegular.VideoClip24,+ Recommendation = RecommendationState.On+ )]public class HardwareAcceleratedGpuScheduling : BaseFeature{protected override IEnumerable<RegistryToggle> RegistryToggles =>diff --git a/optimizerDuck/Domain/Features/Categories/Preferences.cs b/optimizerDuck/Domain/Features/Categories/Preferences.csindex c423fef..6a736f8 100644--- a/optimizerDuck/Domain/Features/Categories/Preferences.cs+++ b/optimizerDuck/Domain/Features/Categories/Preferences.cs@@ -45,7 +45,11 @@ public class Preferences : IFeatureCategory];}- [Feature(Section = nameof(Sections.Taskbar), Icon = SymbolRegular.Grid24, Recommendation = RecommendationState.Off)]+ [Feature(+ Section = nameof(Sections.Taskbar),+ Icon = SymbolRegular.Grid24,+ Recommendation = RecommendationState.Off+ )]public class TaskbarWidgets : BaseFeature{protected override bool NeedsPostAction => true;@@ -99,7 +103,11 @@ public class Preferences : IFeatureCategory];}- [Feature(Section = nameof(Sections.Taskbar), Icon = SymbolRegular.WindowConsole20, Recommendation = RecommendationState.On)]+ [Feature(+ Section = nameof(Sections.Taskbar),+ Icon = SymbolRegular.WindowConsole20,+ Recommendation = RecommendationState.On+ )]public class TaskbarEndTask : BaseFeature{protected override IEnumerable<RegistryToggle> RegistryToggles =>@@ -140,7 +148,11 @@ public class Preferences : IFeatureCategory];}- [Feature(Section = nameof(Sections.Explorer), Icon = SymbolRegular.AlertOff24, Recommendation = RecommendationState.Off)]+ [Feature(+ Section = nameof(Sections.Explorer),+ Icon = SymbolRegular.AlertOff24,+ Recommendation = RecommendationState.Off+ )]public class ExplorerSyncNotifications : BaseFeature{protected override bool NeedsPostAction => true;@@ -158,7 +170,11 @@ public class Preferences : IFeatureCategory];}- [Feature(Section = nameof(Sections.Explorer), Icon = SymbolRegular.Lightbulb24, Recommendation = RecommendationState.Off)]+ [Feature(+ Section = nameof(Sections.Explorer),+ Icon = SymbolRegular.Lightbulb24,+ Recommendation = RecommendationState.Off+ )]public class SystemSuggestions : BaseFeature{protected override IEnumerable<RegistryToggle> RegistryToggles =>@@ -253,7 +269,11 @@ public class Preferences : IFeatureCategory];}- [Feature(Section = nameof(Sections.Explorer), Icon = SymbolRegular.DocumentText24, Recommendation = RecommendationState.On)]+ [Feature(+ Section = nameof(Sections.Explorer),+ Icon = SymbolRegular.DocumentText24,+ Recommendation = RecommendationState.On+ )]public class ShowFileExtensions : BaseFeature{protected override bool NeedsPostAction => true;@@ -271,7 +291,11 @@ public class Preferences : IFeatureCategory];}- [Feature(Section = nameof(Sections.Explorer), Icon = SymbolRegular.FolderProhibited48, Recommendation = RecommendationState.On)]+ [Feature(+ Section = nameof(Sections.Explorer),+ Icon = SymbolRegular.FolderProhibited48,+ Recommendation = RecommendationState.On+ )]public class ShowHiddenFiles : BaseFeature{protected override bool NeedsPostAction => true;@@ -289,7 +313,11 @@ public class Preferences : IFeatureCategory];}- [Feature(Section = nameof(Sections.Explorer), Icon = SymbolRegular.DocumentText24, Recommendation = RecommendationState.On)]+ [Feature(+ Section = nameof(Sections.Explorer),+ Icon = SymbolRegular.DocumentText24,+ Recommendation = RecommendationState.On+ )]public class ClipboardHistory : BaseFeature{protected override IEnumerable<RegistryToggle> RegistryToggles =>@@ -355,7 +383,11 @@ public class Preferences : IFeatureCategory];}- [Feature(Section = nameof(Sections.Taskbar), Icon = SymbolRegular.Search24, Recommendation = RecommendationState.Off)]+ [Feature(+ Section = nameof(Sections.Taskbar),+ Icon = SymbolRegular.Search24,+ Recommendation = RecommendationState.Off+ )]public class BingSearch : BaseFeature{protected override bool NeedsPostAction => true;@@ -373,7 +405,11 @@ public class Preferences : IFeatureCategory];}- [Feature(Section = nameof(Sections.Explorer), Icon = SymbolRegular.CursorClick24, Recommendation = RecommendationState.On)]+ [Feature(+ Section = nameof(Sections.Explorer),+ Icon = SymbolRegular.CursorClick24,+ Recommendation = RecommendationState.On+ )]public class ClassicContextMenu : BaseFeature{private const string BasePath =diff --git a/optimizerDuck/Domain/Features/Categories/SystemFeatures.cs b/optimizerDuck/Domain/Features/Categories/SystemFeatures.csindex 61f71ae..fc664ea 100644--- a/optimizerDuck/Domain/Features/Categories/SystemFeatures.cs+++ b/optimizerDuck/Domain/Features/Categories/SystemFeatures.cs@@ -15,6 +15,8 @@ public class SystemFeatures : IFeatureCategoryprivate enum Sections{Input,+ Services,+ Power,}public string Name => Loc.Instance[$"Features.{nameof(SystemFeatures)}.Name"];@@ -23,7 +25,11 @@ public class SystemFeatures : IFeatureCategorypublic FeatureCategoryOrder Order { get; init; } = FeatureCategoryOrder.System;public ObservableCollection<IFeature> Features { get; init; } = [];- [Feature(Section = nameof(Sections.Input), Icon = SymbolRegular.NumberSymbol24, Recommendation = RecommendationState.On)]+ [Feature(+ Section = nameof(Sections.Input),+ Icon = SymbolRegular.NumberSymbol24,+ Recommendation = RecommendationState.On+ )]public class NumLockOnBoot : BaseFeature{protected override IEnumerable<RegistryToggle> RegistryToggles =>diff --git a/optimizerDuck/Domain/Features/Models/BaseFeature.cs b/optimizerDuck/Domain/Features/Models/BaseFeature.csindex cf2c58f..c49e6e1 100644--- a/optimizerDuck/Domain/Features/Models/BaseFeature.cs+++ b/optimizerDuck/Domain/Features/Models/BaseFeature.cs@@ -44,8 +44,7 @@ public abstract class BaseFeature : IFeaturepublic SymbolRegular Icon => Meta.Icon;- public string RecommendationPrefix =>- $"Features.{OwnerKey}.{FeatureKey}.Recommendation";+ public string RecommendationPrefix => $"Features.{OwnerKey}.{FeatureKey}.Recommendation";public virtual FeatureRecommendationResult? GetRecommendation(){diff --git a/optimizerDuck/Domain/Features/Models/FeatureRecommendationResult.cs b/optimizerDuck/Domain/Features/Models/FeatureRecommendationResult.csindex 630fee4..a8bbd6c 100644--- a/optimizerDuck/Domain/Features/Models/FeatureRecommendationResult.cs+++ b/optimizerDuck/Domain/Features/Models/FeatureRecommendationResult.cs@@ -2,4 +2,5 @@ namespace optimizerDuck.Domain.Features.Models;public sealed record FeatureRecommendationResult(RecommendationState State,- string ReasonTranslationKey);+ string ReasonTranslationKey+);diff --git a/optimizerDuck/Domain/Optimizations/Categories/Performance.cs b/optimizerDuck/Domain/Optimizations/Categories/Performance.csindex ba5071c..b219610 100644--- a/optimizerDuck/Domain/Optimizations/Categories/Performance.cs+++ b/optimizerDuck/Domain/Optimizations/Categories/Performance.cs@@ -141,71 +141,65 @@ public class Performance : IOptimizationCategory}[Optimization(- Id = "D3E93D47-FC7E-44E2-8B58-D8626A75DB93",+ Id = "FFB49D94-CCA9-4591-B329-6FDA3A2758F9",Risk = OptimizationRisk.Safe,- Tags = OptimizationTags.System | OptimizationTags.Performance | OptimizationTags.Power+ Tags = OptimizationTags.System | OptimizationTags.Performance | OptimizationTags.Latency)]- public class GameTaskScheduling : BaseOptimization+ public class OptimizeMultimediaScheduler : BaseOptimization{public override Task<ApplyResult> ApplyAsync(IProgress<ProcessingProgress> progress,OptimizationContext context){+ const string systemProfileKey =+ @"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile";++ // Parent SystemProfile settings (NoLazyMode, AlwaysOn, NetworkThrottlingIndex, SystemResponsiveness)+ RegistryService.Write(+ new RegistryItem(systemProfileKey, "NoLazyMode", 1),+ new RegistryItem(systemProfileKey, "AlwaysOn", 1),+ new RegistryItem(+ systemProfileKey,+ "NetworkThrottlingIndex",+ unchecked((int)0xFFFFFFFF),+ RegistryValueKind.DWord+ ),+ new RegistryItem(+ systemProfileKey,+ "SystemResponsiveness",+ 10,+ RegistryValueKind.DWord+ ) // minimum possible value (Values below 10 and above 100 are clamped to 20.)+ );++ // Games task scheduling (Priority, Scheduling Category, SFIO Priority, GPU Priority)RegistryService.Write(new RegistryItem(- @"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile\Tasks\Games",+ $@"{systemProfileKey}\Tasks\Games","Priority",2),new RegistryItem(- @"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile\Tasks\Games",+ $@"{systemProfileKey}\Tasks\Games","Scheduling Category","High"),new RegistryItem(- @"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile\Tasks\Games",+ $@"{systemProfileKey}\Tasks\Games","SFIO Priority","High"),new RegistryItem(- @"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile\Tasks\Games",+ $@"{systemProfileKey}\Tasks\Games","GPU Priority",8));- context.Logger.LogInformation("Enabled game task scheduling with high priority");- return Task.FromResult(ApplyResult.True());- }- }-- [Optimization(- Id = "FFB49D94-CCA9-4591-B329-6FDA3A2758F9",- Risk = OptimizationRisk.Safe,- Tags = OptimizationTags.System | OptimizationTags.Performance | OptimizationTags.Latency- )]- public class MultimediaResponsiveness : BaseOptimization- {- public override Task<ApplyResult> ApplyAsync(- IProgress<ProcessingProgress> progress,- OptimizationContext context- )- {- const string systemProfileKey =- @"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile";-- RegistryService.Write(- new RegistryItem(- systemProfileKey,- "NetworkThrottlingIndex",- unchecked((int)0xFFFFFFFF),- RegistryValueKind.DWord- ),- new RegistryItem(systemProfileKey, "SystemResponsiveness", 10) // minimum possible value (Values below 10 and above 100 are clamped to 20.)+ context.Logger.LogInformation(+ "Optimized Multimedia Class Scheduler Service (MMCSS) for gaming and low latency");-- context.Logger.LogInformation("Optimized multimedia responsiveness for low latency");return Task.FromResult(ApplyResult.True());}}@@ -234,7 +228,7 @@ public class Performance : IOptimizationCategory[Optimization(Id = "B7BB32F8-C756-47A4-83F2-F6E7EC7D45B8",- Risk = OptimizationRisk.Safe,+ Risk = OptimizationRisk.Moderate,Tags = OptimizationTags.Latency | OptimizationTags.System)]public class DisableAccessibilityKeyboardHotkeys : BaseOptimizationdiff --git a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.csindex 8fd36fb..4aab411 100644--- a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs+++ b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs@@ -1,4 +1,4 @@-using System.Collections.ObjectModel;+using System.Collections.ObjectModel;using System.Text.RegularExpressions;using Microsoft.Extensions.Logging;using optimizerDuck.Common.Helpers;@@ -25,40 +25,26 @@ public class PowerManagement : IOptimizationCategoryRisk = OptimizationRisk.Moderate,Tags = OptimizationTags.System | OptimizationTags.Power | OptimizationTags.Performance)]- public class DisableHibernate : BaseOptimization+ public class DisableHibernateAndFastStartup : BaseOptimization{- public override Task<ApplyResult> ApplyAsync(+ public override async Task<ApplyResult> ApplyAsync(IProgress<ProcessingProgress> progress,OptimizationContext context){- ShellService.CMD("powercfg /h off", "powercfg /h on");- context.Logger.LogInformation("Disabled hibernate");- return Task.FromResult(ApplyResult.True());- }- }+ var wasEnabled = RegistryService.Read<int>(new RegistryItem(@"SYSTEM\CurrentControlSet\Control\Session Manager\Power", "HibernateEnabled")) != 0;+ string revertCommand = wasEnabled+ ? "powercfg /h on"+ : "powercfg /h off";- [Optimization(- Id = "2B49A8A6-E8CA-4D77-A883-DC27BDBE8B05",- Risk = OptimizationRisk.Moderate,- Tags = OptimizationTags.System | OptimizationTags.Power | OptimizationTags.Performance- )]- public class DisableFastStartup : BaseOptimization- {- public override Task<ApplyResult> ApplyAsync(- IProgress<ProcessingProgress> progress,- OptimizationContext context- )- {- RegistryService.Write(- new RegistryItem(- @"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power",- "HiberbootEnabled",- 0- )+ await ShellService.CMDAsync("powercfg /h off", revertCommand);+++ context.Logger.LogInformation(+ "Disabled hibernation and Fast Startup. Previous state: {State}",+ wasEnabled ? "Enabled" : "Disabled");- context.Logger.LogInformation("Disabled fast startup");- return Task.FromResult(ApplyResult.True());+ return ApplyResult.True();}}@@ -69,13 +55,13 @@ public class PowerManagement : IOptimizationCategory)]public class DisableUSBPowerSaving : BaseOptimization{- public override Task<ApplyResult> ApplyAsync(+ public override async Task<ApplyResult> ApplyAsync(IProgress<ProcessingProgress> progress,OptimizationContext context){context.Logger.LogInformation("Saving current USB power state");- var usbStates = ShellService.PowerShell(+ var usbStates = await ShellService.PowerShellAsync("""$states = Get-CimInstance -Namespace root\wmi -ClassName MSPower_DeviceEnable -ErrorAction SilentlyContinue |Where-Object { $_.InstanceName -match 'USB\\ROOT' } |@@ -88,11 +74,11 @@ public class PowerManagement : IOptimizationCategoryif (string.IsNullOrWhiteSpace(usbStates.Stdout)){context.Logger.LogInformation("No USB devices found, skipping");- return Task.FromResult(ApplyResult.True());+ return ApplyResult.True();}context.Logger.LogInformation("Disabling USB power saving");- ShellService.PowerShell(+ await ShellService.PowerShellAsync("""$devices = Get-CimInstance -Namespace root\wmi -ClassName MSPower_DeviceEnable -ErrorAction SilentlyContinue |Where-Object { $_.InstanceName -match 'USB\\ROOT' }@@ -102,23 +88,10 @@ public class PowerManagement : IOptimizationCategorySet-CimInstance -CimInstance $d -Property @{ Enable = $false } | Out-Null}}- """,- $$"""- $states = @('{{usbStates.Stdout}}' | ConvertFrom-Json)-- foreach ($s in $states) {- $obj = Get-CimInstance -Namespace root\wmi -ClassName MSPower_DeviceEnable -ErrorAction SilentlyContinue |- Where-Object { $_.InstanceName -eq $s.InstanceName }-- if ($obj -and $obj.Enable -ne [bool]$s.Enable) {- Write-Host "Reverting $($s.InstanceName) to $([bool]$s.Enable)"- Set-CimInstance -CimInstance $obj -Property @{ Enable = [bool]$s.Enable } | Out-Null- }- }""");- return Task.FromResult(ApplyResult.True());+ return ApplyResult.True();}}@@ -137,7 +110,9 @@ public class PowerManagement : IOptimizationCategoryOptimizationContext context){- var activeQuery = ShellService.CMD("powercfg /getactivescheme");+ var activeQuery = await ShellService.CMDAsync(+ "powercfg /getactivescheme"+ );var match = Regex.Match(activeQuery.Stdout,@"Power Scheme GUID:\s*([a-fA-F0-9\-]{36})",@@ -184,20 +159,9 @@ public class PowerManagement : IOptimizationCategory});- ShellService.CMD(- "powercfg /setactive 381b4222-f694-41f0-9685-ff5bb260df2e",- policy: ShellPolicy.SuccessExitCodes(0, 1)- ); // set Balanced- var result = ShellService.CMD(- $"powercfg /delete {Shared.PowerPlanGUID}",- $"powercfg /setactive {previousPlanGuid}",- ShellPolicy.SuccessExitCodes(0, 1)- );- if (result.ExitCode == 0)- context.Logger.LogInformation("Deleted old power plan");-- var importResult = ShellService.CMD(- $"powercfg /import \"{powerPlanPath}\" {Shared.PowerPlanGUID}"+ var importResult = await ShellService.CMDAsync(+ $"powercfg /import \"{powerPlanPath}\" {Shared.PowerPlanGUID}",+ $"powercfg /delete {Shared.PowerPlanGUID}");if (importResult.ExitCode != 0){@@ -208,7 +172,10 @@ public class PowerManagement : IOptimizationCategoryreturn ApplyResult.False(Loc.Instance[$"{ErrorPrefix}.ImportFailed"]);}- var setActiveResult = ShellService.CMD($"powercfg /setactive {Shared.PowerPlanGUID}");+ var setActiveResult = await ShellService.CMDAsync(+ $"powercfg /setactive {Shared.PowerPlanGUID}",+ $"powercfg /setactive {previousPlanGuid}"+ );if (setActiveResult.ExitCode != 0){context.Logger.LogError(@@ -252,32 +219,4 @@ public class PowerManagement : IOptimizationCategory}}- [Optimization(- Id = "C24B2B0E-A66D-43D0-8B4E-30550D107A68",- Risk = OptimizationRisk.Safe,- Tags = OptimizationTags.Performance | OptimizationTags.Latency | OptimizationTags.Audio- )]- public class OptimizeMultimediaProfile : BaseOptimization- {- public override Task<ApplyResult> ApplyAsync(- IProgress<ProcessingProgress> progress,- OptimizationContext context- )- {- RegistryService.Write(- new RegistryItem(- @"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile",- "NoLazyMode",- 1- ),- new RegistryItem(- @"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile",- "AlwaysOn",- 1- )- );- context.Logger.LogInformation("Optimized multimedia profile settings");- return Task.FromResult(ApplyResult.True());- }- }}diff --git a/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.cs b/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.csindex 2788e77..a945dc7 100644--- a/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.cs+++ b/optimizerDuck/Domain/Optimizations/Categories/SecurityAndPrivacy.cs@@ -1,4 +1,4 @@-using System.Collections.ObjectModel;+using System.Collections.ObjectModel;using Microsoft.Extensions.Logging;using optimizerDuck.Domain.Abstractions;using optimizerDuck.Domain.Attributes;@@ -19,29 +19,7 @@ public class SecurityAndPrivacy : IOptimizationCategoryOptimizationCategoryOrder.SecurityAndPrivacy;public ObservableCollection<IOptimization> Optimizations { get; init; } = [];- [Optimization(- Id = "09F7CE38-93B2-4E1A-AB09-130268165B42",- Risk = OptimizationRisk.Risky,- Tags = OptimizationTags.System | OptimizationTags.Security- )]- public class DisableUAC : BaseOptimization- {- public override Task<ApplyResult> ApplyAsync(- IProgress<ProcessingProgress> progress,- OptimizationContext context- )- {- RegistryService.Write(- new RegistryItem(- @"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System",- "EnableLUA",- 0- )- );- context.Logger.LogInformation("Disabled UAC prompts");- return Task.FromResult(ApplyResult.True());- }- }+[Optimization(Id = "74DC8DAC-1F90-4BBD-ACF7-7E626749D71C",@@ -297,6 +275,11 @@ public class SecurityAndPrivacy : IOptimizationCategory"ShellFeedsTaskbarViewMode",2),+ new RegistryItem(+ @"HKLM\SOFTWARE\Policies\Microsoft\Dsh",+ "AllowNewsAndInterests",+ 0+ ),new RegistryItem(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer","HideSCAMeetNow",@@ -497,16 +480,6 @@ public class SecurityAndPrivacy : IOptimizationCategory"Start",0),- new RegistryItem(- @"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\DefenderApiLogger",- "Start",- 0- ),- new RegistryItem(- @"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\DefenderAuditLogger",- "Start",- 0- ),new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control\WMI\Autologger\DiagLog","Start",diff --git a/optimizerDuck/Domain/Optimizations/Models/Services/RegistryItem.cs b/optimizerDuck/Domain/Optimizations/Models/Services/RegistryItem.csindex b652cdb..b98d811 100644--- a/optimizerDuck/Domain/Optimizations/Models/Services/RegistryItem.cs+++ b/optimizerDuck/Domain/Optimizations/Models/Services/RegistryItem.cs@@ -1,4 +1,4 @@-using Microsoft.Win32;+using Microsoft.Win32;namespace optimizerDuck.Domain.Optimizations.Models.Services;@@ -57,7 +57,7 @@ public record struct RegistryItem}/// <summary>- /// Initializes a new <see cref="RegistryItem" /> for a named value without data (used for deletion).+ /// Initializes a new <see cref="RegistryItem" /> for a named value without data (used for deletion or reading)./// </summary>/// <param name="path">The registry key path.</param>/// <param name="name">The value name to target.</param>diff --git a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.csindex ff7b8a8..daa4a78 100644--- a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs@@ -41,9 +41,7 @@ public class ServiceRevertStep : IRevertStepif (!result)throw new Exception(- string.Format(- Translations.Service_Service_Error_UpdateRegistryForStartupTypeFailed- )+ string.Format(Translations.Service_Service_Error_UpdateRegistryForStartupTypeFailed));return Task.FromResult(result);diff --git a/optimizerDuck/Resources/Embedded/Icons/blank.ico b/optimizerDuck/Resources/Embedded/Icons/blank.iconew file mode 100644index 0000000..f6748faBinary files /dev/null and b/optimizerDuck/Resources/Embedded/Icons/blank.ico differdiff --git a/optimizerDuck/Resources/Languages/Translations.Designer.cs b/optimizerDuck/Resources/Languages/Translations.Designer.csindex 5571a8e..b646979 100644--- a/optimizerDuck/Resources/Languages/Translations.Designer.cs+++ b/optimizerDuck/Resources/Languages/Translations.Designer.cs@@ -2131,6 +2131,24 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to Power Settings.+ /// </summary>+ internal static string Features_SystemFeatures_Section_Power {+ get {+ return ResourceManager.GetString("Features.SystemFeatures.Section.Power", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Services.+ /// </summary>+ internal static string Features_SystemFeatures_Section_Services {+ get {+ return ResourceManager.GetString("Features.SystemFeatures.Section.Services", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to Features./// </summary>@@ -2834,24 +2852,6 @@ namespace optimizerDuck.Resources.Languages {}}- /// <summary>- /// Looks up a localized string similar to Optimize Game Scheduling.- /// </summary>- internal static string Optimizer_Performance_GameTaskScheduling_Name {- get {- return ResourceManager.GetString("Optimizer.Performance.GameTaskScheduling.Name", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Assigns high priority to gaming workloads to ensure consistent frames per second (FPS) and smoother gameplay..- /// </summary>- internal static string Optimizer_Performance_GameTaskScheduling_ShortDescription {- get {- return ResourceManager.GetString("Optimizer.Performance.GameTaskScheduling.ShortDescription", resourceCulture);- }- }-/// <summary>/// Looks up a localized string similar to Optimize Keyboard Repeat./// </summary>@@ -2871,20 +2871,20 @@ namespace optimizerDuck.Resources.Languages {}/// <summary>- /// Looks up a localized string similar to Multimedia & Network Responsiveness.+ /// Looks up a localized string similar to Optimize Multimedia Scheduler./// </summary>- internal static string Optimizer_Performance_MultimediaResponsiveness_Name {+ internal static string Optimizer_Performance_OptimizeMultimediaScheduler_Name {get {- return ResourceManager.GetString("Optimizer.Performance.MultimediaResponsiveness.Name", resourceCulture);+ return ResourceManager.GetString("Optimizer.Performance.OptimizeMultimediaScheduler.Name", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Prioritizes system resources for multimedia and gaming by reducing background CPU reservation and disabling network throttling for lower latency..+ /// Looks up a localized string similar to Configures the Multimedia Class Scheduler Service (MMCSS) for gaming and low latency by prioritizing multimedia workloads and disabling network throttling../// </summary>- internal static string Optimizer_Performance_MultimediaResponsiveness_ShortDescription {+ internal static string Optimizer_Performance_OptimizeMultimediaScheduler_ShortDescription {get {- return ResourceManager.GetString("Optimizer.Performance.MultimediaResponsiveness.ShortDescription", resourceCulture);+ return ResourceManager.GetString("Optimizer.Performance.OptimizeMultimediaScheduler.ShortDescription", resourceCulture);}}@@ -2943,38 +2943,20 @@ namespace optimizerDuck.Resources.Languages {}/// <summary>- /// Looks up a localized string similar to Disable Fast Startup.- /// </summary>- internal static string Optimizer_PowerManagement_DisableFastStartup_Name {- get {- return ResourceManager.GetString("Optimizer.PowerManagement.DisableFastStartup.Name", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Turns off Fast Startup to ensure a full shutdown and cleaner hardware initialization on boot..+ /// Looks up a localized string similar to Disable Hibernation & Fast Startup./// </summary>- internal static string Optimizer_PowerManagement_DisableFastStartup_ShortDescription {+ internal static string Optimizer_PowerManagement_DisableHibernateAndFastStartup_Name {get {- return ResourceManager.GetString("Optimizer.PowerManagement.DisableFastStartup.ShortDescription", resourceCulture);+ return ResourceManager.GetString("Optimizer.PowerManagement.DisableHibernateAndFastStartup.Name", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Disable Hibernation.+ /// Looks up a localized string similar to Turns off hibernation and Fast Startup to reclaim disk space and ensure a full shutdown for cleaner hardware initialization on boot../// </summary>- internal static string Optimizer_PowerManagement_DisableHibernate_Name {+ internal static string Optimizer_PowerManagement_DisableHibernateAndFastStartup_ShortDescription {get {- return ResourceManager.GetString("Optimizer.PowerManagement.DisableHibernate.Name", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Turns off hibernation to reclaim disk space used by the hiberfil.sys file..- /// </summary>- internal static string Optimizer_PowerManagement_DisableHibernate_ShortDescription {- get {- return ResourceManager.GetString("Optimizer.PowerManagement.DisableHibernate.ShortDescription", resourceCulture);+ return ResourceManager.GetString("Optimizer.PowerManagement.DisableHibernateAndFastStartup.ShortDescription", resourceCulture);}}@@ -3087,24 +3069,6 @@ namespace optimizerDuck.Resources.Languages {}}- /// <summary>- /// Looks up a localized string similar to Optimize Multimedia Profile.- /// </summary>- internal static string Optimizer_PowerManagement_OptimizeMultimediaProfile_Name {- get {- return ResourceManager.GetString("Optimizer.PowerManagement.OptimizeMultimediaProfile.Name", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Configures the multimedia system profile to prioritize performance and disable lazy mode for better responsiveness..- /// </summary>- internal static string Optimizer_PowerManagement_OptimizeMultimediaProfile_ShortDescription {- get {- return ResourceManager.GetString("Optimizer.PowerManagement.OptimizeMultimediaProfile.ShortDescription", resourceCulture);- }- }-/// <summary>/// Looks up a localized string similar to Security & Privacy./// </summary>@@ -3303,24 +3267,6 @@ namespace optimizerDuck.Resources.Languages {}}- /// <summary>- /// Looks up a localized string similar to Disable Admin Prompts (UAC).- /// </summary>- internal static string Optimizer_SecurityAndPrivacy_DisableUAC_Name {- get {- return ResourceManager.GetString("Optimizer.SecurityAndPrivacy.DisableUAC.Name", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Turns off User Account Control (UAC) windows that ask for permission when running apps as administrator..- /// </summary>- internal static string Optimizer_SecurityAndPrivacy_DisableUAC_ShortDescription {- get {- return ResourceManager.GetString("Optimizer.SecurityAndPrivacy.DisableUAC.ShortDescription", resourceCulture);- }- }-/// <summary>/// Looks up a localized string similar to This value reflects the level of intervention and the safety of the optimization process. Please exercise caution and consider carefully before applying any optimization../// </summary>@@ -4433,18 +4379,18 @@ namespace optimizerDuck.Resources.Languages {/// <summary>/// Looks up a localized string similar to Delete all files downloaded during the optimization process../// </summary>- internal static string Settings_Advanced_ClearResources_Description {+ internal static string Settings_Advanced_ClearDownloads_Description {get {- return ResourceManager.GetString("Settings.Advanced.ClearResources.Description", resourceCulture);+ return ResourceManager.GetString("Settings.Advanced.ClearDownloads.Description", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Clear resources.+ /// Looks up a localized string similar to Clear downloads./// </summary>- internal static string Settings_Advanced_ClearResources_Title {+ internal static string Settings_Advanced_ClearDownloads_Title {get {- return ResourceManager.GetString("Settings.Advanced.ClearResources.Title", resourceCulture);+ return ResourceManager.GetString("Settings.Advanced.ClearDownloads.Title", resourceCulture);}}@@ -4593,11 +4539,11 @@ namespace optimizerDuck.Resources.Languages {}/// <summary>- /// Looks up a localized string similar to You are about to delete all resources downloaded or generated during the optimization process. Please note that this action is permanent and cannot be undone, so make sure you are certain before proceeding..+ /// Looks up a localized string similar to You are about to delete all files downloaded during the optimization process. Please note that this action is permanent and cannot be undone, so make sure you are certain before proceeding../// </summary>- internal static string Settings_ClearResources_Description {+ internal static string Settings_ClearDownloads_Description {get {- return ResourceManager.GetString("Settings.ClearResources.Description", resourceCulture);+ return ResourceManager.GetString("Settings.ClearDownloads.Description", resourceCulture);}}diff --git a/optimizerDuck/Resources/Languages/Translations.resx b/optimizerDuck/Resources/Languages/Translations.resxindex f65a37f..2a026a5 100644--- a/optimizerDuck/Resources/Languages/Translations.resx+++ b/optimizerDuck/Resources/Languages/Translations.resx@@ -454,10 +454,10 @@<data name="Settings.Optimize.ShellTimeout.Description" xml:space="preserve"><value>Timeout for each shell command execution (milliseconds).</value></data>- <data name="Settings.Advanced.ClearResources.Title" xml:space="preserve">- <value>Clear resources</value>+ <data name="Settings.Advanced.ClearDownloads.Title" xml:space="preserve">+ <value>Clear downloads</value></data>- <data name="Settings.Advanced.ClearResources.Description" xml:space="preserve">+ <data name="Settings.Advanced.ClearDownloads.Description" xml:space="preserve"><value>Delete all files downloaded during the optimization process.</value></data><data name="Settings.Advanced.ClearRevertDatas.Title" xml:space="preserve">@@ -484,8 +484,8 @@<data name="Dialog.AreYouSure.Title" xml:space="preserve"><value>Do you really want to proceed?</value></data>- <data name="Settings.ClearResources.Description" xml:space="preserve">- <value>You are about to delete all resources downloaded or generated during the optimization process. Please note that this action is permanent and cannot be undone, so make sure you are certain before proceeding.</value>+ <data name="Settings.ClearDownloads.Description" xml:space="preserve">+ <value>You are about to delete all files downloaded during the optimization process. Please note that this action is permanent and cannot be undone, so make sure you are certain before proceeding.</value></data><data name="Button.Cancel" xml:space="preserve"><value>Cancel</value>@@ -589,17 +589,11 @@<data name="Optimizer.Performance.ProcessPriority.ShortDescription" xml:space="preserve"><value>Allocates more CPU resources to the application you are currently using for a faster, more responsive experience.</value></data>- <data name="Optimizer.Performance.GameTaskScheduling.Name" xml:space="preserve">- <value>Optimize Game Scheduling</value>+ <data name="Optimizer.Performance.OptimizeMultimediaScheduler.Name" xml:space="preserve">+ <value>Optimize Multimedia Scheduler</value></data>- <data name="Optimizer.Performance.GameTaskScheduling.ShortDescription" xml:space="preserve">- <value>Assigns high priority to gaming workloads to ensure consistent frames per second (FPS) and smoother gameplay.</value>- </data>- <data name="Optimizer.Performance.MultimediaResponsiveness.Name" xml:space="preserve">- <value>Multimedia & Network Responsiveness</value>- </data>- <data name="Optimizer.Performance.MultimediaResponsiveness.ShortDescription" xml:space="preserve">- <value>Prioritizes system resources for multimedia and gaming by reducing background CPU reservation and disabling network throttling for lower latency.</value>+ <data name="Optimizer.Performance.OptimizeMultimediaScheduler.ShortDescription" xml:space="preserve">+ <value>Configures the Multimedia Class Scheduler Service (MMCSS) for gaming and low latency by prioritizing multimedia workloads and disabling network throttling.</value></data><data name="Optimizer.Performance.KeyboardLatencyOptimization.Name" xml:space="preserve"><value>Optimize Keyboard Repeat</value>@@ -613,17 +607,11 @@<data name="Optimizer.Performance.DisableAccessibilityKeyboardHotkeys.ShortDescription" xml:space="preserve"><value>Disables Sticky Keys, Filter Keys, and Toggle Keys keyboard shortcuts to prevent accidental pop-ups during gaming and typing.</value></data>- <data name="Optimizer.PowerManagement.DisableHibernate.Name" xml:space="preserve">- <value>Disable Hibernation</value>- </data>- <data name="Optimizer.PowerManagement.DisableHibernate.ShortDescription" xml:space="preserve">- <value>Turns off hibernation to reclaim disk space used by the hiberfil.sys file.</value>+ <data name="Optimizer.PowerManagement.DisableHibernateAndFastStartup.Name" xml:space="preserve">+ <value>Disable Hibernation & Fast Startup</value></data>- <data name="Optimizer.PowerManagement.DisableFastStartup.Name" xml:space="preserve">- <value>Disable Fast Startup</value>- </data>- <data name="Optimizer.PowerManagement.DisableFastStartup.ShortDescription" xml:space="preserve">- <value>Turns off Fast Startup to ensure a full shutdown and cleaner hardware initialization on boot.</value>+ <data name="Optimizer.PowerManagement.DisableHibernateAndFastStartup.ShortDescription" xml:space="preserve">+ <value>Turns off hibernation and Fast Startup to reclaim disk space and ensure a full shutdown for cleaner hardware initialization on boot.</value></data><data name="Optimizer.PowerManagement.DisableUSBPowerSaving.Name" xml:space="preserve"><value>Disable USB Power Saving</value>@@ -649,18 +637,6 @@<data name="Optimizer.PowerManagement.DisablePowerSaving.ShortDescription" xml:space="preserve"><value>Prevents Windows from limiting CPU performance (Power Throttling) to maintain peak power for active tasks.</value></data>- <data name="Optimizer.PowerManagement.OptimizeMultimediaProfile.Name" xml:space="preserve">- <value>Optimize Multimedia Profile</value>- </data>- <data name="Optimizer.PowerManagement.OptimizeMultimediaProfile.ShortDescription" xml:space="preserve">- <value>Configures the multimedia system profile to prioritize performance and disable lazy mode for better responsiveness.</value>- </data>- <data name="Optimizer.SecurityAndPrivacy.DisableUAC.Name" xml:space="preserve">- <value>Disable Admin Prompts (UAC)</value>- </data>- <data name="Optimizer.SecurityAndPrivacy.DisableUAC.ShortDescription" xml:space="preserve">- <value>Turns off User Account Control (UAC) windows that ask for permission when running apps as administrator.</value>- </data><data name="Optimizer.SecurityAndPrivacy.DisableTelemetry.Name" xml:space="preserve"><value>Disable Data Collection (Telemetry)</value></data>@@ -1635,6 +1611,12 @@ Update now to enjoy the latest features, improvements, and bug fixes.</value><data name="Features.SystemFeatures.NumLockOnBoot.Recommendation.Reason" xml:space="preserve"><value>Enabling NumLock at boot ensures the numpad is ready immediately after login, avoiding manual toggling each time.</value></data>+ <data name="Features.SystemFeatures.Section.Services" xml:space="preserve">+ <value>Services</value>+ </data>+ <data name="Features.SystemFeatures.Section.Power" xml:space="preserve">+ <value>Power Settings</value>+ </data><data name="Features.Desktop.Name" xml:space="preserve"><value>Desktop</value></data>diff --git a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx b/optimizerDuck/Resources/Languages/Translations.vi-VN.resxindex 659b2b8..90bc25a 100644--- a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx+++ b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx@@ -448,10 +448,10 @@<data name="Settings.Optimize.ShellTimeout.Description" xml:space="preserve"><value>Thời gian chờ cho mỗi lệnh shell (tính bằng mili‑giây).</value></data>- <data name="Settings.Advanced.ClearResources.Title" xml:space="preserve">- <value>Dọn dẹp tài nguyên</value>+ <data name="Settings.Advanced.ClearDownloads.Title" xml:space="preserve">+ <value>Dọn dẹp tải xuống</value></data>- <data name="Settings.Advanced.ClearResources.Description" xml:space="preserve">+ <data name="Settings.Advanced.ClearDownloads.Description" xml:space="preserve"><value>Xóa tất cả tệp đã tải về trong quá trình tối ưu.</value></data><data name="Settings.Advanced.ClearRevertDatas.Title" xml:space="preserve">@@ -478,8 +478,8 @@<data name="Dialog.AreYouSure.Title" xml:space="preserve"><value>Bạn có chắc chắn muốn tiếp tục không?</value></data>- <data name="Settings.ClearResources.Description" xml:space="preserve">- <value>Bạn sắp xóa tất cả các tài nguyên đã được tải xuống hoặc tạo ra trong quá trình tối ưu. Xin lưu ý rằng hành động này là vĩnh viễn và không thể hoàn tác, vì vậy hãy chắc chắn trước khi tiếp tục.</value>+ <data name="Settings.ClearDownloads.Description" xml:space="preserve">+ <value>Bạn sắp xóa tất cả các tệp đã được tải xuống trong quá trình tối ưu. Xin lưu ý rằng hành động này là vĩnh viễn và không thể hoàn tác, vì vậy hãy chắc chắn trước khi tiếp tục.</value></data><data name="Button.Cancel" xml:space="preserve"><value>Hủy</value>@@ -571,17 +571,11 @@<data name="Optimizer.Performance.ProcessPriority.ShortDescription" xml:space="preserve"><value>Cấu hình Win32PrioritySeparation thành 38 (Short, Variable, High foreground boost), ưu tiên ứng dụng đang hoạt động và giảm độ trễ đầu vào.</value></data>- <data name="Optimizer.Performance.GameTaskScheduling.Name" xml:space="preserve">- <value>Tối ưu hóa lập lịch trò chơi</value>+ <data name="Optimizer.Performance.OptimizeMultimediaScheduler.Name" xml:space="preserve">+ <value>Tối ưu hóa Multimedia Scheduler</value></data>- <data name="Optimizer.Performance.GameTaskScheduling.ShortDescription" xml:space="preserve">- <value>Cấu hình hồ sơ tác vụ MMCSS "Games" với danh mục lập lịch High và mức ưu tiên GPU/IO cao để đảm bảo frame pacing ổn định.</value>- </data>- <data name="Optimizer.Performance.MultimediaResponsiveness.Name" xml:space="preserve">- <value>Độ phản hồi Đa phương tiện & Mạng</value>- </data>- <data name="Optimizer.Performance.MultimediaResponsiveness.ShortDescription" xml:space="preserve">- <value>Ưu tiên tài nguyên hệ thống cho đa phương tiện và trò chơi bằng cách giảm mức dự phòng CPU cho tác vụ nền và tắt giới hạn băng thông mạng để giảm độ trễ.</value>+ <data name="Optimizer.Performance.OptimizeMultimediaScheduler.ShortDescription" xml:space="preserve">+ <value>Cấu hình dịch vụ Multimedia Class Scheduler Service (MMCSS) cho gaming và độ trễ thấp bằng cách ưu tiên multimedia và tắt giới hạn băng thông mạng.</value></data><data name="Optimizer.Performance.KeyboardLatencyOptimization.Name" xml:space="preserve"><value>Tối ưu lặp phím bàn phím</value>@@ -595,17 +589,11 @@<data name="Optimizer.Performance.DisableAccessibilityKeyboardHotkeys.ShortDescription" xml:space="preserve"><value>Tắt các phím tắt Sticky Keys, Filter Keys và Toggle Keys để tránh bật nhầm khi chơi game hoặc gõ phím.</value></data>- <data name="Optimizer.PowerManagement.DisableHibernate.Name" xml:space="preserve">- <value>Vô hiệu hóa Chế độ ngủ đông</value>- </data>- <data name="Optimizer.PowerManagement.DisableHibernate.ShortDescription" xml:space="preserve">- <value>Tắt Hibernate để giải phóng dung lượng ổ đĩa do tệp hiberfil.sys sử dụng.</value>+ <data name="Optimizer.PowerManagement.DisableHibernateAndFastStartup.Name" xml:space="preserve">+ <value>Vô hiệu hóa Ngủ đông & Fast Startup</value></data>- <data name="Optimizer.PowerManagement.DisableFastStartup.Name" xml:space="preserve">- <value>Tắt Fast Startup</value>- </data>- <data name="Optimizer.PowerManagement.DisableFastStartup.ShortDescription" xml:space="preserve">- <value>Tắt Fast Startup để đảm bảo máy tắt hoàn toàn và khởi tạo phần cứng sạch hơn khi bật lại.</value>+ <data name="Optimizer.PowerManagement.DisableHibernateAndFastStartup.ShortDescription" xml:space="preserve">+ <value>Tắt Hibernate và Fast Startup để giải phóng dung lượng ổ đĩa và đảm bảo máy tắt hoàn toàn để khởi tạo phần cứng sạch hơn khi bật lại.</value></data><data name="Optimizer.PowerManagement.DisableUSBPowerSaving.Name" xml:space="preserve"><value>Ngăn ngắt nguồn cổng USB</value>@@ -631,18 +619,6 @@<data name="Optimizer.PowerManagement.DisablePowerSaving.ShortDescription" xml:space="preserve"><value>Ngăn Windows tự động giảm hiệu năng CPU (Power Throttling) để duy trì sức mạnh tối đa cho hệ thống.</value></data>- <data name="Optimizer.PowerManagement.OptimizeMultimediaProfile.Name" xml:space="preserve">- <value>Tối ưu hóa Multimedia Profile</value>- </data>- <data name="Optimizer.PowerManagement.OptimizeMultimediaProfile.ShortDescription" xml:space="preserve">- <value>Cấu hình profile hệ thống multimedia để ưu tiên hiệu suất và tắt lazy mode để có độ phản hồi tốt hơn.</value>- </data>- <data name="Optimizer.SecurityAndPrivacy.DisableUAC.Name" xml:space="preserve">- <value>Vô hiệu hóa xác nhận Admin (UAC)</value>- </data>- <data name="Optimizer.SecurityAndPrivacy.DisableUAC.ShortDescription" xml:space="preserve">- <value>Tắt các hộp thoại yêu cầu xác nhận khi mở ứng dụng với quyền Admin. Lưu ý: Làm giảm bảo mật.</value>- </data><data name="Optimizer.SecurityAndPrivacy.DisableTelemetry.Name" xml:space="preserve"><value>Vô hiệu hóa thu thập dữ liệu (Telemetry)</value></data>@@ -1753,4 +1729,10 @@ Cập nhật ngay để trải nghiệm các tính năng mới, cải tiến và<data name="Features.SystemFeatures.NumLockOnBoot.Recommendation.Reason" xml:space="preserve"><value>Bật NumLock khi khởi động đảm bảo bàn phím số sẵn sàng ngay sau khi đăng nhập, tránh phải bật/tắt thủ công mỗi lần.</value></data>+ <data name="Features.SystemFeatures.Section.Services" xml:space="preserve">+ <value>Dịch vụ</value>+ </data>+ <data name="Features.SystemFeatures.Section.Power" xml:space="preserve">+ <value>Cài đặt nguồn</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Resources/Languages/Translations.zh-CN.resx b/optimizerDuck/Resources/Languages/Translations.zh-CN.resxindex fd1a64b..df46301 100644--- a/optimizerDuck/Resources/Languages/Translations.zh-CN.resx+++ b/optimizerDuck/Resources/Languages/Translations.zh-CN.resx@@ -454,10 +454,10 @@<data name="Settings.Optimize.ShellTimeout.Description" xml:space="preserve"><value>每条 Shell 命令的执行超时时间(毫秒)。</value></data>- <data name="Settings.Advanced.ClearResources.Title" xml:space="preserve">- <value>清理资源文件</value>+ <data name="Settings.Advanced.ClearDownloads.Title" xml:space="preserve">+ <value>清理下载</value></data>- <data name="Settings.Advanced.ClearResources.Description" xml:space="preserve">+ <data name="Settings.Advanced.ClearDownloads.Description" xml:space="preserve"><value>删除优化过程中下载的所有文件。</value></data><data name="Settings.Advanced.ClearRevertDatas.Title" xml:space="preserve">@@ -484,8 +484,8 @@<data name="Dialog.AreYouSure.Title" xml:space="preserve"><value>确定要继续操作吗?</value></data>- <data name="Settings.ClearResources.Description" xml:space="preserve">- <value>你即将删除优化过程中下载或生成的所有资源文件。请注意,此操作不可逆,请确认后再继续。</value>+ <data name="Settings.ClearDownloads.Description" xml:space="preserve">+ <value>你即将删除优化过程中下载的所有文件。请注意,此操作不可逆,请确认后再继续。</value></data><data name="Button.Cancel" xml:space="preserve"><value>取消</value>@@ -589,17 +589,11 @@<data name="Optimizer.Performance.ProcessPriority.ShortDescription" xml:space="preserve"><value>为当前使用的应用分配更多 CPU 资源,提升运行速度与响应速度。</value></data>- <data name="Optimizer.Performance.GameTaskScheduling.Name" xml:space="preserve">- <value>优化游戏任务调度</value>+ <data name="Optimizer.Performance.OptimizeMultimediaScheduler.Name" xml:space="preserve">+ <value>优化多媒体调度</value></data>- <data name="Optimizer.Performance.GameTaskScheduling.ShortDescription" xml:space="preserve">- <value>为游戏任务分配高优先级,确保帧率稳定、游戏运行更流畅。</value>- </data>- <data name="Optimizer.Performance.MultimediaResponsiveness.Name" xml:space="preserve">- <value>多媒体与网络响应优化</value>- </data>- <data name="Optimizer.Performance.MultimediaResponsiveness.ShortDescription" xml:space="preserve">- <value>减少后台 CPU 占用、关闭网络限流,优先保障多媒体与游戏的系统资源,降低延迟。</value>+ <data name="Optimizer.Performance.OptimizeMultimediaScheduler.ShortDescription" xml:space="preserve">+ <value>配置多媒体类调度服务 (MMCSS) 以优化游戏和低延迟,通过优先处理多媒体工作负载和禁用网络节流。</value></data><data name="Optimizer.Performance.KeyboardLatencyOptimization.Name" xml:space="preserve"><value>优化键盘响应速度</value>@@ -613,17 +607,11 @@<data name="Optimizer.Performance.DisableAccessibilityKeyboardHotkeys.ShortDescription" xml:space="preserve"><value>禁用粘滞键、筛选键、切换键快捷键,避免游戏和打字时误触发弹窗。</value></data>- <data name="Optimizer.PowerManagement.DisableHibernate.Name" xml:space="preserve">- <value>禁用休眠功能</value>- </data>- <data name="Optimizer.PowerManagement.DisableHibernate.ShortDescription" xml:space="preserve">- <value>关闭休眠,释放休眠文件占用的磁盘空间。</value>+ <data name="Optimizer.PowerManagement.DisableHibernateAndFastStartup.Name" xml:space="preserve">+ <value>禁用休眠和快速启动</value></data>- <data name="Optimizer.PowerManagement.DisableFastStartup.Name" xml:space="preserve">- <value>禁用快速启动</value>- </data>- <data name="Optimizer.PowerManagement.DisableFastStartup.ShortDescription" xml:space="preserve">- <value>关闭快速启动,确保系统完全关机,开机时硬件初始化更干净。</value>+ <data name="Optimizer.PowerManagement.DisableHibernateAndFastStartup.ShortDescription" xml:space="preserve">+ <value>关闭休眠和快速启动,释放磁盘空间并确保完全关机,以便开机时硬件初始化更干净。</value></data><data name="Optimizer.PowerManagement.DisableUSBPowerSaving.Name" xml:space="preserve"><value>禁用USB节能</value>@@ -649,18 +637,6 @@<data name="Optimizer.PowerManagement.DisablePowerSaving.ShortDescription" xml:space="preserve"><value>阻止 Windows 限制 CPU 性能,保障前台任务始终处于峰值运行状态。</value></data>- <data name="Optimizer.PowerManagement.OptimizeMultimediaProfile.Name" xml:space="preserve">- <value>优化多媒体配置</value>- </data>- <data name="Optimizer.PowerManagement.OptimizeMultimediaProfile.ShortDescription" xml:space="preserve">- <value>配置多媒体系统配置文件,优先保障性能、关闭延迟模式,提升响应速度。</value>- </data>- <data name="Optimizer.SecurityAndPrivacy.DisableUAC.Name" xml:space="preserve">- <value>禁用管理员权限弹窗(UAC)</value>- </data>- <data name="Optimizer.SecurityAndPrivacy.DisableUAC.ShortDescription" xml:space="preserve">- <value>关闭以管理员身份运行应用时的用户账户控制弹窗。</value>- </data><data name="Optimizer.SecurityAndPrivacy.DisableTelemetry.Name" xml:space="preserve"><value>禁用数据收集(遥测)</value></data>@@ -1634,6 +1610,12 @@<data name="Features.SystemFeatures.NumLockOnBoot.Recommendation.Reason" xml:space="preserve"><value>开机启用数字小键盘,登录后即可直接使用,无需每次手动开启。</value></data>+ <data name="Features.SystemFeatures.Section.Services" xml:space="preserve">+ <value>系统服务</value>+ </data>+ <data name="Features.SystemFeatures.Section.Power" xml:space="preserve">+ <value>电源设置</value>+ </data><data name="Features.Desktop.Name" xml:space="preserve"><value>桌面</value></data>diff --git a/optimizerDuck/Resources/Languages/Translations.zh-TW.resx b/optimizerDuck/Resources/Languages/Translations.zh-TW.resxindex fc0dc50..9f1ee3b 100644--- a/optimizerDuck/Resources/Languages/Translations.zh-TW.resx+++ b/optimizerDuck/Resources/Languages/Translations.zh-TW.resx@@ -423,10 +423,10 @@<data name="Settings.Optimize.ShellTimeout.Description" xml:space="preserve"><value>每個殼層命令執行的逾時時間(毫秒)。</value></data>- <data name="Settings.Advanced.ClearResources.Title" xml:space="preserve">- <value>清除資源</value>+ <data name="Settings.Advanced.ClearDownloads.Title" xml:space="preserve">+ <value>清除下載</value></data>- <data name="Settings.Advanced.ClearResources.Description" xml:space="preserve">+ <data name="Settings.Advanced.ClearDownloads.Description" xml:space="preserve"><value>刪除在最佳化過程中下載的所有檔案。</value></data><data name="Settings.Advanced.ClearRevertDatas.Title" xml:space="preserve">@@ -453,8 +453,8 @@<data name="Dialog.AreYouSure.Title" xml:space="preserve"><value>您真的要繼續嗎?</value></data>- <data name="Settings.ClearResources.Description" xml:space="preserve">- <value>您即將刪除在最佳化過程中下載或產生的所有資源。請注意,此動作是永久的且無法復原,因此在繼續前請確認您已確定。</value>+ <data name="Settings.ClearDownloads.Description" xml:space="preserve">+ <value>您即將刪除在最佳化過程中下載的所有檔案。請注意,此動作是永久的且無法復原,因此在繼續前請確認您已確定。</value></data><data name="Button.Cancel" xml:space="preserve"><value>取消</value>@@ -546,17 +546,11 @@<data name="Optimizer.Performance.ProcessPriority.ShortDescription" xml:space="preserve"><value>將更多 CPU 資源分配給您目前正在使用的應用程式,以獲得更快、反應更靈敏的體驗。</value></data>- <data name="Optimizer.Performance.GameTaskScheduling.Name" xml:space="preserve">- <value>最佳化遊戲排程</value>+ <data name="Optimizer.Performance.OptimizeMultimediaScheduler.Name" xml:space="preserve">+ <value>最佳化多媒體排程器</value></data>- <data name="Optimizer.Performance.GameTaskScheduling.ShortDescription" xml:space="preserve">- <value>將高優先級分配給遊戲工作負載,以確保一致的每秒影格數 (FPS) 和更流暢的遊戲體驗。</value>- </data>- <data name="Optimizer.Performance.MultimediaResponsiveness.Name" xml:space="preserve">- <value>最佳化多媒體反應</value>- </data>- <data name="Optimizer.Performance.MultimediaResponsiveness.ShortDescription" xml:space="preserve">- <value>減少音訊、視訊和網路任務的延遲,以提升即時媒體和遊戲效能。</value>+ <data name="Optimizer.Performance.OptimizeMultimediaScheduler.ShortDescription" xml:space="preserve">+ <value>設定多媒體類別排程器服務 (MMCSS) 以優化遊戲和低延遲,透過優先處理多媒體工作負載和停用網路節流。</value></data><data name="Optimizer.Performance.KeyboardLatencyOptimization.Name" xml:space="preserve"><value>最佳化鍵盤反應</value>@@ -564,10 +558,10 @@<data name="Optimizer.Performance.KeyboardLatencyOptimization.ShortDescription" xml:space="preserve"><value>減少鍵盤輸入延遲並增加重複頻率,讓打字和遊戲速度更快、反應更靈敏。</value></data>- <data name="Optimizer.PowerManagement.DisableHibernate.Name" xml:space="preserve">+ <data name="Optimizer.PowerManagement.DisableHibernateAndFastStartup.Name" xml:space="preserve"><value>停用休眠與快速啟動</value></data>- <data name="Optimizer.PowerManagement.DisableHibernate.ShortDescription" xml:space="preserve">+ <data name="Optimizer.PowerManagement.DisableHibernateAndFastStartup.ShortDescription" xml:space="preserve"><value>關閉休眠和快速啟動以取回數 GB 的磁碟空間,並確保系統全新開機。</value></data><data name="Optimizer.PowerManagement.DisableUSBPowerSaving.Name" xml:space="preserve">@@ -594,12 +588,6 @@<data name="Optimizer.PowerManagement.DisablePowerSaving.ShortDescription" xml:space="preserve"><value>防止 Windows 限制 CPU 效能 (電源限制),以維持執行中任務的最高效能。</value></data>- <data name="Optimizer.SecurityAndPrivacy.DisableUAC.Name" xml:space="preserve">- <value>停用管理員提示 (UAC)</value>- </data>- <data name="Optimizer.SecurityAndPrivacy.DisableUAC.ShortDescription" xml:space="preserve">- <value>關閉在以管理員身分執行應用程式時要求權限的使用者帳戶控制 (UAC) 視窗。</value>- </data><data name="Optimizer.SecurityAndPrivacy.DisableTelemetry.Name" xml:space="preserve"><value>停用資料收集 (遙測)</value></data>@@ -1282,12 +1270,6 @@<data name="Revert.Registry.Description.DeleteKey" xml:space="preserve"><value>刪除登錄檔機碼:{0}</value></data>- <data name="Optimizer.PowerManagement.OptimizeMultimediaProfile.Name" xml:space="preserve">- <value>最佳化多媒體設定檔</value>- </data>- <data name="Optimizer.PowerManagement.OptimizeMultimediaProfile.ShortDescription" xml:space="preserve">- <value>設定多媒體系統設定檔以優先考慮效能,並停用延遲模式以獲得更好的反應速度。</value>- </data><data name="Optimizer.SecurityAndPrivacy.DisableErrorReporting.Name" xml:space="preserve"><value>停用錯誤報告</value></data>@@ -1666,12 +1648,6 @@<data name="Optimizer.Performance.DisableAccessibilityKeyboardHotkeys.ShortDescription" xml:space="preserve"><value>停用黏滞鍵、篩選鍵和切換鍵的鍵盤快速鍵,以防止遊戲和打字時意外彈出視窗。</value></data>- <data name="Optimizer.PowerManagement.DisableFastStartup.Name" xml:space="preserve">- <value>停用快速啟動</value>- </data>- <data name="Optimizer.PowerManagement.DisableFastStartup.ShortDescription" xml:space="preserve">- <value>關閉快速啟動以確保完全關機,並在開機時有更乾淨的硬體初始化。</value>- </data><data name="StartupManager.Apps.CountSuffix" xml:space="preserve"><value>{0} 個項目</value></data>@@ -1756,4 +1732,10 @@<data name="Features.SystemFeatures.NumLockOnBoot.Recommendation.Reason" xml:space="preserve"><value>開機時啟用 NumLock 可確保登入後數字鍵盤立即就緒,避免每次都要手動切換。</value></data>+ <data name="Features.SystemFeatures.Section.Services" xml:space="preserve">+ <value>系統服務</value>+ </data>+ <data name="Features.SystemFeatures.Section.Power" xml:space="preserve">+ <value>電源設定</value>+ </data></root>\ No newline at end of filediff --git a/optimizerDuck/Services/Features/StartupManager/StartupManagerService.cs b/optimizerDuck/Services/Features/StartupManager/StartupManagerService.csindex bf32592..b822823 100644--- a/optimizerDuck/Services/Features/StartupManager/StartupManagerService.cs+++ b/optimizerDuck/Services/Features/StartupManager/StartupManagerService.cs@@ -1,4 +1,4 @@-using System.Diagnostics;+using System.Diagnostics;using System.Drawing;using System.IO;using System.Windows;@@ -78,6 +78,8 @@ public class StartupManagerService(ILogger<StartupManagerService> logger));});+ logger.LogInformation("Retrieved {Count} startup apps", apps.Count);+return apps.OrderBy(a => a.Name).ToList();}diff --git a/optimizerDuck/Services/Optimization/OptimizationRegistry.cs b/optimizerDuck/Services/Optimization/OptimizationRegistry.csindex c4c6997..757fff4 100644--- a/optimizerDuck/Services/Optimization/OptimizationRegistry.cs+++ b/optimizerDuck/Services/Optimization/OptimizationRegistry.cs@@ -16,44 +16,45 @@ public class OptimizationRegistry(ILoggerFactory loggerFactory){// Run reflection work on background thread to avoid blocking startupvar optimizationCategories = await Task.Run(() =>- ReflectionHelper- .FindImplementationsInLoadedAssemblies<IOptimizationCategory>()- .Select(t =>- {- var optimizations = new ObservableCollection<IOptimization>(- t.GetNestedTypes(BindingFlags.Public)- .Where(nt => typeof(IOptimization).IsAssignableFrom(nt))- .Select(nt =>- {- var opt = (IOptimization)Activator.CreateInstance(nt)!;+ ReflectionHelper+ .FindImplementationsInLoadedAssemblies<IOptimizationCategory>()+ .Select(t =>+ {+ var optimizations = new ObservableCollection<IOptimization>(+ t.GetNestedTypes(BindingFlags.Public)+ .Where(nt => typeof(IOptimization).IsAssignableFrom(nt))+ .Select(nt =>+ {+ var opt = (IOptimization)Activator.CreateInstance(nt)!;- if (opt is BaseOptimization bo)- bo.OwnerType = t;+ if (opt is BaseOptimization bo)+ bo.OwnerType = t;- return opt;- })- .ToList()- );+ return opt;+ })+ .ToList()+ );- if (optimizations.Count == 0)- return null;+ if (optimizations.Count == 0)+ return null;- var instance = (IOptimizationCategory)Activator.CreateInstance(t)!;+ var instance = (IOptimizationCategory)Activator.CreateInstance(t)!;- var optProp = t.GetProperty(- nameof(IOptimizationCategory.Optimizations),- BindingFlags.Public | BindingFlags.Instance- );- if (optProp != null && optProp.CanWrite)- optProp.SetValue(instance, optimizations);+ var optProp = t.GetProperty(+ nameof(IOptimizationCategory.Optimizations),+ BindingFlags.Public | BindingFlags.Instance+ );+ if (optProp != null && optProp.CanWrite)+ optProp.SetValue(instance, optimizations);- return instance;- })- .Where(c => c != null) // skip nulls- .Cast<IOptimizationCategory>()- .OrderBy(c => c.Order)- .ToArray()- ).ConfigureAwait(false);+ return instance;+ })+ .Where(c => c != null) // skip nulls+ .Cast<IOptimizationCategory>()+ .OrderBy(c => c.Order)+ .ToArray()+ )+ .ConfigureAwait(false);_logger.LogInformation("Total {CategoryCount} categories and {OptimizationCount} optimizations found",@@ -61,9 +62,9 @@ public class OptimizationRegistry(ILoggerFactory loggerFactory)optimizationCategories.Sum(c => c.Optimizations.Count));- await OptimizationService.UpdateOptimizationStateAsync(- optimizationCategories.SelectMany(c => c.Optimizations)- ).ConfigureAwait(false);+ await OptimizationService+ .UpdateOptimizationStateAsync(optimizationCategories.SelectMany(c => c.Optimizations))+ .ConfigureAwait(false);OptimizationCategories = optimizationCategories;}diff --git a/optimizerDuck/Services/Optimization/OptimizationService.cs b/optimizerDuck/Services/Optimization/OptimizationService.csindex 44ce312..cc6473c 100644--- a/optimizerDuck/Services/Optimization/OptimizationService.cs+++ b/optimizerDuck/Services/Optimization/OptimizationService.cs@@ -50,16 +50,15 @@ public class OptimizationService(new ProcessingProgress{Message = Translations.RestorePoint_Progress_Creating,- IsIndeterminate = true+ IsIndeterminate = true,});using var scope = ExecutionScope.BeginForLogging(_logger);- var result = await ShellService- .PowerShellAsync(- $"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS"- );+ var result = await ShellService.PowerShellAsync(+ $"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS"+ );if (result.Stderr.Contains(@@ -96,8 +95,9 @@ public class OptimizationService(});- var enableResult = await ShellService- .PowerShellAsync("Enable-ComputerRestore -Drive \"$env:SystemDrive\"");+ var enableResult = await ShellService.PowerShellAsync(+ "Enable-ComputerRestore -Drive \"$env:SystemDrive\""+ );if (enableResult.ExitCode != 0){_logger.LogError(@@ -115,10 +115,9 @@ public class OptimizationService(});- result = await ShellService- .PowerShellAsync(- $"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS"- );+ result = await ShellService.PowerShellAsync(+ $"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS"+ );if (result.Stderr.Contains(@@ -154,16 +153,15 @@ public class OptimizationService(try{- var applyResult = await optimization- .ApplyAsync(- progress,- new OptimizationContext- {- Logger = optLogger,- Snapshot = systemInfoService.Snapshot,- StreamService = streamService,- }- );+ var applyResult = await optimization.ApplyAsync(+ progress,+ new OptimizationContext+ {+ Logger = optLogger,+ Snapshot = systemInfoService.Snapshot,+ StreamService = streamService,+ }+ );if (!string.IsNullOrWhiteSpace(applyResult.ErrorMessage))return new OptimizationResult@@ -242,13 +240,13 @@ public class OptimizationService(if (optimizations.Length == 0)return;- // Optimization: List all files in revert directory once instead of checking File.Exists for eachvar revertFiles = await Task.Run(() =>{if (!Directory.Exists(Shared.RevertDirectory))return new HashSet<string>();- return Directory.GetFiles(Shared.RevertDirectory, "*.json")+ return Directory+ .GetFiles(Shared.RevertDirectory, "*.json").Select(Path.GetFileNameWithoutExtension).Where(f => f != null).ToHashSet(StringComparer.OrdinalIgnoreCase)!;@@ -362,37 +360,49 @@ public class OptimizationService(if (success){var retriedStep = retryScope.SuccessfulSteps.LastOrDefault();- var recoveredStep = retriedStep == null- ? step with { Error = null }- : new OperationStepResult- {- Index = step.Index,- Name = retriedStep.Name,- Description = retriedStep.Description,- Success = true,- Error = null,- RetryAction = null,- RevertStep = retriedStep.RevertStep,- };-+ var recoveredStep =+ retriedStep == null+ ? step with+ {+ Error = null,+ }+ : new OperationStepResult+ {+ Index = step.Index,+ Name = retriedStep.Name,+ Description = retriedStep.Description,+ Success = true,+ Error = null,+ RetryAction = null,+ RevertStep = retriedStep.RevertStep,+ };+// Auto-persist recovered revert step if revertManager is available- if (retriedStep?.RevertStep != null && revertManager != null && optimizationId.HasValue)+ if (+ retriedStep?.RevertStep != null+ && revertManager != null+ && optimizationId.HasValue+ ){try{await revertManager.UpsertRevertStepAtIndexAsync(optimizationId.Value,optimizationKey ?? string.Empty,- step.Index, // Use original failed step's index+ step.Index, // Use original failed step's indexretriedStep.RevertStep);}catch (Exception ex){- logger.LogError(ex, "Failed to auto-persist revert step at index {Index}", step.Index);+ logger.LogError(+ ex,+ "Failed to auto-persist revert step at index {Index}",+ step.Index+ );}}-+recoveredSteps.Add(recoveredStep);}}@@ -430,11 +440,11 @@ public class OptimizationService(}}- public static void ClearResources(ILogger logger)+ public static void ClearDownloads(ILogger logger){- if (!Directory.Exists(Shared.ResourcesDirectory))+ if (!Directory.Exists(Shared.DownloadsDirectory))return;- foreach (var f in Directory.GetFiles(Shared.ResourcesDirectory))+ foreach (var f in Directory.GetFiles(Shared.DownloadsDirectory))try{File.Delete(f);diff --git a/optimizerDuck/Services/Optimization/Providers/RegistryService.cs b/optimizerDuck/Services/Optimization/Providers/RegistryService.csindex 08d7847..ba86ca8 100644--- a/optimizerDuck/Services/Optimization/Providers/RegistryService.cs+++ b/optimizerDuck/Services/Optimization/Providers/RegistryService.cs@@ -680,8 +680,9 @@ public static class RegistryServiceint i => (T)(object)(i != 0),long l => (T)(object)(l != 0),string s when bool.TryParse(s, out var b) => (T)(object)b,- string s when s.Equals("1") || s.Equals("yes", StringComparison.OrdinalIgnoreCase) =>- (T)(object)true,+ string s+ when s.Equals("1") || s.Equals("yes", StringComparison.OrdinalIgnoreCase) => (T)+ (object)true,string s when s.Equals("0") || s.Equals("no", StringComparison.OrdinalIgnoreCase) =>(T)(object)false,_ => default,diff --git a/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs b/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.csindex 9945065..09ea4a9 100644--- a/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs+++ b/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs@@ -1,4 +1,4 @@-using System.Diagnostics;+using System.Diagnostics;using System.Management;using optimizerDuck.Common.Extensions;using optimizerDuck.Domain.Execution;@@ -15,7 +15,7 @@ public static class ServiceProcessService/// <summary>/// Get current startup type of a service/// </summary>- private static ServiceStartupType? GetStartupType(string serviceName)+ public static ServiceStartupType? GetStartupType(string serviceName){try{diff --git a/optimizerDuck/Services/Optimization/Providers/ShellService.cs b/optimizerDuck/Services/Optimization/Providers/ShellService.csindex 0dd7555..c0d1f33 100644--- a/optimizerDuck/Services/Optimization/Providers/ShellService.cs+++ b/optimizerDuck/Services/Optimization/Providers/ShellService.cs@@ -349,7 +349,10 @@ public static class ShellServicecatch (OperationCanceledException){// Process timed out, attempt cleanup- ExecutionScope.LogWarning("Process timed out, attempting to kill: PID {ProcessId}", process.Id);+ ExecutionScope.LogWarning(+ "Process timed out, attempting to kill: PID {ProcessId}",+ process.Id+ );try{@@ -361,7 +364,11 @@ public static class ShellService}catch (Exception ex){- ExecutionScope.LogError(ex, "Failed to kill process for timeout (async), PID: {ProcessId}", process.Id);+ ExecutionScope.LogError(+ ex,+ "Failed to kill process for timeout (async), PID: {ProcessId}",+ process.Id+ );}}@@ -373,7 +380,10 @@ public static class ShellService// Process still running after kill attempt, wait for grace periodtry{- ExecutionScope.LogWarning("Process still running after kill, waiting for grace period: PID {ProcessId}", process.Id);+ ExecutionScope.LogWarning(+ "Process still running after kill, waiting for grace period: PID {ProcessId}",+ process.Id+ );process.WaitForExit(ProcessGraceDrainMs);}catch (Exception ex)@@ -390,13 +400,19 @@ public static class ShellService{try{- ExecutionScope.LogWarning("Process still running after grace period, force killing: PID {ProcessId}", process.Id);+ ExecutionScope.LogWarning(+ "Process still running after grace period, force killing: PID {ProcessId}",+ process.Id+ );process.Kill(entireProcessTree: true);// Wait up to 5 seconds for force killif (!process.WaitForExit(5000)){- ExecutionScope.LogWarning("Process did not exit after force kill: PID {ProcessId}. User may need manual cleanup.", process.Id);+ ExecutionScope.LogWarning(+ "Process did not exit after force kill: PID {ProcessId}. User may need manual cleanup.",+ process.Id+ );}}catch (Exception ex)@@ -544,6 +560,15 @@ public static class ShellService/// <param name="policy">The policy to use for determining success.</param>/// <param name="ct">The cancellation token.</param>/// <returns>The result of the command execution.</returns>+ public static Task<ShellResult> CMDAsync(+ string command,+ string revertCommand,+ ShellPolicy? policy = null,+ CancellationToken ct = default+ )+ {+ return RunAsync("cmd.exe", "/c", command, nameof(CMD), new ShellRevertStep { ShellType = ShellType.CMD, Command = revertCommand }, policy, ct);+ }public static Task<ShellResult> CMDAsync(string command,ShellRevertStep? revertStep = null,@@ -554,6 +579,16 @@ public static class ShellServicereturn RunAsync("cmd.exe", "/c", command, nameof(CMD), revertStep, policy, ct);}+ public static Task<ShellResult> CMDAsync(+ string command,+ Func<string> revertCommand,+ ShellPolicy? policy = null,+ CancellationToken ct = default+ )+ {+ return RunAsync("cmd.exe", "/c", command, nameof(CMD), new ShellRevertStep { ShellType = ShellType.CMD, Command = revertCommand() }, policy, ct);+ }+/// <summary>/// Runs a command in the Command Prompt (cmd.exe) with a specific revert command./// </summary>@@ -653,6 +688,52 @@ public static class ShellService);}+ public static Task<ShellResult> PowerShellAsync(+ string command,+ string revertCommand,+ ShellPolicy? policy = null,+ CancellationToken ct = default+ )+ {+ command =+ "$ProgressPreference='SilentlyContinue'; "+ + "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "+ + "$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8; "+ + command;+ return RunAsync(+ "powershell.exe",+ "-NonInteractive -NoLogo -NoProfile -ExecutionPolicy Bypass -EncodedCommand",+ command.EncodeBase64(),+ nameof(PowerShell),+ new ShellRevertStep { ShellType = ShellType.PowerShell, Command = revertCommand },+ policy,+ ct+ );+ }++ public static Task<ShellResult> PowerShellAsync(+ string command,+ Func<string> revertFunction,+ ShellPolicy? policy = null,+ CancellationToken ct = default+ )+ {+ command =+ "$ProgressPreference='SilentlyContinue'; "+ + "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "+ + "$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8; "+ + command;+ return RunAsync(+ "powershell.exe",+ "-NonInteractive -NoLogo -NoProfile -ExecutionPolicy Bypass -EncodedCommand",+ command.EncodeBase64(),+ nameof(PowerShell),+ new ShellRevertStep { ShellType = ShellType.PowerShell, Command = revertFunction() },+ policy,+ ct+ );+ }+/// <summary>/// Runs a command in PowerShell with a specific revert command./// </summary>diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.csindex 0745dbf..27fb382 100644--- a/optimizerDuck/Services/Revert/RevertManager.cs+++ b/optimizerDuck/Services/Revert/RevertManager.cs@@ -14,7 +14,7 @@ using optimizerDuck.Resources.Languages;namespace optimizerDuck.Services.Managers;-public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFactory)+public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _loggerFactory){private static readonly Lazy<Dictionary<string, Func<JObject, IRevertStep>>> _stepRegistry =new(BuildStepRegistry);@@ -23,8 +23,8 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFpublic async Task SaveRevertDataAsync(ExecutionScope scope){- var successfulSteps = scope.ExecutedSteps- .Where(s => s.Success && s.RevertStep != null)+ var successfulSteps = scope+ .ExecutedSteps.Where(s => s.Success && s.RevertStep != null).ToList();if (successfulSteps.Count == 0)@@ -39,7 +39,7 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFsteps[arrayIndex] = new RevertStepData{Index = executedStep.Index,- Type = executedStep.RevertStep.Type,+ Type = executedStep.RevertStep!.Type,Data = executedStep.RevertStep.ToData(),};}@@ -61,7 +61,7 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFIProgress<ProcessingProgress>? progress = null){- var operationLogger = loggerFactory.CreateLogger<RevertManager>();+ var operationLogger = _loggerFactory.CreateLogger<RevertManager>();using var scope = ExecutionScope.BeginForLogging(optimization.Id,optimization.OptimizationKey,@@ -90,7 +90,7 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerF{Message = string.Format(Translations.Optimization_Revert_ExecutingStep,- idx,+ idx - 1,total,step.Type),@@ -193,6 +193,8 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerF}}+ #region Helpers+public static Task<bool> IsAppliedAsync(Guid id){return Task.FromResult(File.Exists(GetFilePath(id)));@@ -218,8 +220,6 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerF}}- #region Helpers-private static string GetFilePath(Guid id){return Path.Combine(Shared.RevertDirectory, $"{id}.json");@@ -231,9 +231,7 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFreturn null;try{- return JsonConvert.DeserializeObject<RevertData>(- await File.ReadAllTextAsync(path)- );+ return JsonConvert.DeserializeObject<RevertData>(await File.ReadAllTextAsync(path));}catch{@@ -246,14 +244,24 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFRemove(id, name);}- private static async Task WriteJsonAsync(string path, RevertData data)+ private async Task WriteJsonAsync(string path, RevertData data){Directory.CreateDirectory(Path.GetDirectoryName(path)!);-+var json = JsonConvert.SerializeObject(data, Formatting.Indented);- await using var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true);+ await using var fileStream = new FileStream(+ path,+ FileMode.Create,+ FileAccess.Write,+ FileShare.None,+ bufferSize: 4096,+ useAsync: true+ );await using var writer = new StreamWriter(fileStream);await writer.WriteAsync(json);++ var totalOperations = data.Steps.Count(s => s != null);+ _logger.LogInformation("Saved {Total} operations to {Path}", totalOperations, path);}private async Task<List<(int Index, IRevertStep Step)>> LoadStepsAsync(Guid id)@@ -266,14 +274,18 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFvar seenIndexes = new HashSet<int>();foreach (var step in data.Steps.Where(s => s != null)){- if (step.Index <= 0)+ if (step!.Index <= 0){- logger.LogWarning("Invalid index {Index} in revert data for {Id}", step.Index, id);+ _logger.LogWarning("Invalid index {Index} in revert data for {Id}", step.Index, id);return [];}if (!seenIndexes.Add(step.Index)){- logger.LogWarning("Duplicate index {Index} in revert data for {Id}", step.Index, id);+ _logger.LogWarning(+ "Duplicate index {Index} in revert data for {Id}",+ step.Index,+ id+ );return [];}}@@ -281,9 +293,9 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFvar result = new List<(int, IRevertStep)>();foreach (var stepData in data.Steps.Where(s => s != null)){- var step = DeserializeStep(stepData.Type, stepData.Data);+ var step = DeserializeStep(stepData!.Type, stepData.Data);if (step != null)- result.Add((stepData.Index, step)); // Use explicit Index+ result.Add((stepData.Index, step)); // Use explicit Index}return result.OrderBy(x => x.Item1).ToList();@@ -297,12 +309,12 @@ public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFif (File.Exists(path)){File.Delete(path);- logger.LogInformation("Removed revert data for {Name}", name ?? id.ToString());+ _logger.LogInformation("Removed revert data for {Name}", name ?? id.ToString());}}catch (Exception ex){- logger.LogError(ex, "Failed to remove revert data for {Id}", id);+ _logger.LogError(ex, "Failed to remove revert data for {Id}", id);}}diff --git a/optimizerDuck/Services/System/StreamService.cs b/optimizerDuck/Services/System/StreamService.csindex 79380d0..3514de9 100644--- a/optimizerDuck/Services/System/StreamService.cs+++ b/optimizerDuck/Services/System/StreamService.cs@@ -1,4 +1,4 @@-using System.IO;+using System.IO;using System.Net.Http;using Microsoft.Extensions.Logging;using optimizerDuck.Common.Helpers;@@ -14,13 +14,13 @@ public class StreamService(ILogger<StreamService> logger)string fileName){- var filePath = Path.Combine(Shared.ResourcesDirectory, fileName);+ var filePath = Path.Combine(Shared.DownloadsDirectory, fileName);logger.LogInformation("Starting download from {Url} to {FilePath}", url, filePath);try{- Directory.CreateDirectory(Shared.ResourcesDirectory);+ Directory.CreateDirectory(Shared.DownloadsDirectory);_client ??= new HttpClient();using var response = await _client.GetAsync(url).ConfigureAwait(false);diff --git a/optimizerDuck/UI/Pages/SettingsPage.xaml b/optimizerDuck/UI/Pages/SettingsPage.xamlindex 9dc5078..18545f0 100644--- a/optimizerDuck/UI/Pages/SettingsPage.xaml+++ b/optimizerDuck/UI/Pages/SettingsPage.xaml@@ -159,7 +159,7 @@<ui:CardActionMargin="0,0,0,4"Padding="16,14"- Command="{Binding ViewModel.ClearResourcesCommand}"+ Command="{Binding ViewModel.ClearDownloadsCommand}"Cursor="Hand"><ui:CardAction.Icon><ui:SymbolIcon Foreground="{DynamicResource SystemFillColorCriticalBrush}" Symbol="Archive24" />@@ -168,11 +168,11 @@<ui:TextBlockMargin="0"FontTypography="BodyStrong"- Text="{ext:Loc Settings.Advanced.ClearResources.Title}"+ Text="{ext:Loc Settings.Advanced.ClearDownloads.Title}"TextWrapping="Wrap" /><ui:TextBlockForeground="{DynamicResource TextFillColorSecondaryBrush}"- Text="{ext:Loc Settings.Advanced.ClearResources.Description}"+ Text="{ext:Loc Settings.Advanced.ClearDownloads.Description}"TextWrapping="Wrap" /></StackPanel></ui:CardAction>diff --git a/optimizerDuck/UI/ViewModels/Features/FeatureViewModel.cs b/optimizerDuck/UI/ViewModels/Features/FeatureViewModel.csindex 66395f1..7606fd8 100644--- a/optimizerDuck/UI/ViewModels/Features/FeatureViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Features/FeatureViewModel.cs@@ -60,9 +60,7 @@ public partial class FeatureViewModel(IFeature feature, ILoggerFactory loggerFac};public string? RecommendationReason =>- Recommendation != null- ? Loc.Instance[Recommendation.ReasonTranslationKey]- : null;+ Recommendation != null ? Loc.Instance[Recommendation.ReasonTranslationKey] : null;public async Task LoadStateAsync(){diff --git a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.csindex 28fe6ec..2eacf5b 100644--- a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs@@ -189,6 +189,7 @@ public partial class OptimizationCategoryViewModel : ViewModel);await OptimizationService.UpdateOptimizationStateAsync(optimization);+ OnPropertyChanged(nameof(HasAppliedOptimizations));return;}@@ -201,7 +202,11 @@ public partial class OptimizationCategoryViewModel : ViewModelOptimizationOperation.Apply);+ // Explicitly update state after all operations completeawait OptimizationService.UpdateOptimizationStateAsync(optimization);++ // Ensure UI reflects the correct state+ OnPropertyChanged(nameof(HasAppliedOptimizations));var notificationState = ResolveApplyNotificationState(applyResult,@@ -255,7 +260,12 @@ public partial class OptimizationCategoryViewModel : ViewModelrevertResult.FailedSteps,OptimizationOperation.Revert);++ // Explicitly update state after revert completesawait OptimizationService.UpdateOptimizationStateAsync(optimization);++ // Ensure UI reflects the correct state+ OnPropertyChanged(nameof(HasAppliedOptimizations));var notificationState = ResolveRevertNotificationState(revertResult,@@ -722,14 +732,21 @@ public partial class OptimizationCategoryViewModel : ViewModel};var result = await _contentDialogService.ShowAsync(dialog, CancellationToken.None);- if (result == ContentDialogResult.None) // User cancelled+ if (result == ContentDialogResult.None)+ { // User cancelled+ _logger.LogInformation("User cancelled the restore point dialog");return (false, false);+ }- if (result == ContentDialogResult.Secondary) // User skipped+ if (result == ContentDialogResult.Secondary)+ { // User skipped+ _logger.LogInformation("User chose to skip creating a restore point");return (true, false);+ }try{+ _logger.LogInformation("User accepted to create a restore point, starting creation");var resultState = await _optimizationService.CreateRestorePointAsync();switch (resultState)@@ -745,11 +762,16 @@ public partial class OptimizationCategoryViewModel : ViewModelShared.RestorePointName),ControlAppearance.Success,- new SymbolIcon { Symbol = SymbolRegular.CheckmarkCircle24, Filled = true },+ new SymbolIcon+ {+ Symbol = SymbolRegular.CheckmarkCircle24,+ Filled = true,+ },TimeSpan.FromSeconds(5));break;}+ _logger.LogInformation("Successfully created restore point");return (true, true);@@ -761,6 +783,7 @@ public partial class OptimizationCategoryViewModel : ViewModelnew SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },TimeSpan.FromSeconds(5));+ _logger.LogWarning("Restore point creation frequency limit reached");break;case RestorePointResult.Failed:@@ -772,6 +795,7 @@ public partial class OptimizationCategoryViewModel : ViewModelnew SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },TimeSpan.FromSeconds(5));+ _logger.LogError("Failed to create restore point");break;}@@ -796,19 +820,17 @@ public partial class OptimizationCategoryViewModel : ViewModelreturn (true, false);return (false, false);-}-catch (Exception e){_logger.LogError(e, "Failed to create restore point");_snackbarService.Show(- Translations.RestorePoint_Snackbar_Error_Title,- Translations.RestorePoint_Snackbar_Error_Message,- ControlAppearance.Caution,- new SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },- TimeSpan.FromSeconds(5)- );+ Translations.RestorePoint_Snackbar_Error_Title,+ Translations.RestorePoint_Snackbar_Error_Message,+ ControlAppearance.Caution,+ new SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },+ TimeSpan.FromSeconds(5)+ );}return (true, false);diff --git a/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.csindex ade956b..8ebe651 100644--- a/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs@@ -1,4 +1,4 @@-using System.Collections.ObjectModel;+using System.Collections.ObjectModel;using System.ComponentModel;using System.Diagnostics;using CommunityToolkit.Mvvm.ComponentModel;@@ -320,6 +320,7 @@ public partial class ScheduledTasksViewModel : ViewModel{var tasks = await Task.Run(() => ScheduledTaskService.GetAllTasks());_allTasks.AddRange(tasks);+ _logger.LogInformation("Loaded {Count} scheduled tasks", _allTasks.Count);ApplyFilter();}catch (Exception ex)diff --git a/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.csindex 129e507..0a2732a 100644--- a/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs@@ -159,13 +159,13 @@ public partial class SettingsViewModel(}[RelayCommand]- private async Task ClearResources()+ private async Task ClearDownloads(){var result = await ConfirmationDialogAsync(- Translations.Settings_ClearResources_Description+ Translations.Settings_ClearDownloads_Description);if (result == ContentDialogResult.Primary)- OptimizationService.ClearResources(logger);+ OptimizationService.ClearDownloads(logger);}[RelayCommand]diff --git a/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.csindex a57acf9..d97ee82 100644--- a/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs@@ -292,8 +292,7 @@ public partial class StartupManagerViewModel : ViewModel{try{- await _startupManagerService- .ToggleStartupApp(app, app.IsEnabled);+ await _startupManagerService.ToggleStartupApp(app, app.IsEnabled);}catch (Exception ex){@@ -308,8 +307,7 @@ public partial class StartupManagerViewModel : ViewModel{try{- await _startupManagerService- .ToggleStartupTask(task, task.IsEnabled);+ await _startupManagerService.ToggleStartupTask(task, task.IsEnabled);}catch (Exception ex){diff --git a/optimizerDuck/optimizerDuck.csproj b/optimizerDuck/optimizerDuck.csprojindex bc8fe74..cab854d 100644--- a/optimizerDuck/optimizerDuck.csproj+++ b/optimizerDuck/optimizerDuck.csproj@@ -9,8 +9,8 @@<Authors>fatDuck</Authors><ApplicationIcon>Logo.ico</ApplicationIcon><Company>fatDuck</Company>- <FileVersion>2.12.0</FileVersion>- <Version>2.12.0</Version>+ <FileVersion>2.13.3</FileVersion>+ <Version>2.13.3</Version><Product>optimizerDuck</Product><Copyright>Copyright fatDuck 2026</Copyright><AssemblyTitle>optimizerDuck</AssemblyTitle>@@ -62,6 +62,10 @@</EmbeddedResource></ItemGroup>+ <ItemGroup>+ <EmbeddedResource Include="Resources\Embedded\Icons\blank.ico" />+ </ItemGroup>+<ItemGroup><Resource Include="Resources\Images\Duck.png" /><Resource Include="Resources\Images\GitHubLogoBlack.png" />