public async void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                this.deferral = taskInstance.GetDeferral();

                this.SafeRun(taskInstance);
            }
            catch (Exception ex)
            {
                ReportStatus(BackgroundExecutionStatus.CompletedRootException);
                this.deferral.Complete();

                DeviceFamily deviceFamily = DeviceFamily.Unkown;
                if (AnalyticsInfo.VersionInfo.DeviceFamily.Equals("Windows.Desktop", StringComparison.OrdinalIgnoreCase))
                {
                    deviceFamily = DeviceFamily.WindowsDesktop;
                }
                else if (AnalyticsInfo.VersionInfo.DeviceFamily.Equals("Windows.Mobile", StringComparison.OrdinalIgnoreCase))
                {
                    deviceFamily = DeviceFamily.WindowsMobile;
                }

                var trackingManager = new TrackingManager(false, deviceFamily);
                trackingManager.Exception(ex, "Exception Background task helper root");
            }
        }
Exemple #2
0
        private async Task BootstrapFrame(LaunchActivatedEventArgs launchActivatedEventArgs, IActivatedEventArgs activatedEventArgs, string addTaskTitle = null)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                try
                {
                    ApplicationView appView = ApplicationView.GetForCurrentView();
                    this.mainview = appView;
                    SetupTitleBar(appView);
                    SetupStatusBar(appColor);

                    appView.SetPreferredMinSize(new Size(Constants.AppMinWidth, Constants.AppMinHeight));

                    this.bootstraper = new Bootstraper(ApplicationVersion.GetAppVersion());

                    InitializeViewLocator();

                    await this.bootstraper.ConfigureAsync(rootFrame);

                    this.navigationService = Ioc.Resolve <INavigationService>();
                    this.platformService   = Ioc.Resolve <IPlatformService>();

                    this.suspensionManager = new SuspensionManager(Ioc.Resolve <IPersistenceLayer>(), Ioc.Resolve <ISynchronizationManager>(), Ioc.Resolve <ITileManager>());

                    rootFrame.Navigated        += this.OnNavigated;
                    rootFrame.NavigationFailed += this.OnNavigationFailed;

                    // Place the frame in the current Window
                    Window.Current.Content = rootFrame;

                    if (rootFrame.Content == null)
                    {
                        Type   startupPage         = typeof(MainPage);
                        object navigationParameter = launchActivatedEventArgs?.Arguments;

                        var startupManager = Ioc.Resolve <IStartupManager>();
                        if (startupManager.IsFirstLaunch)
                        {
                            startupPage = typeof(WelcomePage);
                        }
                        else if (!String.IsNullOrWhiteSpace(addTaskTitle))
                        {
                            startupPage         = typeof(WelcomePage);
                            navigationParameter = new TaskCreationParameters {
                                Title = addTaskTitle
                            };
                        }

                        SystemNavigationManager.GetForCurrentView().BackRequested += this.OnBackRequested;
                        SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = rootFrame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
                        Window.Current.VisibilityChanged += this.OnVisibilityChanged;

                        // When the navigation stack isn't restored navigate to the first page,
                        // configuring the new page by passing required information as a navigation parameter
                        rootFrame.Navigate(startupPage, navigationParameter);
                    }

                    if (launchActivatedEventArgs != null)
                    {
                        LauncherHelper.TryHandleArgs(launchActivatedEventArgs.Arguments);
                    }
                    else if (activatedEventArgs != null)
                    {
                        LauncherHelper.TryHandleArgs(activatedEventArgs);
                    }

                    // Ensure the current window is active
                    Window.Current.Activate();
                }
                catch (Exception ex)
                {
                    var messageBoxService = new MessageBoxService(new NavigationService(rootFrame));
                    await messageBoxService.ShowAsync("Error", "2Day was unable to start please send a screenshot of this page to the development team. Details: " + ex);

                    DeviceFamily deviceFamily = DeviceFamily.Unkown;
                    if (this.platformService != null)
                    {
                        deviceFamily = this.platformService.DeviceFamily;
                    }

                    var trackingManager = new TrackingManager(true, deviceFamily);
                    trackingManager.Exception(ex, "Bootstrap", true);
                }
            }
            else
            {
                if (launchActivatedEventArgs != null)
                {
                    LauncherHelper.TryHandleArgs(launchActivatedEventArgs.Arguments);
                }
                else if (activatedEventArgs != null)
                {
                    LauncherHelper.TryHandleArgs(activatedEventArgs);
                }
            }
        }
        public async void SafeRun(IBackgroundTaskInstance taskInstance)
        {
            bool hadException = false;

            // Register to receive an event if Cortana dismisses the background task. This will
            // occur if the task takes too long to respond, or if Cortana's UI is dismissed.
            // Any pending operations should be cancelled or waited on to clean up where possible.
            taskInstance.Canceled += this.OnTaskCanceled;

            WinSettings.Instance.SetValue(CoreSettings.BackgroundLastStartExecution, DateTime.Now);
            ReportStatus(BackgroundExecutionStatus.Started);

            LogService.Initialize(new WinLogHandler());
            LogService.Level = WinSettings.Instance.GetValue <LogLevel>(CoreSettings.LogLevel);

            ResourcesLocator.Initialize("ms-appx://", UriKind.Absolute);

            var mutex = new Mutex(false, Constants.SyncPrimitiveAppRunningForeground);

            if (!mutex.WaitOne(1))
            {
                LogService.Log("Agent", "Skipping background agent because app is foreground");
                await LogService.SaveAsync();

                this.deferral.Complete();

                ReportStatus(BackgroundExecutionStatus.Skipped);

                return;
            }

            ITrackingManager trackingManager = null;

            try
            {
                this.persistenceLayer = new WinPersistenceLayer(automaticSave: false);

                var deviceFamily = DeviceFamily.Unkown;

                if (AnalyticsInfo.VersionInfo.DeviceFamily.Equals("Windows.Desktop", StringComparison.OrdinalIgnoreCase))
                {
                    deviceFamily = DeviceFamily.WindowsDesktop;
                }
                else if (AnalyticsInfo.VersionInfo.DeviceFamily.Equals("Windows.Mobile", StringComparison.OrdinalIgnoreCase))
                {
                    deviceFamily = DeviceFamily.WindowsMobile;
                }

                trackingManager = new TrackingManager(false, deviceFamily);

                var workbook = this.persistenceLayer.Open(tryUpgrade: true) as Workbook;

                if (workbook != null)
                {
                    ReportStatus(BackgroundExecutionStatus.WorkbookLoaded);

                    Ioc.RegisterInstance <IWorkbook, Workbook>(workbook);
                    workbook.Initialize();

                    // important: load alarm manager so that we update reminders properly is a recurring task is created
                    var alarmManager = new AlarmManager(workbook);

                    var backgroundSyncManager = new BackgroundSynchronizationManager(workbook, trackingManager, ToastHelper.ToastMessage);
                    await backgroundSyncManager.SetupAsync();

                    if (backgroundSyncManager.CanSync())
                    {
                        ReportStatus(BackgroundExecutionStatus.SyncStarted);

                        this.synchronizationManager = backgroundSyncManager.SynchronizationManager;

                        if (workbook.Settings.GetValue <bool>(CoreSettings.BackgroundToast))
                        {
                            this.synchronizationManager.OperationCompleted += (s, e) => ToastHelper.ToastMessage(e.Item);
                            this.synchronizationManager.OperationFailed    += (s, e) => ToastHelper.ToastMessage(e.Message);
                        }

                        bool result = await backgroundSyncManager.TrySyncAsync(this.persistenceLayer);

                        if (result)
                        {
                            ReportStatus(BackgroundExecutionStatus.SyncCompleted);
                        }
                        else
                        {
                            ReportStatus(BackgroundExecutionStatus.SyncError);
                        }
                    }

                    // update tiles
                    ReportStatus(BackgroundExecutionStatus.TileStarted);

                    TileManager timeManager = new TileManager(workbook, trackingManager, null, true);
                    await timeManager.LoadSecondaryTilesAsync();

                    timeManager.UpdateTiles();

                    ReportStatus(BackgroundExecutionStatus.TileCompleted);

                    // save log
                    await LogService.SaveAsync();
                }
                else
                {
                    ReportStatus(BackgroundExecutionStatus.WorkbookNotLoaded);
                }
            }
            catch (Exception ex)
            {
                hadException = true;

                LogService.Level |= LogLevel.Debug;
                LogService.Log("WinBackgroundTaskHelper", "Exception during background execution: " + ex.GetAllMessages());

                if (trackingManager != null)
                {
                    trackingManager.Exception(ex, "Exception Background task helper");
                }

                ReportStatus(BackgroundExecutionStatus.CompletedException);
            }

            if (!hadException)
            {
                ReportStatus(BackgroundExecutionStatus.CompletedSuccess);
            }

            await LogService.SaveAsync();

            WinSettings.Instance.SetValue(CoreSettings.BackgroundLastEndExecution, DateTime.Now);

            this.deferral.Complete();
        }
