From 9a9ae94f34ccf2c4320b8d1caf8b1bc782e6c62b Mon Sep 17 00:00:00 2001 From: Mahdi Hosseini Date: Thu, 7 Aug 2025 16:02:18 +0330 Subject: [PATCH 01/14] Implemented new settings system --- .../Internals/SettingsJsonContext.cs | 13 ++++ .../SettingsHelper/Internals/Vectors.cs | 29 +++++++++ .../SettingsHelper/ObservableSettings.cs | 43 +++++++++++++ .../ApplicationDataSettingsProvider.cs | 64 +++++++++++++++++++ .../Providers/ISettingsProvider.cs | 11 ++++ .../Providers/JsonSettingsProvider.cs | 64 +++++++++++++++++++ .../Providers/SettingsProviderFactory.cs | 27 ++++++++ .../Helpers/SettingsHelper/Settings.cs | 47 ++++++++++++++ 8 files changed, 298 insertions(+) create mode 100644 WinUIGallery/Helpers/SettingsHelper/Internals/SettingsJsonContext.cs create mode 100644 WinUIGallery/Helpers/SettingsHelper/Internals/Vectors.cs create mode 100644 WinUIGallery/Helpers/SettingsHelper/ObservableSettings.cs create mode 100644 WinUIGallery/Helpers/SettingsHelper/Providers/ApplicationDataSettingsProvider.cs create mode 100644 WinUIGallery/Helpers/SettingsHelper/Providers/ISettingsProvider.cs create mode 100644 WinUIGallery/Helpers/SettingsHelper/Providers/JsonSettingsProvider.cs create mode 100644 WinUIGallery/Helpers/SettingsHelper/Providers/SettingsProviderFactory.cs create mode 100644 WinUIGallery/Helpers/SettingsHelper/Settings.cs diff --git a/WinUIGallery/Helpers/SettingsHelper/Internals/SettingsJsonContext.cs b/WinUIGallery/Helpers/SettingsHelper/Internals/SettingsJsonContext.cs new file mode 100644 index 000000000..6afe88b01 --- /dev/null +++ b/WinUIGallery/Helpers/SettingsHelper/Internals/SettingsJsonContext.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace WinUIGallery.Helpers; + +[JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] +[JsonSerializable(typeof(Dictionary))] +[JsonSerializable(typeof(Vector2Data))] +[JsonSerializable(typeof(Vector3Data))] +[JsonSerializable(typeof(Settings))] +internal partial class SettingsJsonContext : JsonSerializerContext +{ +} \ No newline at end of file diff --git a/WinUIGallery/Helpers/SettingsHelper/Internals/Vectors.cs b/WinUIGallery/Helpers/SettingsHelper/Internals/Vectors.cs new file mode 100644 index 000000000..75869b33a --- /dev/null +++ b/WinUIGallery/Helpers/SettingsHelper/Internals/Vectors.cs @@ -0,0 +1,29 @@ +namespace WinUIGallery.Helpers; + +internal partial class Vector4Data +{ + public float W { get; set; } + public float X { get; set; } + public float Y { get; set; } + public float Z { get; set; } + + public static implicit operator System.Numerics.Vector4(Vector4Data d) => new(d.X, d.Y, d.Z, d.W); + public static implicit operator Vector4Data(System.Numerics.Vector4 v) => new() { X = v.X, Y = v.Y, Z = v.Z, W = v.W }; +} +internal partial class Vector3Data +{ + public float X { get; set; } + public float Y { get; set; } + public float Z { get; set; } + + public static implicit operator System.Numerics.Vector3(Vector3Data d) => new(d.X, d.Y, d.Z); + public static implicit operator Vector3Data(System.Numerics.Vector3 v) => new() { X = v.X, Y = v.Y, Z = v.Z }; +} +internal partial class Vector2Data +{ + public float X { get; set; } + public float Y { get; set; } + + public static implicit operator System.Numerics.Vector2(Vector2Data d) => new(d.X, d.Y); + public static implicit operator Vector2Data(System.Numerics.Vector2 v) => new() { X = v.X, Y = v.Y }; +} \ No newline at end of file diff --git a/WinUIGallery/Helpers/SettingsHelper/ObservableSettings.cs b/WinUIGallery/Helpers/SettingsHelper/ObservableSettings.cs new file mode 100644 index 000000000..3a6af432b --- /dev/null +++ b/WinUIGallery/Helpers/SettingsHelper/ObservableSettings.cs @@ -0,0 +1,43 @@ +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace WinUIGallery.Helpers; + +public partial class ObservableSettings : INotifyPropertyChanged +{ + private readonly ISettingsProvider provider; + + public ObservableSettings(ISettingsProvider provider) + { + this.provider = provider; + } + + public event PropertyChangedEventHandler PropertyChanged; + + protected bool Set(T value, [CallerMemberName] string propertyName = null) + { + if (provider.Contains(propertyName)) + { + var currentValue = provider.Get(propertyName); + if (Equals(currentValue, value)) + return false; + } + + provider.Set(propertyName, value); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + return true; + } + + protected T Get([CallerMemberName] string propertyName = null) + { + return provider.Get(propertyName); + } + + protected T GetOrCreateDefault(T defaultValue, [CallerMemberName] string propertyName = null) + { + if (!provider.Contains(propertyName)) + Set(defaultValue, propertyName); + + return Get(propertyName); + } +} diff --git a/WinUIGallery/Helpers/SettingsHelper/Providers/ApplicationDataSettingsProvider.cs b/WinUIGallery/Helpers/SettingsHelper/Providers/ApplicationDataSettingsProvider.cs new file mode 100644 index 000000000..2c1d379ba --- /dev/null +++ b/WinUIGallery/Helpers/SettingsHelper/Providers/ApplicationDataSettingsProvider.cs @@ -0,0 +1,64 @@ +using Microsoft.Windows.Storage; +using System; +using System.Collections.Generic; +using System.Text.Json; + +namespace WinUIGallery.Helpers; + +public partial class ApplicationDataSettingsProvider : ISettingsProvider +{ + private readonly ApplicationDataContainer container; + + public ApplicationDataSettingsProvider(ApplicationDataContainer container) + { + this.container = container ?? throw new ArgumentNullException(nameof(container)); + } + + public bool Contains(string key) => container.Values.ContainsKey(key); + + public object Get(string key) => container.Values.TryGetValue(key, out var value) ? value : null; + + public void Set(string key, object value) => container.Values[key] = value; + + public T Get(string key) + { + if (!container.Values.TryGetValue(key, out var value)) + return default; + + if (value is T t) + return t; + + if (value is string str && !IsSimpleType(typeof(T))) + { + var typeInfo = SettingsJsonContext.Default.GetTypeInfo(typeof(T)); + return (T)JsonSerializer.Deserialize(str, typeInfo); + } + + return (T)Convert.ChangeType(value, typeof(T)); + } + + public void Set(string key, T value) + { + object storedValue = IsSimpleType(typeof(T)) + ? value + : JsonSerializer.Serialize(value, SettingsJsonContext.Default.GetTypeInfo(typeof(T))); + + container.Values[key] = storedValue; + } + + private static readonly HashSet ExtraSimpleTypes = new() + { + typeof(string), + typeof(DateTimeOffset), + typeof(TimeSpan), + typeof(Guid), + typeof(Windows.Foundation.Point), + typeof(Windows.Foundation.Size), + typeof(Windows.Foundation.Rect) + }; + + private static bool IsSimpleType(Type type) + { + return type.IsPrimitive || ExtraSimpleTypes.Contains(type); + } +} diff --git a/WinUIGallery/Helpers/SettingsHelper/Providers/ISettingsProvider.cs b/WinUIGallery/Helpers/SettingsHelper/Providers/ISettingsProvider.cs new file mode 100644 index 000000000..d02ce23b4 --- /dev/null +++ b/WinUIGallery/Helpers/SettingsHelper/Providers/ISettingsProvider.cs @@ -0,0 +1,11 @@ +namespace WinUIGallery.Helpers; + +public interface ISettingsProvider +{ + bool Contains(string key); + object Get(string key); + void Set(string key, object value); + + T Get(string key); + void Set(string key, T value); +} diff --git a/WinUIGallery/Helpers/SettingsHelper/Providers/JsonSettingsProvider.cs b/WinUIGallery/Helpers/SettingsHelper/Providers/JsonSettingsProvider.cs new file mode 100644 index 000000000..51bc4c6b3 --- /dev/null +++ b/WinUIGallery/Helpers/SettingsHelper/Providers/JsonSettingsProvider.cs @@ -0,0 +1,64 @@ +using System.Collections.Generic; +using System.IO; +using System.Text.Json; + +namespace WinUIGallery.Helpers; + +public partial class JsonSettingsProvider : ISettingsProvider +{ + private readonly string filePath; + private Dictionary values = new(); + + public JsonSettingsProvider(string filePath) + { + this.filePath = filePath; + Load(); + } + + public bool Contains(string key) => values.ContainsKey(key); + + public object Get(string key) => values.TryGetValue(key, out var value) ? value : null; + + public void Set(string key, object value) + { + var json = JsonSerializer.SerializeToElement(value, SettingsJsonContext.Default.GetTypeInfo(value.GetType())); + values[key] = json; + Save(); + } + + public T Get(string key) + { + if (!values.TryGetValue(key, out var jsonElement)) + return default; + + return (T)jsonElement.Deserialize(SettingsJsonContext.Default.GetTypeInfo(typeof(T))); + } + + public void Set(string key, T value) + { + var json = JsonSerializer.SerializeToElement(value, SettingsJsonContext.Default.GetTypeInfo(typeof(T))); + values[key] = json; + Save(); + } + + private void Load() + { + if (File.Exists(filePath)) + { + var json = File.ReadAllText(filePath); + values = JsonSerializer.Deserialize( + json, + SettingsJsonContext.Default.DictionaryStringJsonElement + ) ?? new(); + } + } + + private void Save() + { + var json = JsonSerializer.Serialize( + values, + SettingsJsonContext.Default.DictionaryStringJsonElement + ); + File.WriteAllText(filePath, json); + } +} diff --git a/WinUIGallery/Helpers/SettingsHelper/Providers/SettingsProviderFactory.cs b/WinUIGallery/Helpers/SettingsHelper/Providers/SettingsProviderFactory.cs new file mode 100644 index 000000000..ffb4dcd88 --- /dev/null +++ b/WinUIGallery/Helpers/SettingsHelper/Providers/SettingsProviderFactory.cs @@ -0,0 +1,27 @@ +using Microsoft.Windows.Storage; +using System; +using System.IO; + +namespace WinUIGallery.Helpers; + +public static partial class SettingsProviderFactory +{ + public static ISettingsProvider CreateProvider() + { + if (NativeMethods.IsAppPackaged) + { + return new ApplicationDataSettingsProvider(ApplicationData.GetDefault().LocalSettings); + } + else + { + var folder = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + ProcessInfoHelper.ProductNameAndVersion + ); + + Directory.CreateDirectory(folder); + var filePath = Path.Combine(folder, "AppConfig.json"); + return new JsonSettingsProvider(filePath); + } + } +} diff --git a/WinUIGallery/Helpers/SettingsHelper/Settings.cs b/WinUIGallery/Helpers/SettingsHelper/Settings.cs new file mode 100644 index 000000000..dd14fffc6 --- /dev/null +++ b/WinUIGallery/Helpers/SettingsHelper/Settings.cs @@ -0,0 +1,47 @@ +using Microsoft.UI.Xaml; +using System.Collections.Generic; + +namespace WinUIGallery.Helpers; + +public partial class Settings : ObservableSettings +{ + private static readonly Settings instance = new(SettingsProviderFactory.CreateProvider()); + public static Settings Current => instance; + + private Settings(ISettingsProvider provider) + : base(provider) + { + } + + public const int MaxRecentlyVisitedSamples = 7; + + public ElementTheme SelectedAppTheme + { + get => GetOrCreateDefault(ElementTheme.Default); + set => Set(value); + } + + public bool IsLeftMode + { + get => GetOrCreateDefault(true); + set => Set(value); + } + + public bool IsShowCopyLinkTeachingTip + { + get => GetOrCreateDefault(true); + set => Set(value); + } + + public List RecentlyVisited + { + get => GetOrCreateDefault>(new List()); + set => Set(value); + } + + public List Favorites + { + get => GetOrCreateDefault>(new List()); + set => Set(value); + } +} From d5b5b9cd2d17185f722daa59c3464678717326ae Mon Sep 17 00:00:00 2001 From: Mahdi Hosseini Date: Thu, 7 Aug 2025 16:33:20 +0330 Subject: [PATCH 02/14] Replace Old Settings with New Settings --- WinUIGallery/Controls/PageHeader.xaml.cs | 10 ++++-- .../Helpers/NavigationOrientationHelper.cs | 24 ++----------- .../ProtocolActivationClipboardHelper.cs | 25 ++----------- .../Internals/ListExtensions.cs | 36 +++++++++++++++++++ .../Helpers/SettingsHelper/Settings.cs | 2 -- WinUIGallery/Helpers/ThemeHelper.cs | 15 ++------ WinUIGallery/MainWindow.xaml.cs | 4 ++- WinUIGallery/Pages/HomePage.xaml.cs | 25 ++++++++----- WinUIGallery/Pages/SettingsPage.xaml.cs | 13 ++++--- 9 files changed, 78 insertions(+), 76 deletions(-) create mode 100644 WinUIGallery/Helpers/SettingsHelper/Internals/ListExtensions.cs diff --git a/WinUIGallery/Controls/PageHeader.xaml.cs b/WinUIGallery/Controls/PageHeader.xaml.cs index dd3b6f4bf..c064ccac4 100644 --- a/WinUIGallery/Controls/PageHeader.xaml.cs +++ b/WinUIGallery/Controls/PageHeader.xaml.cs @@ -101,7 +101,7 @@ private void UserControl_Loaded(object sender, RoutedEventArgs e) } if (Item != null) { - FavoriteButton.IsChecked = SettingsHelper.Contains(SettingsKeys.Favorites, Item.UniqueId); + FavoriteButton.IsChecked = Settings.Current.Favorites.Contains(Item.UniqueId); } } @@ -119,13 +119,17 @@ private void FavoriteButton_Click(object sender, RoutedEventArgs e) { if (sender is ToggleButton toggleButton && Item != null) { + var favs = Settings.Current.Favorites; + if (toggleButton.IsChecked == true) { - SettingsHelper.TryAddItem(SettingsKeys.Favorites, Item.UniqueId, InsertPosition.Last); + favs.AddToLast(Item.UniqueId, isFavorite: true); + Settings.Current.Favorites = favs; } else { - SettingsHelper.TryRemoveItem(SettingsKeys.Favorites, Item.UniqueId); + favs.Remove(Item.UniqueId); + Settings.Current.Favorites = favs; } } } diff --git a/WinUIGallery/Helpers/NavigationOrientationHelper.cs b/WinUIGallery/Helpers/NavigationOrientationHelper.cs index 57c61db45..255b6e008 100644 --- a/WinUIGallery/Helpers/NavigationOrientationHelper.cs +++ b/WinUIGallery/Helpers/NavigationOrientationHelper.cs @@ -12,33 +12,13 @@ public static partial class NavigationOrientationHelper private static ApplicationData appData = ApplicationData.GetDefault(); public static bool IsLeftMode() { - if (NativeMethods.IsAppPackaged) - { - var valueFromSettings = appData.LocalSettings.Values[SettingsKeys.IsLeftMode]; - if (valueFromSettings == null) - { - appData.LocalSettings.Values[SettingsKeys.IsLeftMode] = true; - valueFromSettings = true; - } - return (bool)valueFromSettings; - } - else - { - return _isLeftMode; - } + return Settings.Current.IsLeftMode; } public static void IsLeftModeForElement(bool isLeftMode) { UpdateNavigationViewForElement(isLeftMode); - if (NativeMethods.IsAppPackaged) - { - appData.LocalSettings.Values[SettingsKeys.IsLeftMode] = isLeftMode; - } - else - { - _isLeftMode = isLeftMode; - } + Settings.Current.IsLeftMode = isLeftMode; } public static void UpdateNavigationViewForElement(bool isLeftMode) diff --git a/WinUIGallery/Helpers/ProtocolActivationClipboardHelper.cs b/WinUIGallery/Helpers/ProtocolActivationClipboardHelper.cs index aa4779350..651025fd0 100644 --- a/WinUIGallery/Helpers/ProtocolActivationClipboardHelper.cs +++ b/WinUIGallery/Helpers/ProtocolActivationClipboardHelper.cs @@ -22,33 +22,12 @@ public static bool ShowCopyLinkTeachingTip { get { - if (NativeMethods.IsAppPackaged) - { - object valueFromSettings = appData.LocalSettings.Values[SettingsKeys.ShowCopyLinkTeachingTip]; - if (valueFromSettings == null) - { - appData.LocalSettings.Values[SettingsKeys.ShowCopyLinkTeachingTip] = true; - valueFromSettings = true; - } - return (bool)valueFromSettings; - } - else - { - return _showCopyLinkTeachingTip; - } + return Settings.Current.IsShowCopyLinkTeachingTip; } set { - if (NativeMethods.IsAppPackaged) - { - appData.LocalSettings.Values[SettingsKeys.ShowCopyLinkTeachingTip] = value; - - } - else - { - _showCopyLinkTeachingTip = value; - } + Settings.Current.IsShowCopyLinkTeachingTip = value; } } diff --git a/WinUIGallery/Helpers/SettingsHelper/Internals/ListExtensions.cs b/WinUIGallery/Helpers/SettingsHelper/Internals/ListExtensions.cs new file mode 100644 index 000000000..f910a69f3 --- /dev/null +++ b/WinUIGallery/Helpers/SettingsHelper/Internals/ListExtensions.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; + +namespace WinUIGallery.Helpers; + +internal static class ListExtensions +{ + public const int MaxRecentlyVisitedSamples = 7; + + public static void AddToFirst(this List list, string item, bool isFavorite) + { + if (string.IsNullOrWhiteSpace(item)) + return; + + list.Remove(item); + list.Insert(0, item); + + if (!isFavorite && MaxRecentlyVisitedSamples > 0 && list.Count > MaxRecentlyVisitedSamples) + { + list.RemoveRange(MaxRecentlyVisitedSamples, list.Count - MaxRecentlyVisitedSamples); + } + } + + public static void AddToLast(this List list, string item, bool isFavorite) + { + if (string.IsNullOrWhiteSpace(item)) + return; + + list.Remove(item); + list.Add(item); + + if (!isFavorite && MaxRecentlyVisitedSamples > 0 && list.Count > MaxRecentlyVisitedSamples) + { + list.RemoveRange(0, list.Count - MaxRecentlyVisitedSamples); + } + } +} diff --git a/WinUIGallery/Helpers/SettingsHelper/Settings.cs b/WinUIGallery/Helpers/SettingsHelper/Settings.cs index dd14fffc6..6c6e19ee8 100644 --- a/WinUIGallery/Helpers/SettingsHelper/Settings.cs +++ b/WinUIGallery/Helpers/SettingsHelper/Settings.cs @@ -13,8 +13,6 @@ private Settings(ISettingsProvider provider) { } - public const int MaxRecentlyVisitedSamples = 7; - public ElementTheme SelectedAppTheme { get => GetOrCreateDefault(ElementTheme.Default); diff --git a/WinUIGallery/Helpers/ThemeHelper.cs b/WinUIGallery/Helpers/ThemeHelper.cs index 161043dfc..e7dba14d3 100644 --- a/WinUIGallery/Helpers/ThemeHelper.cs +++ b/WinUIGallery/Helpers/ThemeHelper.cs @@ -63,24 +63,13 @@ public static ElementTheme RootTheme } } - if (NativeMethods.IsAppPackaged) - { - appData.LocalSettings.Values[SettingsKeys.SelectedAppTheme] = value.ToString(); - } + Settings.Current.SelectedAppTheme = value; } } public static void Initialize() { - if (NativeMethods.IsAppPackaged) - { - string savedTheme = appData.LocalSettings.Values[SettingsKeys.SelectedAppTheme]?.ToString(); - - if (savedTheme != null) - { - RootTheme = EnumHelper.GetEnum(savedTheme); - } - } + RootTheme = Settings.Current.SelectedAppTheme; } public static bool IsDarkTheme() diff --git a/WinUIGallery/MainWindow.xaml.cs b/WinUIGallery/MainWindow.xaml.cs index e2509348d..e11bc76e7 100644 --- a/WinUIGallery/MainWindow.xaml.cs +++ b/WinUIGallery/MainWindow.xaml.cs @@ -120,7 +120,9 @@ public void Navigate(Type pageType, object targetPageArguments = null, Navigatio if (pageType.Equals(typeof(ItemPage)) && targetPageArguments != null) { // Mark the item sample's page visited - SettingsHelper.TryAddItem(SettingsKeys.RecentlyVisited, targetPageArguments.ToString(), InsertPosition.First, SettingsHelper.MaxRecentlyVisitedSamples); + var recentlyVisited = Settings.Current.RecentlyVisited; + recentlyVisited.AddToFirst(targetPageArguments.ToString(), isFavorite: false); + Settings.Current.RecentlyVisited = recentlyVisited; } } diff --git a/WinUIGallery/Pages/HomePage.xaml.cs b/WinUIGallery/Pages/HomePage.xaml.cs index 19e622252..2455e58f2 100644 --- a/WinUIGallery/Pages/HomePage.xaml.cs +++ b/WinUIGallery/Pages/HomePage.xaml.cs @@ -31,26 +31,24 @@ protected override void OnNavigatedTo(NavigationEventArgs e) .OrderBy(i => i.Title) .ToList(); - RecentlyVisitedSamplesList = GetValidItems(SettingsKeys.RecentlyVisited); + RecentlyVisitedSamplesList = GetValidItems(Settings.Current.RecentlyVisited, isFavorite: false); RecentlyAddedOrUpdatedSamplesList = Items.Where(i => i.IsNew || i.IsUpdated).ToList(); - FavoriteSamplesList = GetValidItems(SettingsKeys.Favorites); + FavoriteSamplesList = GetValidItems(Settings.Current.Favorites, isFavorite: true); VisualStateManager.GoToState(this, RecentlyVisitedSamplesList.Count > 0 ? "Recent" : "NoRecent", true); VisualStateManager.GoToState(this, FavoriteSamplesList.Count > 0 ? "Favorites" : "NoFavorites", true); } - public List GetValidItems(string settingsKey) + public List GetValidItems(List items, bool isFavorite) { - List keyList = SettingsHelper.GetList(settingsKey); - - if (keyList == null || keyList.Count == 0) + if (items == null || items.Count == 0) return new List(); Dictionary itemMap = Items.ToDictionary(i => i.UniqueId); List result = new(); - foreach (string id in keyList) + foreach (string id in items) { if (itemMap.TryGetValue(id, out var item)) { @@ -58,7 +56,18 @@ public List GetValidItems(string settingsKey) } else { - SettingsHelper.TryRemoveItem(settingsKey, id); + if (isFavorite) + { + var favs = Settings.Current.Favorites; + favs.Remove(id); + Settings.Current.Favorites = favs; + } + else + { + var recentlyVisited = Settings.Current.RecentlyVisited; + recentlyVisited.Remove(id); + Settings.Current.RecentlyVisited = recentlyVisited; + } } } diff --git a/WinUIGallery/Pages/SettingsPage.xaml.cs b/WinUIGallery/Pages/SettingsPage.xaml.cs index ddba4fe0a..18bf757bc 100644 --- a/WinUIGallery/Pages/SettingsPage.xaml.cs +++ b/WinUIGallery/Pages/SettingsPage.xaml.cs @@ -43,8 +43,8 @@ protected override void OnNavigatedTo(NavigationEventArgs e) private void CheckRecentAndFavoriteButtonStates() { - ClearRecentBtn.IsEnabled = SettingsHelper.Exists(SettingsKeys.RecentlyVisited); - UnfavoriteBtn.IsEnabled = SettingsHelper.Exists(SettingsKeys.Favorites); + ClearRecentBtn.IsEnabled = Settings.Current.RecentlyVisited.Count > 0; + UnfavoriteBtn.IsEnabled = Settings.Current.Favorites.Count > 0; } private void OnSettingsPageLoaded(object sender, RoutedEventArgs e) @@ -180,7 +180,10 @@ private async void UnfavoriteBtn_Click(object sender, RoutedEventArgs e) }; dialog.PrimaryButtonClick += (s, args) => { - SettingsHelper.Delete(SettingsKeys.Favorites); + var favs = Settings.Current.Favorites; + favs.Clear(); + Settings.Current.Favorites = favs; + CheckRecentAndFavoriteButtonStates(); }; var result = await dialog.ShowAsync(); @@ -200,7 +203,9 @@ private async void ClearRecentBtn_Click(object sender, RoutedEventArgs e) }; dialog.PrimaryButtonClick += (s, args) => { - SettingsHelper.Delete(SettingsKeys.RecentlyVisited); + var recentlyVisited = Settings.Current.RecentlyVisited; + recentlyVisited.Clear(); + Settings.Current.RecentlyVisited = recentlyVisited; CheckRecentAndFavoriteButtonStates(); }; var result = await dialog.ShowAsync(); From 8def68c60078a02e5a7824b464993ef8c0e90e86 Mon Sep 17 00:00:00 2001 From: Mahdi Hosseini Date: Thu, 7 Aug 2025 16:41:42 +0330 Subject: [PATCH 03/14] Remove Old Settings --- WinUIGallery/Helpers/SettingsHelper.cs | 192 ------------------------- WinUIGallery/Helpers/SettingsKeys.cs | 34 ----- 2 files changed, 226 deletions(-) delete mode 100644 WinUIGallery/Helpers/SettingsHelper.cs delete mode 100644 WinUIGallery/Helpers/SettingsKeys.cs diff --git a/WinUIGallery/Helpers/SettingsHelper.cs b/WinUIGallery/Helpers/SettingsHelper.cs deleted file mode 100644 index 12be0453e..000000000 --- a/WinUIGallery/Helpers/SettingsHelper.cs +++ /dev/null @@ -1,192 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using Microsoft.Windows.Storage; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; - -namespace WinUIGallery.Helpers; - -/// -/// Enum to specify whether an item should be inserted at the beginning or end of the list. -/// -public enum InsertPosition -{ - /// - /// Insert at the beginning of the list. - /// - First, - - /// - /// Insert at the end of the list. - /// - Last -} - -/// -/// Provides utility methods for managing application settings, including operations for storing, retrieving, and -/// manipulating lists of strings in the application's local settings. -/// -public static partial class SettingsHelper -{ - /// - /// The maximum number of items to retain in the recently visited list. - /// - public const int MaxRecentlyVisitedSamples = 7; - - /// - /// An instance of ApplicationData for the current user. - /// - private static ApplicationData appData = ApplicationData.GetDefault(); - - /// - /// Information Separator: Represents an invisible, JSON-safe delimiter used for internal string serialization. - /// - /// This delimiter is intended for separating values in serialized strings where compatibility - /// with JSON is a concern. It is not intended for public use or modification. - private const char delimiter = '\u001f'; - - /// - /// Attempts to add an item to a list associated with the specified key, ensuring no duplicates and optionally - /// enforcing a size limit. - /// - /// The key identifying the list to which the item will be added. Cannot be null, empty, or whitespace. - /// The item to add to the list. Cannot be null, empty, or whitespace. - /// The position at which to insert the item in the list. Use to insert at the - /// beginning, or to insert at the end. - /// The maximum allowed size of the list. If greater than zero, the list will be trimmed to this size after adding - /// the item. Defaults to 0, meaning no size limit is enforced. - /// if the item was successfully added to the list and the list was saved; otherwise, . - public static bool TryAddItem(string key, string item, InsertPosition position, int maxSize = 0) - { - if (string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(item)) - return false; - - bool enforceSizeLimit = maxSize > 0; - var list = GetList(key); - - // Prevent duplicates by removing if already exists - list.Remove(item); - - // Add item at the specified position - if (position == InsertPosition.First) - list.Insert(0, item); - else - list.Add(item); - - // Trim list if needed - if (enforceSizeLimit && list.Count > maxSize) - { - int excess = list.Count - maxSize; - if (position == InsertPosition.First) - list.RemoveRange(maxSize, excess); // Remove from end - else - list.RemoveRange(0, excess); // Remove from start - } - - return TrySaveList(key, list); - } - - /// - /// Attempts to remove the specified item from the list associated with the given key. - /// - /// The key identifying the list from which the item should be removed. Cannot be null or empty. - /// The item to remove from the list. Cannot be null. - /// if the item was successfully removed and the updated list was saved; otherwise, . - public static bool TryRemoveItem(string key, string item) - { - if (!Exists(key) || !Contains(key, item)) - { - return false; - } - - var list = GetList(key); - if (list.Remove(item)) - { - return TrySaveList(key, list); - } - return false; - } - - /// - /// Retrieves a list of strings associated with the specified key from the application's local settings. - /// - /// The key used to locate the stored value in the application's local settings. Cannot be null. - /// A list of strings parsed from the stored value associated with the specified key. Returns an empty list if the - /// key does not exist or the stored value is null. - public static List GetList(string key) - { - string raw = appData.LocalSettings.Values[key] as string; - return raw != null - ? raw.Split(delimiter, StringSplitOptions.RemoveEmptyEntries).ToList() - : new List(); - } - - /// - /// Determines whether the specified item exists within the set of values associated with the given key. - /// - /// The key used to retrieve the stored set of values. Cannot be null or empty. - /// The item to search for within the set of values. Cannot be null. - /// if the item exists in the set of values associated with the key; otherwise, . - public static bool Contains(string key, string item) - { - string raw = appData.LocalSettings.Values[key] as string; - if (string.IsNullOrEmpty(raw)) - return false; - - var set = new HashSet( - raw.Split(delimiter, StringSplitOptions.RemoveEmptyEntries) - ); - - return set.Contains(item); - } - - /// - /// Deletes the specified key and its associated value from the application's local settings. - /// - /// The key of the setting to remove. Cannot be or empty. - public static void Delete(string key) - { - appData.LocalSettings.Values.Remove(key); - } - - /// - /// Determines whether a specified key exists in the application's local settings. - /// - /// The key to check for existence in the local settings. Cannot be null or empty. - /// if the specified key exists and its associated value is not null or empty; otherwise, - /// . - public static bool Exists(string key) - { - string raw = appData.LocalSettings.Values[key] as string; - return !string.IsNullOrEmpty(raw); - } - - /// - /// Attempts to save a list of strings to the application's local settings storage. - /// - /// The unique key used to store the list in local settings. Cannot be null or empty. - /// The list of strings to save. Cannot be null. - /// if the list is successfully saved; otherwise, if the total size - /// of the list exceeds the storage limit. - private static bool TrySaveList(string key, List items) - { - string joined = string.Join(delimiter, items); - int byteSize = System.Text.Encoding.Unicode.GetByteCount(joined); - - // If the size exceeds or equals 8 KB (8192 bytes), reject the save operation - if (byteSize >= 8192) - { - Debug.WriteLine($"Storage limit exceeded for key: {key}."); - return false; - } - - appData.LocalSettings.Values[key] = joined; - return true; - } -} diff --git a/WinUIGallery/Helpers/SettingsKeys.cs b/WinUIGallery/Helpers/SettingsKeys.cs deleted file mode 100644 index 3ef302c54..000000000 --- a/WinUIGallery/Helpers/SettingsKeys.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -namespace WinUIGallery.Helpers; - -/// -/// Provides constant keys used for accessing application settings. -/// -public static partial class SettingsKeys -{ - /// - /// The key used to store or retrieve the selected application theme. - /// - public const string SelectedAppTheme = "SelectedAppTheme"; - - /// - /// Represents the key used to determine whether the navigation is in "left mode." - /// - public const string IsLeftMode = "NavigationIsOnLeftMode"; - - /// - /// Key for the list of recently visited Pages. - /// - public const string RecentlyVisited = "RecentlyVisited"; - - /// - /// Key for the list of favorited Pages. - /// - public const string Favorites = "Favorites"; - - /// - /// Represents the key used to identify the "Show Copy Link" teaching tip of the protocol activation clipboard. - /// - public const string ShowCopyLinkTeachingTip = "ShowCopyLinkTeachingTip"; -} From c42d4d0de0e268e87d13a609f4612396c3ace7c9 Mon Sep 17 00:00:00 2001 From: Mahdi Hosseini Date: Thu, 7 Aug 2025 16:42:20 +0330 Subject: [PATCH 04/14] Rename Settings to SettingsHelper --- WinUIGallery/Controls/PageHeader.xaml.cs | 8 ++++---- WinUIGallery/Helpers/NavigationOrientationHelper.cs | 4 ++-- .../Helpers/ProtocolActivationClipboardHelper.cs | 4 ++-- .../SettingsHelper/Internals/SettingsJsonContext.cs | 2 +- .../{Settings.cs => SettingsHelper.cs} | 8 ++++---- WinUIGallery/Helpers/ThemeHelper.cs | 4 ++-- WinUIGallery/MainWindow.xaml.cs | 4 ++-- WinUIGallery/Pages/HomePage.xaml.cs | 12 ++++++------ WinUIGallery/Pages/SettingsPage.xaml.cs | 12 ++++++------ 9 files changed, 29 insertions(+), 29 deletions(-) rename WinUIGallery/Helpers/SettingsHelper/{Settings.cs => SettingsHelper.cs} (75%) diff --git a/WinUIGallery/Controls/PageHeader.xaml.cs b/WinUIGallery/Controls/PageHeader.xaml.cs index c064ccac4..86e3f6659 100644 --- a/WinUIGallery/Controls/PageHeader.xaml.cs +++ b/WinUIGallery/Controls/PageHeader.xaml.cs @@ -101,7 +101,7 @@ private void UserControl_Loaded(object sender, RoutedEventArgs e) } if (Item != null) { - FavoriteButton.IsChecked = Settings.Current.Favorites.Contains(Item.UniqueId); + FavoriteButton.IsChecked = SettingsHelper.Current.Favorites.Contains(Item.UniqueId); } } @@ -119,17 +119,17 @@ private void FavoriteButton_Click(object sender, RoutedEventArgs e) { if (sender is ToggleButton toggleButton && Item != null) { - var favs = Settings.Current.Favorites; + var favs = SettingsHelper.Current.Favorites; if (toggleButton.IsChecked == true) { favs.AddToLast(Item.UniqueId, isFavorite: true); - Settings.Current.Favorites = favs; + SettingsHelper.Current.Favorites = favs; } else { favs.Remove(Item.UniqueId); - Settings.Current.Favorites = favs; + SettingsHelper.Current.Favorites = favs; } } } diff --git a/WinUIGallery/Helpers/NavigationOrientationHelper.cs b/WinUIGallery/Helpers/NavigationOrientationHelper.cs index 255b6e008..8e4850555 100644 --- a/WinUIGallery/Helpers/NavigationOrientationHelper.cs +++ b/WinUIGallery/Helpers/NavigationOrientationHelper.cs @@ -12,13 +12,13 @@ public static partial class NavigationOrientationHelper private static ApplicationData appData = ApplicationData.GetDefault(); public static bool IsLeftMode() { - return Settings.Current.IsLeftMode; + return SettingsHelper.Current.IsLeftMode; } public static void IsLeftModeForElement(bool isLeftMode) { UpdateNavigationViewForElement(isLeftMode); - Settings.Current.IsLeftMode = isLeftMode; + SettingsHelper.Current.IsLeftMode = isLeftMode; } public static void UpdateNavigationViewForElement(bool isLeftMode) diff --git a/WinUIGallery/Helpers/ProtocolActivationClipboardHelper.cs b/WinUIGallery/Helpers/ProtocolActivationClipboardHelper.cs index 651025fd0..dbd5c6e1d 100644 --- a/WinUIGallery/Helpers/ProtocolActivationClipboardHelper.cs +++ b/WinUIGallery/Helpers/ProtocolActivationClipboardHelper.cs @@ -22,12 +22,12 @@ public static bool ShowCopyLinkTeachingTip { get { - return Settings.Current.IsShowCopyLinkTeachingTip; + return SettingsHelper.Current.IsShowCopyLinkTeachingTip; } set { - Settings.Current.IsShowCopyLinkTeachingTip = value; + SettingsHelper.Current.IsShowCopyLinkTeachingTip = value; } } diff --git a/WinUIGallery/Helpers/SettingsHelper/Internals/SettingsJsonContext.cs b/WinUIGallery/Helpers/SettingsHelper/Internals/SettingsJsonContext.cs index 6afe88b01..b31056c57 100644 --- a/WinUIGallery/Helpers/SettingsHelper/Internals/SettingsJsonContext.cs +++ b/WinUIGallery/Helpers/SettingsHelper/Internals/SettingsJsonContext.cs @@ -7,7 +7,7 @@ namespace WinUIGallery.Helpers; [JsonSerializable(typeof(Dictionary))] [JsonSerializable(typeof(Vector2Data))] [JsonSerializable(typeof(Vector3Data))] -[JsonSerializable(typeof(Settings))] +[JsonSerializable(typeof(SettingsHelper))] internal partial class SettingsJsonContext : JsonSerializerContext { } \ No newline at end of file diff --git a/WinUIGallery/Helpers/SettingsHelper/Settings.cs b/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs similarity index 75% rename from WinUIGallery/Helpers/SettingsHelper/Settings.cs rename to WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs index 6c6e19ee8..88f109064 100644 --- a/WinUIGallery/Helpers/SettingsHelper/Settings.cs +++ b/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs @@ -3,12 +3,12 @@ namespace WinUIGallery.Helpers; -public partial class Settings : ObservableSettings +public partial class SettingsHelper : ObservableSettings { - private static readonly Settings instance = new(SettingsProviderFactory.CreateProvider()); - public static Settings Current => instance; + private static readonly SettingsHelper instance = new(SettingsProviderFactory.CreateProvider()); + public static SettingsHelper Current => instance; - private Settings(ISettingsProvider provider) + private SettingsHelper(ISettingsProvider provider) : base(provider) { } diff --git a/WinUIGallery/Helpers/ThemeHelper.cs b/WinUIGallery/Helpers/ThemeHelper.cs index e7dba14d3..dee5a8511 100644 --- a/WinUIGallery/Helpers/ThemeHelper.cs +++ b/WinUIGallery/Helpers/ThemeHelper.cs @@ -63,13 +63,13 @@ public static ElementTheme RootTheme } } - Settings.Current.SelectedAppTheme = value; + SettingsHelper.Current.SelectedAppTheme = value; } } public static void Initialize() { - RootTheme = Settings.Current.SelectedAppTheme; + RootTheme = SettingsHelper.Current.SelectedAppTheme; } public static bool IsDarkTheme() diff --git a/WinUIGallery/MainWindow.xaml.cs b/WinUIGallery/MainWindow.xaml.cs index e11bc76e7..4eefd479d 100644 --- a/WinUIGallery/MainWindow.xaml.cs +++ b/WinUIGallery/MainWindow.xaml.cs @@ -120,9 +120,9 @@ public void Navigate(Type pageType, object targetPageArguments = null, Navigatio if (pageType.Equals(typeof(ItemPage)) && targetPageArguments != null) { // Mark the item sample's page visited - var recentlyVisited = Settings.Current.RecentlyVisited; + var recentlyVisited = SettingsHelper.Current.RecentlyVisited; recentlyVisited.AddToFirst(targetPageArguments.ToString(), isFavorite: false); - Settings.Current.RecentlyVisited = recentlyVisited; + SettingsHelper.Current.RecentlyVisited = recentlyVisited; } } diff --git a/WinUIGallery/Pages/HomePage.xaml.cs b/WinUIGallery/Pages/HomePage.xaml.cs index 2455e58f2..06492df1b 100644 --- a/WinUIGallery/Pages/HomePage.xaml.cs +++ b/WinUIGallery/Pages/HomePage.xaml.cs @@ -31,9 +31,9 @@ protected override void OnNavigatedTo(NavigationEventArgs e) .OrderBy(i => i.Title) .ToList(); - RecentlyVisitedSamplesList = GetValidItems(Settings.Current.RecentlyVisited, isFavorite: false); + RecentlyVisitedSamplesList = GetValidItems(SettingsHelper.Current.RecentlyVisited, isFavorite: false); RecentlyAddedOrUpdatedSamplesList = Items.Where(i => i.IsNew || i.IsUpdated).ToList(); - FavoriteSamplesList = GetValidItems(Settings.Current.Favorites, isFavorite: true); + FavoriteSamplesList = GetValidItems(SettingsHelper.Current.Favorites, isFavorite: true); VisualStateManager.GoToState(this, RecentlyVisitedSamplesList.Count > 0 ? "Recent" : "NoRecent", true); VisualStateManager.GoToState(this, FavoriteSamplesList.Count > 0 ? "Favorites" : "NoFavorites", true); @@ -58,15 +58,15 @@ public List GetValidItems(List items, bool isFavori { if (isFavorite) { - var favs = Settings.Current.Favorites; + var favs = SettingsHelper.Current.Favorites; favs.Remove(id); - Settings.Current.Favorites = favs; + SettingsHelper.Current.Favorites = favs; } else { - var recentlyVisited = Settings.Current.RecentlyVisited; + var recentlyVisited = SettingsHelper.Current.RecentlyVisited; recentlyVisited.Remove(id); - Settings.Current.RecentlyVisited = recentlyVisited; + SettingsHelper.Current.RecentlyVisited = recentlyVisited; } } } diff --git a/WinUIGallery/Pages/SettingsPage.xaml.cs b/WinUIGallery/Pages/SettingsPage.xaml.cs index 18bf757bc..9d9fc32c4 100644 --- a/WinUIGallery/Pages/SettingsPage.xaml.cs +++ b/WinUIGallery/Pages/SettingsPage.xaml.cs @@ -43,8 +43,8 @@ protected override void OnNavigatedTo(NavigationEventArgs e) private void CheckRecentAndFavoriteButtonStates() { - ClearRecentBtn.IsEnabled = Settings.Current.RecentlyVisited.Count > 0; - UnfavoriteBtn.IsEnabled = Settings.Current.Favorites.Count > 0; + ClearRecentBtn.IsEnabled = SettingsHelper.Current.RecentlyVisited.Count > 0; + UnfavoriteBtn.IsEnabled = SettingsHelper.Current.Favorites.Count > 0; } private void OnSettingsPageLoaded(object sender, RoutedEventArgs e) @@ -180,9 +180,9 @@ private async void UnfavoriteBtn_Click(object sender, RoutedEventArgs e) }; dialog.PrimaryButtonClick += (s, args) => { - var favs = Settings.Current.Favorites; + var favs = SettingsHelper.Current.Favorites; favs.Clear(); - Settings.Current.Favorites = favs; + SettingsHelper.Current.Favorites = favs; CheckRecentAndFavoriteButtonStates(); }; @@ -203,9 +203,9 @@ private async void ClearRecentBtn_Click(object sender, RoutedEventArgs e) }; dialog.PrimaryButtonClick += (s, args) => { - var recentlyVisited = Settings.Current.RecentlyVisited; + var recentlyVisited = SettingsHelper.Current.RecentlyVisited; recentlyVisited.Clear(); - Settings.Current.RecentlyVisited = recentlyVisited; + SettingsHelper.Current.RecentlyVisited = recentlyVisited; CheckRecentAndFavoriteButtonStates(); }; var result = await dialog.ShowAsync(); From ec0bacf8b11ef1e05a80db273b46d0ef15418c66 Mon Sep 17 00:00:00 2001 From: Mahdi Hosseini Date: Thu, 7 Aug 2025 16:46:16 +0330 Subject: [PATCH 05/14] Remove unused codes --- WinUIGallery/Helpers/NavigationOrientationHelper.cs | 3 --- WinUIGallery/Helpers/ProtocolActivationClipboardHelper.cs | 3 --- WinUIGallery/Helpers/ThemeHelper.cs | 3 --- 3 files changed, 9 deletions(-) diff --git a/WinUIGallery/Helpers/NavigationOrientationHelper.cs b/WinUIGallery/Helpers/NavigationOrientationHelper.cs index 8e4850555..cb98e5726 100644 --- a/WinUIGallery/Helpers/NavigationOrientationHelper.cs +++ b/WinUIGallery/Helpers/NavigationOrientationHelper.cs @@ -2,14 +2,11 @@ // Licensed under the MIT License. using Microsoft.UI.Xaml.Controls; -using Microsoft.Windows.Storage; namespace WinUIGallery.Helpers; public static partial class NavigationOrientationHelper { - private static bool _isLeftMode = true; - private static ApplicationData appData = ApplicationData.GetDefault(); public static bool IsLeftMode() { return SettingsHelper.Current.IsLeftMode; diff --git a/WinUIGallery/Helpers/ProtocolActivationClipboardHelper.cs b/WinUIGallery/Helpers/ProtocolActivationClipboardHelper.cs index dbd5c6e1d..aa8763bf4 100644 --- a/WinUIGallery/Helpers/ProtocolActivationClipboardHelper.cs +++ b/WinUIGallery/Helpers/ProtocolActivationClipboardHelper.cs @@ -15,9 +15,6 @@ namespace WinUIGallery.Helpers; /// public static partial class ProtocolActivationClipboardHelper { - private static bool _showCopyLinkTeachingTip = true; - private static ApplicationData appData = ApplicationData.GetDefault(); - public static bool ShowCopyLinkTeachingTip { get diff --git a/WinUIGallery/Helpers/ThemeHelper.cs b/WinUIGallery/Helpers/ThemeHelper.cs index dee5a8511..ca3cd7fea 100644 --- a/WinUIGallery/Helpers/ThemeHelper.cs +++ b/WinUIGallery/Helpers/ThemeHelper.cs @@ -2,7 +2,6 @@ // Licensed under the MIT License. using Microsoft.UI.Xaml; -using Microsoft.Windows.Storage; namespace WinUIGallery.Helpers; @@ -11,8 +10,6 @@ namespace WinUIGallery.Helpers; /// public static partial class ThemeHelper { - private static ApplicationData appData = ApplicationData.GetDefault(); - /// /// Gets the current actual theme of the app based on the requested theme of the /// root element, or if that value is Default, the requested theme of the Application. From 51c34477004a6cb55c5dfbd19ad01481ee3ac4a1 Mon Sep 17 00:00:00 2001 From: Mahdi Hosseini Date: Thu, 7 Aug 2025 16:59:34 +0330 Subject: [PATCH 06/14] Fix ScratchPadPage --- .../Helpers/SettingsHelper/SettingsHelper.cs | 6 ++ .../Fundamentals/ScratchPadPage.xaml.cs | 55 +------------------ 2 files changed, 9 insertions(+), 52 deletions(-) diff --git a/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs b/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs index 88f109064..68e7d839d 100644 --- a/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs +++ b/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs @@ -42,4 +42,10 @@ public List Favorites get => GetOrCreateDefault>(new List()); set => Set(value); } + + public string ScratchPadXaml + { + get => GetOrCreateDefault(string.Empty); + set => Set(value); + } } diff --git a/WinUIGallery/Samples/ControlPages/Fundamentals/ScratchPadPage.xaml.cs b/WinUIGallery/Samples/ControlPages/Fundamentals/ScratchPadPage.xaml.cs index 80aa7c575..283599a25 100644 --- a/WinUIGallery/Samples/ControlPages/Fundamentals/ScratchPadPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/Fundamentals/ScratchPadPage.xaml.cs @@ -9,27 +9,18 @@ using Microsoft.UI.Xaml.Markup; using System; using System.Linq; -using Windows.Storage; using Windows.System; +using WinUIGallery.Helpers; namespace WinUIGallery.ControlPages; public sealed partial class ScratchPadPage : Page { - // The name of the ApplicationData container used to store all ScratchPad-related settings. - private const string containerKey = "ScratchPad"; - - // The key under the ScratchPad container for storing the XAML composite value. - private const string xamlCompositeValueKey = "ScratchPadXAML"; - - // The key within the XAML composite value that stores the number of 4KB segments. - private const string xamlSegmentCountKey = "count"; - public ScratchPadPage() { this.InitializeComponent(); - var xamlStr = ReadScratchPadXAMLinLocalSettings(); + var xamlStr = SettingsHelper.Current.ScratchPadXaml; // If there is no stored XAML, load the default. if (xamlStr == null || xamlStr.Trim().Length == 0) @@ -69,46 +60,6 @@ private string GetDefaultScratchXAML() "; } - public string ReadScratchPadXAMLinLocalSettings() - { - var appData = Microsoft.Windows.Storage.ApplicationData.GetDefault(); - if (appData.LocalSettings.Containers.ContainsKey(containerKey)) - { - var scratchPadContainer = appData.LocalSettings.CreateContainer(containerKey, Microsoft.Windows.Storage.ApplicationDataCreateDisposition.Existing); - if (scratchPadContainer != null && scratchPadContainer.Values.ContainsKey(xamlCompositeValueKey)) - { - // String values are limited to 4K characters. Use a composite value to support a longer string. - var compositeStr = scratchPadContainer.Values[xamlCompositeValueKey] as ApplicationDataCompositeValue; - var xamlStr = ""; - int count = (int)compositeStr[xamlSegmentCountKey]; - for (int i = 0; i < count; i++) - { - xamlStr += compositeStr[i.ToString()]; - } - return xamlStr; - } - } - return null; - } - - public void SaveScratchPadXAMLinLocalSettings(string xamlStr) - { - var appData = Microsoft.Windows.Storage.ApplicationData.GetDefault(); - var scratchPadContainer = appData.LocalSettings.CreateContainer(containerKey, Microsoft.Windows.Storage.ApplicationDataCreateDisposition.Existing); - // String values are limited to 4K characters. Use a composite value to support a longer string. - var compositeStr = new ApplicationDataCompositeValue(); - int count = 0; - while (xamlStr.Length > 0) - { - var len = Math.Min(xamlStr.Length, 4000); - compositeStr[count.ToString()] = xamlStr.Substring(0, len); - count++; - xamlStr = xamlStr.Substring(len); - } - compositeStr[xamlSegmentCountKey] = count; - scratchPadContainer.Values[xamlCompositeValueKey] = compositeStr; - } - private async void ResetToDefaultClick(object sender, RoutedEventArgs e) { ContentDialog dialog = new ContentDialog(); @@ -153,7 +104,7 @@ private void LoadContent() textbox.TextDocument.GetText(TextGetOptions.None, out newText); //System.Diagnostics.Debug.WriteLine("new text: " + newText); - SaveScratchPadXAMLinLocalSettings(newText); + SettingsHelper.Current.ScratchPadXaml = newText; // TODO: Strip out x:Bind -- maybe just convert it to spaces? try From b3da70f729adc44921da1a9e2a188d87f6d76809 Mon Sep 17 00:00:00 2001 From: Mahdi Hosseini Date: Thu, 7 Aug 2025 17:00:58 +0330 Subject: [PATCH 07/14] Update MainWindow.xaml.cs --- WinUIGallery/MainWindow.xaml.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WinUIGallery/MainWindow.xaml.cs b/WinUIGallery/MainWindow.xaml.cs index 4eefd479d..6aa027551 100644 --- a/WinUIGallery/MainWindow.xaml.cs +++ b/WinUIGallery/MainWindow.xaml.cs @@ -50,7 +50,7 @@ private void RootGrid_Loaded(object sender, RoutedEventArgs e) private void SetWindowProperties() { -#if DEBUG +#if DEBUG || DEBUG_UNPACKAGED this.Title = "WinUI 3 Gallery Dev"; titleBar.Subtitle = "Dev"; #else From 5bf1266a8d4356f582f46812634dd3e6f4f39b81 Mon Sep 17 00:00:00 2001 From: Mahdi Hosseini Date: Thu, 7 Aug 2025 17:48:41 +0330 Subject: [PATCH 08/14] use Try/Catch in Get methods --- .../Internals/ListExtensions.cs | 10 ++--- .../ApplicationDataSettingsProvider.cs | 29 +++++++++++--- .../Providers/JsonSettingsProvider.cs | 40 +++++++++++++++++-- .../Helpers/SettingsHelper/SettingsHelper.cs | 1 + 4 files changed, 65 insertions(+), 15 deletions(-) diff --git a/WinUIGallery/Helpers/SettingsHelper/Internals/ListExtensions.cs b/WinUIGallery/Helpers/SettingsHelper/Internals/ListExtensions.cs index f910a69f3..bff04572d 100644 --- a/WinUIGallery/Helpers/SettingsHelper/Internals/ListExtensions.cs +++ b/WinUIGallery/Helpers/SettingsHelper/Internals/ListExtensions.cs @@ -4,8 +4,6 @@ namespace WinUIGallery.Helpers; internal static class ListExtensions { - public const int MaxRecentlyVisitedSamples = 7; - public static void AddToFirst(this List list, string item, bool isFavorite) { if (string.IsNullOrWhiteSpace(item)) @@ -14,9 +12,9 @@ public static void AddToFirst(this List list, string item, bool isFavori list.Remove(item); list.Insert(0, item); - if (!isFavorite && MaxRecentlyVisitedSamples > 0 && list.Count > MaxRecentlyVisitedSamples) + if (!isFavorite && SettingsHelper.MaxRecentlyVisitedSamples > 0 && list.Count > SettingsHelper.MaxRecentlyVisitedSamples) { - list.RemoveRange(MaxRecentlyVisitedSamples, list.Count - MaxRecentlyVisitedSamples); + list.RemoveRange(SettingsHelper.MaxRecentlyVisitedSamples, list.Count - SettingsHelper.MaxRecentlyVisitedSamples); } } @@ -28,9 +26,9 @@ public static void AddToLast(this List list, string item, bool isFavorit list.Remove(item); list.Add(item); - if (!isFavorite && MaxRecentlyVisitedSamples > 0 && list.Count > MaxRecentlyVisitedSamples) + if (!isFavorite && SettingsHelper.MaxRecentlyVisitedSamples > 0 && list.Count > SettingsHelper.MaxRecentlyVisitedSamples) { - list.RemoveRange(0, list.Count - MaxRecentlyVisitedSamples); + list.RemoveRange(0, list.Count - SettingsHelper.MaxRecentlyVisitedSamples); } } } diff --git a/WinUIGallery/Helpers/SettingsHelper/Providers/ApplicationDataSettingsProvider.cs b/WinUIGallery/Helpers/SettingsHelper/Providers/ApplicationDataSettingsProvider.cs index 2c1d379ba..dbdbeca09 100644 --- a/WinUIGallery/Helpers/SettingsHelper/Providers/ApplicationDataSettingsProvider.cs +++ b/WinUIGallery/Helpers/SettingsHelper/Providers/ApplicationDataSettingsProvider.cs @@ -25,16 +25,33 @@ public T Get(string key) if (!container.Values.TryGetValue(key, out var value)) return default; - if (value is T t) - return t; + try + { + if (value is T t) + return t; + + if (value is string str && !IsSimpleType(typeof(T))) + { + var typeInfo = SettingsJsonContext.Default.GetTypeInfo(typeof(T)); + return (T)JsonSerializer.Deserialize(str, typeInfo); + } - if (value is string str && !IsSimpleType(typeof(T))) + return (T)Convert.ChangeType(value, typeof(T)); + } + catch (Exception) { - var typeInfo = SettingsJsonContext.Default.GetTypeInfo(typeof(T)); - return (T)JsonSerializer.Deserialize(str, typeInfo); + HandleCorruptedKey(key); + return default; } + } - return (T)Convert.ChangeType(value, typeof(T)); + private void HandleCorruptedKey(string key) + { + try + { + container.Values.Remove(key); + } + catch {} } public void Set(string key, T value) diff --git a/WinUIGallery/Helpers/SettingsHelper/Providers/JsonSettingsProvider.cs b/WinUIGallery/Helpers/SettingsHelper/Providers/JsonSettingsProvider.cs index 51bc4c6b3..c97305f97 100644 --- a/WinUIGallery/Helpers/SettingsHelper/Providers/JsonSettingsProvider.cs +++ b/WinUIGallery/Helpers/SettingsHelper/Providers/JsonSettingsProvider.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.IO; using System.Text.Json; @@ -31,9 +32,18 @@ public T Get(string key) if (!values.TryGetValue(key, out var jsonElement)) return default; - return (T)jsonElement.Deserialize(SettingsJsonContext.Default.GetTypeInfo(typeof(T))); + try + { + return (T)jsonElement.Deserialize(SettingsJsonContext.Default.GetTypeInfo(typeof(T))); + } + catch (Exception) + { + HandleCorruptedKey(key); + return default; + } } + public void Set(string key, T value) { var json = JsonSerializer.SerializeToElement(value, SettingsJsonContext.Default.GetTypeInfo(typeof(T))); @@ -43,7 +53,10 @@ public void Set(string key, T value) private void Load() { - if (File.Exists(filePath)) + if (!File.Exists(filePath)) + return; + + try { var json = File.ReadAllText(filePath); values = JsonSerializer.Deserialize( @@ -51,7 +64,28 @@ private void Load() SettingsJsonContext.Default.DictionaryStringJsonElement ) ?? new(); } + catch (Exception) + { + HandleCorruptedFile(); + } } + private void HandleCorruptedFile() + { + try + { + File.Delete(filePath); + } + catch { } + + values = new(); + } + + private void HandleCorruptedKey(string key) + { + values.Remove(key); + Save(); + } + private void Save() { diff --git a/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs b/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs index 68e7d839d..126fc3fd6 100644 --- a/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs +++ b/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs @@ -12,6 +12,7 @@ private SettingsHelper(ISettingsProvider provider) : base(provider) { } + public const int MaxRecentlyVisitedSamples = 7; public ElementTheme SelectedAppTheme { From 181fc43e9b7ad49234b08fb336a4592edc25ac1b Mon Sep 17 00:00:00 2001 From: Mahdi Hosseini Date: Sun, 10 Aug 2025 21:32:57 +0330 Subject: [PATCH 09/14] Make ListExtensions More Generic --- WinUIGallery/Controls/PageHeader.xaml.cs | 2 +- .../SettingsHelper/Internals/ListExtensions.cs | 16 ++++++++-------- WinUIGallery/MainWindow.xaml.cs | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/WinUIGallery/Controls/PageHeader.xaml.cs b/WinUIGallery/Controls/PageHeader.xaml.cs index 86e3f6659..3ed8c6ad3 100644 --- a/WinUIGallery/Controls/PageHeader.xaml.cs +++ b/WinUIGallery/Controls/PageHeader.xaml.cs @@ -123,7 +123,7 @@ private void FavoriteButton_Click(object sender, RoutedEventArgs e) if (toggleButton.IsChecked == true) { - favs.AddToLast(Item.UniqueId, isFavorite: true); + favs.AddToLast(Item.UniqueId); SettingsHelper.Current.Favorites = favs; } else diff --git a/WinUIGallery/Helpers/SettingsHelper/Internals/ListExtensions.cs b/WinUIGallery/Helpers/SettingsHelper/Internals/ListExtensions.cs index bff04572d..904b46201 100644 --- a/WinUIGallery/Helpers/SettingsHelper/Internals/ListExtensions.cs +++ b/WinUIGallery/Helpers/SettingsHelper/Internals/ListExtensions.cs @@ -4,31 +4,31 @@ namespace WinUIGallery.Helpers; internal static class ListExtensions { - public static void AddToFirst(this List list, string item, bool isFavorite) + public static void AddToFirst(this List list, T item, int? maxSize = null) { - if (string.IsNullOrWhiteSpace(item)) + if (item == null || (item is string data && string.IsNullOrWhiteSpace(data))) return; list.Remove(item); list.Insert(0, item); - if (!isFavorite && SettingsHelper.MaxRecentlyVisitedSamples > 0 && list.Count > SettingsHelper.MaxRecentlyVisitedSamples) + if (maxSize.HasValue && maxSize.Value > 0 && list.Count > maxSize.Value) { - list.RemoveRange(SettingsHelper.MaxRecentlyVisitedSamples, list.Count - SettingsHelper.MaxRecentlyVisitedSamples); + list.RemoveRange(maxSize.Value, list.Count - maxSize.Value); } } - public static void AddToLast(this List list, string item, bool isFavorite) + public static void AddToLast(this List list, T item, int? maxSize = null) { - if (string.IsNullOrWhiteSpace(item)) + if (item == null || (item is string data && string.IsNullOrWhiteSpace(data))) return; list.Remove(item); list.Add(item); - if (!isFavorite && SettingsHelper.MaxRecentlyVisitedSamples > 0 && list.Count > SettingsHelper.MaxRecentlyVisitedSamples) + if (maxSize.HasValue && maxSize.Value > 0 && list.Count > maxSize.Value) { - list.RemoveRange(0, list.Count - SettingsHelper.MaxRecentlyVisitedSamples); + list.RemoveRange(0, list.Count - maxSize.Value); } } } diff --git a/WinUIGallery/MainWindow.xaml.cs b/WinUIGallery/MainWindow.xaml.cs index 6aa027551..d2d4e16d3 100644 --- a/WinUIGallery/MainWindow.xaml.cs +++ b/WinUIGallery/MainWindow.xaml.cs @@ -121,7 +121,7 @@ public void Navigate(Type pageType, object targetPageArguments = null, Navigatio { // Mark the item sample's page visited var recentlyVisited = SettingsHelper.Current.RecentlyVisited; - recentlyVisited.AddToFirst(targetPageArguments.ToString(), isFavorite: false); + recentlyVisited.AddToFirst(targetPageArguments.ToString(), SettingsHelper.MaxRecentlyVisitedSamples); SettingsHelper.Current.RecentlyVisited = recentlyVisited; } } From 40e76e0d7a8f1a2cc26168d1aaf5f0971dfc7c72 Mon Sep 17 00:00:00 2001 From: Mahdi Hosseini Date: Mon, 11 Aug 2025 20:21:59 +0330 Subject: [PATCH 10/14] Add Common Methods for Favorites and RecentlyVisited to Simplify Their Usage --- WinUIGallery/Controls/PageHeader.xaml.cs | 8 ++------ .../Helpers/SettingsHelper/SettingsHelper.cs | 19 +++++++++++++++++-- WinUIGallery/MainWindow.xaml.cs | 4 +--- WinUIGallery/Pages/HomePage.xaml.cs | 8 ++------ WinUIGallery/Pages/SettingsPage.xaml.cs | 10 ++-------- 5 files changed, 24 insertions(+), 25 deletions(-) diff --git a/WinUIGallery/Controls/PageHeader.xaml.cs b/WinUIGallery/Controls/PageHeader.xaml.cs index 3ed8c6ad3..4500d3c0d 100644 --- a/WinUIGallery/Controls/PageHeader.xaml.cs +++ b/WinUIGallery/Controls/PageHeader.xaml.cs @@ -119,17 +119,13 @@ private void FavoriteButton_Click(object sender, RoutedEventArgs e) { if (sender is ToggleButton toggleButton && Item != null) { - var favs = SettingsHelper.Current.Favorites; - if (toggleButton.IsChecked == true) { - favs.AddToLast(Item.UniqueId); - SettingsHelper.Current.Favorites = favs; + SettingsHelper.Current.UpdateFavorites(items => items.AddToLast(Item.UniqueId)); } else { - favs.Remove(Item.UniqueId); - SettingsHelper.Current.Favorites = favs; + SettingsHelper.Current.UpdateFavorites(items => items.Remove(Item.UniqueId)); } } } diff --git a/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs b/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs index 126fc3fd6..9851b00a4 100644 --- a/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs +++ b/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs @@ -1,4 +1,5 @@ using Microsoft.UI.Xaml; +using System; using System.Collections.Generic; namespace WinUIGallery.Helpers; @@ -35,13 +36,13 @@ public bool IsShowCopyLinkTeachingTip public List RecentlyVisited { get => GetOrCreateDefault>(new List()); - set => Set(value); + private set => Set(value); } public List Favorites { get => GetOrCreateDefault>(new List()); - set => Set(value); + private set => Set(value); } public string ScratchPadXaml @@ -49,4 +50,18 @@ public string ScratchPadXaml get => GetOrCreateDefault(string.Empty); set => Set(value); } + + public void UpdateFavorites(Action> updater) + { + var list = Favorites; + updater(list); + Favorites = list; + } + public void UpdateRecentlyVisited(Action> updater) + { + var list = RecentlyVisited; + updater(list); + RecentlyVisited = list; + } + } diff --git a/WinUIGallery/MainWindow.xaml.cs b/WinUIGallery/MainWindow.xaml.cs index d2d4e16d3..94a026ddb 100644 --- a/WinUIGallery/MainWindow.xaml.cs +++ b/WinUIGallery/MainWindow.xaml.cs @@ -120,9 +120,7 @@ public void Navigate(Type pageType, object targetPageArguments = null, Navigatio if (pageType.Equals(typeof(ItemPage)) && targetPageArguments != null) { // Mark the item sample's page visited - var recentlyVisited = SettingsHelper.Current.RecentlyVisited; - recentlyVisited.AddToFirst(targetPageArguments.ToString(), SettingsHelper.MaxRecentlyVisitedSamples); - SettingsHelper.Current.RecentlyVisited = recentlyVisited; + SettingsHelper.Current.UpdateRecentlyVisited(items => items.AddToFirst(targetPageArguments.ToString(), SettingsHelper.MaxRecentlyVisitedSamples)); } } diff --git a/WinUIGallery/Pages/HomePage.xaml.cs b/WinUIGallery/Pages/HomePage.xaml.cs index 06492df1b..a9d28275f 100644 --- a/WinUIGallery/Pages/HomePage.xaml.cs +++ b/WinUIGallery/Pages/HomePage.xaml.cs @@ -58,15 +58,11 @@ public List GetValidItems(List items, bool isFavori { if (isFavorite) { - var favs = SettingsHelper.Current.Favorites; - favs.Remove(id); - SettingsHelper.Current.Favorites = favs; + SettingsHelper.Current.UpdateFavorites(items => items.Remove(id)); } else { - var recentlyVisited = SettingsHelper.Current.RecentlyVisited; - recentlyVisited.Remove(id); - SettingsHelper.Current.RecentlyVisited = recentlyVisited; + SettingsHelper.Current.UpdateRecentlyVisited(items => items.Remove(id)); } } } diff --git a/WinUIGallery/Pages/SettingsPage.xaml.cs b/WinUIGallery/Pages/SettingsPage.xaml.cs index 9d9fc32c4..ebd61b5cc 100644 --- a/WinUIGallery/Pages/SettingsPage.xaml.cs +++ b/WinUIGallery/Pages/SettingsPage.xaml.cs @@ -8,7 +8,6 @@ using System; using Windows.ApplicationModel.DataTransfer; using Windows.System; -using WinUIGallery.ControlPages; using WinUIGallery.Helpers; namespace WinUIGallery.Pages; @@ -180,10 +179,7 @@ private async void UnfavoriteBtn_Click(object sender, RoutedEventArgs e) }; dialog.PrimaryButtonClick += (s, args) => { - var favs = SettingsHelper.Current.Favorites; - favs.Clear(); - SettingsHelper.Current.Favorites = favs; - + SettingsHelper.Current.UpdateFavorites(items => items.Clear()); CheckRecentAndFavoriteButtonStates(); }; var result = await dialog.ShowAsync(); @@ -203,9 +199,7 @@ private async void ClearRecentBtn_Click(object sender, RoutedEventArgs e) }; dialog.PrimaryButtonClick += (s, args) => { - var recentlyVisited = SettingsHelper.Current.RecentlyVisited; - recentlyVisited.Clear(); - SettingsHelper.Current.RecentlyVisited = recentlyVisited; + SettingsHelper.Current.UpdateRecentlyVisited(items => items.Clear()); CheckRecentAndFavoriteButtonStates(); }; var result = await dialog.ShowAsync(); From 7f04f89a002670138e2ef9c14db25e13908cc5fb Mon Sep 17 00:00:00 2001 From: Mahdi Hosseini Date: Mon, 11 Aug 2025 20:26:11 +0330 Subject: [PATCH 11/14] Remove Unsued Vector Wrapper --- .../Internals/SettingsJsonContext.cs | 2 -- .../SettingsHelper/Internals/Vectors.cs | 29 ------------------- 2 files changed, 31 deletions(-) delete mode 100644 WinUIGallery/Helpers/SettingsHelper/Internals/Vectors.cs diff --git a/WinUIGallery/Helpers/SettingsHelper/Internals/SettingsJsonContext.cs b/WinUIGallery/Helpers/SettingsHelper/Internals/SettingsJsonContext.cs index b31056c57..50105a119 100644 --- a/WinUIGallery/Helpers/SettingsHelper/Internals/SettingsJsonContext.cs +++ b/WinUIGallery/Helpers/SettingsHelper/Internals/SettingsJsonContext.cs @@ -5,8 +5,6 @@ namespace WinUIGallery.Helpers; [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata)] [JsonSerializable(typeof(Dictionary))] -[JsonSerializable(typeof(Vector2Data))] -[JsonSerializable(typeof(Vector3Data))] [JsonSerializable(typeof(SettingsHelper))] internal partial class SettingsJsonContext : JsonSerializerContext { diff --git a/WinUIGallery/Helpers/SettingsHelper/Internals/Vectors.cs b/WinUIGallery/Helpers/SettingsHelper/Internals/Vectors.cs deleted file mode 100644 index 75869b33a..000000000 --- a/WinUIGallery/Helpers/SettingsHelper/Internals/Vectors.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace WinUIGallery.Helpers; - -internal partial class Vector4Data -{ - public float W { get; set; } - public float X { get; set; } - public float Y { get; set; } - public float Z { get; set; } - - public static implicit operator System.Numerics.Vector4(Vector4Data d) => new(d.X, d.Y, d.Z, d.W); - public static implicit operator Vector4Data(System.Numerics.Vector4 v) => new() { X = v.X, Y = v.Y, Z = v.Z, W = v.W }; -} -internal partial class Vector3Data -{ - public float X { get; set; } - public float Y { get; set; } - public float Z { get; set; } - - public static implicit operator System.Numerics.Vector3(Vector3Data d) => new(d.X, d.Y, d.Z); - public static implicit operator Vector3Data(System.Numerics.Vector3 v) => new() { X = v.X, Y = v.Y, Z = v.Z }; -} -internal partial class Vector2Data -{ - public float X { get; set; } - public float Y { get; set; } - - public static implicit operator System.Numerics.Vector2(Vector2Data d) => new(d.X, d.Y); - public static implicit operator Vector2Data(System.Numerics.Vector2 v) => new() { X = v.X, Y = v.Y }; -} \ No newline at end of file From d8c789102777f8b4ab45ba47024915989251ea8a Mon Sep 17 00:00:00 2001 From: Mahdi Hosseini Date: Fri, 15 Aug 2025 15:33:19 +0330 Subject: [PATCH 12/14] Remove ScratchPadXaml Setting --- .../Helpers/SettingsHelper/SettingsHelper.cs | 7 ------- .../Fundamentals/ScratchPadPage.xaml.cs | 13 +------------ 2 files changed, 1 insertion(+), 19 deletions(-) diff --git a/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs b/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs index 9851b00a4..790268c02 100644 --- a/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs +++ b/WinUIGallery/Helpers/SettingsHelper/SettingsHelper.cs @@ -45,12 +45,6 @@ public List Favorites private set => Set(value); } - public string ScratchPadXaml - { - get => GetOrCreateDefault(string.Empty); - set => Set(value); - } - public void UpdateFavorites(Action> updater) { var list = Favorites; @@ -63,5 +57,4 @@ public void UpdateRecentlyVisited(Action> updater) updater(list); RecentlyVisited = list; } - } diff --git a/WinUIGallery/Samples/ControlPages/Fundamentals/ScratchPadPage.xaml.cs b/WinUIGallery/Samples/ControlPages/Fundamentals/ScratchPadPage.xaml.cs index 283599a25..d883a5d6b 100644 --- a/WinUIGallery/Samples/ControlPages/Fundamentals/ScratchPadPage.xaml.cs +++ b/WinUIGallery/Samples/ControlPages/Fundamentals/ScratchPadPage.xaml.cs @@ -10,7 +10,6 @@ using System; using System.Linq; using Windows.System; -using WinUIGallery.Helpers; namespace WinUIGallery.ControlPages; @@ -20,15 +19,7 @@ public ScratchPadPage() { this.InitializeComponent(); - var xamlStr = SettingsHelper.Current.ScratchPadXaml; - - // If there is no stored XAML, load the default. - if (xamlStr == null || xamlStr.Trim().Length == 0) - { - xamlStr = GetDefaultScratchXAML(); - } - - m_oldText = xamlStr; + m_oldText = GetDefaultScratchXAML(); textbox.TextDocument.SetText(TextSetOptions.None, m_oldText); var formatter = new XamlTextFormatter(textbox); formatter.ApplyColors(); @@ -104,8 +95,6 @@ private void LoadContent() textbox.TextDocument.GetText(TextGetOptions.None, out newText); //System.Diagnostics.Debug.WriteLine("new text: " + newText); - SettingsHelper.Current.ScratchPadXaml = newText; - // TODO: Strip out x:Bind -- maybe just convert it to spaces? try { From 9bcced4dbf3c4d50fbcd823a943bae1a2e65fed4 Mon Sep 17 00:00:00 2001 From: Mahdi Hosseini Date: Sat, 30 Aug 2025 16:50:03 +0330 Subject: [PATCH 13/14] Update WinUIGallery/Helpers/SettingsHelper/Providers/JsonSettingsProvider.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../Helpers/SettingsHelper/Providers/JsonSettingsProvider.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/WinUIGallery/Helpers/SettingsHelper/Providers/JsonSettingsProvider.cs b/WinUIGallery/Helpers/SettingsHelper/Providers/JsonSettingsProvider.cs index c97305f97..8f6e0d3b6 100644 --- a/WinUIGallery/Helpers/SettingsHelper/Providers/JsonSettingsProvider.cs +++ b/WinUIGallery/Helpers/SettingsHelper/Providers/JsonSettingsProvider.cs @@ -75,7 +75,10 @@ private void HandleCorruptedFile() { File.Delete(filePath); } - catch { } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to delete corrupted settings file '{filePath}': {ex}"); + } values = new(); } From b14fbb0873cc5e8510d779e26f4411a9c80b317b Mon Sep 17 00:00:00 2001 From: Mahdi Hosseini Date: Sat, 30 Aug 2025 16:50:22 +0330 Subject: [PATCH 14/14] Update WinUIGallery/Helpers/SettingsHelper/Providers/ApplicationDataSettingsProvider.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../Providers/ApplicationDataSettingsProvider.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/WinUIGallery/Helpers/SettingsHelper/Providers/ApplicationDataSettingsProvider.cs b/WinUIGallery/Helpers/SettingsHelper/Providers/ApplicationDataSettingsProvider.cs index dbdbeca09..ada030c6b 100644 --- a/WinUIGallery/Helpers/SettingsHelper/Providers/ApplicationDataSettingsProvider.cs +++ b/WinUIGallery/Helpers/SettingsHelper/Providers/ApplicationDataSettingsProvider.cs @@ -51,7 +51,10 @@ private void HandleCorruptedKey(string key) { container.Values.Remove(key); } - catch {} + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to remove corrupted key '{key}': {ex}"); + } } public void Set(string key, T value)