Files
Wino-Mail/Wino.Core.UWP/Services/ConfigurationService.cs

52 lines
1.7 KiB
C#
Raw Normal View History

2024-04-18 01:44:37 +02:00
using System;
using System.ComponentModel;
using System.Globalization;
2024-04-18 01:44:37 +02:00
using Windows.Foundation.Collections;
using Windows.Storage;
using Wino.Core.Domain.Interfaces;
2025-02-16 11:54:23 +01:00
namespace Wino.Core.UWP.Services;
public class ConfigurationService : IConfigurationService
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
public T Get<T>(string key, T defaultValue = default)
=> GetInternal(key, ApplicationData.Current.LocalSettings.Values, defaultValue);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
public T GetRoaming<T>(string key, T defaultValue = default)
=> GetInternal(key, ApplicationData.Current.RoamingSettings.Values, defaultValue);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
public void Set(string key, object value)
=> SetInternal(key, value, ApplicationData.Current.LocalSettings.Values);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
public void SetRoaming(string key, object value)
=> SetInternal(key, value, ApplicationData.Current.RoamingSettings.Values);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
private static T GetInternal<T>(string key, IPropertySet collection, T defaultValue = default)
{
if (collection.TryGetValue(key, out object value))
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
var stringValue = value?.ToString();
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
if (typeof(T).IsEnum)
return (T)Enum.Parse(typeof(T), stringValue);
2025-02-16 11:54:23 +01:00
if ((typeof(T) == typeof(Guid?) || typeof(T) == typeof(Guid)) && Guid.TryParse(stringValue, out Guid guidResult))
{
return (T)(object)guidResult;
}
2025-02-16 11:54:23 +01:00
if (typeof(T) == typeof(TimeSpan))
{
return (T)(object)TimeSpan.Parse(stringValue);
2024-04-18 01:44:37 +02:00
}
2025-02-16 11:54:23 +01:00
return (T)Convert.ChangeType(stringValue, typeof(T));
2024-04-18 01:44:37 +02:00
}
2025-02-16 11:54:23 +01:00
return defaultValue;
2024-04-18 01:44:37 +02:00
}
2025-02-16 11:54:23 +01:00
private static void SetInternal(string key, object value, IPropertySet collection)
=> collection[key] = value?.ToString();
2024-04-18 01:44:37 +02:00
}