// Handle background task completion event.
        private async void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
        {
            // Update the UI with the complrtion status reported by the background task.
            // Dispatch an anonymous task to the UI thread to do the update.
            await sampleDispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                            () =>
            {
                try
                {
                    if ((sender != null) && (e != null))
                    {
                        // this method throws if the event is reporting an error
                        e.CheckResult();

                        // Update the UI with the background task's completion status.
                        // The task stores status in the application data settings indexed by the task ID.
                        var key      = sender.TaskId.ToString();
                        var settings = ApplicationData.Current.LocalSettings;
                        BackgroundTaskStatus.Text = settings.Values[key].ToString();
                    }
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                }
            });
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Background task completion handler. When authenticating through the foreground app, this triggers the authentication flow if the app is currently running.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public async void OnBackgroundTaskCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
        {
            // Update the UI with progress reported by the background task.
            await coreDispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                          new DispatchedHandler(() =>
            {
                try
                {
                    if ((sender != null) && (e != null))
                    {
                        // If the background task threw an exception, display the exception in the error text box.
                        e.CheckResult();

                        // Update the UI with the completion status of the background task
                        // The Run method of the background task sets this status.
                        if (sender.Name == BackgroundTaskName)
                        {
                            rootPage.NotifyUser("Background task completed", NotifyType.StatusMessage);

                            // Signal callback for foreground authentication
                            if (!ConfigStore.AuthenticateThroughBackgroundTask && ForegroundAuthenticationCallback != null)
                            {
                                ForegroundAuthenticationCallback(this, null);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                }
            }));
        }
        /// <summary>
        /// This is the callback when background event has been handled
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
        {
            if (sender != null)
            {
                // Update the UI with progress reported by the background task
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    try
                    {
                        // If the background task threw an exception, display the exception in
                        // the error text box.
                        e.CheckResult();

                        // Update the UI with the completion status of the background task
                        // The Run method of the background task sets the LocalSettings.
                        var settings = ApplicationData.Current.LocalSettings;

                        // get status
                        if (settings.Values.ContainsKey("Status"))
                        {
                            rootPage.NotifyUser(settings.Values["Status"].ToString(), NotifyType.StatusMessage);
                        }

                        FillEventListBoxWithExistingEvents();
                    }
                    catch (Exception ex)
                    {
                        // The background task had an error
                        rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                    }
                });
            }
        }
Ejemplo n.º 4
0
        //处理通知
        private async void Task_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            if (sender != null)
            {
                // Update the UI with progress reported by the background task.
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    try
                    {
                        // If the background task threw an exception, display the exception in
                        // the error text box.
                        args.CheckResult();

                        // Update the UI with the completion status of the background task.
                        // The Run method of the background task sets the LocalSettings.
                        // var settings = ApplicationData.Current.LocalSettings;

                        // Get the status.

                        // Do your app work here.

                        showMessage("围栏过期");
                    }
                    catch (Exception ex)
                    {
                        // The background task had an error.
                        //  rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                        Debug.Write(ex.Message);
                    }
                });
            }
        }
Ejemplo n.º 5
0
        private void WeatherUpdateTaskOnCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            try
            {
                args.CheckResult();

                WeatherCondition condition;
                Enum.TryParse(GetSetting("weather.condition"), out condition);

                double celsius;
                double.TryParse(GetSetting("weather.celsius"), out celsius);

                double fahrenheit;
                double.TryParse(GetSetting("weather.fahrenheit"), out fahrenheit);

                CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    Weather = new WeatherForecast()
                    {
                        Condition             = condition,
                        TemperatureCelsius    = celsius,
                        TemperatureFahrenheit = fahrenheit
                    };
                });
            }
            catch (Exception exc)
            {
                new MessageDialog(exc.Message).ShowAsync();
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Event handle to be raised when the background task is completed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
        {
            if (sender != null)
            {
                // Update the UI with progress reported by the background task
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    try
                    {
                        // If the background task threw an exception, display the exception in
                        // the error text box.
                        e.CheckResult();

                        // Update the UI with the completion status of the background task
                        // The Run method of the background task sets this status.
                        var settings = ApplicationData.Current.LocalSettings;
                        if (settings.Values["Status"] != null)
                        {
                            _rootPage.NotifyUser(settings.Values["Status"].ToString(), NotifyType.StatusMessage);
                        }

                        // Extract and display location data set by the background task if not null
                        ScenarioOutput_Latitude.Text  = (settings.Values["Latitude"] == null) ? "No data" : settings.Values["Latitude"].ToString();
                        ScenarioOutput_Longitude.Text = (settings.Values["Longitude"] == null) ? "No data" : settings.Values["Longitude"].ToString();
                        ScenarioOutput_Accuracy.Text  = (settings.Values["Accuracy"] == null) ? "No data" : settings.Values["Accuracy"].ToString();
                    }
                    catch (Exception ex)
                    {
                        // The background task had an error
                        _rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                    }
                });
            }
        }
