Skip to content

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

feat: improve optimization sẻvice

itsfatduckdba06c3c8c38
diff --git a/optimizerDuck/App.xaml.cs b/optimizerDuck/App.xaml.cs
index c8d54da..23efd55 100644
--- a/optimizerDuck/App.xaml.cs
+++ b/optimizerDuck/App.xaml.cs
@@ -180,7 +180,6 @@ public partial class App : Application
services.AddSingleton<BloatwareService>();
services.AddSingleton<DiskCleanupService>();
services.AddSingleton<StartupManagerService>();
- services.AddSingleton<ScheduledTaskService>();
services.AddSingleton<SystemInfoService>();
services.AddSingleton<StreamService>();
services.AddSingleton<UpdaterService>();
diff --git a/optimizerDuck/Core/Models/Revert/Steps/ScheduledTaskRevertStep.cs b/optimizerDuck/Core/Models/Revert/Steps/ScheduledTaskRevertStep.cs
new file mode 100644
index 0000000..2ef2750
--- /dev/null
+++ b/optimizerDuck/Core/Models/Revert/Steps/ScheduledTaskRevertStep.cs
@@ -0,0 +1,68 @@
+using Newtonsoft.Json.Linq;
+using optimizerDuck.Core.Interfaces;
+using optimizerDuck.Services.OptimizationServices;
+
+namespace optimizerDuck.Core.Models.Revert.Steps;
+
+/// <summary>
+/// Represents a revert step that restores a scheduled task to its original enabled/disabled state.
+/// </summary>
+public class ScheduledTaskRevertStep : IRevertStep
+{
+ /// <summary>
+ /// The full path of the scheduled task (e.g., \Microsoft\Windows\...).
+ /// </summary>
+ public string FullPath { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Whether the task was originally enabled before the optimization.
+ /// </summary>
+ public bool OriginalEnabled { get; set; }
+
+ /// <inheritdoc />
+ public string Type => "ScheduledTask";
+
+ /// <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;
+ }
+ });
+ }
+
+ /// <inheritdoc />
+ public JObject ToData()
+ {
+ return new JObject
+ {
+ [nameof(FullPath)] = FullPath,
+ [nameof(OriginalEnabled)] = OriginalEnabled
+ };
+ }
+
+ /// <summary>
+ /// Deserializes a <see cref="ScheduledTaskRevertStep" /> from JSON data.
+ /// </summary>
+ /// <param name="data">The JSON data to deserialize.</param>
+ /// <returns>A new <see cref="ScheduledTaskRevertStep" /> instance.</returns>
+ public static ScheduledTaskRevertStep FromData(JObject data)
+ {
+ return new ScheduledTaskRevertStep
+ {
+ FullPath = data[nameof(FullPath)]?.ToString() ?? string.Empty,
+ OriginalEnabled = data[nameof(OriginalEnabled)]?.Value<bool>() ?? true
+ };
+ }
+}
diff --git a/optimizerDuck/Resources/Languages/Translations.Designer.cs b/optimizerDuck/Resources/Languages/Translations.Designer.cs
index efb91d3..8f1ed66 100644
--- a/optimizerDuck/Resources/Languages/Translations.Designer.cs
+++ b/optimizerDuck/Resources/Languages/Translations.Designer.cs
@@ -1158,6 +1158,24 @@ namespace optimizerDuck.Resources.Languages {
}
}
+ /// <summary>
+ /// Looks up a localized string similar to Optimization applied successfully.
+ /// </summary>
+ internal static string Optimization_Apply_Snackbar_Success_Title {
+ get {
+ return ResourceManager.GetString("Optimization.Apply.Snackbar.Success.Title", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Optimization reverted successfully.
+ /// </summary>
+ internal static string Optimization_Revert_Snackbar_Success_Title {
+ get {
+ return ResourceManager.GetString("Optimization.Revert.Snackbar.Success.Title", resourceCulture);
+ }
+ }
+
/// <summary>
/// Looks up a localized string similar to Successfully reverted {0}!.
/// </summary>
@@ -2656,6 +2674,15 @@ namespace optimizerDuck.Resources.Languages {
}
}
+ /// <summary>
+ /// Looks up a localized string similar to Revert step failed.
+ /// </summary>
+ internal static string Revert_Error_StepFailed {
+ get {
+ return ResourceManager.GetString("Revert.Error.StepFailed", resourceCulture);
+ }
+ }
+
/// <summary>
/// Looks up a localized string similar to No revert data found for {0}..
/// </summary>
diff --git a/optimizerDuck/Resources/Languages/Translations.resx b/optimizerDuck/Resources/Languages/Translations.resx
index 22c26f6..d210af8 100644
--- a/optimizerDuck/Resources/Languages/Translations.resx
+++ b/optimizerDuck/Resources/Languages/Translations.resx
@@ -348,6 +348,9 @@
</data>
<data name="Revert.Error.InvalidSteps" xml:space="preserve">
<value>Invalid revert steps: {0}</value>
+ </data>
+ <data name="Revert.Error.StepFailed" xml:space="preserve">
+ <value>Revert step failed</value>
</data>
<data name="Revert.Error.OptimizationIdMismatch" xml:space="preserve">
<value>OptimizationId mismatch.</value>
@@ -485,6 +488,12 @@ Current version: {0}</value>
</data>
<data name="Optimization.Revert.Snackbar.Error.Title" xml:space="preserve">
<value>Couldn't revert optimization</value>
+ </data>
+ <data name="Optimization.Apply.Snackbar.Success.Title" xml:space="preserve">
+ <value>Optimization applied successfully</value>
+ </data>
+ <data name="Optimization.Revert.Snackbar.Success.Title" xml:space="preserve">
+ <value>Optimization reverted successfully</value>
</data>
<data name="Optimization.Toggle.Snackbar.Error.Title" xml:space="preserve">
<value>Couldn't toggle optimization</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
index 5c8fa21..1832eff 100644
--- a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
+++ b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
@@ -350,6 +350,9 @@
</data>
<data name="Revert.Error.InvalidSteps" xml:space="preserve">
<value>Các bước hoàn tác không hợp lệ: {0}</value>
+ </data>
+ <data name="Revert.Error.StepFailed" xml:space="preserve">
+ <value>Bước hoàn tác thất bại</value>
</data>
<data name="Revert.Error.OptimizationIdMismatch" xml:space="preserve">
<value>OptimizationId không khớp.</value>
@@ -483,6 +486,12 @@ Phiên bản hiện tại: {0} </value>
</data>
<data name="Optimization.Revert.Snackbar.Error.Title" xml:space="preserve">
<value>Đã xảy ra lỗi sau khi hoàn tác</value>
+ </data>
+ <data name="Optimization.Apply.Snackbar.Success.Title" xml:space="preserve">
+ <value>Áp dụng tối ưu thành công</value>
+ </data>
+ <data name="Optimization.Revert.Snackbar.Success.Title" xml:space="preserve">
+ <value>Hoàn tác tối ưu thành công</value>
</data>
<data name="Optimization.Toggle.Snackbar.Error.Title" xml:space="preserve">
<value>Không thể áp dụng/hoàn tác tối ưu</value>
diff --git a/optimizerDuck/Services/Managers/RevertManager.cs b/optimizerDuck/Services/Managers/RevertManager.cs
index 80f014d..8191eb8 100644
--- a/optimizerDuck/Services/Managers/RevertManager.cs
+++ b/optimizerDuck/Services/Managers/RevertManager.cs
@@ -1,9 +1,11 @@
using System.IO;
+using System.Reflection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
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;
@@ -21,6 +23,12 @@ public class RevertManager(ILogger<RevertManager> logger)
/// </summary>
private static readonly AsyncLocal<RevertContext?> _current = new();
+ /// <summary>
+ /// Auto-discovered registry mapping step type strings to their FromData factory methods.
+ /// Built once at startup via reflection.
+ /// </summary>
+ private static readonly Dictionary<string, Func<JObject, IRevertStep>> _stepRegistry = BuildStepRegistry();
+
/// <summary>
/// Gets the current revert context for the active async operation.
/// </summary>
@@ -96,9 +104,8 @@ public class RevertManager(ILogger<RevertManager> logger)
}
public async Task<RevertResult> RevertAsync(Guid optimizationId, string optimizationKey,
- IProgress<ProcessingProgress>? progress = null)
+ IProgress<ProcessingProgress>? progress = null, int maxRetries = 1)
{
- // Load revert data, validate, then execute steps in reverse order.
try
{
var validation = await ValidateAsync(optimizationId);
@@ -124,9 +131,11 @@ public class RevertManager(ILogger<RevertManager> logger)
};
}
- logger.LogInformation("Reverting {Name} with {Count} steps", optimizationKey, steps.Count);
+ logger.LogInformation("Reverting {Name} with {Count} steps (maxRetries={MaxRetries})",
+ optimizationKey, steps.Count, maxRetries);
- var failedSteps = 0;
+ var failedStepDetails = new List<OperationStepResult>();
+ var totalSteps = steps.Count;
var stack = new Stack<RevertStepEntry>(steps);
while (stack.Count > 0)
@@ -135,22 +144,69 @@ public class RevertManager(ILogger<RevertManager> logger)
progress?.Report(new ProcessingProgress
{
- Message = string.Format(Translations.Optimization_Revert_ExecutingStep, currentIndex, steps.Count,
+ Message = string.Format(Translations.Optimization_Revert_ExecutingStep, currentIndex, totalSteps,
step.Type),
IsIndeterminate = false,
Value = currentIndex,
- Total = steps.Count
+ Total = totalSteps
});
- var success = await step.ExecuteAsync();
- if (!success) failedSteps++;
+ var success = false;
+ Exception? lastError = null;
+
+ // Retry loop: attempt up to maxRetries + 1 times total
+ for (var attempt = 0; attempt <= maxRetries; attempt++)
+ {
+ 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)); // progressive delay
+ }
+ }
+
+ if (!success)
+ {
+ logger.LogError(lastError, "Revert step {Index} ({Type}) failed after {Attempts} attempt(s)",
+ currentIndex, step.Type, maxRetries + 1);
+
+ failedStepDetails.Add(new OperationStepResult
+ {
+ Index = currentIndex,
+ Name = step.Type,
+ Description = $"Revert step #{currentIndex}",
+ Success = false,
+ Error = lastError?.Message ?? Translations.Revert_Error_StepFailed,
+ RetryAction = async () => await step.ExecuteAsync()
+ });
+ }
}
- var allFailed = failedSteps == steps.Count;
- var hasFailures = failedSteps > 0;
+ var failedCount = failedStepDetails.Count;
+ var allFailed = failedCount == totalSteps;
+ var hasFailures = failedCount > 0;
- if (!hasFailures)
+ // Partial revert: save remaining failed steps back to file for later retry
+ 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)
+ {
await RemoveAsync(optimizationId, optimizationKey);
+ }
return new RevertResult
{
@@ -159,8 +215,9 @@ public class RevertManager(ILogger<RevertManager> logger)
? string.Format(Translations.Optimization_Revert_Error_Failed, optimizationKey)
: hasFailures
? string.Format(Translations.Optimization_Revert_Error_FailedWithSteps, optimizationKey,
- failedSteps)
- : string.Format(Translations.Optimization_Revert_Success, optimizationKey)
+ failedCount)
+ : string.Format(Translations.Optimization_Revert_Success, optimizationKey),
+ FailedStepDetails = failedStepDetails
};
}
catch (Exception ex)
@@ -175,21 +232,73 @@ public class RevertManager(ILogger<RevertManager> logger)
}
}
+ /// <summary>
+ /// Saves only the failed steps back to the revert file so a subsequent revert can retry them.
+ /// </summary>
+ private async Task SaveFailedStepsAsync(Guid optimizationId, string optimizationName,
+ List<RevertStepEntry> allSteps, List<OperationStepResult> failedDetails)
+ {
+ var filePath = Path.Combine(Shared.RevertDirectory, optimizationId + ".json");
+ var tempPath = filePath + ".tmp";
+
+ try
+ {
+ var failedIndices = new HashSet<int>(failedDetails.Select(f => f.Index));
+ var remainingSteps = allSteps
+ .Where(s => failedIndices.Contains(s.Index))
+ .Select(s => new RevertStepData
+ {
+ Type = s.Step.Type,
+ Data = s.Step.ToData()
+ })
+ .ToList();
+
+ var payload = new RevertData
+ {
+ OptimizationId = optimizationId,
+ OptimizationName = optimizationName,
+ AppliedAt = DateTime.Now,
+ Steps = remainingSteps
+ };
+
+ 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);
+ }
+ catch
+ {
+ // Best-effort cleanup only.
+ }
+
+ logger.LogError(ex, "Failed to save remaining failed steps for {Name}", optimizationName);
+ }
+ }
+
private async Task<List<RevertStepEntry>> LoadStepsAsync(Guid optimizationId)
{
var filePath = Path.Combine(Shared.RevertDirectory, optimizationId + ".json");
if (!File.Exists(filePath))
- return new List<RevertStepEntry>();
+ return [];
try
{
var content = await File.ReadAllTextAsync(filePath);
if (string.IsNullOrWhiteSpace(content))
- return new List<RevertStepEntry>();
+ return [];
var revertData = JsonConvert.DeserializeObject<RevertData>(content);
if (revertData == null || revertData.Steps.Count == 0)
- return new List<RevertStepEntry>();
+ return [];
var stepsList = new List<RevertStepEntry>();
var index = 0;
@@ -197,7 +306,12 @@ public class RevertManager(ILogger<RevertManager> logger)
{
var step = DeserializeStep(stepData.Type, stepData.Data);
if (step == null)
- throw new InvalidDataException($"Invalid revert step type '{stepData.Type}'.");
+ {
+ logger.LogWarning("Skipping unknown revert step type '{Type}' at index {Index}",
+ stepData.Type, index);
+ continue;
+ }
+
index++;
stepsList.Add(new RevertStepEntry(index, step));
}
@@ -207,7 +321,7 @@ public class RevertManager(ILogger<RevertManager> logger)
catch (Exception ex)
{
logger.LogError(ex, "Failed to load revert steps for {Id}", optimizationId);
- return new List<RevertStepEntry>();
+ return [];
}
}
@@ -230,8 +344,7 @@ public class RevertManager(ILogger<RevertManager> logger)
if (string.IsNullOrWhiteSpace(content))
return null;
- var revertData = JsonConvert.DeserializeObject<RevertData>(content);
- return revertData;
+ return JsonConvert.DeserializeObject<RevertData>(content);
}
catch
{
@@ -258,6 +371,69 @@ public class RevertManager(ILogger<RevertManager> logger)
return Task.CompletedTask;
}
+ #region Auto-Discovery
+
+ /// <summary>
+ /// Builds the step registry by scanning all IRevertStep implementations via reflection.
+ /// Each step type must have a static FromData(JObject) method.
+ /// </summary>
+ private static Dictionary<string, Func<JObject, IRevertStep>> BuildStepRegistry()
+ {
+ var registry = new Dictionary<string, Func<JObject, IRevertStep>>(StringComparer.OrdinalIgnoreCase);
+
+ try
+ {
+ var stepTypes = Assembly.GetExecutingAssembly()
+ .GetTypes()
+ .Where(t => t is { IsAbstract: false, IsInterface: false }
+ && typeof(IRevertStep).IsAssignableFrom(t));
+
+ foreach (var type in stepTypes)
+ {
+ try
+ {
+ // Create a temporary instance to get the Type property value
+ var instance = (IRevertStep)Activator.CreateInstance(type)!;
+ var typeKey = instance.Type;
+
+ // Find the static FromData method (accepts JObject or JToken)
+ var fromDataMethod = type.GetMethod("FromData",
+ BindingFlags.Static | BindingFlags.Public,
+ null,
+ [typeof(JObject)],
+ null);
+
+ // Fallback: try JToken parameter
+ fromDataMethod ??= type.GetMethod("FromData",
+ BindingFlags.Static | BindingFlags.Public,
+ null,
+ [typeof(JToken)],
+ null);
+
+ if (fromDataMethod != null)
+ registry[typeKey] = data =>
+ (IRevertStep)fromDataMethod.Invoke(null, [data])!;
+ }
+ catch
+ {
+ // Skip types that can't be instantiated or lack FromData
+ }
+ }
+ }
+ catch
+ {
+ // Fallback: if reflection fails entirely, the registry remains empty
+ // and DeserializeStep will return null for all types.
+ }
+
+ return registry;
+ }
+
+ /// <summary>
+ /// Returns the list of registered revert step type names.
+ /// </summary>
+ public static IReadOnlyCollection<string> RegisteredStepTypes => _stepRegistry.Keys.ToList().AsReadOnly();
+
private IRevertStep? DeserializeStep(string serviceType, JToken data)
{
try
@@ -272,13 +448,12 @@ public class RevertManager(ILogger<RevertManager> logger)
return null;
}
- return serviceType switch
- {
- "Registry" => RegistryRevertStep.FromData(obj),
- "Service" => ServiceRevertStep.FromData(obj),
- "Shell" => ShellRevertStep.FromData(obj),
- _ => null
- };
+ if (_stepRegistry.TryGetValue(serviceType, out var factory))
+ return factory(obj);
+
+ logger.LogWarning("Unknown revert step type '{Type}'. Registered types: {Types}",
+ serviceType, string.Join(", ", _stepRegistry.Keys));
+ return null;
}
catch (Exception ex)
{
@@ -287,6 +462,10 @@ public class RevertManager(ILogger<RevertManager> logger)
}
}
+ #endregion Auto-Discovery
+
+ #region Validation
+
private async Task<RevertValidationResult> ValidateAsync(Guid optimizationId)
{
var filePath = Path.Combine(Shared.RevertDirectory, optimizationId + ".json");
@@ -332,6 +511,12 @@ public class RevertManager(ILogger<RevertManager> logger)
foreach (var stepData in data.Steps)
{
if (string.IsNullOrWhiteSpace(stepData.Type))
+ {
+ invalidSteps.Add("(empty)");
+ continue;
+ }
+
+ if (!_stepRegistry.ContainsKey(stepData.Type))
{
invalidSteps.Add(stepData.Type);
continue;
@@ -349,6 +534,8 @@ public class RevertManager(ILogger<RevertManager> logger)
return RevertValidationResult.Success();
}
+ #endregion Validation
+
internal static void ClearCurrent()
{
_current.Value = null;
diff --git a/optimizerDuck/Services/OptimizationService.cs b/optimizerDuck/Services/OptimizationService.cs
index 2721670..e27e8e3 100644
--- a/optimizerDuck/Services/OptimizationService.cs
+++ b/optimizerDuck/Services/OptimizationService.cs
@@ -263,7 +263,7 @@ public class OptimizationService(
{
Status = status,
Message = string.Format(Translations.Optimization_Apply_Error_Failed,
- optimization.OptimizationKey, ex.Message),
+ optimization.OptimizationKey),
Exception = ex,
FailedSteps = failedSteps
};
@@ -275,9 +275,10 @@ public class OptimizationService(
await revertContext.DisposeAsync();
revertContextDisposed = true;
}
- catch
+ catch (Exception saveEx)
{
- // Best-effort cleanup only.
+ _logger.LogError(saveEx, "Failed to save revert data after exception for {Name}",
+ optimization.OptimizationKey);
}
}
finally
@@ -326,10 +327,10 @@ public class OptimizationService(
optimization.OptimizationKey,
progress);
- var steps = tracker.GetSteps().ToList();
- result.FailedStepDetails = steps
- .Where(s => s.Error != null)
- .ToList();
+ // Merge tracker steps with revert result details
+ var trackerSteps = tracker.GetSteps().ToList();
+ if (result.FailedStepDetails.Count == 0 && trackerSteps.Any(s => !s.Success))
+ result.FailedStepDetails = trackerSteps.Where(s => !s.Success).ToList();
progress?.Report(new ProcessingProgress
{
@@ -428,16 +429,18 @@ public class OptimizationService(
}
/// <summary>
- /// Retries failed optimization steps.
+ /// Retries failed optimization steps with configurable max retry attempts.
/// </summary>
/// <param name="failedSteps">The steps that previously failed.</param>
/// <param name="reverseOrder">Whether to execute steps in reverse order.</param>
/// <param name="progress">A progress reporter for UI updates (optional).</param>
+ /// <param name="maxRetries">Maximum number of retry attempts per step (default 3).</param>
/// <returns>A list of steps that still failed after retry.</returns>
public static async Task<List<OperationStepResult>> RetryFailedStepsAsync(
IReadOnlyList<OperationStepResult> failedSteps,
bool reverseOrder,
- IProgress<ProcessingProgress>? progress = null)
+ IProgress<ProcessingProgress>? progress = null,
+ int maxRetries = 3)
{
if (failedSteps.Count == 0)
return [];
@@ -477,7 +480,23 @@ public class OptimizationService(
continue;
}
- var success = await step.RetryAction();
+ var success = false;
+ for (var attempt = 0; attempt < maxRetries; attempt++)
+ {
+ try
+ {
+ success = await step.RetryAction();
+ if (success) break;
+ }
+ catch
+ {
+ // Retry on next attempt
+ }
+
+ if (attempt < maxRetries - 1)
+ await Task.Delay(200 * (attempt + 1)); // progressive delay
+ }
+
if (!success)
stillFailed.Add(step);
}
diff --git a/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs b/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs
index 368038e..e6b5c89 100644
--- a/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs
+++ b/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs
@@ -1,19 +1,17 @@
using System.Collections.ObjectModel;
-using Microsoft.Extensions.Logging;
using Microsoft.Win32.TaskScheduler;
+using optimizerDuck.Core.Models.Revert.Steps;
using optimizerDuck.Core.Models.ScheduledTask;
using optimizerDuck.Resources.Languages;
+using optimizerDuck.Services.Managers;
using Task = Microsoft.Win32.TaskScheduler.Task;
namespace optimizerDuck.Services.OptimizationServices;
-public class ScheduledTaskService(ILogger<ScheduledTaskService> logger)
+public static class ScheduledTaskService
{
- #region Optimization uses
-
/// <summary>
/// Checks whether a task at the given full path exists and is enabled.
- /// Static overload for use from optimizers.
/// </summary>
public static bool IsTaskEnabled(string fullPath)
{
@@ -23,44 +21,137 @@ public class ScheduledTaskService(ILogger<ScheduledTaskService> logger)
var task = ts.GetTask(fullPath);
return task is { Enabled: true };
}
- catch
+ catch (Exception ex)
{
+ ServiceTracker.LogDebug("Failed to check task enabled state {Path}: {Error}", fullPath, ex.Message);
return false;
}
}
/// <summary>
- /// Disables a task by full path. Static overload for use from optimizers.
+ /// Disables a task by full path with logging, tracking, and revert recording.
/// </summary>
- public static void DisableTask(string fullPath)
+ public static bool DisableTask(string fullPath)
{
- using var ts = new TaskService();
- var task = ts.GetTask(fullPath) ??
- throw new InvalidOperationException(string.Format(Translations.ScheduledTasks_Error_TaskNotFound,
- fullPath));
- task.Enabled = false;
+ var description = $"Disable: {fullPath}";
+ try
+ {
+ using var ts = new TaskService();
+ var task = ts.GetTask(fullPath) ??
+ throw new InvalidOperationException(string.Format(Translations.ScheduledTasks_Error_TaskNotFound,
+ fullPath));
+
+ var wasEnabled = task.Enabled;
+ task.Enabled = false;
+
+ // Record revert step: restore to previous enabled state
+ if (wasEnabled)
+ RevertManager.Record(new ScheduledTaskRevertStep
+ {
+ FullPath = fullPath,
+ OriginalEnabled = true
+ });
+
+ ServiceTracker.LogInfo("Disabled task {Path}", fullPath);
+ ServiceTracker.Track(nameof(DisableTask), true);
+ ServiceTracker.TrackStep(
+ "ScheduledTask",
+ description,
+ true,
+ null,
+ () => System.Threading.Tasks.Task.Run(() => DisableTask(fullPath)));
+ return true;
+ }
+ catch (UnauthorizedAccessException)
+ {
+ ServiceTracker.LogError(null, "Access denied disabling task {Path}", fullPath);
+ ServiceTracker.Track(nameof(DisableTask), false);
+ ServiceTracker.TrackStep(
+ "ScheduledTask",
+ description,
+ false,
+ Translations.Service_Common_Error_AccessDenied,
+ () => System.Threading.Tasks.Task.Run(() => DisableTask(fullPath)));
+ return false;
+ }
+ catch (Exception ex)
+ {
+ ServiceTracker.LogError(ex, "Failed to disable task {Path}", fullPath);
+ ServiceTracker.Track(nameof(DisableTask), false);
+ ServiceTracker.TrackStep(
+ "ScheduledTask",
+ description,
+ false,
+ ex.Message,
+ () => System.Threading.Tasks.Task.Run(() => DisableTask(fullPath)));
+ return false;
+ }
}
/// <summary>
- /// Enables a task by full path. Static overload for use from optimizers.
+ /// Enables a task by full path with logging, tracking, and revert recording.
/// </summary>
- public static void EnableTask(string fullPath)
+ public static bool EnableTask(string fullPath)
{
- using var ts = new TaskService();
- var task = ts.GetTask(fullPath) ??
- throw new InvalidOperationException(string.Format(Translations.ScheduledTasks_Error_TaskNotFound,
- fullPath));
- task.Enabled = true;
- }
+ var description = $"Enable: {fullPath}";
+ try
+ {
+ using var ts = new TaskService();
+ var task = ts.GetTask(fullPath) ??
+ throw new InvalidOperationException(string.Format(Translations.ScheduledTasks_Error_TaskNotFound,
+ fullPath));
+
+ var wasEnabled = task.Enabled;
+ task.Enabled = true;
- #endregion Optimization uses
+ // Record revert step: restore to previous enabled state
+ if (!wasEnabled)
+ RevertManager.Record(new ScheduledTaskRevertStep
+ {
+ FullPath = fullPath,
+ OriginalEnabled = false
+ });
- #region Main Methods
+ ServiceTracker.LogInfo("Enabled task {Path}", fullPath);
+ ServiceTracker.Track(nameof(EnableTask), true);
+ ServiceTracker.TrackStep(
+ "ScheduledTask",
+ description,
+ true,
+ null,
+ () => System.Threading.Tasks.Task.Run(() => EnableTask(fullPath)));
+ return true;
+ }
+ catch (UnauthorizedAccessException)
+ {
+ ServiceTracker.LogError(null, "Access denied enabling task {Path}", fullPath);
+ ServiceTracker.Track(nameof(EnableTask), false);
+ ServiceTracker.TrackStep(
+ "ScheduledTask",
+ description,
+ false,
+ Translations.Service_Common_Error_AccessDenied,
+ () => System.Threading.Tasks.Task.Run(() => EnableTask(fullPath)));
+ return false;
+ }
+ catch (Exception ex)
+ {
+ ServiceTracker.LogError(ex, "Failed to enable task {Path}", fullPath);
+ ServiceTracker.Track(nameof(EnableTask), false);
+ ServiceTracker.TrackStep(
+ "ScheduledTask",
+ description,
+ false,
+ ex.Message,
+ () => System.Threading.Tasks.Task.Run(() => EnableTask(fullPath)));
+ return false;
+ }
+ }
/// <summary>
/// Recursively retrieves all scheduled tasks from the system.
/// </summary>
- public List<ScheduledTaskModel> GetAllTasks()
+ public static List<ScheduledTaskModel> GetAllTasks()
{
var results = new List<ScheduledTaskModel>();
try
@@ -78,7 +169,7 @@ public class ScheduledTaskService(ILogger<ScheduledTaskService> logger)
}
catch (Exception ex)
{
- logger.LogError(ex, "Failed to enumerate scheduled tasks");
+ ServiceTracker.LogError(ex, "Failed to enumerate scheduled tasks");
}
return results;
@@ -87,7 +178,7 @@ public class ScheduledTaskService(ILogger<ScheduledTaskService> logger)
/// <summary>
/// Returns only tasks that have a LogonTrigger or BootTrigger (startup-related).
/// </summary>
- public List<ScheduledTaskModel> GetStartupTasks()
+ public static List<ScheduledTaskModel> GetStartupTasks()
{
return GetAllTasks()
.Where(t => t.HasLogonTrigger || t.HasBootTrigger)
@@ -95,62 +186,36 @@ public class ScheduledTaskService(ILogger<ScheduledTaskService> logger)
.ToList();
}
- public void EnableTaskLogged(string fullPath)
- {
- try
- {
- EnableTask(fullPath);
- logger.LogInformation("Enabled task {Path}", fullPath);
- }
- catch (Exception ex)
- {
- logger.LogError(ex, "Failed to enable task {Path}", fullPath);
- throw;
- }
- }
-
- public void DisableTaskLogged(string fullPath)
- {
- try
- {
- DisableTask(fullPath);
- logger.LogInformation("Disabled task {Path}", fullPath);
- }
- catch (Exception ex)
- {
- logger.LogError(ex, "Failed to disable task {Path}", fullPath);
- throw;
- }
- }
-
- public void RunTask(string fullPath)
+ public static void RunTask(string fullPath)
{
try
{
using var ts = new TaskService();
- var task = ts.GetTask(fullPath) ?? throw new InvalidOperationException($"Task not found: {fullPath}");
+ var task = ts.GetTask(fullPath) ?? throw new InvalidOperationException(
+ string.Format(Translations.ScheduledTasks_Error_TaskNotFound, fullPath));
task.Run();
- logger.LogInformation("Started task {Path}", fullPath);
+ ServiceTracker.LogInfo("Started task {Path}", fullPath);
}
catch (Exception ex)
{
- logger.LogError(ex, "Failed to run task {Path}", fullPath);
+ ServiceTracker.LogError(ex, "Failed to run task {Path}", fullPath);
throw;
}
}
- public void StopTask(string fullPath)
+ public static void StopTask(string fullPath)
{
try
{
using var ts = new TaskService();
- var task = ts.GetTask(fullPath) ?? throw new InvalidOperationException($"Task not found: {fullPath}");
+ var task = ts.GetTask(fullPath) ?? throw new InvalidOperationException(
+ string.Format(Translations.ScheduledTasks_Error_TaskNotFound, fullPath));
task.Stop();
- logger.LogInformation("Stopped task {Path}", fullPath);
+ ServiceTracker.LogInfo("Stopped task {Path}", fullPath);
}
catch (Exception ex)
{
- logger.LogError(ex, "Failed to stop task {Path}", fullPath);
+ ServiceTracker.LogError(ex, "Failed to stop task {Path}", fullPath);
throw;
}
}
@@ -158,7 +223,7 @@ public class ScheduledTaskService(ILogger<ScheduledTaskService> logger)
/// <summary>
/// Gets the current state string of a task by its full path.
/// </summary>
- public string? GetTaskState(string fullPath)
+ public static string? GetTaskState(string fullPath)
{
try
{
@@ -168,24 +233,25 @@ public class ScheduledTaskService(ILogger<ScheduledTaskService> logger)
}
catch (Exception ex)
{
- logger.LogDebug(ex, "Failed to get state for task {Path}", fullPath);
+ ServiceTracker.LogDebug("Failed to get state for task {Path}: {Error}", fullPath, ex.Message);
return null;
}
}
- public void DeleteTask(string fullPath)
+ public static void DeleteTask(string fullPath)
{
try
{
using var ts = new TaskService();
- var task = ts.GetTask(fullPath) ?? throw new InvalidOperationException($"Task not found: {fullPath}");
+ var task = ts.GetTask(fullPath) ?? throw new InvalidOperationException(
+ string.Format(Translations.ScheduledTasks_Error_TaskNotFound, fullPath));
var folderPath = task.Folder.Path;
ts.GetFolder(folderPath).DeleteTask(task.Name);
- logger.LogInformation("Deleted task {Path}", fullPath);
+ ServiceTracker.LogInfo("Deleted task {Path}", fullPath);
}
catch (Exception ex)
{
- logger.LogError(ex, "Failed to delete task {Path}", fullPath);
+ ServiceTracker.LogError(ex, "Failed to delete task {Path}", fullPath);
throw;
}
}
@@ -193,7 +259,7 @@ public class ScheduledTaskService(ILogger<ScheduledTaskService> logger)
/// <summary>
/// [WIP] Registers a new scheduled task from a model definition.
/// </summary>
- public void RegisterTask(string folderPath, ScheduledTaskModel model)
+ public static void RegisterTask(string folderPath, ScheduledTaskModel model)
{
try
{
@@ -250,20 +316,18 @@ public class ScheduledTaskService(ILogger<ScheduledTaskService> logger)
}
folder.RegisterTaskDefinition(model.Name, td);
- logger.LogInformation("Registered task {Name} in folder {Folder}", model.Name, folderPath);
+ ServiceTracker.LogInfo("Registered task {Name} in folder {Folder}", model.Name, folderPath);
}
catch (Exception ex)
{
- logger.LogError(ex, "Failed to register task {Name} in {Folder}", model.Name, folderPath);
+ ServiceTracker.LogError(ex, "Failed to register task {Name} in {Folder}", model.Name, folderPath);
throw;
}
}
-
- #endregion Main Methods
-
+
#region Helpers
- private void CollectTasks(TaskFolder folder, List<ScheduledTaskModel> results)
+ private static void CollectTasks(TaskFolder folder, List<ScheduledTaskModel> results)
{
try
{
@@ -274,7 +338,7 @@ public class ScheduledTaskService(ILogger<ScheduledTaskService> logger)
}
catch (Exception ex)
{
- logger.LogDebug(ex, "Failed to map task {Name}", task.Name);
+ ServiceTracker.LogDebug("Failed to map task {Name}: {Error}", task.Name, ex.Message);
}
foreach (var subFolder in folder.SubFolders)
@@ -282,7 +346,7 @@ public class ScheduledTaskService(ILogger<ScheduledTaskService> logger)
}
catch (Exception ex)
{
- logger.LogDebug(ex, "Failed to enumerate folder {Path}", folder.Path);
+ ServiceTracker.LogDebug("Failed to enumerate folder {Path}: {Error}", folder.Path, ex.Message);
}
}
diff --git a/optimizerDuck/Services/StartupManagerService.cs b/optimizerDuck/Services/StartupManagerService.cs
index 047f94d..52d51a4 100644
--- a/optimizerDuck/Services/StartupManagerService.cs
+++ b/optimizerDuck/Services/StartupManagerService.cs
@@ -11,7 +11,7 @@ using optimizerDuck.Services.OptimizationServices;
namespace optimizerDuck.Services;
-public class StartupManagerService(ILogger<StartupManagerService> logger, ScheduledTaskService scheduledTaskService)
+public class StartupManagerService(ILogger<StartupManagerService> logger)
{
public async Task<List<StartupApp>> GetStartupAppsAsync()
{
@@ -232,7 +232,7 @@ public class StartupManagerService(ILogger<StartupManagerService> logger, Schedu
{
try
{
- var models = scheduledTaskService.GetStartupTasks();
+ var models = ScheduledTaskService.GetStartupTasks();
var tasks = models.Select(m => new StartupTask
{
TaskName = m.Name,
@@ -270,9 +270,15 @@ public class StartupManagerService(ILogger<StartupManagerService> logger, Schedu
{
var fullPath = task.TaskPath.TrimEnd('\\') + "\\" + task.TaskName;
if (enable)
- scheduledTaskService.EnableTaskLogged(fullPath);
+ {
+ ScheduledTaskService.EnableTask(fullPath);
+ logger.LogInformation("Enabled task {Name} ({Path})", task.TaskName, fullPath);
+ }
else
- scheduledTaskService.DisableTaskLogged(fullPath);
+ {
+ ScheduledTaskService.DisableTask(fullPath);
+ logger.LogInformation("Disabled task {Name} ({Path})", task.TaskName, fullPath);
+ }
}
catch (Exception ex)
{
diff --git a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
index 194c46d..ad30095 100644
--- a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
@@ -227,6 +227,47 @@ public partial class OptimizationCategoryViewModel : ViewModel
return RetryOutcome.Succeeded;
}
+ /// <summary>
+ /// Shows a snackbar notification based on the operation outcome.
+ /// </summary>
+ 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
+ : Translations.Optimization_Revert_Snackbar_Success_Title,
+ message,
+ 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
+ : Translations.Optimization_Revert_Snackbar_Error_Title,
+ message,
+ 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
+ : Translations.Optimization_Revert_Snackbar_Error_Title,
+ message,
+ ControlAppearance.Danger,
+ new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
+ TimeSpan.FromSeconds(5));
+ }
+ }
+
private async Task<bool> HandleRestorePointAsync()
{
var dialogContent = new RestorePointDialog();
@@ -347,16 +388,20 @@ public partial class OptimizationCategoryViewModel : ViewModel
await OptimizationService.UpdateOptimizationStateAsync(optimization);
// If result status is Failed, we can't retry it
- // We just need to show the error message and let the user know
- // It's "not possible" to retry failed steps and save revert data again
if (applyResult.Status == OptimizationSuccessResult.Failed)
{
- _snackbarService.Show(
- Translations.Optimization_Apply_Snackbar_Error_Title,
- applyResult.Message,
- ControlAppearance.Danger,
- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
- TimeSpan.FromSeconds(5));
+ ShowOutcomeSnackbar(false, false, true, "apply",
+ applyResult.Message, optimization.OptimizationKey);
+
+ if (applyResult.Exception != null)
+ _logger.LogError(applyResult.Exception, "Failed to apply {Name}",
+ optimization.OptimizationKey);
+ else
+ _logger.LogWarning("Failed to apply {Name}", optimization.OptimizationKey);
+
+ _logger.LogInformation(
+ "===== END applying optimization {OptimizationName} ({OptimizationId}) =====",
+ optimization.OptimizationKey, optimization.Id);
return;
}
@@ -366,33 +411,14 @@ public partial class OptimizationCategoryViewModel : ViewModel
applyResult.FailedSteps,
false);
- // If applied successfully or retry succeeded, mark as applied
var succeeded = applyResult.Status == OptimizationSuccessResult.Success ||
retryOutcome == RetryOutcome.Succeeded;
-
- // If retry skipped, mark as partially applied
var partial = retryOutcome == RetryOutcome.Skipped;
-
- // If retry failed, mark as failed
var failed = retryOutcome == RetryOutcome.None &&
applyResult.Status != OptimizationSuccessResult.Success;
- // If retry skipped or failed, mark as failed
- if (failed)
- _snackbarService.Show(
- Translations.Optimization_Apply_Snackbar_Error_Title,
- applyResult.Message,
- ControlAppearance.Danger,
- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
- TimeSpan.FromSeconds(5));
-
- if (partial)
- _snackbarService.Show(
- Translations.Optimization_Apply_Snackbar_Error_Title,
- applyResult.Message,
- ControlAppearance.Caution,
- new SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },
- TimeSpan.FromSeconds(5));
+ ShowOutcomeSnackbar(succeeded, partial, failed, "apply",
+ applyResult.Message, optimization.OptimizationKey);
if (applyResult.Exception != null)
_logger.LogError(applyResult.Exception, "Failed to apply {Name}", optimization.OptimizationKey);
@@ -409,14 +435,15 @@ public partial class OptimizationCategoryViewModel : ViewModel
else
{
// Revert optimization if already applied
- _logger.LogInformation("===== START reverting optimization {OptimizationName} ({OptimizationId}) =====",
+ _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. Failed steps can still be retried in the current session.
+ // Refresh state after revert attempt.
await OptimizationService.UpdateOptimizationStateAsync(optimization);
var retryOutcome = await HandleFailedStepsAsync(
@@ -428,31 +455,20 @@ public partial class OptimizationCategoryViewModel : ViewModel
var partial = retryOutcome == RetryOutcome.Skipped;
var failed = retryOutcome == RetryOutcome.None && !revertResult.Success;
- if (failed)
- _snackbarService.Show(
- Translations.Optimization_Revert_Snackbar_Error_Title,
- revertResult.Message,
- ControlAppearance.Danger,
- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
- TimeSpan.FromSeconds(5));
-
- if (partial)
- _snackbarService.Show(
- Translations.Optimization_Revert_Snackbar_Error_Title,
- revertResult.Message,
- ControlAppearance.Caution,
- new SymbolIcon { Symbol = SymbolRegular.Warning24, Filled = true },
- TimeSpan.FromSeconds(5));
+ ShowOutcomeSnackbar(succeeded, partial, failed, "revert",
+ revertResult.Message, optimization.OptimizationKey);
if (revertResult.Exception != null)
- _logger.LogError(revertResult.Exception, "Failed to revert {Name}", optimization.OptimizationKey);
+ _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}) =====",
+ _logger.LogInformation(
+ "===== END reverting optimization {OptimizationName} ({OptimizationId}) =====",
optimization.OptimizationKey, optimization.Id);
}
}
diff --git a/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs
index 0fb8452..c299d31 100644
--- a/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs
@@ -18,7 +18,6 @@ public partial class ScheduledTasksViewModel : ViewModel
private readonly List<ScheduledTaskModel> _allTasks = [];
private readonly IContentDialogService _contentDialogService;
private readonly ILogger<ScheduledTasksViewModel> _logger;
- private readonly ScheduledTaskService _scheduledTaskService;
private readonly ISnackbarService _snackbarService;
[ObservableProperty] private bool _hideMicrosoftTasks = true;
private bool _isInitialized;
@@ -30,12 +29,10 @@ public partial class ScheduledTasksViewModel : ViewModel
[ObservableProperty] private int _sortByIndex;
public ScheduledTasksViewModel(
- ScheduledTaskService scheduledTaskService,
IContentDialogService contentDialogService,
ISnackbarService snackbarService,
ILogger<ScheduledTasksViewModel> logger)
{
- _scheduledTaskService = scheduledTaskService;
_contentDialogService = contentDialogService;
_snackbarService = snackbarService;
_logger = logger;
@@ -83,9 +80,15 @@ public partial class ScheduledTasksViewModel : ViewModel
await Task.Run(() =>
{
if (task.IsEnabled)
- _scheduledTaskService.EnableTaskLogged(task.FullPath);
+ {
+ ScheduledTaskService.EnableTask(task.FullPath);
+ _logger.LogInformation("Enabled task {Name} ({Path})", task.Name, task.FullPath);
+ }
else
- _scheduledTaskService.DisableTaskLogged(task.FullPath);
+ {
+ ScheduledTaskService.DisableTask(task.FullPath);
+ _logger.LogInformation("Disabled task {Name} ({Path})", task.Name, task.FullPath);
+ }
});
_snackbarService.Show(
@@ -101,7 +104,7 @@ public partial class ScheduledTasksViewModel : ViewModel
}
catch (Exception ex)
{
- _logger.LogError(ex, "Failed to toggle task {Name}", task.Name);
+ _logger.LogError(ex, "Failed to toggle task {Name} ({Path})", task.Name, task.FullPath);
// Revert UI without triggering PropertyChanged to avoid infinite loop
task.PropertyChanged -= Task_PropertyChanged;
@@ -123,7 +126,8 @@ public partial class ScheduledTasksViewModel : ViewModel
if (task == null) return;
try
{
- await Task.Run(() => _scheduledTaskService.RunTask(task.FullPath));
+ await Task.Run(() => ScheduledTaskService.RunTask(task.FullPath));
+ _logger.LogInformation("Ran task {Name} ({Path})", task.Name, task.FullPath);
_snackbarService.Show(
Translations.ScheduledTasks_Snackbar_Run_Title,
@@ -136,7 +140,7 @@ public partial class ScheduledTasksViewModel : ViewModel
}
catch (Exception ex)
{
- _logger.LogError(ex, "Failed to run task {Name}", task.Name);
+ _logger.LogError(ex, "Failed to run task {Name} ({Path})", task.Name, task.FullPath);
_snackbarService.Show(
Translations.ScheduledTasks_Snackbar_Error_Title,
@@ -153,7 +157,8 @@ public partial class ScheduledTasksViewModel : ViewModel
if (task == null) return;
try
{
- await Task.Run(() => _scheduledTaskService.StopTask(task.FullPath));
+ await Task.Run(() => ScheduledTaskService.StopTask(task.FullPath));
+ _logger.LogInformation("Stopped task {Name} ({Path})", task.Name, task.FullPath);
_snackbarService.Show(
Translations.ScheduledTasks_Snackbar_Stop_Title,
@@ -166,7 +171,7 @@ public partial class ScheduledTasksViewModel : ViewModel
}
catch (Exception ex)
{
- _logger.LogError(ex, "Failed to stop task {Name}", task.Name);
+ _logger.LogError(ex, "Failed to stop task {Name} ({Path})", task.Name, task.FullPath);
_snackbarService.Show(
Translations.ScheduledTasks_Snackbar_Error_Title,
@@ -195,7 +200,8 @@ public partial class ScheduledTasksViewModel : ViewModel
try
{
- await Task.Run(() => _scheduledTaskService.DeleteTask(task.FullPath));
+ await Task.Run(() => ScheduledTaskService.DeleteTask(task.FullPath));
+ _logger.LogInformation("Deleted task {Name} ({Path})", task.Name, task.FullPath);
_allTasks.RemoveAll(t => t.FullPath == task.FullPath);
ApplyFilter();
@@ -208,7 +214,7 @@ public partial class ScheduledTasksViewModel : ViewModel
}
catch (Exception ex)
{
- _logger.LogError(ex, "Failed to delete task {Name}", task.Name);
+ _logger.LogError(ex, "Failed to delete task {Name} ({Path})", task.Name, task.FullPath);
_snackbarService.Show(
Translations.ScheduledTasks_Snackbar_Error_Title,
@@ -258,7 +264,7 @@ public partial class ScheduledTasksViewModel : ViewModel
{
try
{
- var newState = await Task.Run(() => _scheduledTaskService.GetTaskState(task.FullPath));
+ var newState = await Task.Run(() => ScheduledTaskService.GetTaskState(task.FullPath));
if (newState != null)
{
task.State = newState;
@@ -279,7 +285,7 @@ public partial class ScheduledTasksViewModel : ViewModel
try
{
- var tasks = await Task.Run(() => _scheduledTaskService.GetAllTasks());
+ var tasks = await Task.Run(() => ScheduledTaskService.GetAllTasks());
_allTasks.AddRange(tasks);
ApplyFilter();
}
diff --git a/optimizerDuck/UI/Views/Dialogs/OptimizationResultDialog.xaml b/optimizerDuck/UI/Views/Dialogs/OptimizationResultDialog.xaml
index 170e414..2d23352 100644
--- a/optimizerDuck/UI/Views/Dialogs/OptimizationResultDialog.xaml
+++ b/optimizerDuck/UI/Views/Dialogs/OptimizationResultDialog.xaml
@@ -17,7 +17,14 @@
x:Key="NullToVisibilityConverter" />
</UserControl.Resources>
<StackPanel>
- <StackPanel Orientation="Horizontal">
+ <!-- Header with failed count summary -->
+ <StackPanel Orientation="Horizontal" Margin="0,0,0,4">
+ <ui:SymbolIcon
+ Filled="True"
+ Foreground="{DynamicResource SystemFillColorCriticalBrush}"
+ Margin="0,0,8,0"
+ Symbol="ErrorCircle24"
+ VerticalAlignment="Center" />
<ui:TextBlock
FontTypography="Subtitle"
@@ -30,74 +37,82 @@
<ui:TextBlock
Appearance="Secondary"
FontTypography="Body"
- Margin="0,2,0,8"
+ Margin="0,2,0,12"
Text="{ext:Loc OptimizationResultDialog.Description}"
TextWrapping="Wrap" />
- <ScrollViewer VerticalScrollBarVisibility="Auto">
+ <ScrollViewer MaxHeight="350" VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding FailedSteps}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ui:CardControl Margin="0,0,0,8">
<ui:CardControl.Header>
- <Grid ColumnDefinitions="Auto, Auto, *">
- <Grid ColumnDefinitions="Auto,Auto">
+ <StackPanel>
+ <!-- Top row: index + service type badge + step name -->
+ <StackPanel Orientation="Horizontal" Margin="0,0,0,6">
+ <!-- Step index badge -->
<Border
Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"
CornerRadius="4"
HorizontalAlignment="Left"
- Margin="0,0,10,0"
+ Margin="0,0,8,0"
Padding="6,2"
VerticalAlignment="Center">
- <StackPanel Orientation="Horizontal">
- <ui:SymbolIcon
- Filled="True"
- Foreground="{DynamicResource SystemFillColorAttentionBrush}"
- Margin="0,0,5,0"
- Symbol="Warning24"
- VerticalAlignment="Center" />
- <ui:TextBlock
- Appearance="Disabled"
- FontTypography="Caption"
- Text="{Binding Index, StringFormat=# {0}}"
- VerticalAlignment="Center" />
- </StackPanel>
+ <ui:TextBlock
+ Appearance="Disabled"
+ FontTypography="Caption"
+ Text="{Binding Index, StringFormat=# {0}}"
+ VerticalAlignment="Center" />
</Border>
- <ui:TextBlock
- FontTypography="BodyStrong"
- Grid.Column="1"
- Text="{Binding Name}"
- TextWrapping="Wrap"
- VerticalAlignment="Center" />
- </Grid>
-
- <Separator Grid.Column="1" Margin="5,0,5,0" />
-
- <StackPanel Grid.Column="2">
- <ui:TextBlock
- Appearance="Secondary"
- FontTypography="Caption"
- Text="{Binding Description}"
- TextWrapping="Wrap" />
-
+ <!-- Service type badge -->
<Border
- BorderBrush="{DynamicResource SystemFillColorCriticalBrush}"
- BorderThickness="1"
- CornerRadius="6"
+ Background="{DynamicResource SystemFillColorAttentionBackgroundBrush}"
+ CornerRadius="4"
HorizontalAlignment="Left"
- Margin="0,8,0,0"
- Padding="8,6"
- Visibility="{Binding Error, Converter={StaticResource NullToVisibilityConverter}}">
+ Margin="0,0,8,0"
+ Padding="6,2"
+ VerticalAlignment="Center">
+ <ui:TextBlock
+ FontTypography="Caption"
+ Foreground="{DynamicResource SystemFillColorAttentionBrush}"
+ Text="{Binding Name}"
+ VerticalAlignment="Center" />
+ </Border>
+ </StackPanel>
+
+ <!-- Step description -->
+ <ui:TextBlock
+ FontTypography="BodyStrong"
+ Margin="0,0,0,4"
+ Text="{Binding Description}"
+ TextWrapping="Wrap" />
+
+ <!-- Error message -->
+ <Border
+ BorderBrush="{DynamicResource SystemFillColorCriticalBrush}"
+ BorderThickness="1"
+ CornerRadius="6"
+ HorizontalAlignment="Left"
+ Margin="0,4,0,0"
+ Padding="8,6"
+ Visibility="{Binding Error, Converter={StaticResource NullToVisibilityConverter}}">
+ <StackPanel Orientation="Horizontal">
+ <ui:SymbolIcon
+ Filled="True"
+ Foreground="{DynamicResource SystemFillColorCriticalBrush}"
+ Margin="0,0,6,0"
+ Symbol="Warning24"
+ VerticalAlignment="Center" />
<ui:TextBlock
FontTypography="Caption"
Foreground="{DynamicResource SystemFillColorCriticalBrush}"
HorizontalAlignment="Stretch"
Text="{Binding Error}"
TextWrapping="Wrap" />
- </Border>
- </StackPanel>
- </Grid>
+ </StackPanel>
+ </Border>
+ </StackPanel>
</ui:CardControl.Header>
</ui:CardControl>
</DataTemplate>