Xamarin.Forms 앱 속성 사전에서 .NET MAUI 기본 설정으로 데이터 마이그레이션

Xamarin.Forms에는 Properties 데이터를 저장하는 데 사용할 수 있고 속성을 사용하여 액세스할 수 있는 사전이 Application.Current.Properties 있습니다. 이 사전은 string 키를 사용하고 object 값을 저장합니다. 사전의 값은 앱이 일시 중지 또는 종료될 때 디바이스에 저장되고, 앱을 다시 시작하거나 백그라운드에서 반환할 때 로드됩니다. 속성 사전에 대한 자세한 내용은 속성 사전을 참조 하세요.

앱 속성 사전의 데이터를 저장하는 Xamarin.Forms 앱을 .NET MAUI로 마이그레이션하는 경우 이 데이터를 .NET MAUI 기본 설정으로 마이그레이션해야 합니다. 이 작업은 이 문서에서 제공하는 클래스 및 도우미 클래스를 사용하여 수행할 LegacyApplication 수 있습니다. 이 클래스를 사용하면 Android, iOS 및 Windows의 .NET MAUI 앱이 이전 Xamarin.Forms 버전의 앱으로 만든 앱 속성 사전에서 데이터를 읽을 수 있습니다. .NET MAUI 기본 설정에 대한 자세한 내용은 기본 설정을 참조 하세요.

Important

.NET MAUI에서 앱 속성 사전에 액세스할 수 있는 API가 없습니다.

레거시 앱 속성 데이터에 액세스

다음 코드는 Xamarin.Forms 앱에서 만든 앱 속성 데이터에 대한 액세스를 제공하는 클래스를 보여 LegacyApplication 줍니다.

참고 항목

이 코드를 사용하려면 .NET MAUI 앱 프로젝트에서 명명된 LegacyApplication 클래스에 추가합니다.

namespace MigrationHelpers;

public class LegacyApplication
{
    readonly PropertiesDeserializer deserializer;
    Task<IDictionary<string, object>>? propertiesTask;

    static LegacyApplication? current;
    public static LegacyApplication? Current
    {
        get
        {
            current ??= (LegacyApplication)Activator.CreateInstance(typeof(LegacyApplication));
            return current;
        }
    }

    public LegacyApplication()
    {
        deserializer = new PropertiesDeserializer();
    }

    public IDictionary<string, object> Properties
    {
        get
        {
            propertiesTask ??= GetPropertiesAsync();
            return propertiesTask.Result;
        }
    }

    async Task<IDictionary<string, object>> GetPropertiesAsync()
    {
        IDictionary<string, object> properties = await deserializer.DeserializePropertiesAsync().ConfigureAwait(false);
        properties ??= new Dictionary<string, object>(4);
        return properties;
    }
}

Android

Android에서 클래스는 LegacyApplication 클래스를 PropertiesDeserializer 사용하여 앱 속성 사전 파일의 데이터를 역직렬화합니다. 다음 코드에서는 PropertiesDeserializer 클래스를 보여 줍니다.

참고 항목

이 코드를 사용하려면 .NET MAUI 앱 프로젝트의 Platforms\Android 폴더에 있는 PropertiesDeserializer 클래스에 추가합니다.

using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using System.Xml;

namespace MigrationHelpers;

public class PropertiesDeserializer
{
    const string PropertyStoreFile = "PropertyStore.forms";

    public Task<IDictionary<string, object>> DeserializePropertiesAsync()
    {
        // Deserialize property dictionary to local storage
        return Task.Run(() =>
        {
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists(PropertyStoreFile))
                    return null;

                using (IsolatedStorageFileStream stream = store.OpenFile(PropertyStoreFile, FileMode.Open, FileAccess.Read))
                using (XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max))
                {
                    if (stream.Length == 0)
                        return null;

                    try
                    {
                        var dcs = new DataContractSerializer(typeof(Dictionary<string, object>));
                        return (IDictionary<string, object>)dcs.ReadObject(reader);
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("Could not deserialize properties: " + e.Message);
                        Console.WriteLine($"PropertyStore Exception while reading Application properties: {e}");
                    }
                }
            }
            return null;
        });
    }
}

iOS