Ejemplo n.º 7
0
        private async void OnBackgroundTaskCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                try
                {
                    args.CheckResult();
                    if (ApplicationData.Current.LocalSettings.Values.ContainsKey("TaskCancelationReason"))
                    {
                        string cancelationReason = (string)ApplicationData.Current.LocalSettings.Values["TaskCancelationReason"];
                        Error = cancelationReason;
                    }
                }
                catch (Exception ex)
                {
                    Error = "Exception" + ex.Message;
                }

#warning unregisters the background task

                if (null != saferAccelerometerRegistrationManual)
                {
                    saferAccelerometerRegistrationManual.Unregister(false);
                    saferAccelerometerRegistrationManual = null;
                }
            });
        }
Ejemplo n.º 8
0
        private async void GeofenceTask_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            if (sender != null)
            {
                // Update the UI with progress reported by the background task
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    try
                    {
                        // If the background task threw an exception, display the exception
                        args.CheckResult();

                        var settings = ApplicationData.Current.LocalSettings;

                        // get status
                        if (settings.Values.ContainsKey("Status"))
                        {
                            Status.Text = settings.Values["Status"].ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        ShowMessage(ex.Message);
                    }
                });
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Event handler called when the background task is completed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
        {
            // Update the UI with progress reported by the background task
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                try
                {
                    // Rethrow any exception that occurred in the background task.
                    e.CheckResult();

                    // Update the UI with the completion status of the background task
                    // The Run method of the background task sets this status.
                    MainPage.ReportSavedStatus();

                    // Extract and display location data set by the background task if not null
                    ScenarioOutput_Latitude.Text  = MainPage.LookupSavedString("Latitude", "No data");
                    ScenarioOutput_Longitude.Text = MainPage.LookupSavedString("Longitude", "No data");
                    ScenarioOutput_Accuracy.Text  = MainPage.LookupSavedString("Accuracy", "No data");
                }
                catch (Exception ex)
                {
                    // The background task had an error
                    _rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                }
            });
        }
        /// <summary>
        /// This is the background task completion handler.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnBackgroundTaskCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
        {
            // Dispatch to the UI thread to display the output.
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                // An exception may be thrown if an error occurs in the background task.
                try
                {
                    e.CheckResult();
                    if (ApplicationData.Current.LocalSettings.Values.ContainsKey("TaskCancelationReason"))
                    {
                        string cancelationReason = (string)ApplicationData.Current.LocalSettings.Values["TaskCancelationReason"];
                        rootPage.NotifyUser("Background task was stopped, reason: " + cancelationReason, NotifyType.StatusMessage);
                    }
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser("Exception in background task: " + ex.Message, NotifyType.ErrorMessage);
                }

                _refreshTimer.Stop();
            });

            // Unregister the background task and let the remaining task finish until completion.
            if (null != _deviceUseBackgroundTaskRegistration)
            {
                _deviceUseBackgroundTaskRegistration.Unregister(false);
                _deviceUseBackgroundTaskRegistration = null;
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// This is the callback when background event has been handled
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
        {
            if (sender != null)
            {
                try
                {
                    // If the background task threw an exception, display the exception in
                    // the error text box.
                    e.CheckResult();

                    // Update the UI with the completion status of the background task
                    // The Run method of the background task sets the LocalSettings.
                    var settings = ApplicationData.Current.LocalSettings;

                    // get status
                    if (settings.Values.ContainsKey("Status"))
                    {
                        //_rootPage.NotifyUser(settings.Values["Status"].ToString(), NotifyType.StatusMessage);
                    }

                    //FillEventListBoxWithExistingEvents();
                }
                catch { }
            }
        }
        /// <summary>
        /// This is the callback when background event has been handled
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
        {
            try
            {
                // Update the UI with progress reported by the background task
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    try
                    {
                        // If the background task threw an exception, display the exception in
                        // the status text box.
                        e.CheckResult();
                    }
                    catch (Exception ex)
                    {
                        // The background task had an error
                        ShowStatus(ex.ToString());
                    }
                });

                await RestoreStateAsync();
                await AttemptDeferredCheckinsAsync();
                await LogBackgroundEventsAsync();
            }
            catch (Exception exception)
            {
                Logger.Trace(TraceLevel.Error, "Background Task: OnCompleted exception " + Logger.FormatException(exception));
            }
        }
        /// <summary>
        /// Called when background task defferal is completed.  This can happen for a number of reasons (both expected and unexpected).
        /// IF this is expected, we'll notify the user.  If it's not, we'll show that this is an error.  Finally, clean up the connection by calling Disconnect().
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void OnCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            var settings = ApplicationData.Current.LocalSettings;

            if (settings.Values.ContainsKey("TaskCancelationReason"))
            {
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    rootPage.NotifyUser("Task cancelled unexpectedly - reason: " + settings.Values["TaskCancelationReason"].ToString(), NotifyType.ErrorMessage);
                });
            }
            else
            {
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    rootPage.NotifyUser("Background task completed", NotifyType.StatusMessage);
                });
            }
            try
            {
                args.CheckResult();
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
            }
            Disconnect();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// background task completion handler
        ///
        /// </summary>
        private async void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
        {
            // Update the UI with the completion status reported by the background task.
            // Dispatch an anonymous task to the UI thread to do the update.
            await sampleDispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                            () =>
            {
                try
                {
                    e.CheckResult();

                    // get the completion status
                    var key      = sender.TaskId.ToString() + "_type";
                    var settings = ApplicationData.Current.LocalSettings;
                    var status   = settings.Values[key].ToString();
                    if ((status == NetworkOperatorEventMessageType.TetheringOperationalStateChanged.ToString()) ||
                        (status == NetworkOperatorEventMessageType.TetheringNumberOfClientsChanged.ToString()))
                    {
                        UpdateUIWithTetheringState();
                    }
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser("Unexpected exception occured: " + ex.ToString(), NotifyType.ErrorMessage);
                }
            });
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Reopen the device after the background task is done syncing. Notify the UI of how many bytes we wrote to the device.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void OnSyncWithDeviceCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            isSyncing = false;

            // Exception may be thrown if an error occurs during running the background task
            args.CheckResult();

            await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                               new DispatchedHandler(async() =>
            {
                // Reopen the device once the background task is completed
                // Don't attempt to reconnect if the device failed to connect
                var isDeviceSuccessfullyConnected = await EventHandlerForDevice.Current.OpenDeviceAsync(syncDeviceInformation, syncDeviceSelector);

                if (!isDeviceSuccessfullyConnected)
                {
                    EventHandlerForDevice.Current.IsEnabledAutoReconnect = false;
                }

                syncDeviceInformation = null;
                syncDeviceSelector = null;

                // Since we are navigating away, don't touch the UI; we don't care what the output/result of the background task is
                if (!navigatedAway)
                {
                    var taskCompleteStatus = (String)ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.SyncBackgroundTaskStatus];

                    if (taskCompleteStatus == SyncBackgroundTaskInformation.TaskCompleted)
                    {
                        UInt32 totalBytesWritten = (UInt32)ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.SyncBackgroundTaskResult];

                        // Set the progress bar to be completely filled in case the progress was not updated (this can happen if the app is suspended)
                        SyncProgressBar.Value = 100;

                        rootPage.NotifyUser("Sync: Wrote " + totalBytesWritten.ToString() + " bytes to the device", NotifyType.StatusMessage);
                    }
                    else if (taskCompleteStatus == SyncBackgroundTaskInformation.TaskCanceled)
                    {
                        // Reset the progress bar in case the progress was not updated (this can happen if the app is suspended)
                        SyncProgressBar.Value = 0;

                        rootPage.NotifyUser("Syncing was canceled", NotifyType.StatusMessage);
                    }

                    UpdateButtonStates();
                }

                // Remove all local setting values
                ApplicationData.Current.LocalSettings.Values.Clear();
            }));

            // Unregister the background task and let the remaining task finish until completion
            if (backgroundSyncTaskRegistration != null)
            {
                backgroundSyncTaskRegistration.Unregister(false);
            }
        }
