Skip to content

Commit

Permalink
ObjectStorage enhancements (#4102)
Browse files Browse the repository at this point in the history
<!-- 🚨 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!
  • Loading branch information
msftbot[bot] authored Jul 29, 2021
2 parents cbefac4 + b0a33c5 commit f7d00c7
Show file tree
Hide file tree
Showing 28 changed files with 1,074 additions and 100 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Toolkit.Helpers;
using Microsoft.Toolkit.Parsers.Markdown;
using Microsoft.Toolkit.Parsers.Markdown.Blocks;
using Microsoft.Toolkit.Parsers.Markdown.Inlines;
Expand Down Expand Up @@ -407,19 +408,19 @@ public string DesiredLang
{
get
{
return storage.Read<string>(DesiredLangKey);
return settingsStorage.Read<string>(DesiredLangKey);
}

set
{
storage.Save(DesiredLangKey, value);
settingsStorage.Save(DesiredLangKey, value);
}
}

/// <summary>
/// The Local Storage Helper.
/// The local app data storage helper for storing settings.
/// </summary>
private LocalObjectStorageHelper storage = new LocalObjectStorageHelper(new SystemSerializer());
private readonly ApplicationDataStorageHelper settingsStorage = ApplicationDataStorageHelper.GetCurrent();

/// <summary>
/// DocFX note types and styling info, keyed by identifier.
Expand Down
3 changes: 2 additions & 1 deletion Microsoft.Toolkit.Uwp.SampleApp/Models/Sample.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
// TODO Reintroduce graph controls
// using Microsoft.Toolkit.Graph.Converters;
// using Microsoft.Toolkit.Graph.Providers;
using Microsoft.Toolkit.Helpers;
using Microsoft.Toolkit.Uwp.Helpers;
using Microsoft.Toolkit.Uwp.Input.GazeInteraction;
using Microsoft.Toolkit.Uwp.SampleApp.Models;
Expand All @@ -45,7 +46,7 @@ public class Sample

public static async void EnsureCacheLatest()
{
var settingsStorage = new LocalObjectStorageHelper(new SystemSerializer());
var settingsStorage = ApplicationDataStorageHelper.GetCurrent();

var onlineDocsSHA = await GetDocsSHA();
var cacheSHA = settingsStorage.Read<string>(_cacheSHAKey);
Expand Down
7 changes: 4 additions & 3 deletions Microsoft.Toolkit.Uwp.SampleApp/Models/Samples.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Toolkit.Helpers;
using Microsoft.Toolkit.Uwp.Helpers;

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

private static LinkedList<Sample> _recentSamples;
private static LocalObjectStorageHelper _localObjectStorageHelper = new LocalObjectStorageHelper(new SystemSerializer());
private static ApplicationDataStorageHelper _settingsStorage = ApplicationDataStorageHelper.GetCurrent();

public static async Task<SampleCategory> GetCategoryBySample(Sample sample)
{
Expand Down Expand Up @@ -98,7 +99,7 @@ public static async Task<LinkedList<Sample>> GetRecentSamples()
if (_recentSamples == null)
{
_recentSamples = new LinkedList<Sample>();
var savedSamples = _localObjectStorageHelper.Read<string>(_recentSamplesStorageKey);
var savedSamples = _settingsStorage.Read<string>(_recentSamplesStorageKey);

if (savedSamples != null)
{
Expand Down Expand Up @@ -144,7 +145,7 @@ private static void SaveRecentSamples()
}

var str = string.Join(";", _recentSamples.Take(10).Select(s => s.Name).ToArray());
_localObjectStorageHelper.Save<string>(_recentSamplesStorageKey, str);
_settingsStorage.Save<string>(_recentSamplesStorageKey, str);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,25 +1,24 @@
var localObjectStorageHelper = new LocalObjectStorageHelper();
var roamingObjectStorageHelper = new RoamingObjectStorageHelper();
ApplicationDataStorageHelper appDataStorageHelper = ApplicationDataStorageHelper.GetCurrent(new Toolkit.Helpers.SystemSerializer());

// Read and Save with simple objects
string keySimpleObject = "simple";
string result = localObjectStorageHelper.Read<string>(keySimpleObject);
localObjectStorageHelper.Save(keySimpleObject, 47);
string result = appDataStorageHelper.Read<string>(keySimpleObject);
appDataStorageHelper.Save(keySimpleObject, 47);

// Read and Save with complex/large objects
string keyLargeObject = "large";
var result = localObjectStorageHelper.ReadFileAsync<MyLargeObject>(keyLargeObject);
string complexObjectKey = "complexObject";
var complexObject = await appDataStorageHelper.ReadFileAsync<MyLargeObject>(complexObjectKey);

var o = new MyLargeObject
var myComplexObject = new MyComplexObject()
{
...
};
localObjectStorageHelper.SaveFileAsync(keySimpleObject, o);
await appDataStorageHelper.SaveFileAsync(complexObjectKey, myComplexObject);

// Complex object
public class MyLargeObject
public class MyComplexObject
{
public string MyContent { get; set; }
public List<string> MyContents { get; set; }
public List<MyLargeObject> MyObjects { get; set; }
public List<MyComplexObject> MyObjects { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Microsoft.Toolkit.Helpers;
using Microsoft.Toolkit.Uwp.Helpers;
using Windows.UI.Xaml;

namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages
{
public sealed partial class ObjectStoragePage
{
private readonly IObjectStorageHelper localStorageHelper = new LocalObjectStorageHelper(new SystemSerializer());
private readonly ApplicationDataStorageHelper _settingsStorage = ApplicationDataStorageHelper.GetCurrent();

public ObjectStoragePage()
{
Expand All @@ -24,9 +25,9 @@ private void ReadButton_Click(object sender, RoutedEventArgs e)
}

// Read from local storage
if (localStorageHelper.KeyExists(KeyTextBox.Text))
if (_settingsStorage.KeyExists(KeyTextBox.Text))
{
ContentTextBox.Text = localStorageHelper.Read<string>(KeyTextBox.Text);
ContentTextBox.Text = _settingsStorage.Read<string>(KeyTextBox.Text);
}
}

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

// Save into local storage
localStorageHelper.Save(KeyTextBox.Text, ContentTextBox.Text);
_settingsStorage.Save(KeyTextBox.Text, ContentTextBox.Text);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Toolkit.Helpers;
using Windows.Storage;

namespace Microsoft.Toolkit.Uwp.Helpers
{
/// <summary>
/// An extension of ApplicationDataStorageHelper with additional features for interop with the LocalCacheFolder.
/// </summary>
public partial class ApplicationDataStorageHelper
{
/// <summary>
/// Gets the local cache folder.
/// </summary>
public StorageFolder CacheFolder => AppData.LocalCacheFolder;

/// <summary>
/// Retrieves an object from a file in the LocalCacheFolder.
/// </summary>
/// <typeparam name="T">Type of object retrieved.</typeparam>
/// <param name="filePath">Path to the file that contains the object.</param>
/// <param name="default">Default value of the object.</param>
/// <returns>Waiting task until completion with the object in the file.</returns>
public Task<T> ReadCacheFileAsync<T>(string filePath, T @default = default)
{
return ReadFileAsync<T>(CacheFolder, filePath, @default);
}

/// <summary>
/// Retrieves the listings for a folder and the item types in the LocalCacheFolder.
/// </summary>
/// <param name="folderPath">The path to the target folder.</param>
/// <returns>A list of file types and names in the target folder.</returns>
public Task<IEnumerable<(DirectoryItemType ItemType, string Name)>> ReadCacheFolderAsync(string folderPath)
{
return ReadFolderAsync(CacheFolder, folderPath);
}

/// <summary>
/// Saves an object inside a file in the LocalCacheFolder.
/// </summary>
/// <typeparam name="T">Type of object saved.</typeparam>
/// <param name="filePath">Path to the file that will contain the object.</param>
/// <param name="value">Object to save.</param>
/// <returns>Waiting task until completion.</returns>
public Task CreateCacheFileAsync<T>(string filePath, T value)
{
return SaveFileAsync<T>(CacheFolder, filePath, value);
}

/// <summary>
/// Ensure a folder exists at the folder path specified in the LocalCacheFolder.
/// </summary>
/// <param name="folderPath">The path and name of the target folder.</param>
/// <returns>Waiting task until completion.</returns>
public Task CreateCacheFolderAsync(string folderPath)
{
return CreateFolderAsync(CacheFolder, folderPath);
}

/// <summary>
/// Deletes a file or folder item in the LocalCacheFolder.
/// </summary>
/// <param name="itemPath">The path to the item for deletion.</param>
/// <returns>Waiting task until completion.</returns>
public Task DeleteCacheItemAsync(string itemPath)
{
return DeleteItemAsync(CacheFolder, itemPath);
}
}
}
Loading

0 comments on commit f7d00c7

Please sign in to comment.