iOS에서 클래스는 LegacyApplication 클래스를 PropertiesDeserializer 사용하여 앱 속성 사전 파일의 데이터를 역직렬화합니다. 다음 코드에서는 PropertiesDeserializer 클래스를 보여 줍니다.

참고 항목

이 코드를 사용하려면 .NET MAUI 앱 프로젝트의 Platforms\iOS 폴더에 명명된 PropertiesDeserializer 클래스에 추가합니다.

using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using System.Xml;

namespace MigrationHelpers;

public class PropertiesDeserializer
{
    const string PropertyStoreFile = "PropertyStore.forms";

    public Task<IDictionary<string, object>> DeserializePropertiesAsync()
    {
        // Deserialize property dictionary to local storage
        return Task.Run(() =>
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            using (var stream = store.OpenFile(PropertyStoreFile, System.IO.FileMode.OpenOrCreate))
            using (var reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max))
            {
                if (stream.Length == 0)
                    return null;

                try
                {
                    var dcs = new DataContractSerializer(typeof(Dictionary<string, object>));
                    return (IDictionary<string, object>)dcs.ReadObject(reader);
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Could not deserialize properties: " + e.Message);
                    Console.WriteLine($"PropertyStore Exception while reading Application properties: {e}");
                }
            }
            return null;
        });
    }
}

Windows

Windows에서 클래스는 LegacyApplication 클래스를 PropertiesDeserializer 사용하여 앱 속성 사전 파일의 데이터를 역직렬화합니다. 다음 코드에서는 PropertiesDeserializer 클래스를 보여 줍니다.

참고 항목

이 코드를 사용하려면 .NET MAUI 앱 프로젝트의 Platforms\Windows 폴더에 있는 PropertiesDeserializer 클래스에 추가합니다.

using System.Diagnostics;
using System.Runtime.Serialization;
using Windows.Storage;

namespace MigrationHelpers;

public class PropertiesDeserializer
{
    const string PropertyStoreFile = "PropertyStore.forms";

    public async Task<IDictionary<string, object>> DeserializePropertiesAsync()
    {
        try
        {
            StorageFile file = await ApplicationData.Current.RoamingFolder.GetFileAsync(PropertyStoreFile).DontSync();
            using (Stream stream = (await file.OpenReadAsync().DontSync()).AsStreamForRead())
            {
                if (stream.Length == 0)
                    return new Dictionary<string, object>(4);

                try
                {
                    var serializer = new DataContractSerializer(typeof(IDictionary<string, object>));
                    return (IDictionary<string, object>)serializer.ReadObject(stream);
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Could not deserialize properties: " + e.Message);
                    Console.WriteLine($"PropertyStore Exception while reading Application properties: {e}");
                }
                return null;
            }
        }
        catch (FileNotFoundException)
        {
            return new Dictionary<string, object>(4);
        }
    }
}

이 Windows 버전의 클래스에는 PropertiesDeserializer 확장 메서드가 DontSync 필요합니다. 다음 코드는 이 확장 메서드를 보여줍니다.

참고 항목

이 코드를 사용하려면 .NET MAUI 앱 프로젝트의 Platforms\Windows 폴더에 있는 Extensions 클래스에 추가합니다.

using System.Runtime.CompilerServices;
using Windows.Foundation;

namespace MigrationHelpers;

internal static class Extensions
{
    public static ConfiguredTaskAwaitable<T> DontSync<T>(this IAsyncOperation<T> self)
    {
        return self.AsTask().ConfigureAwait(false);
    }
}

레거시 앱 속성 데이터 사용

이 클래스는 LegacyApplication 앱의 이전 Xamarin.Forms 버전으로 만든 앱 속성 사전, Android, iOS 및 Windows의 데이터를 사용하는 데 사용할 수 있습니다.

#if ANDROID || IOS || WINDOWS
using MigrationHelpers;
...

int id;
if (LegacyApplication.Current.Properties.ContainsKey("id"))
{
    id = (int)LegacyApplication.Current.Properties["id"];
    Preferences.Set("id", id);
}
#endif

이 예제에서는 클래스를 LegacyApplication 사용하여 앱 속성 사전에서 값을 읽은 다음.NET MAUI 기본 설정에 값을 쓰는 방법을 보여 줍니다.

Important

예기치 않은 오류를 방지하기 위해 액세스하기 전에 항상 앱 속성 사전에 키가 있는지 검사.