Ejemplo n.º 16
0
 private void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
 {
     try
     {
         e.CheckResult();
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.Message);
     }
 }
Ejemplo n.º 17
0
        /// <summary>
        /// This is the event handler for background task completion.
        /// </summary>
        /// <param name="task">The task that is reporting completion.</param>
        /// <param name="args">The completion report arguments.</param>
        private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
        {
            string status = "Completed";

            try
            {
                args.CheckResult();
            }
            catch (Exception e)
            {
                status = e.Message;
            }
            UpdateUIAsync(status);
        }
Ejemplo n.º 18
0
        private void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
        {
            if (sender != null)
            {
                // If the background task threw an exception, display the exception in
                // the error text box.
                e.CheckResult();

                LocationChanged();

                // if( settings.Values[ "Longitude" ] != null )
                // if( settings.Values[ "Accuracy" ] != null )
            }
        }
Ejemplo n.º 19
0
        private void RegisteredOnCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            var messageDict = new Dictionary <string, string>();

            try
            {
                args.CheckResult();
                messageDict.Add("Successful", "true");
            } catch (Exception ex)
            {
                messageDict.Add("Successful", "false");
                messageDict.Add("Exception", ex.ToString());
            }
            Analytics.TrackEvent("Sync Backup Task finished", messageDict);
        }
        public void OnTaskCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            Debug.WriteLine("BackgroundAudioRun.TaskOnCompleted() " + _id);

            try
            {
                args.CheckResult();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("BackgroundAudioRun.TaskOnCompleted() " + _id + " failed: " + ex.Message);
            }

            _completionSource.TrySetResult(null);
        }
