Skip to content

Free, open-source Windows optimization tool for performance, privacy, and simplicity.

feat: rewrite fully core optimization

itsfatduckf38951cdce8e
diff --git a/README.md b/README.md
index bc7a1c5..ea5c8fe 100644
--- a/README.md
+++ b/README.md
@@ -12,6 +12,7 @@
[![License](https://img.shields.io/badge/License-GPL_v3-red)](./LICENSE)
[![Discord](https://img.shields.io/discord/1091675679994675240?color=5865f2&label=Discord)](https://discord.gg/tDUBDCYw9Q)
<br>
+[![CI](https://github.com/itsfatduck/optimizerDuck/actions/workflows/ci.yml/badge.svg)](https://github.com/itsfatduck/optimizerDuck/actions/workflows/ci.yml)
[![.NET Latest](https://img.shields.io/badge/.NET_Runtime-Latest-ef99dd)](https://dotnet.microsoft.com/en-us/download)
[![Supported OS](https://img.shields.io/badge/Supported-Windows_10+_x64-0078d4)](https://www.microsoft.com/en-us/software-download/)
diff --git a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
index d5fd174..b48cfdc 100644
--- a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
+++ b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
@@ -1,8 +1,12 @@
using Microsoft.Extensions.Logging.Abstractions;
using Newtonsoft.Json;
using optimizerDuck.Common.Helpers;
+using optimizerDuck.Core.Interfaces;
+using optimizerDuck.Core.Models.Optimization;
using optimizerDuck.Core.Models.Revert;
using optimizerDuck.Core.Models.Revert.Steps;
+using optimizerDuck.Core.Models.UI;
+using optimizerDuck.Core.Optimizers;
using optimizerDuck.Services.Managers;
namespace optimizerDuck.Test.Services.Managers;
@@ -65,7 +69,8 @@ public class RevertManagerTests
await File.WriteAllTextAsync(path, "{ invalid json }");
var manager = new RevertManager(NullLogger<RevertManager>.Instance);
- var result = await manager.RevertAsync(id, "TestOptimization");
+ var op = new MockOptimization(id);
+ var result = await manager.RevertAsync(op);
Assert.False(result.Success);
}
@@ -77,7 +82,7 @@ public class RevertManagerTests
}
[Fact]
- public async Task RevertAsync_WithPartialStepFailures_ReturnsFailure_And_KeepsFile()
+ public async Task RevertAsync_WithPartialStepFailures_ReturnsFailure_And_DeletesFile()
{
var id = Guid.NewGuid();
var path = Path.Combine(Shared.RevertDirectory, id + ".json");
@@ -117,10 +122,10 @@ public class RevertManagerTests
await File.WriteAllTextAsync(path, json);
var manager = new RevertManager(NullLogger<RevertManager>.Instance);
- var result = await manager.RevertAsync(id, "TestOptimization");
+ var result = await manager.RevertAsync(new MockOptimization(id));
Assert.False(result.Success);
- Assert.True(File.Exists(path));
+ Assert.False(File.Exists(path));
}
finally
{
@@ -128,4 +133,19 @@ public class RevertManagerTests
File.Delete(path);
}
}
+}
+
+public class MockOptimization(Guid id) : IOptimization
+{
+ public Guid Id { get; } = id;
+ public OptimizationRisk Risk => OptimizationRisk.Safe;
+ public string OptimizationKey => "TestOptimization";
+ public string Name => "TestOptimization";
+ public string ShortDescription => "Mock description";
+ public OptimizationState State { get; set; } = new();
+
+ public Task<ApplyResult> ApplyAsync(IProgress<ProcessingProgress> progress, OptimizationContext context)
+ {
+ return Task.FromResult(ApplyResult.True());
+ }
}
\ No newline at end of file
diff --git a/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs b/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
index 96005b5..9813044 100644
--- a/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging.Abstractions;
+using Newtonsoft.Json.Linq;
using optimizerDuck.Core.Interfaces;
using optimizerDuck.Core.Models.Execution;
using optimizerDuck.Core.Models.Optimization;
@@ -14,7 +15,7 @@ public class ExecutionScopeTests
{
var logger = NullLogger.Instance;
- using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+ using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
ExecutionScope.RecordStep("TestStep", "Test description", true);
@@ -28,7 +29,7 @@ public class ExecutionScopeTests
{
var logger = NullLogger.Instance;
- using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+ using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
ExecutionScope.RecordStep("TestStep", "Test description", false, error: "Test error");
@@ -44,7 +45,7 @@ public class ExecutionScopeTests
var logger = NullLogger.Instance;
var revertStep = new MockRevertStep();
- using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+ using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
ExecutionScope.RecordStep("TestStep", "Test description", true, revertStep);
@@ -57,7 +58,7 @@ public class ExecutionScopeTests
{
var logger = NullLogger.Instance;
- using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+ using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
ExecutionScope.RecordStep("SuccessStep1", "Description", true);
ExecutionScope.RecordStep("FailedStep", "Description", false, error: "Error");
@@ -74,7 +75,7 @@ public class ExecutionScopeTests
{
var logger = NullLogger.Instance;
- using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+ using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
ExecutionScope.RecordStep("Step1", "Description", true);
ExecutionScope.RecordStep("Step2", "Description", true);
@@ -90,7 +91,7 @@ public class ExecutionScopeTests
{
var logger = NullLogger.Instance;
- var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+ var scope = ExecutionScope.Begin(new MockOptimization(), logger);
ExecutionScope.RecordStep("Success", "Description", true);
ExecutionScope.RecordStep("Fail", "Description", false);
@@ -121,10 +122,10 @@ public class ExecutionScopeTests
{
var logger = NullLogger.Instance;
- using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+ using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
Assert.Throws<InvalidOperationException>(() =>
- ExecutionScope.Begin(Guid.NewGuid(), "Another", logger));
+ ExecutionScope.Begin(new MockOptimization(), logger));
}
[Fact]
@@ -140,7 +141,7 @@ public class ExecutionScopeTests
{
var logger = NullLogger.Instance;
- using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+ using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
ExecutionScope.Track("Registry", true);
ExecutionScope.Track("Registry", true);
@@ -155,7 +156,7 @@ public class ExecutionScopeTests
{
var logger = NullLogger.Instance;
- using var scope = ExecutionScope.Begin(Guid.NewGuid(), "TestOptimization", logger);
+ using var scope = ExecutionScope.Begin(new MockOptimization(), logger);
ExecutionScope.RecordStep("Step1", "Desc1", true);
ExecutionScope.RecordStep("Step2", "Desc2", false, error: "err");
@@ -187,6 +188,20 @@ public class MockOptimization : IOptimization
public class MockRevertStep : IRevertStep
{
public string Type => "Mock";
- public Task<bool> ExecuteAsync() => Task.FromResult(true);
- public Newtonsoft.Json.Linq.JObject ToData() => new();
-}
+ public string Description => "Mock Description";
+
+ public static MockRevertStep FromData(JObject data)
+ {
+ return new MockRevertStep();
+ }
+
+ public Task<bool> ExecuteAsync()
+ {
+ return Task.FromResult(true);
+ }
+
+ public JObject ToData()
+ {
+ return new JObject();
+ }
+}
\ No newline at end of file
diff --git a/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
index 52312e2..52ec2cf 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
@@ -6,7 +6,7 @@ namespace optimizerDuck.Test.Services.OptimizationServices;
public class ServiceProcessServiceTests
{
[Fact]
- public void ChangeServiceStartupType_WithMissingService_ReturnsFalse()
+ public void ChangeServiceStartupType_WithMissingService_ReturnsTrue()
{
var item = new ServiceItem
{
@@ -16,6 +16,6 @@ public class ServiceProcessServiceTests
var result = ServiceProcessService.ChangeServiceStartupType(item);
- Assert.False(result);
+ Assert.True(result);
}
}
\ No newline at end of file
diff --git a/optimizerDuck/App.xaml.cs b/optimizerDuck/App.xaml.cs
index 23efd55..88ec38c 100644
--- a/optimizerDuck/App.xaml.cs
+++ b/optimizerDuck/App.xaml.cs
@@ -106,6 +106,7 @@ public partial class App : Application
protected override async void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
+
try
{
// Create the required directories if they don't exist
diff --git a/optimizerDuck/Core/Interfaces/IRevertStep.cs b/optimizerDuck/Core/Interfaces/IRevertStep.cs
index 1d584dc..8c227c3 100644
--- a/optimizerDuck/Core/Interfaces/IRevertStep.cs
+++ b/optimizerDuck/Core/Interfaces/IRevertStep.cs
@@ -11,6 +11,11 @@ public interface IRevertStep
/// The type identifier for this revert step (e.g., "Registry", "Service", "Shell").
/// </summary>
public string Type { get; }
+
+ /// <summary>
+ /// A localized description of what this revert step does.
+ /// </summary>
+ public string Description { get; }
/// <summary>
/// Executes this revert step asynchronously.
diff --git a/optimizerDuck/Core/Models/Execution/ExecutionScope.cs b/optimizerDuck/Core/Models/Execution/ExecutionScope.cs
index 7d85c48..0a52288 100644
--- a/optimizerDuck/Core/Models/Execution/ExecutionScope.cs
+++ b/optimizerDuck/Core/Models/Execution/ExecutionScope.cs
@@ -4,37 +4,39 @@ using Microsoft.Extensions.Logging;
using optimizerDuck.Core.Interfaces;
using optimizerDuck.Core.Models.Optimization;
using optimizerDuck.Core.Models.UI;
+using optimizerDuck.Resources.Languages;
namespace optimizerDuck.Core.Models.Execution;
public sealed class ExecutionScope : IDisposable
{
private static readonly AsyncLocal<ExecutionScope?> _current = new();
-
- private readonly Guid _optimizationId;
- private readonly string _optimizationKey;
- private readonly ILogger _logger;
- private readonly Stopwatch _stopwatch;
private readonly List<ExecutedStep> _executedSteps = [];
private readonly ConcurrentDictionary<string, Stats> _stats = new();
- private int _stepIndex;
+
+ private readonly Stopwatch _stopwatch;
private bool _disposed;
+ private int _stepIndex;
- private ExecutionScope(Guid optimizationId, string optimizationKey, ILogger logger)
+ private ExecutionScope(Guid optimizationId, string optimizationKey, string optimizationName, ILogger logger, bool loggingOnly = false)
{
- _optimizationId = optimizationId;
- _optimizationKey = optimizationKey;
- _logger = logger;
+ OptimizationId = optimizationId;
+ OptimizationKey = optimizationKey;
+ OptimizationName = optimizationName;
+ Logger = logger;
+ LoggingOnly = loggingOnly;
_stopwatch = Stopwatch.StartNew();
}
public static ExecutionScope? Current => _current.Value;
- public Guid OptimizationId => _optimizationId;
+ public Guid OptimizationId { get; }
+
+ public string OptimizationKey { get; }
- public string OptimizationKey => _optimizationKey;
+ public string OptimizationName { get; }
- public ILogger Logger => _logger;
+ public ILogger Logger { get; }
public IReadOnlyList<ExecutedStep> ExecutedSteps => _executedSteps.AsReadOnly();
@@ -46,14 +48,52 @@ public sealed class ExecutionScope : IDisposable
public bool HasSuccessfulSteps => _executedSteps.Any(s => s.Success);
- public static ExecutionScope Begin(Guid optimizationId, string optimizationKey, ILogger logger)
+ public void Dispose()
+ {
+ if (_disposed)
+ return;
+ _disposed = true;
+
+ _stopwatch.Stop();
+
+ if (_stats.IsEmpty)
+ {
+ Logger.LogInformation(
+ "[{Key}] Completed in {Time} (no operations tracked)",
+ OptimizationKey,
+ _stopwatch.Elapsed.ToString(@"mm\:ss\.fff"));
+ }
+ else
+ {
+ var summary = string.Join(", ", _stats.Select(kv =>
+ $"{kv.Key}: +({kv.Value.Success}) -({kv.Value.Fail})"));
+
+ Logger.LogInformation(
+ "[{Key}] Completed in {Time} | {Summary}",
+ OptimizationKey,
+ _stopwatch.Elapsed.ToString(@"mm\:ss\.fff"),
+ summary);
+ }
+
+ Logger.LogInformation(
+ "[{Key}] Steps: {Total} ({Success} success, {Failed} failed)",
+ OptimizationKey,
+ _executedSteps.Count,
+ SuccessfulSteps.Count,
+ FailedSteps.Count
+ );
+
+ _current.Value = null;
+ }
+
+ public static ExecutionScope Begin(IOptimization optimization, ILogger logger)
{
if (_current.Value != null)
throw new InvalidOperationException("An execution scope is already active in the current context.");
- var scope = new ExecutionScope(optimizationId, optimizationKey, logger);
+ var scope = new ExecutionScope(optimization.Id, optimization.OptimizationKey, optimization.Name, logger);
_current.Value = scope;
- logger.LogDebug("Execution scope started for {Key} (ID: {Id})", optimizationKey, optimizationId);
+ logger.LogDebug("Execution scope started for {Key} (ID: {Id})", optimization.OptimizationKey, optimization.Id);
return scope;
}
@@ -62,12 +102,25 @@ public sealed class ExecutionScope : IDisposable
if (_current.Value != null)
throw new InvalidOperationException("An execution scope is already active in the current context.");
- var scope = new ExecutionScope(Guid.Empty, string.Empty, logger);
+ var scope = new ExecutionScope(Guid.Empty, string.Empty, string.Empty, logger);
_current.Value = scope;
logger.LogDebug("Execution scope started");
return scope;
}
+ public static ExecutionScope BeginForLogging(Guid optimizationId, string optimizationKey, ILogger logger)
+ {
+ if (_current.Value != null)
+ throw new InvalidOperationException("An execution scope is already active in the current context.");
+
+ var scope = new ExecutionScope(optimizationId, optimizationKey, string.Empty, logger, loggingOnly: true);
+ _current.Value = scope;
+ logger.LogDebug("Execution scope started for {Key} (logging only)", optimizationKey);
+ return scope;
+ }
+
+ public bool LoggingOnly { get; private set; }
+
public static ExecutedStep? RecordStep(
string name,
string description,
@@ -77,19 +130,15 @@ public sealed class ExecutionScope : IDisposable
Func<Task<bool>>? retryAction = null)
{
var scope = Current;
- if (scope == null)
- return null;
- return scope.RecordStepInternal(name, description, success, revertStep, error, retryAction);
+ return scope?.RecordStepInternal(name, description, success, revertStep, error, retryAction);
}
public static void Track(string serviceName, bool success)
{
var scope = Current;
- if (scope == null)
- return;
- scope._stats.AddOrUpdate(
+ scope?._stats.AddOrUpdate(
serviceName,
_ => success
? new Stats { Success = 1 }
@@ -111,7 +160,8 @@ public sealed class ExecutionScope : IDisposable
Description = s.Description,
Success = s.Success,
Error = s.Error,
- RetryAction = s.RetryAction
+ RetryAction = s.RetryAction,
+ RevertStep = s.RevertStep
}).ToList();
}
@@ -125,7 +175,8 @@ public sealed class ExecutionScope : IDisposable
Description = s.Description,
Success = s.Success,
Error = s.Error,
- RetryAction = s.RetryAction
+ RetryAction = s.RetryAction,
+ RevertStep = s.RevertStep
}).ToList();
var allFailed = failedSteps.Count == ExecutedSteps.Count;
@@ -137,23 +188,23 @@ public sealed class ExecutionScope : IDisposable
Message = status switch
{
OptimizationSuccessResult.Success =>
- string.Format(optimizerDuck.Resources.Languages.Translations.Optimization_Apply_Success,
- _optimizationKey),
+ string.Format(Translations.Optimization_Apply_Success,
+ OptimizationName),
OptimizationSuccessResult.Failed when allFailed =>
- string.Format(optimizerDuck.Resources.Languages.Translations.Optimization_Apply_Error_Failed,
- _optimizationKey),
+ string.Format(Translations.Optimization_Apply_Error_Failed,
+ OptimizationName),
OptimizationSuccessResult.PartialSuccess or OptimizationSuccessResult.Failed =>
string.Format(
- optimizerDuck.Resources.Languages.Translations.Optimization_Apply_Error_FailedWithSteps,
- _optimizationKey,
+ Translations.Optimization_Apply_Error_FailedWithSteps,
+ OptimizationName,
failedSteps.Count),
- _ => $"Unknown result for {_optimizationKey}"
+ _ => $"Unknown result for {OptimizationName}"
},
FailedSteps = failedSteps
};
}
- private ExecutedStep RecordStepInternal(
+ private ExecutedStep? RecordStepInternal(
string name,
string description,
bool success,
@@ -161,6 +212,9 @@ public sealed class ExecutionScope : IDisposable
string? error,
Func<Task<bool>>? retryAction = null)
{
+ if (LoggingOnly)
+ return null;
+
var step = new ExecutedStep(
++_stepIndex,
name,
@@ -172,17 +226,35 @@ public sealed class ExecutionScope : IDisposable
_executedSteps.Add(step);
- _logger.LogDebug("Step {Index} ({Name}): {Result}",
- step.Index, name, success ? "SUCCESS" : "FAILED");
-
return step;
}
+ private OptimizationSuccessResult ResolveStatus()
+ {
+ if (_executedSteps.Count == 0)
+ return OptimizationSuccessResult.Failed;
+
+ var failed = FailedSteps.Count;
+ var total = ExecutedSteps.Count;
+
+ return failed == 0
+ ? OptimizationSuccessResult.Success
+ : failed < total
+ ? OptimizationSuccessResult.PartialSuccess
+ : OptimizationSuccessResult.Failed;
+ }
+
+ private class Stats
+ {
+ public int Fail;
+ public int Success;
+ }
+
#region Logging
public static void Log(LogLevel level, string message, params object[] args)
{
- Current?._logger.Log(level, message, args);
+ Current?.Logger.Log(level, message, args);
}
public static void LogDebug(string message, params object[] args)
@@ -207,69 +279,10 @@ public sealed class ExecutionScope : IDisposable
public static void LogError(Exception? ex, string message, params object[] args)
{
- Current?._logger.LogError(ex, message, args);
+ Current?.Logger.LogError(ex, message, args);
}
#endregion Logging
-
- private OptimizationSuccessResult ResolveStatus()
- {
- if (_executedSteps.Count == 0)
- return OptimizationSuccessResult.Failed;
-
- var failed = FailedSteps.Count;
- var total = ExecutedSteps.Count;
-
- return failed == 0
- ? OptimizationSuccessResult.Success
- : failed < total
- ? OptimizationSuccessResult.PartialSuccess
- : OptimizationSuccessResult.Failed;
- }
-
- public void Dispose()
- {
- if (_disposed)
- return;
- _disposed = true;
-
- _stopwatch.Stop();
-
- if (_stats.IsEmpty)
- {
- _logger.LogInformation(
- "[{Key}] Completed in {Time} (no operations tracked)",
- _optimizationKey,
- _stopwatch.Elapsed.ToString(@"mm\:ss\.fff"));
- }
- else
- {
- var summary = string.Join(", ", _stats.Select(kv =>
- $"{kv.Key}: +({kv.Value.Success}) -({kv.Value.Fail})"));
-
- _logger.LogInformation(
- "[{Key}] Completed in {Time} | {Summary}",
- _optimizationKey,
- _stopwatch.Elapsed.ToString(@"mm\:ss\.fff"),
- summary);
- }
-
- _logger.LogInformation(
- "[{Key}] Steps: {Total} ({Success} success, {Failed} failed)",
- _optimizationKey,
- _executedSteps.Count,
- _executedSteps.Count(s => s.Success),
- _executedSteps.Count(s => !s.Success)
- );
-
- _current.Value = null;
- }
-
- private class Stats
- {
- public int Success;
- public int Fail;
- }
}
/// <summary>
@@ -277,6 +290,21 @@ public sealed class ExecutionScope : IDisposable
/// </summary>
public sealed record ExecutedStep
{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExecutedStep" /> class.
+ /// </summary>
+ public ExecutedStep(int index, string name, string description, bool success,
+ IRevertStep? revertStep, string? error, Func<Task<bool>>? retryAction = null)
+ {
+ Index = index;
+ Name = name;
+ Description = description;
+ Success = success;
+ RevertStep = revertStep;
+ Error = error;
+ RetryAction = retryAction;
+ }
+
/// <summary>
/// The index of the step in the execution sequence.
/// </summary>
@@ -311,19 +339,4 @@ public sealed record ExecutedStep
/// An optional action to retry this step if it failed.
/// </summary>
public Func<Task<bool>>? RetryAction { get; init; }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ExecutedStep" /> class.
- /// </summary>
- public ExecutedStep(int index, string name, string description, bool success,
- IRevertStep? revertStep, string? error, Func<Task<bool>>? retryAction = null)
- {
- Index = index;
- Name = name;
- Description = description;
- Success = success;
- RevertStep = revertStep;
- Error = error;
- RetryAction = retryAction;
- }
-}
+}
\ No newline at end of file
diff --git a/optimizerDuck/Core/Models/Optimization/OperationStepResult.cs b/optimizerDuck/Core/Models/Optimization/OperationStepResult.cs
index 8954ff8..e117ef9 100644
--- a/optimizerDuck/Core/Models/Optimization/OperationStepResult.cs
+++ b/optimizerDuck/Core/Models/Optimization/OperationStepResult.cs
@@ -1,3 +1,5 @@
+using optimizerDuck.Core.Interfaces;
+
namespace optimizerDuck.Core.Models.Optimization;
/// <summary>
@@ -34,4 +36,9 @@ public record OperationStepResult
/// An optional action to retry this step.
/// </summary>
public Func<Task<bool>>? RetryAction { get; init; }
+
+ /// <summary>
+ /// The revert data generated when applying this step, used to support retry synchronization.
+ /// </summary>
+ public IRevertStep? RevertStep { get; init; }
}
\ No newline at end of file
diff --git a/optimizerDuck/Core/Models/Revert/RevertResult.cs b/optimizerDuck/Core/Models/Revert/RevertResult.cs
index d9e6a74..80cc506 100644
--- a/optimizerDuck/Core/Models/Revert/RevertResult.cs
+++ b/optimizerDuck/Core/Models/Revert/RevertResult.cs
@@ -26,4 +26,9 @@ public class RevertResult
/// Details of any steps that failed during revert.
/// </summary>
public List<OperationStepResult> FailedStepDetails { get; set; } = [];
+
+ /// <summary>
+ /// Indicates whether the revert failed completely (all steps failed).
+ /// </summary>
+ public bool IsCompleteFailure { get; set; }
}
\ No newline at end of file
diff --git a/optimizerDuck/Core/Models/Revert/Steps/RegistryRevertStep.cs b/optimizerDuck/Core/Models/Revert/Steps/RegistryRevertStep.cs
index 35941c6..f7b62dd 100644
--- a/optimizerDuck/Core/Models/Revert/Steps/RegistryRevertStep.cs
+++ b/optimizerDuck/Core/Models/Revert/Steps/RegistryRevertStep.cs
@@ -2,6 +2,7 @@ using Microsoft.Win32;
using Newtonsoft.Json.Linq;
using optimizerDuck.Core.Interfaces;
using optimizerDuck.Core.Models.Optimization.Services;
+using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.OptimizationServices;
namespace optimizerDuck.Core.Models.Revert.Steps;
@@ -45,6 +46,13 @@ public class RegistryRevertStep : IRevertStep
/// <inheritdoc />
public string Type => "Registry";
+ /// <inheritdoc />
+ public string Description => string.Format(
+ Action == RevertAction.RestorePrevious
+ ? Translations.Revert_Registry_Description_Restore
+ : Translations.Revert_Registry_Description_Delete,
+ Path, Name ?? "(Default)");
+
/// <inheritdoc />
public async Task<bool> ExecuteAsync()
{
@@ -65,6 +73,9 @@ public class RegistryRevertStep : IRevertStep
_ => false
};
+ if (!result)
+ throw new Exception(string.Format(Translations.Service_Common_Error_AccessDenied)); // Generic for now, but better than nothing
+
// Cleanup empty subkeys if they were created during apply
if (result && CreatedSubKeys?.Count > 0) RegistryService.CleanupEmptyKeys(CreatedSubKeys);
diff --git a/optimizerDuck/Core/Models/Revert/Steps/ScheduledTaskRevertStep.cs b/optimizerDuck/Core/Models/Revert/Steps/ScheduledTaskRevertStep.cs
index 2ef2750..c8d82f0 100644
--- a/optimizerDuck/Core/Models/Revert/Steps/ScheduledTaskRevertStep.cs
+++ b/optimizerDuck/Core/Models/Revert/Steps/ScheduledTaskRevertStep.cs
@@ -1,5 +1,6 @@
using Newtonsoft.Json.Linq;
using optimizerDuck.Core.Interfaces;
+using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.OptimizationServices;
namespace optimizerDuck.Core.Models.Revert.Steps;
@@ -22,23 +23,23 @@ public class ScheduledTaskRevertStep : IRevertStep
/// <inheritdoc />
public string Type => "ScheduledTask";
+ /// <inheritdoc />
+ public string Description => string.Format(
+ OriginalEnabled
+ ? Translations.Revert_ScheduledTask_Description_Enable
+ : Translations.Revert_ScheduledTask_Description_Disable,
+ FullPath);
+
/// <inheritdoc />
public async Task<bool> ExecuteAsync()
{
return await Task.Run(() =>
{
- try
- {
- if (OriginalEnabled)
- ScheduledTaskService.EnableTask(FullPath);
- else
- ScheduledTaskService.DisableTask(FullPath);
- return true;
- }
- catch
- {
- return false;
- }
+ if (OriginalEnabled)
+ ScheduledTaskService.EnableTask(FullPath);
+ else
+ ScheduledTaskService.DisableTask(FullPath);
+ return true;
});
}
@@ -65,4 +66,4 @@ public class ScheduledTaskRevertStep : IRevertStep
OriginalEnabled = data[nameof(OriginalEnabled)]?.Value<bool>() ?? true
};
}
-}
+}
\ No newline at end of file
diff --git a/optimizerDuck/Core/Models/Revert/Steps/ServiceRevertStep.cs b/optimizerDuck/Core/Models/Revert/Steps/ServiceRevertStep.cs
index 78a53bb..3e987d2 100644
--- a/optimizerDuck/Core/Models/Revert/Steps/ServiceRevertStep.cs
+++ b/optimizerDuck/Core/Models/Revert/Steps/ServiceRevertStep.cs
@@ -1,6 +1,7 @@
using Newtonsoft.Json.Linq;
using optimizerDuck.Core.Interfaces;
using optimizerDuck.Core.Models.Optimization.Services;
+using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.OptimizationServices;
namespace optimizerDuck.Core.Models.Revert.Steps;
@@ -23,15 +24,28 @@ public class ServiceRevertStep : IRevertStep
/// <inheritdoc />
public string Type => "Service";
+ /// <inheritdoc />
+ public string Description => string.Format(
+ Translations.Revert_Service_Description_Restore,
+ ServiceName, OriginalStartupType);
+
/// <inheritdoc />
public async Task<bool> ExecuteAsync()
{
- return await Task.Run(() => ServiceProcessService.ChangeServiceStartupType(new ServiceItem
+ return await Task.Run(() =>
{
- Name = ServiceName,
- StartupType = OriginalStartupType
- }));
+ var result = ServiceProcessService.ChangeServiceStartupType(new ServiceItem
+ {
+ Name = ServiceName,
+ StartupType = OriginalStartupType
+ });
+
+ if (!result)
+ throw new Exception(string.Format(Translations.Service_Service_Error_UpdateRegistryForStartupTypeFailed));
+
+ return result;
+ });
}
diff --git a/optimizerDuck/Core/Models/Revert/Steps/ShellRevertStep.cs b/optimizerDuck/Core/Models/Revert/Steps/ShellRevertStep.cs
index dbcfdc3..e0d0fa6 100644
--- a/optimizerDuck/Core/Models/Revert/Steps/ShellRevertStep.cs
+++ b/optimizerDuck/Core/Models/Revert/Steps/ShellRevertStep.cs
@@ -1,6 +1,7 @@
using Newtonsoft.Json.Linq;
using optimizerDuck.Core.Interfaces;
using optimizerDuck.Core.Models.Optimization.Services;
+using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.OptimizationServices;
namespace optimizerDuck.Core.Models.Revert.Steps;
@@ -23,6 +24,11 @@ public class ShellRevertStep : IRevertStep
/// <inheritdoc />
public string Type => "Shell";
+ /// <inheritdoc />
+ public string Description => string.Format(
+ Translations.Revert_Shell_Description_Run,
+ ShellType, Command);
+
/// <inheritdoc />
public async Task<bool> ExecuteAsync()
{
@@ -38,6 +44,12 @@ public class ShellRevertStep : IRevertStep
Duration = TimeSpan.Zero
}
};
+
+ if (result.ExitCode != 0)
+ throw new Exception(!string.IsNullOrWhiteSpace(result.Stderr)
+ ? result.Stderr
+ : $"Command failed with exit code {result.ExitCode}");
+
return result.ExitCode == 0;
});
}
diff --git a/optimizerDuck/Resources/Languages/Translations.Designer.cs b/optimizerDuck/Resources/Languages/Translations.Designer.cs
index 8f1ed66..a403cb0 100644
--- a/optimizerDuck/Resources/Languages/Translations.Designer.cs
+++ b/optimizerDuck/Resources/Languages/Translations.Designer.cs
@@ -1140,6 +1140,15 @@ namespace optimizerDuck.Resources.Languages {
}
}
+ /// <summary>
+ /// Looks up a localized string similar to Revert step #{0}.
+ /// </summary>
+ internal static string Optimization_Revert_StepDescription {
+ get {
+ return ResourceManager.GetString("Optimization.Revert.StepDescription", resourceCulture);
+ }
+ }
+
/// <summary>
/// Looks up a localized string similar to Reverting....
/// </summary>
@@ -3097,6 +3106,15 @@ namespace optimizerDuck.Resources.Languages {
}
}
+ /// <summary>
+ /// Looks up a localized string similar to Failed to change service &apos;{0}&apos;: {1}.
+ /// </summary>
+ internal static string Service_Service_Error_ExceptionOccurred {
+ get {
+ return ResourceManager.GetString("Service.Service.Error.ExceptionOccurred", resourceCulture);
+ }
+ }
+
/// <summary>
/// Looks up a localized string similar to Service not found.
/// </summary>
@@ -3682,5 +3700,95 @@ namespace optimizerDuck.Resources.Languages {
return ResourceManager.GetString("StartupManager.Tasks.Title", resourceCulture);
}
}
+
+ /// <summary>
+ /// Looks up a localized string similar to Registry.
+ /// </summary>
+ internal static string Service_Registry_Name {
+ get {
+ return ResourceManager.GetString("Service.Registry.Name", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Service.
+ /// </summary>
+ internal static string Service_Service_Name {
+ get {
+ return ResourceManager.GetString("Service.Service.Name", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Scheduled Task.
+ /// </summary>
+ internal static string Service_ScheduledTask_Name {
+ get {
+ return ResourceManager.GetString("Service.ScheduledTask.Name", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Shell.
+ /// </summary>
+ internal static string Service_Shell_Name {
+ get {
+ return ResourceManager.GetString("Service.Shell.Name", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Restore registry value: {0}\{1}.
+ /// </summary>
+ internal static string Revert_Registry_Description_Restore {
+ get {
+ return ResourceManager.GetString("Revert.Registry.Description.Restore", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Delete registry value: {0}\{1}.
+ /// </summary>
+ internal static string Revert_Registry_Description_Delete {
+ get {
+ return ResourceManager.GetString("Revert.Registry.Description.Delete", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Restore service &apos;{0}&apos; to {1} startup.
+ /// </summary>
+ internal static string Revert_Service_Description_Restore {
+ get {
+ return ResourceManager.GetString("Revert.Service.Description.Restore", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Enable scheduled task: {0}.
+ /// </summary>
+ internal static string Revert_ScheduledTask_Description_Enable {
+ get {
+ return ResourceManager.GetString("Revert.ScheduledTask.Description.Enable", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Disable scheduled task: {0}.
+ /// </summary>
+ internal static string Revert_ScheduledTask_Description_Disable {
+ get {
+ return ResourceManager.GetString("Revert.ScheduledTask.Description.Disable", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Run {0} command: {1}.
+ /// </summary>
+ internal static string Revert_Shell_Description_Run {
+ get {
+ return ResourceManager.GetString("Revert.Shell.Description.Run", resourceCulture);
+ }
+ }
}
}
diff --git a/optimizerDuck/Resources/Languages/Translations.resx b/optimizerDuck/Resources/Languages/Translations.resx
index d210af8..6947fe6 100644
--- a/optimizerDuck/Resources/Languages/Translations.resx
+++ b/optimizerDuck/Resources/Languages/Translations.resx
@@ -327,6 +327,9 @@
</data>
<data name="Optimization.Revert.ExecutingStep" xml:space="preserve">
<value>Executing revert step: {0}/{1} ({2})</value>
+ </data>
+ <data name="Optimization.Revert.StepDescription" xml:space="preserve">
+ <value>Revert step #{0}</value>
</data>
<data name="Revert.Error.FileNotFound" xml:space="preserve">
<value>Revert file not found</value>
@@ -390,6 +393,9 @@
</data>
<data name="Service.Service.Error.ChangeStartModeFailedWithCode" xml:space="preserve">
<value>ChangeStartMode failed (code: {0})</value>
+ </data>
+ <data name="Service.Service.Error.ExceptionOccurred" xml:space="preserve">
+ <value>Failed to change service '{0}': {1}</value>
</data>
<data name="Service.Shell.Error.ExitCode" xml:space="preserve">
<value>Exit code {0}</value>
@@ -1061,7 +1067,7 @@ Update now to enjoy the latest features, improvements, and bug fixes.</value>
<value>Temporary Files</value>
</data>
<data name="DiskCleanup.Item.TempFiles.Description" xml:space="preserve">
- <value>User temporary files created by applications</value>
+ <value>User temporary files created by applications (excluding the .net temp directory)</value>
</data>
<data name="DiskCleanup.Item.SystemTemp" xml:space="preserve">
<value>System Temp Files</value>
@@ -1351,4 +1357,34 @@ Update now to enjoy the latest features, improvements, and bug fixes.</value>
<data name="ScheduledTasks.Error.TaskNotFound" xml:space="preserve">
<value>Task not found: {0}</value>
</data>
+ <data name="Service.Registry.Name" xml:space="preserve">
+ <value>Registry</value>
+ </data>
+ <data name="Service.Service.Name" xml:space="preserve">
+ <value>Service</value>
+ </data>
+ <data name="Service.ScheduledTask.Name" xml:space="preserve">
+ <value>Scheduled Task</value>
+ </data>
+ <data name="Service.Shell.Name" xml:space="preserve">
+ <value>Shell</value>
+ </data>
+ <data name="Revert.Registry.Description.Restore" xml:space="preserve">
+ <value>Restore registry value: {0}\{1}</value>
+ </data>
+ <data name="Revert.Registry.Description.Delete" xml:space="preserve">
+ <value>Delete registry value: {0}\{1}</value>
+ </data>
+ <data name="Revert.Service.Description.Restore" xml:space="preserve">
+ <value>Restore service '{0}' to {1} startup</value>
+ </data>
+ <data name="Revert.ScheduledTask.Description.Enable" xml:space="preserve">
+ <value>Enable scheduled task: {0}</value>
+ </data>
+ <data name="Revert.ScheduledTask.Description.Disable" xml:space="preserve">
+ <value>Disable scheduled task: {0}</value>
+ </data>
+ <data name="Revert.Shell.Description.Run" xml:space="preserve">
+ <value>Run {0} command: {1}</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
index 1832eff..16225cc 100644
--- a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
+++ b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
@@ -329,6 +329,9 @@
</data>
<data name="Optimization.Revert.ExecutingStep" xml:space="preserve">
<value>Đang thực hiện bước hoàn tác: {0}/{1} ({2})</value>
+ </data>
+ <data name="Optimization.Revert.StepDescription" xml:space="preserve">
+ <value>Đang hoàn tác bước #{0}</value>
</data>
<data name="Revert.Error.FileNotFound" xml:space="preserve">
<value>Không tìm thấy tệp hoàn tác</value>
@@ -392,6 +395,9 @@
</data>
<data name="Service.Service.Error.ChangeStartModeFailedWithCode" xml:space="preserve">
<value>ChangeStartMode thất bại (mã: {0})</value>
+ </data>
+ <data name="Service.Service.Error.ExceptionOccurred" xml:space="preserve">
+ <value>Không thể thay đổi dịch vụ '{0}': {1}</value>
</data>
<data name="Service.Shell.Error.ExitCode" xml:space="preserve">
<value>Mã thoát {0}</value>
@@ -1059,7 +1065,7 @@ Cập nhật ngay để trải nghiệm các tính năng mới, cải tiến và
<value>Tệp tạm thời</value>
</data>
<data name="DiskCleanup.Item.TempFiles.Description" xml:space="preserve">
- <value>Tệp tạm thời của người dùng được tạo bởi các ứng dụng</value>
+ <value>Tệp tạm thời của người dùng được tạo bởi các ứng dụng (đã bỏ qua thư mục .net để tránh lỗi)</value>
</data>
<data name="DiskCleanup.Item.SystemTemp" xml:space="preserve">
<value>Tệp tạm hệ thống</value>
@@ -1334,4 +1340,34 @@ Cập nhật ngay để trải nghiệm các tính năng mới, cải tiến và
<data name="ScheduledTasks.Error.TaskNotFound" xml:space="preserve">
<value>Không tìm thấy task: {0}</value>
</data>
+ <data name="Service.Registry.Name" xml:space="preserve">
+ <value>Registry</value>
+ </data>
+ <data name="Service.Service.Name" xml:space="preserve">
+ <value>Dịch vụ</value>
+ </data>
+ <data name="Service.ScheduledTask.Name" xml:space="preserve">
+ <value>Tác vụ hệ thống</value>
+ </data>
+ <data name="Service.Shell.Name" xml:space="preserve">
+ <value>Lệnh hệ thống</value>
+ </data>
+ <data name="Revert.Registry.Description.Restore" xml:space="preserve">
+ <value>Khôi phục giá trị registry: {0}\{1}</value>
+ </data>
+ <data name="Revert.Registry.Description.Delete" xml:space="preserve">
+ <value>Xóa giá trị registry: {0}\{1}</value>
+ </data>
+ <data name="Revert.Service.Description.Restore" xml:space="preserve">
+ <value>Khôi phục dịch vụ '{0}' về kiểu khởi động {1}</value>
+ </data>
+ <data name="Revert.ScheduledTask.Description.Enable" xml:space="preserve">
+ <value>Bật tác vụ hệ thống: {0}</value>
+ </data>
+ <data name="Revert.ScheduledTask.Description.Disable" xml:space="preserve">
+ <value>Tắt tác vụ hệ thống: {0}</value>
+ </data>
+ <data name="Revert.Shell.Description.Run" xml:space="preserve">
+ <value>Chạy lệnh {0}: {1}</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Services/BloatwareService.cs b/optimizerDuck/Services/BloatwareService.cs
index 8de1681..927fa2e 100644
--- a/optimizerDuck/Services/BloatwareService.cs
+++ b/optimizerDuck/Services/BloatwareService.cs
@@ -22,7 +22,7 @@ public class BloatwareService(ILogger<BloatwareService> logger, IOptionsMonitor<
/// <summary>
/// Gets all removable AppX packages on the system.
/// </summary>
- /// <returns>A list of <see cref="AppXPackage"/>.</returns>
+ /// <returns>A list of <see cref="AppXPackage" />.</returns>
public async Task<List<AppXPackage>> GetAppXPackagesAsync()
{
try
diff --git a/optimizerDuck/Services/DiskCleanupService.cs b/optimizerDuck/Services/DiskCleanupService.cs
index 0157533..747c80c 100644
--- a/optimizerDuck/Services/DiskCleanupService.cs
+++ b/optimizerDuck/Services/DiskCleanupService.cs
@@ -230,9 +230,19 @@ public class DiskCleanupService(ILogger<DiskCleanupService> logger)
// For non-thumbnail items, also include subdirectories
if (itemId != "Thumbnails")
+ {
+ var dotNetTempPath = Path.GetFullPath(Path.Combine(Path.GetTempPath(), ".net"))
+ .TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
foreach (var dir in Directory.EnumerateDirectories(path))
try
{
+ // Skip .net temp files
+ var fullDir = Path.GetFullPath(dir)
+ .TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
+
+ if (fullDir.StartsWith(dotNetTempPath, StringComparison.OrdinalIgnoreCase))
+ continue;
+
foreach (var file in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories))
try
{
@@ -248,6 +258,7 @@ public class DiskCleanupService(ILogger<DiskCleanupService> logger)
{
// skip inaccessible directories
}
+ }
}
catch (Exception ex)
{
@@ -264,11 +275,15 @@ public class DiskCleanupService(ILogger<DiskCleanupService> logger)
long freed = 0;
var searchPattern = itemId == "Thumbnails" ? "thumbcache_*" : "*";
+ var dotNetTempPath = Path.GetFullPath(Path.Combine(Path.GetTempPath(), ".net"))
+ .TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
// Delete files
foreach (var file in Directory.EnumerateFiles(path, searchPattern, SearchOption.TopDirectoryOnly))
try
{
+ // Skip .net temp files
+ if (file.StartsWith(dotNetTempPath, StringComparison.OrdinalIgnoreCase)) continue;
var length = new FileInfo(file).Length;
File.Delete(file);
freed += length;
@@ -283,9 +298,15 @@ public class DiskCleanupService(ILogger<DiskCleanupService> logger)
foreach (var dir in Directory.EnumerateDirectories(path))
try
{
+ var fullDir = Path.GetFullPath(dir)
+ .TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
+
+ if (fullDir.StartsWith(dotNetTempPath, StringComparison.OrdinalIgnoreCase)) continue;
+
foreach (var file in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories))
try
{
+ if (file.StartsWith(dotNetTempPath, StringComparison.OrdinalIgnoreCase)) continue;
var length = new FileInfo(file).Length;
File.Delete(file);
freed += length;
diff --git a/optimizerDuck/Services/Managers/RevertManager.cs b/optimizerDuck/Services/Managers/RevertManager.cs
index 1fb9c05..7201fb4 100644
--- a/optimizerDuck/Services/Managers/RevertManager.cs
+++ b/optimizerDuck/Services/Managers/RevertManager.cs
@@ -1,3 +1,4 @@
+using System.Collections.Concurrent;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.Logging;
@@ -5,6 +6,7 @@ using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using optimizerDuck.Common.Helpers;
using optimizerDuck.Core.Interfaces;
+using optimizerDuck.Core.Models.Execution;
using optimizerDuck.Core.Models.Optimization;
using optimizerDuck.Core.Models.Revert;
using optimizerDuck.Core.Models.UI;
@@ -15,10 +17,11 @@ namespace optimizerDuck.Services.Managers;
public class RevertManager(ILogger<RevertManager> logger)
{
private static readonly Dictionary<string, Func<JObject, IRevertStep>> _stepRegistry = BuildStepRegistry();
+ private static readonly ConcurrentDictionary<Guid, object> _fileLocks = new();
public static IReadOnlyCollection<string> RegisteredStepTypes => _stepRegistry.Keys.ToList().AsReadOnly();
- public async Task SaveRevertDataAsync(Core.Models.Execution.ExecutionScope executionScope)
+ public async Task SaveRevertDataAsync(ExecutionScope executionScope)
{
var successfulSteps = executionScope.SuccessfulSteps
.Where(s => s.RevertStep != null)
@@ -65,8 +68,9 @@ public class RevertManager(ILogger<RevertManager> logger)
if (File.Exists(tempPath))
File.Delete(tempPath);
}
- catch
+ catch (Exception deleteEx)
{
+ logger.LogWarning(deleteEx, "Failed to delete temp file {File} after save failure", tempPath);
}
logger.LogError(ex, "Failed to save revert data for {Name}", executionScope.OptimizationKey);
@@ -74,36 +78,39 @@ public class RevertManager(ILogger<RevertManager> logger)
}
}
- public async Task<RevertResult> RevertAsync(Guid optimizationId, string optimizationKey,
- IProgress<ProcessingProgress>? progress = null, int maxRetries = 1)
+ public async Task<RevertResult> RevertAsync(IOptimization optimization,
+ IProgress<ProcessingProgress>? progress = null)
{
+ using var scope = ExecutionScope.BeginForLogging(optimization.Id, optimization.OptimizationKey, logger);
+
try
{
- var validation = await ValidateAsync(optimizationId);
+ var validation = await ValidateAsync(optimization.Id);
if (!validation.IsValid)
{
- logger.LogWarning("Invalid revert data for {Name}: {Message}", optimizationKey, validation.Message);
+ logger.LogWarning("Invalid revert data for {Key}: {Message}", optimization.OptimizationKey,
+ validation.Message);
return new RevertResult
{
Success = false,
- Message = string.Format(Translations.Revert_Error_InvalidData, optimizationKey,
+ Message = string.Format(Translations.Revert_Error_InvalidData, optimization.Name,
validation.LocalizedMessage)
};
}
- var steps = await LoadStepsAsync(optimizationId);
+ var steps = await LoadStepsAsync(optimization.Id);
if (steps.Count == 0)
{
- logger.LogWarning("No revert steps found for {Name}", optimizationKey);
+ logger.LogWarning("No revert steps found for {Key}", optimization.OptimizationKey);
return new RevertResult
{
Success = false,
- Message = string.Format(Translations.Revert_Error_NoDataFound, optimizationKey)
+ Message = string.Format(Translations.Revert_Error_NoDataFound, optimization.Name)
};
}
- logger.LogInformation("Reverting {Name} with {Count} steps (maxRetries={MaxRetries})",
- optimizationKey, steps.Count, maxRetries);
+ logger.LogInformation("Reverting {Key} ({StepCount} steps)",
+ optimization.OptimizationKey, steps.Count);
var failedStepDetails = new List<OperationStepResult>();
var totalSteps = steps.Count;
@@ -125,38 +132,28 @@ public class RevertManager(ILogger<RevertManager> logger)
var success = false;
Exception? lastError = null;
- for (var attempt = 0; attempt <= maxRetries; attempt++)
+ try
{
- try
- {
- success = await step.ExecuteAsync();
- if (success) break;
- }
- catch (Exception ex)
- {
- lastError = ex;
- }
-
- if (attempt < maxRetries)
- {
- logger.LogWarning("Revert step {Index} ({Type}) failed on attempt {Attempt}, retrying...",
- currentIndex, step.Type, attempt + 1);
- await Task.Delay(200 * (attempt + 1));
- }
+ success = await step.ExecuteAsync();
+ }
+ catch (Exception ex)
+ {
+ lastError = ex;
}
if (!success)
{
- logger.LogError(lastError, "Revert step {Index} ({Type}) failed after {Attempts} attempt(s)",
- currentIndex, step.Type, maxRetries + 1);
+ var errorMessage = lastError?.Message ?? Translations.Revert_Error_StepFailed;
+ logger.LogError(lastError, "Revert step {Index} ({Type}) failed: {Message}",
+ currentIndex, step.Type, errorMessage);
failedStepDetails.Add(new OperationStepResult
{
Index = currentIndex,
Name = step.Type,
- Description = $"Revert step #{currentIndex}",
+ Description = step.Description,
Success = false,
- Error = lastError?.Message ?? Translations.Revert_Error_StepFailed,
+ Error = errorMessage,
RetryAction = async () => await step.ExecuteAsync()
});
}
@@ -166,87 +163,105 @@ public class RevertManager(ILogger<RevertManager> logger)
var allFailed = failedCount == totalSteps;
var hasFailures = failedCount > 0;
+ // if some steps failed but not all, log a warning
if (hasFailures && !allFailed)
- {
- await SaveFailedStepsAsync(optimizationId, optimizationKey, steps, failedStepDetails);
- logger.LogWarning("Partial revert for {Name}: {Failed}/{Total} steps failed, saved for later retry",
- optimizationKey, failedCount, totalSteps);
- }
- else if (!hasFailures)
- {
- Remove(optimizationId, optimizationKey);
- }
+ logger.LogWarning(
+ "Partial revert for {Key}: {FailedCount}/{TotalCount} steps failed. " +
+ "Revert data file will be removed; remaining retries operate in-memory.",
+ optimization.OptimizationKey, failedCount, totalSteps);
+
+ // keep revert data if its all failed
+ if (!allFailed) Remove(optimization.Id, optimization.Name);
return new RevertResult
{
Success = !hasFailures,
+ IsCompleteFailure = allFailed,
Message = allFailed
- ? string.Format(Translations.Optimization_Revert_Error_Failed, optimizationKey)
+ ? string.Format(Translations.Optimization_Revert_Error_Failed, optimization.Name)
: hasFailures
- ? string.Format(Translations.Optimization_Revert_Error_FailedWithSteps, optimizationKey,
+ ? string.Format(Translations.Optimization_Revert_Error_FailedWithSteps, optimization.Name,
failedCount)
- : string.Format(Translations.Optimization_Revert_Success, optimizationKey),
+ : string.Format(Translations.Optimization_Revert_Success, optimization.Name),
FailedStepDetails = failedStepDetails
};
}
catch (Exception ex)
{
- logger.LogError(ex, "Failed to revert {Name}", optimizationKey);
+ logger.LogError(ex, "Failed to revert {Key}", optimization.OptimizationKey);
return new RevertResult
{
Success = false,
- Message = string.Format(Translations.Revert_Error_RevertFailed, optimizationKey, ex.Message),
+ IsCompleteFailure = true,
+ Message = string.Format(Translations.Revert_Error_RevertFailed, optimization.Name, ex.Message),
Exception = ex
};
}
}
- private async Task SaveFailedStepsAsync(Guid optimizationId, string optimizationName,
- List<RevertStepEntry> allSteps, List<OperationStepResult> failedDetails)
+ public Task AppendOrUpdateRevertStepAsync(Guid optimizationId, string optimizationName, int stepIndex,
+ IRevertStep newStep)
{
var filePath = Path.Combine(Shared.RevertDirectory, optimizationId + ".json");
var tempPath = filePath + ".tmp";
- try
+ // Use a per-file lock keyed by optimizationId to ensure thread-safe file access
+ var fileLockObj = _fileLocks.GetOrAdd(optimizationId, _ => new object());
+ lock (fileLockObj)
{
- var failedIndices = new HashSet<int>(failedDetails.Select(f => f.Index));
- var remainingSteps = allSteps
- .Where(s => failedIndices.Contains(s.Index))
- .Select(s => new RevertStepData
+ try
+ {
+ var content = File.Exists(filePath) ? File.ReadAllText(filePath) : string.Empty;
+ var revertData = string.IsNullOrWhiteSpace(content)
+ ? new RevertData
+ {
+ OptimizationId = optimizationId,
+ OptimizationName = optimizationName,
+ AppliedAt = DateTime.Now,
+ Steps = []
+ }
+ : JsonConvert.DeserializeObject<RevertData>(content);
+
+ if (revertData == null)
+ return Task.CompletedTask;
+
+ // Adjust the steps list to match exactly the 1-based index length
+ while (revertData.Steps.Count < stepIndex)
+ revertData.Steps.Add(new RevertStepData { Type = "Unknown", Data = new JObject() });
+
+ // Replace at exact 0-based index
+ revertData.Steps[stepIndex - 1] = new RevertStepData
{
- Type = s.Step.Type,
- Data = s.Step.ToData()
- })
- .ToList();
+ Type = newStep.Type,
+ Data = newStep.ToData()
+ };
- var payload = new RevertData
- {
- OptimizationId = optimizationId,
- OptimizationName = optimizationName,
- AppliedAt = DateTime.Now,
- Steps = remainingSteps
- };
+ Directory.CreateDirectory(Shared.RevertDirectory);
+ var json = JsonConvert.SerializeObject(revertData, Formatting.Indented);
+ File.WriteAllText(tempPath, json);
+ File.Move(tempPath, filePath, true);
- Directory.CreateDirectory(Shared.RevertDirectory);
- var json = JsonConvert.SerializeObject(payload, Formatting.Indented);
- await File.WriteAllTextAsync(tempPath, json);
- File.Move(tempPath, filePath, true);
- logger.LogInformation("Updated revert file for {Name} with {Count} remaining failed steps",
- optimizationName, remainingSteps.Count);
- }
- catch (Exception ex)
- {
- try
- {
- if (File.Exists(tempPath))
- File.Delete(tempPath);
+ logger.LogInformation("Successfully inserted retried revert step at index {Index} for {Name}",
+ stepIndex, optimizationName);
}
- catch
+ catch (Exception ex)
{
- }
+ try
+ {
+ if (File.Exists(tempPath))
+ File.Delete(tempPath);
+ }
+ catch (Exception deleteEx)
+ {
+ logger.LogWarning(deleteEx, "Failed to delete temp file {File} after save failure", tempPath);
+ }
- logger.LogError(ex, "Failed to save remaining failed steps for {Name}", optimizationName);
+ logger.LogError(ex, "Failed to append/update revert step {Index} for {Name}", stepIndex,
+ optimizationName);
+ }
}
+
+ return Task.CompletedTask;
}
private async Task<List<RevertStepEntry>> LoadStepsAsync(Guid optimizationId)
@@ -345,7 +360,6 @@ public class RevertManager(ILogger<RevertManager> logger)
&& typeof(IRevertStep).IsAssignableFrom(t));
foreach (var type in stepTypes)
- {
try
{
var instance = (IRevertStep)Activator.CreateInstance(type)!;
@@ -370,7 +384,6 @@ public class RevertManager(ILogger<RevertManager> logger)
catch
{
}
- }
}
catch
{
@@ -412,7 +425,7 @@ public class RevertManager(ILogger<RevertManager> logger)
var filePath = Path.Combine(Shared.RevertDirectory, optimizationId + ".json");
if (!File.Exists(filePath))
return RevertValidationResult.Fail(Translations.Revert_Error_FileNotFound,
- "Invalid revert data file not found.");
+ "Revert data file not found.");
string content;
try
@@ -420,7 +433,7 @@ public class RevertManager(ILogger<RevertManager> logger)
content = await File.ReadAllTextAsync(filePath);
if (string.IsNullOrWhiteSpace(content))
return RevertValidationResult.Fail(Translations.Revert_Error_FileEmpty,
- "Invalid revert data file is empty.");
+ "Revert data file is empty.");
}
catch (Exception ex)
{
@@ -433,7 +446,7 @@ public class RevertManager(ILogger<RevertManager> logger)
{
data = JsonConvert.DeserializeObject<RevertData>(content);
if (data == null)
- return RevertValidationResult.Fail(Translations.Revert_Error_InvalidJson, "Invalid revert data JSON.");
+ return RevertValidationResult.Fail(Translations.Revert_Error_InvalidJson, "Revert data JSON is null after deserialization.");
}
catch (Exception ex)
{
@@ -443,10 +456,10 @@ public class RevertManager(ILogger<RevertManager> logger)
if (data.OptimizationId != optimizationId)
return RevertValidationResult.Fail(Translations.Revert_Error_OptimizationIdMismatch,
- "Invalid optimization ID.");
+ $"Optimization ID mismatch: expected {optimizationId}, found {data.OptimizationId}.");
if (data.Steps.Count == 0)
- return RevertValidationResult.Fail(Translations.Revert_Error_NoSteps, "No revert steps found.");
+ return RevertValidationResult.Fail(Translations.Revert_Error_NoSteps, "Revert data contains zero steps.");
var invalidSteps = new List<string>();
foreach (var stepData in data.Steps)
@@ -470,12 +483,12 @@ public class RevertManager(ILogger<RevertManager> logger)
if (invalidSteps.Count > 0)
return RevertValidationResult.Fail(string.Format(Translations.Revert_Error_InvalidSteps,
- string.Join(", ", invalidSteps)), "Invalid revert steps.");
+ string.Join(", ", invalidSteps)), $"Invalid or unrecognized step types: {string.Join(", ", invalidSteps)}.");
return RevertValidationResult.Success();
}
- public static void ClearAllRevertData()
+ public static void ClearAllRevertData(ILogger logger)
{
if (!Directory.Exists(Shared.RevertDirectory))
return;
@@ -485,10 +498,11 @@ public class RevertManager(ILogger<RevertManager> logger)
{
File.Delete(filePath);
}
- catch
+ catch (Exception ex)
{
+ logger.LogError(ex, "Failed to delete revert data file {File}", filePath);
}
}
- private sealed record RevertStepEntry(int Index, IRevertStep Step);
-}
+ public sealed record RevertStepEntry(int Index, IRevertStep Step);
+}
\ No newline at end of file
diff --git a/optimizerDuck/Services/OptimizationPageRegistryExtensions.cs b/optimizerDuck/Services/OptimizationPageRegistryExtensions.cs
index dad92af..314f001 100644
--- a/optimizerDuck/Services/OptimizationPageRegistryExtensions.cs
+++ b/optimizerDuck/Services/OptimizationPageRegistryExtensions.cs
@@ -4,6 +4,7 @@ using Microsoft.Extensions.Logging;
using optimizerDuck.Common.Helpers;
using optimizerDuck.Core.Interfaces;
using optimizerDuck.Core.Models.Attributes;
+using optimizerDuck.Services.Managers;
using Wpf.Ui;
using OptimizationCategoryViewModel = optimizerDuck.UI.ViewModels.Optimizer.OptimizationCategoryViewModel;
@@ -33,6 +34,7 @@ public static class OptimizationPageRegistryExtensions
{
var optimizationRegistry = serviceProvider.GetRequiredService<OptimizationRegistry>();
var optimizationService = serviceProvider.GetRequiredService<OptimizationService>();
+ var revertManager = serviceProvider.GetRequiredService<RevertManager>();
var snackbarService = serviceProvider.GetRequiredService<ISnackbarService>();
var contentDialogService = serviceProvider.GetRequiredService<IContentDialogService>();
var logger = serviceProvider.GetRequiredService<ILogger<OptimizationCategoryViewModel>>();
@@ -42,6 +44,7 @@ public static class OptimizationPageRegistryExtensions
var viewModel = new OptimizationCategoryViewModel(
optimizationCategoryType,
optimizationService,
+ revertManager,
snackbarService,
contentDialogService,
logger
diff --git a/optimizerDuck/Services/OptimizationRegistry.cs b/optimizerDuck/Services/OptimizationRegistry.cs
index ac247b6..ed28bc3 100644
--- a/optimizerDuck/Services/OptimizationRegistry.cs
+++ b/optimizerDuck/Services/OptimizationRegistry.cs
@@ -14,9 +14,6 @@ public class OptimizationRegistry(ILoggerFactory loggerFactory)
public async Task PreloadOptimizations()
{
- // Clear state cache before preloading to ensure fresh data
- OptimizationService.ClearStateCache();
-
var optimizationCategories = ReflectionHelper
.FindImplementationsInLoadedAssemblies<IOptimizationCategory>()
.Select(t =>
diff --git a/optimizerDuck/Services/OptimizationService.cs b/optimizerDuck/Services/OptimizationService.cs
index 4d618ba..3e36071 100644
--- a/optimizerDuck/Services/OptimizationService.cs
+++ b/optimizerDuck/Services/OptimizationService.cs
@@ -26,8 +26,6 @@ public class OptimizationService(
IContentDialogService contentDialogService,
ILogger<OptimizationService> logger)
{
- private static readonly Dictionary<Guid, (bool IsApplied, DateTime? AppliedAt)> _stateCache = new();
- private static readonly object _cacheLock = new();
private readonly ILogger _logger = logger;
public bool WasRequestedRestorePoint { get; set; } = false;
@@ -135,13 +133,17 @@ public class OptimizationService(
#region Main Methods
+ /// <summary>
+ /// Apply an optimization.
+ /// </summary>
+ /// <param name="optimization">The optimization to apply.</param>
+ /// <param name="progress">The progress reporter.</param>
+ /// <returns>The result of the optimization.</returns>
public async Task<OptimizationResult> ApplyAsync(IOptimization optimization,
IProgress<ProcessingProgress> progress)
{
var optimizationLogger = loggerFactory.CreateLogger(optimization.GetType());
-
- using var executionScope = ExecutionScope.Begin(optimization.Id, optimization.OptimizationKey,
- optimizationLogger);
+ using var executionScope = ExecutionScope.Begin(optimization, optimizationLogger);
OptimizationResult result;
@@ -192,14 +194,7 @@ public class OptimizationService(
result = executionScope.ToResult();
- if (result.Status == OptimizationSuccessResult.Success)
- lock (_cacheLock)
- {
- _stateCache[optimization.Id] = (true, DateTime.Now);
- }
-
if (executionScope.HasSuccessfulSteps)
- {
try
{
await revertManager.SaveRevertDataAsync(executionScope);
@@ -209,7 +204,6 @@ public class OptimizationService(
_logger.LogError(saveEx, "Failed to save revert data for {Name}, but optimization was applied",
optimization.OptimizationKey);
}
- }
}
catch (Exception ex)
{
@@ -223,18 +217,20 @@ public class OptimizationService(
RetryAction = step.RetryAction
}).ToList();
- var status = GetStatus(executionScope);
+ var hasAnySuccess = executionScope.HasSuccessfulSteps;
+ var status = hasAnySuccess
+ ? OptimizationSuccessResult.PartialSuccess
+ : OptimizationSuccessResult.Failed;
result = new OptimizationResult
{
Status = status,
Message = string.Format(Translations.Optimization_Apply_Error_Failed,
- optimization.OptimizationKey),
+ optimization.Name),
Exception = ex,
FailedSteps = failedStepResults
};
if (executionScope.HasSuccessfulSteps)
- {
try
{
await revertManager.SaveRevertDataAsync(executionScope);
@@ -245,33 +241,21 @@ public class OptimizationService(
_logger.LogError(saveEx, "Critical: Failed to save revert data after exception for {Name}",
optimization.OptimizationKey);
}
- }
}
return result;
-
- OptimizationSuccessResult GetStatus(Core.Models.Execution.ExecutionScope scope)
- {
- if (scope.ExecutedSteps.Count == 0)
- return OptimizationSuccessResult.Failed;
-
- var failed = scope.FailedSteps.Count;
- var total = scope.ExecutedSteps.Count;
-
- return failed switch
- {
- 0 => OptimizationSuccessResult.Success,
- _ when failed < total => OptimizationSuccessResult.PartialSuccess,
- _ => OptimizationSuccessResult.Failed
- };
- }
}
+ /// <summary>
+ /// Revert an optimization.
+ /// </summary>
+ /// <param name="optimization">The optimization to revert.</param>
+ /// <param name="progress">The progress reporter.</param>
+ /// <returns>The result of the revert.</returns>
public async Task<RevertResult> RevertAsync(IOptimization optimization,
IProgress<ProcessingProgress>? progress = null)
{
var optimizationLogger = loggerFactory.CreateLogger(optimization.GetType());
- using var scope = ExecutionScope.Begin(optimizationLogger);
progress?.Report(new ProcessingProgress
{
@@ -280,14 +264,9 @@ public class OptimizationService(
});
var result = await revertManager.RevertAsync(
- optimization.Id,
- optimization.OptimizationKey,
+ optimization,
progress);
- var scopeSteps = scope.GetStepResults();
- if (result.FailedStepDetails.Count == 0 && scopeSteps.Any(s => !s.Success))
- result.FailedStepDetails = scopeSteps.Where(s => !s.Success).ToList();
-
progress?.Report(new ProcessingProgress
{
Message = result.Message,
@@ -296,12 +275,6 @@ public class OptimizationService(
Total = 1
});
- if (result.Success)
- lock (_cacheLock)
- {
- _stateCache.Remove(optimization.Id);
- }
-
return result;
}
@@ -309,57 +282,30 @@ public class OptimizationService(
#region Helpers
+ /// <summary>
+ /// Check if an optimization is applied.
+ /// </summary>
+ /// <param name="optimizationId">The ID of the optimization.</param>
+ /// <returns>Whether the optimization is applied.</returns>
public static Task<bool> IsAppliedAsync(Guid optimizationId)
{
return RevertManager.IsAppliedAsync(optimizationId);
}
+ /// <summary>
+ /// Update the state of optimizations.
+ /// </summary>
+ /// <param name="optimizations">The optimizations to update.</param>
public static async Task UpdateOptimizationStateAsync(params IOptimization[] optimizations)
{
- var optimizationIds = optimizations.Select(o => o.Id).ToArray();
- var uncachedIds = new List<Guid>();
-
- lock (_cacheLock)
+ var tasks = optimizations.Select(async optimization =>
{
- foreach (var optimization in optimizations)
- if (_stateCache.TryGetValue(optimization.Id, out var cachedState))
- {
- optimization.State.IsApplied = cachedState.IsApplied;
- optimization.State.AppliedAt = cachedState.AppliedAt;
- }
- else
- {
- uncachedIds.Add(optimization.Id);
- }
- }
-
- if (uncachedIds.Count > 0)
- {
- var tasks = uncachedIds.Select(async id =>
- {
- var revertData = await RevertManager.GetRevertDataAsync(id);
- var state = (IsApplied: revertData != null, revertData?.AppliedAt);
-
- lock (_cacheLock)
- {
- _stateCache[id] = state;
- }
-
- return (Id: id, State: state);
- });
-
- var results = await Task.WhenAll(tasks);
+ var revertData = await RevertManager.GetRevertDataAsync(optimization.Id);
+ optimization.State.IsApplied = revertData != null;
+ optimization.State.AppliedAt = revertData?.AppliedAt;
+ });
- foreach (var optimization in optimizations)
- {
- var result = results.FirstOrDefault(r => r.Id == optimization.Id);
- if (result.Id != Guid.Empty)
- {
- optimization.State.IsApplied = result.State.IsApplied;
- optimization.State.AppliedAt = result.State.AppliedAt;
- }
- }
- }
+ await Task.WhenAll(tasks);
}
public static async Task UpdateOptimizationStateAsync(IEnumerable<IOptimization> optimizations)
@@ -367,22 +313,31 @@ public class OptimizationService(
await UpdateOptimizationStateAsync(optimizations.ToArray());
}
+ /// <summary>
+ /// Retry failed steps for an optimization.
+ /// </summary>
+ /// <param name="failedSteps">The failed steps.</param>
+ /// <param name="reverseOrder">Whether to reverse the order of the steps.</param>
+ /// <param name="logger">The logger.</param>
+ /// <param name="progress">The progress reporter.</param>
+ /// <returns>The result of the retry.</returns>
public static async Task<List<OperationStepResult>> RetryFailedStepsAsync(
IReadOnlyList<OperationStepResult> failedSteps,
bool reverseOrder,
- IProgress<ProcessingProgress>? progress = null,
- int maxRetries = 3)
+ ILogger logger,
+ IProgress<ProcessingProgress>? progress = null)
{
if (failedSteps.Count == 0)
return [];
var stillFailed = new List<OperationStepResult>();
+ // Order steps by index, reverse if reverseOrder is true (revert flow)
var orderedSteps = reverseOrder
? failedSteps.OrderByDescending(s => s.Index)
: failedSteps.OrderBy(s => s.Index);
+
var totalSteps = failedSteps.Count;
- var stepIndex = 0;
progress?.Report(new ProcessingProgress
{
@@ -394,14 +349,12 @@ public class OptimizationService(
foreach (var step in orderedSteps)
{
- stepIndex++;
-
progress?.Report(new ProcessingProgress
{
- Message = string.Format(Translations.Optimization_RetryStep_Processing, step.Name, stepIndex,
+ Message = string.Format(Translations.Optimization_RetryStep_Processing, step.Name, step.Index,
totalSteps),
IsIndeterminate = false,
- Value = stepIndex,
+ Value = step.Index,
Total = totalSteps
});
@@ -412,35 +365,31 @@ public class OptimizationService(
}
var success = false;
- for (var attempt = 0; attempt < maxRetries; attempt++)
- {
- try
- {
- success = await step.RetryAction();
- if (success) break;
- }
- catch
- {
- }
+ Exception? lastEx = null;
- if (attempt < maxRetries - 1)
- await Task.Delay(200 * (attempt + 1));
+ try
+ {
+ success = await step.RetryAction();
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Retry step {Name} failed", step.Name);
+ lastEx = ex;
}
if (!success)
- stillFailed.Add(step);
+ stillFailed.Add(lastEx != null ? step with { Error = lastEx.Message } : step);
}
return stillFailed;
}
- public static void ClearResources()
+ /// <summary>
+ /// Clear resources.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ public static void ClearResources(ILogger logger)
{
- lock (_cacheLock)
- {
- _stateCache.Clear();
- }
-
if (!Directory.Exists(Shared.ResourcesDirectory))
return;
@@ -449,25 +398,30 @@ public class OptimizationService(
{
File.Delete(filePath);
}
- catch
+ catch (Exception ex)
{
+ logger.LogError(ex, "Failed to delete resource file {File}", filePath);
}
}
- public static void ClearStateCache()
- {
- lock (_cacheLock)
- {
- _stateCache.Clear();
- }
- }
-
#endregion Helpers
}
+/// <summary>
+/// The result of a restore point operation.
+/// </summary>
public enum RestorePointResult
{
+ /// <summary>
+ /// The restore point was created successfully.
+ /// </summary>
Success,
+ /// <summary>
+ /// The restore point creation failed.
+ /// </summary>
Failed,
+ /// <summary>
+ /// The restore point creation was skipped due to a frequency limit.
+ /// </summary>
FrequencyLimitReached
}
\ No newline at end of file
diff --git a/optimizerDuck/Services/OptimizationServices/RegistryService.cs b/optimizerDuck/Services/OptimizationServices/RegistryService.cs
index b09f433..5e41f01 100644
--- a/optimizerDuck/Services/OptimizationServices/RegistryService.cs
+++ b/optimizerDuck/Services/OptimizationServices/RegistryService.cs
@@ -178,9 +178,6 @@ public static class RegistryService
ExecutionScope.LogError(ex, "Failed to read registry {Path}:{Name}",
item.Path, item.Name!);
- ExecutionScope.LogInfo("Read registry {Path}:{Name} = <default> (raw={RawType})",
- item.Path, item.Name!, value?.GetType().FullName ?? "<null>");
-
return default;
}
});
@@ -258,7 +255,7 @@ public static class RegistryService
ExecutionScope.LogInfo("Wrote {Path}:{Name}[{Kind}] = {Value}",
item.Path, item.Name!, item.Kind, item.Value);
ExecutionScope.Track(nameof(Write), true);
- ExecutionScope.RecordStep("Registry", description, true, revertStep, null);
+ ExecutionScope.RecordStep(Translations.Service_Registry_Name, description, true, revertStep);
return true;
}
catch (UnauthorizedAccessException)
@@ -266,9 +263,9 @@ public static class RegistryService
ExecutionScope.LogError(null, "Access denied writing {Path}:{Name}",
item.Path, item.Name!);
ExecutionScope.Track(nameof(Write), false);
- ExecutionScope.RecordStep("Registry", description, false, null,
+ ExecutionScope.RecordStep(Translations.Service_Registry_Name, description, false, null,
Translations.Service_Common_Error_AccessDenied,
- retryAction: () => Task.FromResult(Write(item)));
+ () => Task.FromResult(Write(item)));
return false;
}
catch (Exception ex)
@@ -276,8 +273,8 @@ public static class RegistryService
ExecutionScope.LogError(ex, "Failed to write registry {Path}:{Name}",
item.Path, item.Name!);
ExecutionScope.Track(nameof(Write), false);
- ExecutionScope.RecordStep("Registry", description, false, null, ex.Message,
- retryAction: () => Task.FromResult(Write(item)));
+ ExecutionScope.RecordStep(Translations.Service_Registry_Name, description, false, null, ex.Message,
+ () => Task.FromResult(Write(item)));
return false;
}
}, true, true, createdSubKeys);
@@ -307,7 +304,7 @@ public static class RegistryService
ExecutionScope.LogInfo("Skip delete registry {Path}:{Name} (subkey missing)",
item.Path, item.Name!);
ExecutionScope.Track(nameof(DeleteValue), true);
- ExecutionScope.RecordStep("Registry", description, true, null, null);
+ ExecutionScope.RecordStep(Translations.Service_Registry_Name, description, true);
return true;
}
@@ -318,7 +315,7 @@ public static class RegistryService
if (key.GetValue(item.Name) == null)
{
ExecutionScope.Track(nameof(DeleteValue), true);
- ExecutionScope.RecordStep("Registry", description, true, null, null);
+ ExecutionScope.RecordStep(Translations.Service_Registry_Name, description, true);
return true;
}
@@ -339,7 +336,7 @@ public static class RegistryService
ExecutionScope.LogInfo("Deleted registry {Path}:{Name}", item.Path, item.Name!);
ExecutionScope.Track(nameof(DeleteValue), true);
- ExecutionScope.RecordStep("Registry", description, true, revertStep, null);
+ ExecutionScope.RecordStep(Translations.Service_Registry_Name, description, true, revertStep);
return true;
}
catch (UnauthorizedAccessException)
@@ -347,9 +344,9 @@ public static class RegistryService
ExecutionScope.LogError(null, "Access denied deleting {Path}:{Name}",
item.Path, item.Name!);
ExecutionScope.Track(nameof(DeleteValue), false);
- ExecutionScope.RecordStep("Registry", $"{item.Path}:{item.Name}", false, null,
+ ExecutionScope.RecordStep(Translations.Service_Registry_Name, $"{item.Path}:{item.Name}", false, null,
Translations.Service_Common_Error_AccessDenied,
- retryAction: () => Task.FromResult(DeleteValue(item)));
+ () => Task.FromResult(DeleteValue(item)));
return false;
}
catch (Exception ex)
@@ -357,8 +354,8 @@ public static class RegistryService
ExecutionScope.LogError(ex, "Failed to delete registry {Path}:{Name}",
item.Path, item.Name!);
ExecutionScope.Track(nameof(DeleteValue), false);
- ExecutionScope.RecordStep("Registry", $"{item.Path}:{item.Name}", false, null, ex.Message,
- retryAction: () => Task.FromResult(DeleteValue(item)));
+ ExecutionScope.RecordStep(Translations.Service_Registry_Name, $"{item.Path}:{item.Name}", false, null, ex.Message,
+ () => Task.FromResult(DeleteValue(item)));
return false;
}
finally
@@ -440,7 +437,7 @@ public static class RegistryService
ExecutionScope.Track(nameof(RegistryService), false);
- ExecutionScope.RecordStep("Registry", path, false, null, uiReason);
+ ExecutionScope.RecordStep(Translations.Service_Registry_Name, path, false, null, uiReason);
}
/// <summary>
diff --git a/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs b/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs
index 1535f16..57378d8 100644
--- a/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs
+++ b/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs
@@ -56,11 +56,10 @@ public static class ScheduledTaskService
ExecutionScope.LogInfo("Disabled task {Path}", fullPath);
ExecutionScope.Track(nameof(DisableTask), true);
ExecutionScope.RecordStep(
- "ScheduledTask",
+ Translations.Service_ScheduledTask_Name,
description,
true,
- revertStep,
- null);
+ revertStep);
return true;
}
catch (UnauthorizedAccessException)
@@ -68,12 +67,12 @@ public static class ScheduledTaskService
ExecutionScope.LogError(null, "Access denied disabling task {Path}", fullPath);
ExecutionScope.Track(nameof(DisableTask), false);
ExecutionScope.RecordStep(
- "ScheduledTask",
+ Translations.Service_ScheduledTask_Name,
description,
false,
null,
Translations.Service_Common_Error_AccessDenied,
- retryAction: () => System.Threading.Tasks.Task.FromResult(DisableTask(fullPath)));
+ () => System.Threading.Tasks.Task.FromResult(DisableTask(fullPath)));
return false;
}
catch (Exception ex)
@@ -81,12 +80,12 @@ public static class ScheduledTaskService
ExecutionScope.LogError(ex, "Failed to disable task {Path}", fullPath);
ExecutionScope.Track(nameof(DisableTask), false);
ExecutionScope.RecordStep(
- "ScheduledTask",
+ Translations.Service_ScheduledTask_Name,
description,
false,
null,
ex.Message,
- retryAction: () => System.Threading.Tasks.Task.FromResult(DisableTask(fullPath)));
+ () => System.Threading.Tasks.Task.FromResult(DisableTask(fullPath)));
return false;
}
}
@@ -119,11 +118,10 @@ public static class ScheduledTaskService
ExecutionScope.LogInfo("Enabled task {Path}", fullPath);
ExecutionScope.Track(nameof(EnableTask), true);
ExecutionScope.RecordStep(
- "ScheduledTask",
+ Translations.Service_ScheduledTask_Name,
description,
true,
- revertStep,
- null);
+ revertStep);
return true;
}
catch (UnauthorizedAccessException)
@@ -131,12 +129,12 @@ public static class ScheduledTaskService
ExecutionScope.LogError(null, "Access denied enabling task {Path}", fullPath);
ExecutionScope.Track(nameof(EnableTask), false);
ExecutionScope.RecordStep(
- "ScheduledTask",
+ Translations.Service_ScheduledTask_Name,
description,
false,
null,
Translations.Service_Common_Error_AccessDenied,
- retryAction: () => System.Threading.Tasks.Task.FromResult(EnableTask(fullPath)));
+ () => System.Threading.Tasks.Task.FromResult(EnableTask(fullPath)));
return false;
}
catch (Exception ex)
@@ -144,12 +142,12 @@ public static class ScheduledTaskService
ExecutionScope.LogError(ex, "Failed to enable task {Path}", fullPath);
ExecutionScope.Track(nameof(EnableTask), false);
ExecutionScope.RecordStep(
- "ScheduledTask",
+ Translations.Service_ScheduledTask_Name,
description,
false,
null,
ex.Message,
- retryAction: () => System.Threading.Tasks.Task.FromResult(EnableTask(fullPath)));
+ () => System.Threading.Tasks.Task.FromResult(EnableTask(fullPath)));
return false;
}
}
@@ -330,7 +328,7 @@ public static class ScheduledTaskService
throw;
}
}
-
+
#region Helpers
private static void CollectTasks(TaskFolder folder, List<ScheduledTaskModel> results)
diff --git a/optimizerDuck/Services/OptimizationServices/ServiceProcessService.cs b/optimizerDuck/Services/OptimizationServices/ServiceProcessService.cs
index 3cbe2d9..212e822 100644
--- a/optimizerDuck/Services/OptimizationServices/ServiceProcessService.cs
+++ b/optimizerDuck/Services/OptimizationServices/ServiceProcessService.cs
@@ -61,19 +61,18 @@ public static class ServiceProcessService
if (service == null)
{
ExecutionScope.LogInfo(
- "[SERVICE][{Name}][FAIL][NOT_FOUND][D=0ms] startup -> {StartupType}",
+ "[SERVICE][{Name}][OK][NOT_FOUND][D=0ms] startup -> {StartupType}",
item.Name,
item.StartupType
);
- ExecutionScope.Track(nameof(ChangeServiceStartupType), false);
+ ExecutionScope.Track(nameof(ChangeServiceStartupType), true);
ExecutionScope.RecordStep(
- "Service",
+ Translations.Service_Service_Name,
description,
- false,
+ true,
null,
- Translations.Service_Service_Error_NotFound,
- retryAction: () => Task.FromResult(ChangeServiceStartupType(item)));
- return false;
+ null);
+ return true;
}
// Record revert: backup current startup type
@@ -124,12 +123,12 @@ public static class ServiceProcessService
ExecutionScope.Track(nameof(ChangeServiceStartupType), registrySuccess);
ExecutionScope.RecordStep(
- "Service",
+ Translations.Service_Service_Name,
description,
registrySuccess,
registrySuccess ? revertStep : null,
registrySuccess ? null : Translations.Service_Service_Error_UpdateRegistryForStartupTypeFailed,
- retryAction: registrySuccess ? null : () => Task.FromResult(ChangeServiceStartupType(item)));
+ registrySuccess ? null : () => Task.FromResult(ChangeServiceStartupType(item)));
return registrySuccess;
}
@@ -143,12 +142,12 @@ public static class ServiceProcessService
ExecutionScope.Track(nameof(ChangeServiceStartupType), false);
ExecutionScope.RecordStep(
- "Service",
+ Translations.Service_Service_Name,
description,
false,
null,
string.Format(Translations.Service_Service_Error_ChangeStartModeFailedWithCode, resultCode),
- retryAction: () => Task.FromResult(ChangeServiceStartupType(item)));
+ () => Task.FromResult(ChangeServiceStartupType(item)));
return false;
}
catch (Exception ex)
@@ -161,12 +160,12 @@ public static class ServiceProcessService
);
ExecutionScope.Track(nameof(ChangeServiceStartupType), false);
ExecutionScope.RecordStep(
- "Service",
+ Translations.Service_Service_Name,
description,
false,
null,
- ex.Message,
- retryAction: () => Task.FromResult(ChangeServiceStartupType(item)));
+ string.Format(Translations.Service_Service_Error_ExceptionOccurred, item.Name, ex.Message),
+ () => Task.FromResult(ChangeServiceStartupType(item)));
return false;
}
}
diff --git a/optimizerDuck/Services/OptimizationServices/ShellService.cs b/optimizerDuck/Services/OptimizationServices/ShellService.cs
index 7151e48..344ee48 100644
--- a/optimizerDuck/Services/OptimizationServices/ShellService.cs
+++ b/optimizerDuck/Services/OptimizationServices/ShellService.cs
@@ -182,17 +182,24 @@ public static class ShellService
var error = success ? null : policy.ErrorFactory(result);
ExecutionScope.RecordStep(
- "Shell",
+ Translations.Service_Shell_Name,
fullCommandForUser,
success,
revertStep,
error,
- retryAction: success ? null : () => Task.FromResult(Run(fileName, arguments, command, serviceName, revertStep, policy).ExitCode == 0));
+ success
+ ? null
+ : () => Task.FromResult(
+ Run(fileName, arguments, command, serviceName, revertStep, policy).ExitCode == 0));
return result;
}
catch (Exception ex)
{
+ ExecutionScope.LogError(ex, "[{Service}][FAIL][EXCEPTION] {Command}",
+ serviceName, fullCommandForUser);
+ ExecutionScope.Track(serviceName, false);
+
var result = new ShellResult
{
Command = fullCommandForUser,
@@ -203,12 +210,13 @@ public static class ShellService
};
ExecutionScope.RecordStep(
- "Shell",
+ Translations.Service_Shell_Name,
fullCommandForUser,
false,
revertStep,
ex.Message,
- retryAction: () => Task.FromResult(Run(fileName, arguments, command, serviceName, revertStep, policy).ExitCode == 0));
+ () => Task.FromResult(Run(fileName, arguments, command, serviceName, revertStep, policy).ExitCode ==
+ 0));
return result;
}
@@ -323,17 +331,25 @@ public static class ShellService
var error = success ? null : policy.ErrorFactory(result);
ExecutionScope.RecordStep(
- "Shell",
+ Translations.Service_Shell_Name,
fullCommandForUser,
success,
revertStep,
error,
- retryAction: success ? null : async () => (await RunAsync(fileName, arguments, command, serviceName, revertStep, policy, ct)).ExitCode == 0);
+ success
+ ? null
+ : async () =>
+ (await RunAsync(fileName, arguments, command, serviceName, revertStep, policy, ct)).ExitCode ==
+ 0);
return result;
}
catch (Exception ex)
{
+ ExecutionScope.LogError(ex, "[{Service}][FAIL][EXCEPTION] {Command}",
+ serviceName, fullCommandForUser);
+ ExecutionScope.Track(serviceName, false);
+
var result = new ShellResult
{
Command = fullCommandForUser,
@@ -344,12 +360,13 @@ public static class ShellService
};
ExecutionScope.RecordStep(
- "Shell",
+ Translations.Service_Shell_Name,
fullCommandForUser,
false,
revertStep,
ex.Message,
- retryAction: async () => (await RunAsync(fileName, arguments, command, serviceName, revertStep, policy, ct)).ExitCode == 0);
+ async () =>
+ (await RunAsync(fileName, arguments, command, serviceName, revertStep, policy, ct)).ExitCode == 0);
return result;
}
diff --git a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
index ad30095..5248df5 100644
--- a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
@@ -13,6 +13,7 @@ using optimizerDuck.Core.Models.UI;
using optimizerDuck.Core.Optimizers;
using optimizerDuck.Resources.Languages;
using optimizerDuck.Services;
+using optimizerDuck.Services.Managers;
using optimizerDuck.UI.ViewModels.Dialogs;
using optimizerDuck.UI.Views.Dialogs;
using Wpf.Ui;
@@ -32,8 +33,10 @@ public partial class OptimizationCategoryViewModel : ViewModel
private readonly IContentDialogService _contentDialogService;
private readonly ILogger<OptimizationCategoryViewModel> _logger;
private readonly OptimizationService _optimizationService;
+ private readonly RevertManager _revertManager;
private readonly ISnackbarService _snackbarService;
[ObservableProperty] private bool _hideApplied;
+ [ObservableProperty] private bool _isProcessing;
[ObservableProperty] private ObservableCollection<IOptimization> _optimizations = [];
// Search, Filter, Sort
@@ -45,12 +48,14 @@ public partial class OptimizationCategoryViewModel : ViewModel
public OptimizationCategoryViewModel(
IOptimizationCategory category,
OptimizationService optimizationService,
+ RevertManager revertManager,
ISnackbarService snackbarService,
IContentDialogService contentDialogService,
ILogger<OptimizationCategoryViewModel> logger)
{
_category = category;
_optimizationService = optimizationService;
+ _revertManager = revertManager;
_snackbarService = snackbarService;
_logger = logger;
_contentDialogService = contentDialogService;
@@ -83,6 +88,9 @@ public partial class OptimizationCategoryViewModel : ViewModel
await LoadOptimizationStatesAsync();
}
+ /// <summary>
+ /// Load all optimizations from the category and apply filters.
+ /// </summary>
private async Task LoadOptimizationStatesAsync()
{
if (_allOptimizations.Count > 0) return;
@@ -101,6 +109,9 @@ public partial class OptimizationCategoryViewModel : ViewModel
ApplyFilter();
}
+ /// <summary>
+ /// Apply current filters to the optimizations.
+ /// </summary>
private void ApplyFilter()
{
var query = _allOptimizations.AsEnumerable();
@@ -141,7 +152,13 @@ public partial class OptimizationCategoryViewModel : ViewModel
OnPropertyChanged(nameof(HasAppliedOptimizations));
}
- // Keep the progress dialog visible while long-running work is running.
+ /// <summary>
+ /// Run a long-running action with a processing dialog.
+ /// </summary>
+ /// <param name="optimization">The optimization to run the action for.</param>
+ /// <param name="action">The action to run.</param>
+ /// <typeparam name="T">The return type of the action.</typeparam>
+ /// <returns>The result of the action.</returns>
private async Task<T> RunWithProcessingDialogAsync<T>(
IOptimization optimization,
Func<IProgress<ProcessingProgress>, Task<T>> action)
@@ -166,6 +183,13 @@ public partial class OptimizationCategoryViewModel : ViewModel
}
}
+ /// <summary>
+ /// Handle failed steps for an optimization.
+ /// </summary>
+ /// <param name="optimization">The optimization that failed.</param>
+ /// <param name="failedSteps">The failed steps.</param>
+ /// <param name="isRevert">Whether the optimization is being reverted.</param>
+ /// <returns>The retry outcome.</returns>
private async Task<RetryOutcome> HandleFailedStepsAsync(IOptimization optimization,
List<OperationStepResult> failedSteps, bool isRevert)
{
@@ -199,6 +223,7 @@ public partial class OptimizationCategoryViewModel : ViewModel
progress => OptimizationService.RetryFailedStepsAsync(
currentFailed,
true,
+ _logger,
progress)))
.OrderByDescending(s => s.Index)
.ToList();
@@ -211,15 +236,25 @@ public partial class OptimizationCategoryViewModel : ViewModel
}
else
{
- currentFailed = (await RunWithProcessingDialogAsync(
+ var newFailed = (await RunWithProcessingDialogAsync(
optimization,
progress => OptimizationService.RetryFailedStepsAsync(
currentFailed,
false,
+ _logger,
progress)))
.OrderBy(s => s.Index)
.ToList();
+ // If any apply step succeeded during this specific retry pass, update RevertManager
+ var succeededThisAttempt =
+ currentFailed.Where(old => newFailed.All(n => n.Index != old.Index)).ToList();
+ foreach (var s in succeededThisAttempt)
+ if (s.RevertStep != null)
+ await _revertManager.AppendOrUpdateRevertStepAsync(optimization.Id,
+ optimization.OptimizationKey, s.Index, s.RevertStep);
+
+ currentFailed = newFailed;
if (currentFailed.Count == 0) return RetryOutcome.Succeeded;
}
}
@@ -230,11 +265,16 @@ public partial class OptimizationCategoryViewModel : ViewModel
/// <summary>
/// Shows a snackbar notification based on the operation outcome.
/// </summary>
+ /// <param name="succeeded">Whether the operation succeeded.</param>
+ /// <param name="partial">Whether the operation was partially successful.</param>
+ /// <param name="failed">Whether the operation failed.</param>
+ /// <param name="operationType">The type of operation.</param>
+ /// <param name="message">The message to show.</param>
+ /// <param name="optimizationName">The name of the optimization.</param>
private void ShowOutcomeSnackbar(bool succeeded, bool partial, bool failed, string operationType,
string message, string optimizationName)
{
if (succeeded)
- {
_snackbarService.Show(
operationType == "apply"
? Translations.Optimization_Apply_Snackbar_Success_Title
@@ -243,9 +283,7 @@ public partial class OptimizationCategoryViewModel : ViewModel
ControlAppearance.Success,
new SymbolIcon { Symbol = SymbolRegular.CheckmarkCircle24, Filled = true },
TimeSpan.FromSeconds(5));
- }
else if (partial)
- {
_snackbarService.Show(
operationType == "apply"
? Translations.Optimization_Apply_Snackbar_Error_Title
@@ -254,9 +292,7 @@ public partial class OptimizationCategoryViewModel : ViewModel
ControlAppearance.Caution,
new SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },
TimeSpan.FromSeconds(5));
- }
else if (failed)
- {
_snackbarService.Show(
operationType == "apply"
? Translations.Optimization_Apply_Snackbar_Error_Title
@@ -265,9 +301,12 @@ public partial class OptimizationCategoryViewModel : ViewModel
ControlAppearance.Danger,
new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
TimeSpan.FromSeconds(5));
- }
}
+ /// <summary>
+ /// Handles the restore point dialog.
+ /// </summary>
+ /// <returns>Whether the user accepted the restore point dialog.</returns>
private async Task<bool> HandleRestorePointAsync()
{
var dialogContent = new RestorePointDialog();
@@ -327,6 +366,11 @@ public partial class OptimizationCategoryViewModel : ViewModel
return true;
}
+ /// <summary>
+ /// Builds the dialog title for an optimization.
+ /// </summary>
+ /// <param name="optimization">The optimization to build the title for.</param>
+ /// <returns>The dialog title.</returns>
private static StackPanel BuildDialogTitle(IOptimization optimization)
{
return new StackPanel
@@ -357,135 +401,157 @@ public partial class OptimizationCategoryViewModel : ViewModel
#region Commands
+
+ /// <summary>
+ /// Toggles the optimization.
+ /// </summary>
+ /// <param name="optimization">The optimization to toggle.</param>
[RelayCommand]
private async Task ToggleOptimizationAsync(IOptimization optimization)
{
- // Keep a stable reference to the previous state in case we need to roll back UI changes.
- var wasApplied = await OptimizationService.IsAppliedAsync(optimization.Id);
-
- if (!_optimizationService.WasRequestedRestorePoint)
+ if (IsProcessing)
{
- if (!await HandleRestorePointAsync())
- {
- optimization.State.IsApplied = wasApplied;
- return;
- }
-
- _optimizationService.WasRequestedRestorePoint = true;
+ _logger.LogWarning("An optimization is already being processed, ignoring spam");
+ return;
}
+ IsProcessing = true;
+
try
{
- // Apply optimization if not already applied
- if (!wasApplied)
+ // Keep a stable reference to the previous state in case we need to roll back UI changes.
+ var wasApplied = await OptimizationService.IsAppliedAsync(optimization.Id);
+
+ if (!_optimizationService.WasRequestedRestorePoint)
{
- _logger.LogInformation("===== START applying optimization {OptimizationName} ({OptimizationId}) =====",
- optimization.OptimizationKey, optimization.Id);
- var applyResult = await RunWithProcessingDialogAsync(
- optimization,
- progress => _optimizationService.ApplyAsync(optimization, progress));
+ if (!await HandleRestorePointAsync())
+ {
+ optimization.State.IsApplied = wasApplied;
+ return;
+ }
- await OptimizationService.UpdateOptimizationStateAsync(optimization);
+ _optimizationService.WasRequestedRestorePoint = true;
+ }
- // If result status is Failed, we can't retry it
- if (applyResult.Status == OptimizationSuccessResult.Failed)
+ try
+ {
+ // Apply optimization if not already applied
+ if (!wasApplied)
{
- ShowOutcomeSnackbar(false, false, true, "apply",
+ _logger.LogInformation(
+ "===== START applying optimization {OptimizationName} ({OptimizationId}) =====",
+ optimization.OptimizationKey, optimization.Id);
+ var applyResult = await RunWithProcessingDialogAsync(
+ optimization,
+ progress => _optimizationService.ApplyAsync(optimization, progress));
+
+
+ // If result status is Failed, we can't retry it
+ if (applyResult.Status == OptimizationSuccessResult.Failed)
+ {
+ ShowOutcomeSnackbar(false, false, true, "apply",
+ applyResult.Message, optimization.OptimizationKey);
+
+ _logger.LogWarning("Apply failed for {Name}: {Message}",
+ optimization.OptimizationKey, applyResult.Message);
+
+ _logger.LogInformation(
+ "===== END applying optimization {OptimizationName} ({OptimizationId}) =====",
+ optimization.OptimizationKey, optimization.Id);
+
+ await OptimizationService.UpdateOptimizationStateAsync(optimization);
+ return;
+ }
+
+ // Retry only if there are some successful steps and some failed steps
+ var retryOutcome = await HandleFailedStepsAsync(
+ optimization,
+ applyResult.FailedSteps,
+ false);
+
+ await OptimizationService.UpdateOptimizationStateAsync(optimization);
+
+ var succeeded = applyResult.Status == OptimizationSuccessResult.Success ||
+ retryOutcome == RetryOutcome.Succeeded;
+ var partial = retryOutcome == RetryOutcome.Skipped;
+ var failed = retryOutcome == RetryOutcome.None &&
+ applyResult.Status != OptimizationSuccessResult.Success;
+
+ ShowOutcomeSnackbar(succeeded, partial, failed, "apply",
applyResult.Message, optimization.OptimizationKey);
- if (applyResult.Exception != null)
- _logger.LogError(applyResult.Exception, "Failed to apply {Name}",
- optimization.OptimizationKey);
+ if (succeeded)
+ _logger.LogInformation("Successfully applied {Name}", optimization.OptimizationKey);
+ else if (partial)
+ _logger.LogWarning("Partially applied {Name}", optimization.OptimizationKey);
else
_logger.LogWarning("Failed to apply {Name}", optimization.OptimizationKey);
_logger.LogInformation(
"===== END applying optimization {OptimizationName} ({OptimizationId}) =====",
optimization.OptimizationKey, optimization.Id);
- return;
}
-
- // Retry only if there are some successful steps and some failed steps
- var retryOutcome = await HandleFailedStepsAsync(
- optimization,
- applyResult.FailedSteps,
- false);
-
- var succeeded = applyResult.Status == OptimizationSuccessResult.Success ||
- retryOutcome == RetryOutcome.Succeeded;
- var partial = retryOutcome == RetryOutcome.Skipped;
- var failed = retryOutcome == RetryOutcome.None &&
- applyResult.Status != OptimizationSuccessResult.Success;
-
- ShowOutcomeSnackbar(succeeded, partial, failed, "apply",
- applyResult.Message, optimization.OptimizationKey);
-
- if (applyResult.Exception != null)
- _logger.LogError(applyResult.Exception, "Failed to apply {Name}", optimization.OptimizationKey);
- else if (succeeded)
- _logger.LogInformation("Successfully applied {Name}", optimization.OptimizationKey);
- else if (partial)
- _logger.LogWarning("Partially applied {Name}", optimization.OptimizationKey);
else
- _logger.LogWarning("Failed to apply {Name}", optimization.OptimizationKey);
+ {
+ // Revert optimization if already applied
+ _logger.LogInformation(
+ "===== START reverting optimization {OptimizationName} ({OptimizationId}) =====",
+ optimization.OptimizationKey, optimization.Id);
+
+ var revertResult = await RunWithProcessingDialogAsync(
+ optimization,
+ progress => _optimizationService.RevertAsync(optimization, progress));
+
+
+ var retryOutcome = await HandleFailedStepsAsync(
+ optimization,
+ revertResult.FailedStepDetails,
+ true);
+
+ await OptimizationService.UpdateOptimizationStateAsync(optimization);
+
+ var succeeded = revertResult.Success || retryOutcome == RetryOutcome.Succeeded;
+ var partial = retryOutcome == RetryOutcome.Skipped && !revertResult.IsCompleteFailure;
+ var failed = (retryOutcome == RetryOutcome.None && !revertResult.Success) ||
+ (revertResult.IsCompleteFailure && retryOutcome == RetryOutcome.Skipped);
+
+ ShowOutcomeSnackbar(succeeded, partial, failed, "revert",
+ revertResult.Message, optimization.OptimizationKey);
- _logger.LogInformation("===== END applying optimization {OptimizationName} ({OptimizationId}) =====",
- optimization.OptimizationKey, optimization.Id);
+ if (succeeded)
+ _logger.LogInformation("Successfully reverted {Name}", optimization.OptimizationKey);
+ else if (partial)
+ _logger.LogWarning("Partially reverted {Name}", optimization.OptimizationKey);
+ else
+ _logger.LogWarning("Failed to revert {Name}", optimization.OptimizationKey);
+ _logger.LogInformation(
+ "===== END reverting optimization {OptimizationName} ({OptimizationId}) =====",
+ optimization.OptimizationKey, optimization.Id);
+ }
}
- else
+ catch (Exception ex)
{
- // Revert optimization if already applied
- _logger.LogInformation(
- "===== START reverting optimization {OptimizationName} ({OptimizationId}) =====",
- optimization.OptimizationKey, optimization.Id);
-
- var revertResult = await RunWithProcessingDialogAsync(
- optimization,
- progress => _optimizationService.RevertAsync(optimization, progress));
-
- // Refresh state after revert attempt.
- await OptimizationService.UpdateOptimizationStateAsync(optimization);
-
- var retryOutcome = await HandleFailedStepsAsync(
- optimization,
- revertResult.FailedStepDetails,
- true);
-
- var succeeded = revertResult.Success || retryOutcome == RetryOutcome.Succeeded;
- var partial = retryOutcome == RetryOutcome.Skipped;
- var failed = retryOutcome == RetryOutcome.None && !revertResult.Success;
-
- ShowOutcomeSnackbar(succeeded, partial, failed, "revert",
- revertResult.Message, optimization.OptimizationKey);
-
- if (revertResult.Exception != null)
- _logger.LogError(revertResult.Exception, "Failed to revert {Name}",
- optimization.OptimizationKey);
- else if (succeeded)
- _logger.LogInformation("Successfully reverted {Name}", optimization.OptimizationKey);
- else if (partial)
- _logger.LogWarning("Partially reverted {Name}", optimization.OptimizationKey);
- else
- _logger.LogWarning("Failed to revert {Name}", optimization.OptimizationKey);
- _logger.LogInformation(
- "===== END reverting optimization {OptimizationName} ({OptimizationId}) =====",
- optimization.OptimizationKey, optimization.Id);
+ optimization.State.IsApplied = wasApplied; // revert UI state on failure
+ _logger.LogError(ex, "Failed to toggle optimization {Name}", optimization.OptimizationKey);
+ _snackbarService.Show(
+ Translations.Optimization_Toggle_Snackbar_Error_Title,
+ string.Format(Translations.Optimization_Toggle_Snackbar_Error_Message, ex.Message),
+ ControlAppearance.Danger,
+ new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
+ TimeSpan.FromSeconds(5)
+ );
}
}
- catch (Exception ex)
+ finally
{
- optimization.State.IsApplied = wasApplied; // revert UI state on failure
- _logger.LogError(ex, "Failed to toggle optimization {Name}", optimization.OptimizationKey);
- _snackbarService.Show(
- Translations.Optimization_Toggle_Snackbar_Error_Title,
- string.Format(Translations.Optimization_Toggle_Snackbar_Error_Message, ex.Message),
- ControlAppearance.Danger,
- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
- TimeSpan.FromSeconds(5)
- );
+ IsProcessing = false;
}
}
+ /// <summary>
+ /// Shows the details of an optimization.
+ /// </summary>
+ /// <param name="optimization">The optimization to show details for.</param>
[RelayCommand]
private async Task ShowDetailsAsync(IOptimization optimization)
{
@@ -500,6 +566,10 @@ public partial class OptimizationCategoryViewModel : ViewModel
var result = await _contentDialogService.ShowAsync(dialog, CancellationToken.None);
}
+ /// <summary>
+ /// Opens the source code of an optimization on GitHub.
+ /// </summary>
+ /// <param name="optimization">The optimization to view the source code for.</param>
[RelayCommand]
private async Task ViewSourceOnGitHubAsync(IOptimization optimization)
{
diff --git a/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs
index 3d5ab35..1f959bc 100644
--- a/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs
@@ -126,7 +126,7 @@ public partial class SettingsViewModel(
{
var result = await ConfirmationDialogAsync(Translations.Settings_ClearResources_Description);
if (result == ContentDialogResult.Primary)
- OptimizationService.ClearResources();
+ OptimizationService.ClearResources(logger);
}
[RelayCommand]
@@ -135,7 +135,7 @@ public partial class SettingsViewModel(
var result = await ConfirmationDialogAsync(Translations.Settings_ClearRevertData_Description);
if (result == ContentDialogResult.Primary)
{
- RevertManager.ClearAllRevertData();
+ RevertManager.ClearAllRevertData(logger);
// Refresh optimizations
await OptimizationService.UpdateOptimizationStateAsync(
optimizationRegistry.OptimizationCategories.SelectMany(c => c.Optimizations));
diff --git a/optimizerDuck/UI/Views/Pages/Optimizations/OptimizationPage.xaml b/optimizerDuck/UI/Views/Pages/Optimizations/OptimizationPage.xaml
index 1f78a5c..e085eaa 100644
--- a/optimizerDuck/UI/Views/Pages/Optimizations/OptimizationPage.xaml
+++ b/optimizerDuck/UI/Views/Pages/Optimizations/OptimizationPage.xaml
@@ -341,7 +341,7 @@
CommandParameter="{Binding}"
Cursor="Hand"
HorizontalAlignment="Right"
- IsChecked="{Binding State.IsApplied, Mode=TwoWay}"
+ IsChecked="{Binding State.IsApplied, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,5,0"
VerticalAlignment="Center" />
<ui:Button