Files
ReminderOrganizer/Services/DataService.cs
Michi 1918712f7f Fix data loss risk, reminder bugs; theme, credits, tests
- Store tasks in %APPDATA% (single-file extract dir lost data on update),
  atomic serialized saves, corrupt-file backup, migration of old tasks.json
- Reminders without description never showed (empty balloon text threw)
- Catch up missed reminders on start; monthly recurrence no longer drifts
- Task dialog: date pick kept 00:00, cancel leaked recurrence changes
- CSV import understands quoted fields written by export
- Confirm before deleting; name folders on create; tasks sorted by date
- Single instance, autostart starts hidden in tray, tray icon disposed
- Theme helper for all dialogs, MDL2/Path icons instead of emojis,
  fixed folder selection/badge, localized counts and messages
- Credits (c) Michael Media + Discord link, exe Company/Copyright
- Locales embedded; xUnit tests (24); README, CLAUDE.md, sprite-generator

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:08:53 +01:00

112 lines
3.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#nullable enable
using System;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using ReminderOrganizer.Models;
namespace ReminderOrganizer.Services
{
/// <summary>
/// Stores tasks in %APPDATA%\ReminderOrganizer\tasks.json.
/// Writes are serialized and atomic (temp file + replace), a corrupt file is
/// backed up instead of being overwritten.
/// </summary>
public class DataService : IDataService
{
private static readonly JsonSerializerOptions _jsonOptions = new()
{
WriteIndented = true,
PropertyNameCaseInsensitive = true
};
private readonly SemaphoreSlim _writeLock = new(1, 1);
public string DataFilePath { get; }
/// <summary>%APPDATA%\ReminderOrganizer – or REMINDER_ORGANIZER_DATA (for tests/screenshots).</summary>
public static string DefaultDataDirectory =>
Environment.GetEnvironmentVariable("REMINDER_ORGANIZER_DATA") is { Length: > 0 } custom
? custom
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ReminderOrganizer");
public DataService() : this(DefaultDataDirectory) { }
public DataService(string dataDirectory)
{
Directory.CreateDirectory(dataDirectory);
DataFilePath = Path.Combine(dataDirectory, "tasks.json");
}
/// <summary>Copies tasks.json from an old location (next to the exe) if no data exists yet.</summary>
public void MigrateFrom(string? legacyDirectory)
{
if (string.IsNullOrEmpty(legacyDirectory) || File.Exists(DataFilePath)) return;
var legacy = Path.Combine(legacyDirectory, "tasks.json");
try
{
if (File.Exists(legacy) && !string.Equals(Path.GetFullPath(legacy), Path.GetFullPath(DataFilePath), StringComparison.OrdinalIgnoreCase))
File.Copy(legacy, DataFilePath);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[DataService] Migration failed: {ex.Message}");
}
}
public async Task<AppData> LoadAsync()
{
if (!File.Exists(DataFilePath))
return new AppData();
try
{
var json = await File.ReadAllTextAsync(DataFilePath);
var data = JsonSerializer.Deserialize<AppData>(json, _jsonOptions);
return data ?? new AppData();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[DataService] Load failed: {ex.Message}");
BackupCorruptFile();
return new AppData();
}
}
private void BackupCorruptFile()
{
try
{
var backup = DataFilePath + $".corrupt-{DateTime.Now:yyyyMMdd-HHmmss}";
File.Copy(DataFilePath, backup, overwrite: true);
}
catch { }
}
public async Task SaveAsync(AppData data)
{
await _writeLock.WaitAsync();
try
{
var json = JsonSerializer.Serialize(data, _jsonOptions);
var tmp = DataFilePath + ".tmp";
await File.WriteAllTextAsync(tmp, json);
if (File.Exists(DataFilePath))
File.Replace(tmp, DataFilePath, DataFilePath + ".bak");
else
File.Move(tmp, DataFilePath);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[DataService] Save failed: {ex.Message}");
throw;
}
finally
{
_writeLock.Release();
}
}
}
}