Exemple #4
0
        public static void Run(TrackingManager trackingManager, SQLiteConnection connection)
        {
            foreach (var table in new List <string> {
                "folder", "tasks"
            })
            {
                try
                {
                    var databaseEntries = connection.Query <DatabaseEntry>("SELECT * FROM " + table);
                    foreach (var databaseEntry in databaseEntries)
                    {
                        string update = string.Empty;

                        if (!string.IsNullOrWhiteSpace(databaseEntry.Added))
                        {
                            update += string.Format(" Added = '{0}',", NormalizeDatetime(databaseEntry.Added));
                        }

                        if (!string.IsNullOrWhiteSpace(databaseEntry.Alarm))
                        {
                            update += string.Format(" Alarm = '{0}',", NormalizeDatetime(databaseEntry.Alarm));
                        }

                        if (!string.IsNullOrWhiteSpace(databaseEntry.Modified))
                        {
                            update += string.Format(" Modified = '{0}',", NormalizeDatetime(databaseEntry.Modified));
                        }

                        if (!string.IsNullOrWhiteSpace(databaseEntry.Due))
                        {
                            update += string.Format(" Due = '{0}',", NormalizeDatetime(databaseEntry.Due));
                        }

                        if (!string.IsNullOrWhiteSpace(databaseEntry.Start))
                        {
                            update += string.Format(" Start = '{0}',", NormalizeDatetime(databaseEntry.Start));
                        }

                        if (!string.IsNullOrWhiteSpace(databaseEntry.Completed))
                        {
                            update += string.Format(" Completed = '{0}',", NormalizeDatetime(databaseEntry.Completed));
                        }

                        update = update.TrimEnd(',');

                        try
                        {
                            connection.Execute(string.Format("UPDATE {0} SET {1} WHERE Id = {2}", table, update, databaseEntry.Id));
                        }
                        catch (Exception e1)
                        {
                            trackingManager.Exception(e1, "DatebaseDateTimeFixer update query");
                        }
                    }
                }
                catch (Exception e2)
                {
                    trackingManager.Exception(e2, "DatebaseDateTimeFixer select query");
                }
            }
        }