Wednesday 12 July 2017

Roaming DataChanged

Should our data change while we are running two instances of our application we can use datachanged event of our applicationdata.current to update our application with the latest data.

using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System;
using System.Threading.Tasks;
using Windows.UI.Popups;
using Windows.UI.Core;

namespace pc.NavigateExample
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            InitializeComponent();

            Task.Run(async () =>
            {
                var roamingFolder = ApplicationData.Current.RoamingFolder;
                var storageFile = await roamingFolder.GetFileAsync("data1.txt");

                if (storageFile != null)
                    return storageFile;

                throw new ArgumentNullException();
            }).ContinueWith(async tr =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                {
                    if (tr.Status == TaskStatus.Faulted)
                       await new MessageDialog("No File detected").ShowAsync();
                    else
                        Input_TextBox.Text = await FileIO.ReadTextAsync(tr.Result);
                });
            });

            ApplicationData.Current.DataChanged += Current_DataChanged;
        }

        private async void Current_DataChanged(ApplicationData sender, object args)
        {
            var storageFile = await sender.RoamingFolder.GetFileAsync("data1.txt");
            Input_TextBox.Text = await FileIO.ReadTextAsync(storageFile);
        }

        async void Save_Button_Click(object sender, RoutedEventArgs e)
        {
            var parameter = Input_TextBox.Text;
            var roamingFolder = ApplicationData.Current.RoamingFolder;
            var storageFile = await roamingFolder.CreateFileAsync("data1.txt",
                                    CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteTextAsync(storageFile, parameter);
        }
    }
}

Now as mentioned before the whole app cannot exceed 100kb of roaming data, on top of that if the app is not used for ~30 days the roaming data is deleted. also remember that if your app exceeds the 100kb threshold there will be no exception, just your roaming data syncing will stop working.