Ejemplo n.º 21
0
        private void OnBackgroundTaskCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            args.CheckResult();      // TODO: What kind of errors does this report?
            Debug.WriteLine(sender); // BackgroundTaskRegistration
            string instanceIdString = args.InstanceId.ToString();

            if (!ApplicationData.Current.LocalSettings.Values.ContainsKey(instanceIdString))
            {
                // This task didn't schedule a download.
                return;
            }

            Guid transferGuid = (Guid)ApplicationData.Current.LocalSettings.Values[instanceIdString];

            Debug.WriteLine("Background task completed! Last download was {0}", transferGuid);
        }
Ejemplo n.º 22
0
        private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
        {
            // 后台任务已经执行完成
            _taskProgress = "完成";

            // 如果此次后台任务的执行出现了错误,则调用 CheckResult() 后会抛出异常
            try
            {
                args.CheckResult();
            }
            catch (Exception ex)
            {
                _taskProgress = ex.ToString();
            }

            UpdateUI();
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Optional: Callback for geofence background task completion.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void OnGeofenceBackgroundTaskCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
 {
     Debug.WriteLine("Background task completed.");
     if (sender != null)
     {
         // Update the UI with progress reported by the background task
         try
         {
             e.CheckResult();
         }
         catch (Exception ex)
         {
             // The background task had an error
             Debug.WriteLine(ex.ToString());
         }
     }
 }
Ejemplo n.º 24
0
 private async void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
 {
     if (sender != null)
     {
         // Update the UI with progress reported by the background task
         await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
         {
             try
             {
                 // If the background task threw an exception, display the exception in
                 // the error text box.
                 e.CheckResult();
             }
             catch (Exception ex)
             {
             }
         });
     }
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Reopen the device after the background task is done syncing. Notify the UI of how many bytes we wrote to the device.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void OnSyncWithDeviceCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            // Exception may be thrown if an error occurs during running the background task
            args.CheckResult();

            await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                               new DispatchedHandler(async() =>
            {
                // Reopen the device once the background task is completed
                await EventHandlerForDevice.Current.OpenDeviceAsync(syncDeviceInformation, syncDeviceSelector);

                syncDeviceInformation = null;
                syncDeviceSelector = null;

                var taskCompleteStatus = (String)ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.SyncBackgroundTaskStatus];

                if (taskCompleteStatus == SyncBackgroundTaskInformation.TaskCompleted)
                {
                    UInt32 totalBytesWritten = (UInt32)ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.SyncBackgroundTaskResult];

                    rootPage.NotifyUser("Sync: Wrote " + totalBytesWritten.ToString() + " bytes to the device", NotifyType.StatusMessage);
                }
                else if (taskCompleteStatus == SyncBackgroundTaskInformation.TaskCanceled)
                {
                    rootPage.NotifyUser("Syncing was canceled", NotifyType.StatusMessage);
                }

                // Remove all local setting values
                ApplicationData.Current.LocalSettings.Values.Clear();

                isSyncing = false;

                UpdateButtonStates();
            }));

            // Unregister the background task and let the remaining task finish until completion
            if (backgroundSyncTaskRegistration != null)
            {
                backgroundSyncTaskRegistration.Unregister(false);
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// This is the callback when background event has been handled
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
        {
            // Update the UI with progress reported by the background task
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                try
                {
                    // If the background task threw an exception, display the exception in
                    // the error text box.
                    e.CheckResult();

                    // Update the UI with the completion status of the background task
                    FillEventListBoxWithExistingEvents();
                }
                catch (Exception ex)
                {
                    // The background task had an error
                    _rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                }
            });
        }
        /// <summary>
        /// This is the callback when background event has been handled
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
        {
            // Update the UI with progress reported by the background task
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                try
                {
                    // Rethrow any exception that occurred in the background task.
                    e.CheckResult();

                    // Update the UI with the completion status of the background task
                    MainPage.ReportSavedStatus();
                    FillEventListBoxWithExistingEvents();
                }
                catch (Exception ex)
                {
                    // The background task had an error
                    _rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                }
            });
        }
        /// <summary>
        /// Task registration complete handler.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void OnTaskRegistrationCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            bool unregister = false;

            // check for exceptions in registration
            try
            {
                args.CheckResult();
            }
            catch (Exception e)
            {
                // note: this code-path never actually got hit in testing.
                Utilities.OnException(e);
                unregister = true;
            }

            if (unregister)
            {
                await TaskUnregisterForToastAsync();
            }
        }
        /// <summary>
        /// Background task completion handler. When authenticating through the foreground app, this triggers the authentication flow if the app is currently running.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnBackgroundTaskCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
        {
            if (sender.Name == BackgroundTaskName)
            {
                Exception exception = null;
                try
                {
                    // If the background task threw an exception, re-raise it here so we can pass it to the event handler.
                    e.CheckResult();
                }
                catch (Exception ex)
                {
                    exception = ex;
                }

                if (!ConfigStore.AuthenticateThroughBackgroundTask)
                {
                    BackgroundAuthenticationCompleted?.Invoke(this, new BackgroundAuthenticationCompletedEventArgs(null));
                }
            }
        }
        /// <summary>
        /// Print the version number
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void OnFirmwareUpdateCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            // Exception may be thrown if an error occurs during running the background task
            args.CheckResult();

            await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                               new DispatchedHandler(() =>
            {
                var taskCompleteStatus = (String)ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.FirmwareUpdateBackgroundTask.TaskStatus];

                if (taskCompleteStatus == FirmwareUpdateTaskInformation.TaskCompleted)
                {
                    // Display firmware version after the firmware update
                    var newFirmwareVersion = (UInt32)ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.FirmwareUpdateBackgroundTask.NewFirmwareVersion];

                    var newFirmwareVersionHex = "0x" + newFirmwareVersion.ToString("X4", NumberFormatInfo.InvariantInfo);

                    UpdateNewFirmwareVersionInUI(newFirmwareVersionHex);

                    rootPage.NotifyUser("Firmware update completed", NotifyType.StatusMessage);
                }
                else if (taskCompleteStatus == FirmwareUpdateTaskInformation.TaskCanceled)
                {
                    rootPage.NotifyUser("Firmware update was canceled", NotifyType.StatusMessage);
                }

                // Remove all local setting values
                ApplicationData.Current.LocalSettings.Values.Clear();

                isUpdatingFirmware = false;

                UpdateButtonStates();
            }));

            if (firmwareUpdateBackgroundTaskRegistration != null)
            {
                // Unregister the background task and let the remaining task finish until completion
                firmwareUpdateBackgroundTaskRegistration.Unregister(false);
            }
        }