Skip to content

Commit f7d00c7

Browse files
author
msftbot[bot]
authored
ObjectStorage enhancements (#4102)
<!-- 🚨 Please Do Not skip any instructions and information mentioned below as they are all required and essential to evaluate and test the PR. By fulfilling all the required information you will be able to reduce the volume of questions and most likely help merge the PR faster 🚨 --> <!-- 👉 It is imperative to resolve ONE ISSUE PER PR and avoid making multiple changes unless the changes interrelate with each other --> <!-- 📝 Please always keep the "☑️ Allow edits by maintainers" button checked in the Pull Request Template as it increases collaboration with the Toolkit maintainers by permitting commits to your PR branch (only) created from your fork. This can let us quickly make fixes for minor typos or forgotten StyleCop issues during review without needing to wait on you doing extra work. Let us help you help us! 🎉 --> ## Fixes #3903 <!-- Add the relevant issue number after the "#" mentioned above (for ex: "## Fixes #1234") which will automatically close the issue once the PR is merged. --> <!-- Add a brief overview here of the feature/bug & fix. --> ## PR Type What kind of change does this PR introduce? <!-- Please uncomment one or more options below that apply to this PR. --> <!-- - Bugfix --> - Feature <!-- - Code style update (formatting) --> <!-- - Refactoring (no functional changes, no api changes) --> <!-- - Build or CI related changes --> <!-- - Documentation content changes --> <!-- - Sample app changes --> <!-- - Other... Please describe: --> ## What is the current behavior? <!-- Please describe the current behavior that you are modifying, or link to a relevant issue. --> The ObjectStorage helper interfaces and implementations currently live in the `*.Uwp` package. This means that they are not consumable from NetStandard projects, such as the `CommunityToolkit.Graph` package. In addition, the `IObjectStorageHelper` is a mixture of support for both dictionary style settings storage, with some file storage features as well. Currently, supporting both file and folder scenarios is odd/difficult for storage endpoints that don't operate in a similar manner to `Windows.Storage.ApplicationData`. Lastly, the support for file storage in `IObjectStorageHelper` is not complete and missing some basic CRUD operations that can make it difficult to work with in real-world application scenarios. ## What is the new behavior? <!-- Describe how was this issue resolved or changed? --> I've done a few things: 1. Deprecated the existing structures in the `Microsoft.Toolkit.Uwp/Helpers/ObjectStorage` folder: - `BaseObjectStorageHelper` - `IObjectSerializer` - `IObjectStorageHelper` - `LocalObjectStorageHelper` - `SystemSerializer` 2. Migrated some of the previous structures up into the `Microsoft.Toolkit/Helpers/ObjectStorage` folder so that they are consumable from NetStandard: - `IObjectSerializer` - `SystemSerializer` 3. Created new interfaces to replace the functionality defined in the now defunct `IObjectStorageHelper`: - `ISettingsStorageHelper` - Interop with values as key/value pairs, like a dictionary. - `IFileStorageHelper` - Interop with a file system to store values in files and folders. 4. Replaced the functionality provided by `BaseObjectStorageHelper` and `LocalObjectStorageHelper` with an implementation of `ISettingsStorageHelper` and `IFileStorageHelper`: - `ApplicationDataStorageHelper` - Interop with local settings and files through `Windows.Storage.ApplicationData`. Use it like so: ``` ApplicationDataStorageHelper appDataStorageHelper = ApplicationDataStorageHelper.GetCurrent(new Toolkit.Helpers.SystemSerializer()); // Save and Read simple objects string keySimpleObject = "simple"; appDataStorageHelper.Save(keySimpleObject, 42); appDataStorageHelper.TryRead<string>(keySimpleObject, out string result); // Save and Read complex objects string complexObjectKey = "complexObject"; await appDataStorageHelper.SaveFileAsync(complexObjectKey, new MyComplexObject()); var complexObject = await appDataStorageHelper.ReadFileAsync<MyComplexObject>(complexObjectKey); // Complex object example public class MyComplexObject { public string MyContent { get; set; } public List<string> MyContents { get; set; } public List<MyComplexObject> MyObjects { get; set; } } ``` Altogether, this provides a transition path from the previous ObjectStorage constructs to a more granular set of interfaces with identical signatures plus enhanced support for file and folder CRUD operations. ## PR Checklist Please check if your PR fulfills the following requirements: - [x] Tested code with current [supported SDKs](../readme.md#supported) - [ ] Pull Request has been submitted to the documentation repository [instructions](..\contributing.md#docs). Link: <!-- docs PR link --> - [x] Sample in sample app has been added / updated (for bug fixes / features) - [x] Icon has been created (if new sample) following the [Thumbnail Style Guide and templates](https://github.com/windows-toolkit/WindowsCommunityToolkit-design-assets) - [x] New major technical changes in the toolkit have or will be added to the [Wiki](https://github.com/windows-toolkit/WindowsCommunityToolkit/wiki) e.g. build changes, source generators, testing infrastructure, sample creation changes, etc... - [x] Tests for the changes have been added (for bug fixes / features) (if applicable) - [x] Header has been added to all new source files (run *build/UpdateHeaders.bat*) - [x] Contains **NO** breaking changes <!-- If this PR contains a breaking change, please describe the impact and migration path for existing applications below. Please note that breaking changes are likely to be rejected within minor release cycles or held until major versions. --> ## Other information Looking for feedback!
2 parents cbefac4 + b0a33c5 commit f7d00c7

28 files changed

+1074
-100
lines changed

Microsoft.Toolkit.Uwp.SampleApp/Controls/SampleAppMarkdownRenderer.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System;
66
using System.Collections.Generic;
77
using System.Linq;
8+
using Microsoft.Toolkit.Helpers;
89
using Microsoft.Toolkit.Parsers.Markdown;
910
using Microsoft.Toolkit.Parsers.Markdown.Blocks;
1011
using Microsoft.Toolkit.Parsers.Markdown.Inlines;
@@ -407,19 +408,19 @@ public string DesiredLang
407408
{
408409
get
409410
{
410-
return storage.Read<string>(DesiredLangKey);
411+
return settingsStorage.Read<string>(DesiredLangKey);
411412
}
412413

413414
set
414415
{
415-
storage.Save(DesiredLangKey, value);
416+
settingsStorage.Save(DesiredLangKey, value);
416417
}
417418
}
418419

419420
/// <summary>
420-
/// The Local Storage Helper.
421+
/// The local app data storage helper for storing settings.
421422
/// </summary>
422-
private LocalObjectStorageHelper storage = new LocalObjectStorageHelper(new SystemSerializer());
423+
private readonly ApplicationDataStorageHelper settingsStorage = ApplicationDataStorageHelper.GetCurrent();
423424

424425
/// <summary>
425426
/// DocFX note types and styling info, keyed by identifier.

Microsoft.Toolkit.Uwp.SampleApp/Models/Sample.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
// TODO Reintroduce graph controls
2121
// using Microsoft.Toolkit.Graph.Converters;
2222
// using Microsoft.Toolkit.Graph.Providers;
23+
using Microsoft.Toolkit.Helpers;
2324
using Microsoft.Toolkit.Uwp.Helpers;
2425
using Microsoft.Toolkit.Uwp.Input.GazeInteraction;
2526
using Microsoft.Toolkit.Uwp.SampleApp.Models;
@@ -45,7 +46,7 @@ public class Sample
4546

4647
public static async void EnsureCacheLatest()
4748
{
48-
var settingsStorage = new LocalObjectStorageHelper(new SystemSerializer());
49+
var settingsStorage = ApplicationDataStorageHelper.GetCurrent();
4950

5051
var onlineDocsSHA = await GetDocsSHA();
5152
var cacheSHA = settingsStorage.Read<string>(_cacheSHAKey);

Microsoft.Toolkit.Uwp.SampleApp/Models/Samples.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
using System.Text.Json;
1010
using System.Threading;
1111
using System.Threading.Tasks;
12+
using Microsoft.Toolkit.Helpers;
1213
using Microsoft.Toolkit.Uwp.Helpers;
1314

1415
namespace Microsoft.Toolkit.Uwp.SampleApp
@@ -21,7 +22,7 @@ public static class Samples
2122
private static SemaphoreSlim _semaphore = new SemaphoreSlim(1);
2223

2324
private static LinkedList<Sample> _recentSamples;
24-
private static LocalObjectStorageHelper _localObjectStorageHelper = new LocalObjectStorageHelper(new SystemSerializer());
25+
private static ApplicationDataStorageHelper _settingsStorage = ApplicationDataStorageHelper.GetCurrent();
2526

2627
public static async Task<SampleCategory> GetCategoryBySample(Sample sample)
2728
{
@@ -98,7 +99,7 @@ public static async Task<LinkedList<Sample>> GetRecentSamples()
9899
if (_recentSamples == null)
99100
{
100101
_recentSamples = new LinkedList<Sample>();
101-
var savedSamples = _localObjectStorageHelper.Read<string>(_recentSamplesStorageKey);
102+
var savedSamples = _settingsStorage.Read<string>(_recentSamplesStorageKey);
102103

103104
if (savedSamples != null)
104105
{
@@ -144,7 +145,7 @@ private static void SaveRecentSamples()
144145
}
145146

146147
var str = string.Join(";", _recentSamples.Take(10).Select(s => s.Name).ToArray());
147-
_localObjectStorageHelper.Save<string>(_recentSamplesStorageKey, str);
148+
_settingsStorage.Save<string>(_recentSamplesStorageKey, str);
148149
}
149150
}
150151
}
Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,24 @@
1-
var localObjectStorageHelper = new LocalObjectStorageHelper();
2-
var roamingObjectStorageHelper = new RoamingObjectStorageHelper();
1+
ApplicationDataStorageHelper appDataStorageHelper = ApplicationDataStorageHelper.GetCurrent(new Toolkit.Helpers.SystemSerializer());
32

43
// Read and Save with simple objects
54
string keySimpleObject = "simple";
6-
string result = localObjectStorageHelper.Read<string>(keySimpleObject);
7-
localObjectStorageHelper.Save(keySimpleObject, 47);
5+
string result = appDataStorageHelper.Read<string>(keySimpleObject);
6+
appDataStorageHelper.Save(keySimpleObject, 47);
87

98
// Read and Save with complex/large objects
10-
string keyLargeObject = "large";
11-
var result = localObjectStorageHelper.ReadFileAsync<MyLargeObject>(keyLargeObject);
9+
string complexObjectKey = "complexObject";
10+
var complexObject = await appDataStorageHelper.ReadFileAsync<MyLargeObject>(complexObjectKey);
1211

13-
var o = new MyLargeObject
12+
var myComplexObject = new MyComplexObject()
1413
{
1514
...
1615
};
17-
localObjectStorageHelper.SaveFileAsync(keySimpleObject, o);
16+
await appDataStorageHelper.SaveFileAsync(complexObjectKey, myComplexObject);
1817

1918
// Complex object
20-
public class MyLargeObject
19+
public class MyComplexObject
2120
{
2221
public string MyContent { get; set; }
2322
public List<string> MyContents { get; set; }
24-
public List<MyLargeObject> MyObjects { get; set; }
23+
public List<MyComplexObject> MyObjects { get; set; }
2524
}

Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Object Storage/ObjectStoragePage.xaml.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33
// See the LICENSE file in the project root for more information.
44

5+
using Microsoft.Toolkit.Helpers;
56
using Microsoft.Toolkit.Uwp.Helpers;
67
using Windows.UI.Xaml;
78

89
namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages
910
{
1011
public sealed partial class ObjectStoragePage
1112
{
12-
private readonly IObjectStorageHelper localStorageHelper = new LocalObjectStorageHelper(new SystemSerializer());
13+
private readonly ApplicationDataStorageHelper _settingsStorage = ApplicationDataStorageHelper.GetCurrent();
1314

1415
public ObjectStoragePage()
1516
{
@@ -24,9 +25,9 @@ private void ReadButton_Click(object sender, RoutedEventArgs e)
2425
}
2526

2627
// Read from local storage
27-
if (localStorageHelper.KeyExists(KeyTextBox.Text))
28+
if (_settingsStorage.KeyExists(KeyTextBox.Text))
2829
{
29-
ContentTextBox.Text = localStorageHelper.Read<string>(KeyTextBox.Text);
30+
ContentTextBox.Text = _settingsStorage.Read<string>(KeyTextBox.Text);
3031
}
3132
}
3233

@@ -43,7 +44,7 @@ private void SaveButton_Click(object sender, RoutedEventArgs e)
4344
}
4445

4546
// Save into local storage
46-
localStorageHelper.Save(KeyTextBox.Text, ContentTextBox.Text);
47+
_settingsStorage.Save(KeyTextBox.Text, ContentTextBox.Text);
4748
}
4849
}
4950
}
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using System;
6+
using System.Collections.Generic;
7+
using System.Threading.Tasks;
8+
using Microsoft.Toolkit.Helpers;
9+
using Windows.Storage;
10+
11+
namespace Microsoft.Toolkit.Uwp.Helpers
12+
{
13+
/// <summary>
14+
/// An extension of ApplicationDataStorageHelper with additional features for interop with the LocalCacheFolder.
15+
/// </summary>
16+
public partial class ApplicationDataStorageHelper
17+
{
18+
/// <summary>
19+
/// Gets the local cache folder.
20+
/// </summary>
21+
public StorageFolder CacheFolder => AppData.LocalCacheFolder;
22+
23+
/// <summary>
24+
/// Retrieves an object from a file in the LocalCacheFolder.
25+
/// </summary>
26+
/// <typeparam name="T">Type of object retrieved.</typeparam>
27+
/// <param name="filePath">Path to the file that contains the object.</param>
28+
/// <param name="default">Default value of the object.</param>
29+
/// <returns>Waiting task until completion with the object in the file.</returns>
30+
public Task<T> ReadCacheFileAsync<T>(string filePath, T @default = default)
31+
{
32+
return ReadFileAsync<T>(CacheFolder, filePath, @default);
33+
}
34+
35+
/// <summary>
36+
/// Retrieves the listings for a folder and the item types in the LocalCacheFolder.
37+
/// </summary>
38+
/// <param name="folderPath">The path to the target folder.</param>
39+
/// <returns>A list of file types and names in the target folder.</returns>
40+
public Task<IEnumerable<(DirectoryItemType ItemType, string Name)>> ReadCacheFolderAsync(string folderPath)
41+
{
42+
return ReadFolderAsync(CacheFolder, folderPath);
43+
}
44+
45+
/// <summary>
46+
/// Saves an object inside a file in the LocalCacheFolder.
47+
/// </summary>
48+
/// <typeparam name="T">Type of object saved.</typeparam>
49+
/// <param name="filePath">Path to the file that will contain the object.</param>
50+
/// <param name="value">Object to save.</param>
51+
/// <returns>Waiting task until completion.</returns>
52+
public Task CreateCacheFileAsync<T>(string filePath, T value)
53+
{
54+
return SaveFileAsync<T>(CacheFolder, filePath, value);
55+
}
56+
57+
/// <summary>
58+
/// Ensure a folder exists at the folder path specified in the LocalCacheFolder.
59+
/// </summary>
60+
/// <param name="folderPath">The path and name of the target folder.</param>
61+
/// <returns>Waiting task until completion.</returns>
62+
public Task CreateCacheFolderAsync(string folderPath)
63+
{
64+
return CreateFolderAsync(CacheFolder, folderPath);
65+
}
66+
67+
/// <summary>
68+
/// Deletes a file or folder item in the LocalCacheFolder.
69+
/// </summary>
70+
/// <param name="itemPath">The path to the item for deletion.</param>
71+
/// <returns>Waiting task until completion.</returns>
72+
public Task DeleteCacheItemAsync(string itemPath)
73+
{
74+
return DeleteItemAsync(CacheFolder, itemPath);
75+
}
76+
}
77+
}

0 commit comments

Comments
 (0)