Aracılığıyla paylaş


Xamarin.Forms uygulama özellikleri sözlüğündeki verileri .NET MAUI tercihlerine geçirme

Xamarin.Forms, verileri depolamak için kullanılabilecek ve özelliği kullanılarak Application.Current.Properties erişilen bir Properties sözlüğe sahiptir. Bu sözlük bir string anahtarı kullanarak bir object değeri depolar. Sözlükteki değerler, uygulama duraklatıldığında veya kapatıldığında cihaza kaydedilir ve bir uygulama yeniden başlatıldığında veya arka planda döndürdüğünde yüklenir. Özellikler sözlüğü hakkında daha fazla bilgi için bkz . Özellikler sözlüğü.

Uygulama özellikleri sözlüğündeki verileri depolayan bir Xamarin.Forms uygulamasını .NET MAUI'ye geçirirken, bu verileri .NET MAUI tercihlerine geçirmeniz gerekir. Bu, bu makalede sunulan sınıfı ve yardımcı sınıfları ile LegacyApplication gerçekleştirilebilir. Bu sınıf, Android, iOS ve Windows'ta .NET MAUI uygulamanızın uygulamanızın önceki bir Xamarin.Forms sürümüyle oluşturulan uygulama özellikleri sözlüğündeki verileri okumasını sağlar. .NET MAUI tercihleri hakkında daha fazla bilgi için bkz . Tercihler.

Önemli

.NET MAUI'de uygulama özellikleri sözlüğüne erişecek API yoktur.

Eski uygulama özellikleri verilerine erişme

Aşağıdaki kod, Xamarin.Forms uygulamanız tarafından oluşturulan uygulama özellikleri verilerine erişim sağlayan sınıfını gösterir LegacyApplication :

Not

Bu kodu kullanmak için .NET MAUI uygulama projenizde adlı LegacyApplication bir sınıfa ekleyin.

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'de LegacyApplication sınıfı, uygulama özellikleri sözlük dosyasındaki PropertiesDeserializer verileri seri durumdan çıkarmak için sınıfını kullanır. Aşağıdaki kod sınıfını PropertiesDeserializer gösterir:

Not

Bu kodu kullanmak için.NET MAUI uygulama projenizin Platforms\Android klasöründe adlı PropertiesDeserializerbir sınıfa ekleyin.

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'ta LegacyApplication sınıfı, uygulama özellikleri sözlük dosyasındaki verileri seri durumdan çıkarmak için sınıfını kullanır PropertiesDeserializer . Aşağıdaki kod sınıfını PropertiesDeserializer gösterir:

Not

Bu kodu kullanmak için,.NET MAUI uygulama projenizin Platforms\iOS klasöründe adlı PropertiesDeserializerbir sınıfa ekleyin.

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'da sınıfı, LegacyApplication uygulama özellikleri sözlük dosyasındaki verileri seri durumdan çıkarmak için sınıfını kullanır PropertiesDeserializer . Aşağıdaki kod sınıfını PropertiesDeserializer gösterir:

Not

Bu kodu kullanmak için,.NET MAUI uygulama projenizin Platforms\Windows klasöründe adlı PropertiesDeserializerbir sınıfa ekleyin.

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);
        }
    }
}

Sınıfının bu Windows sürümü PropertiesDeserializer için uzantı yöntemi gerekir DontSync . Aşağıdaki kod bu uzantı yöntemini gösterir:

Not

Bu kodu kullanmak için,.NET MAUI uygulama projenizin Platforms\Windows klasöründe adlı Extensionsbir sınıfa ekleyin.

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);
    }
}

Eski uygulama özellik verilerini kullanma

LegacyApplication sınıfı, uygulamanızın önceki bir Xamarin.Forms sürümüyle oluşturulan Android, iOS ve Windows'da uygulama özellikleri sözlüğündeki verileri kullanmak için kullanılabilir:

#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

Bu örnekte, uygulama özellikleri sözlüğünden bir değeri okumak ve ardından değeri .NET MAUI tercihlerine yazmak için sınıfın kullanılması LegacyApplication gösterilmektedir.

Önemli

Beklenmeyen hataları önlemek için, anahtarın uygulama özellikleri sözlüğüne erişmeden önce her zaman mevcut olup olmadığını denetleyin.