microsoft / TemplateStudio

Template Studio accelerates the creation of new WinUI 3, WPF, and UWP apps using a wizard-based experience.
Other
2.65k stars 459 forks source link

Json Serialization doubled when using Setting Storage Template / FileService Bug? #4703

Open Oali3n opened 11 months ago

Oali3n commented 11 months ago

Describe the bug

When using the Setting Storage Template the Setting-Object is serialized twice. At LocalSettingsService.cs the method Json.StringifyAsync(value) is called which serializes the object and after that in the FileService-Method .Save the setting will be serialized again. I think the Json-serialization in FileService is wrong, because it makes the FileService useless for other text file IO cases (see line var fileContent = JsonConvert.SerializeObject(content, Formatting.Indented);).

Of course same with deserialization.

And maybe it would be better to use JsonConvert.SerializeObject(content, Formatting.Indented); instead of JsonConvert.SerializeObject(content).

In LocalSettingsService.cs:
public async Task SaveSettingAsync<T>(string key, T value)
    {
        if (RuntimeHelper.IsMSIX)
        {
            ApplicationData.Current.LocalSettings.Values[key] = await Json.StringifyAsync(value);
        }
        else
        {
            await InitializeAsync();

            _settings[key] = await Json.StringifyAsync(value);

            await Task.Run(() => _fileService.Save(_applicationDataFolder, _localsettingsFile, _settings));
        }
    }
In Json.cs in the Core Project:
public static class Json
{
    public static async Task<T> ToObjectAsync<T>(string value)
    {
        return await Task.Run<T>(() =>
        {
            return JsonConvert.DeserializeObject<T>(value);
        });
    }

    public static async Task<string> StringifyAsync(object value)
    {
        return await Task.Run<string>(() =>
        {
            return JsonConvert.SerializeObject(value);
        });
    }
}
In FileService.cs in the Core Project:
public void Save<T>(string folderPath, string fileName, T content)
    {
        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }

        var fileContent = JsonConvert.SerializeObject(content, Formatting.Indented);
        File.WriteAllText(Path.Combine(folderPath, fileName), fileContent, Encoding.UTF8);
    }

Greetings Martin

To Reproduce

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Additional context

No response

Applies to the following platforms:

About your setup