private async void TryAskingForRatingIfNeeded() { try { // If we haven't asked for rating yet if (!ApplicationData.Current.RoamingSettings.Values.ContainsKey("HasAskedForRating")) { if (ViewModel.CurrentAccount != null) { var dataStore = await AccountDataStore.Get(ViewModel.CurrentLocalAccountId); // If they actually have a decent amount of tasks/events if (await System.Threading.Tasks.Task.Run(async delegate { using (await Locks.LockDataForReadAsync()) { return(dataStore.TableMegaItems.Count() > 15); } })) { CustomMessageBox mb = new CustomMessageBox("Thanks for using Power Planner! If you love the app, please leave a rating in the Store! If you have any suggestions or issues, please email me!", "★ Review App ★", "Review", "Email Dev", "Close"); mb.Response += mbAskForReview_Response; mb.Show(); ApplicationData.Current.RoamingSettings.Values["HasAskedForRating"] = true; } } } } catch { } }
public static async Task <XmlDocument> GetCurrentPrimaryTileNotificationContentAsync(AccountDataItem forAccount) { try { if (forAccount == null || forAccount.MainTileSettings.IsDisabled()) { return(null); } AccountDataStore data = await AccountDataStore.Get(forAccount.LocalAccountId); return(await Task.Run(async delegate { DateTime todayInLocal = DateTime.Today; var allUpcoming = await getAllUpcomingBlocking(forAccount, data, DateTime.SpecifyKind(todayInLocal, DateTimeKind.Utc), forAccount.MainTileSettings); List <ItemsOnDay> groupedByDay = GroupByDay(allUpcoming); return GenerateUpcomingTileNotificationContent( groupedByDay: groupedByDay, todayAsUtc: DateTime.SpecifyKind(todayInLocal, DateTimeKind.Utc), useFriendlyDates: true, type: UpcomingTileType.PrimaryTile); })); } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); return(null); } }
/// <summary> /// Selects the class, or if not found, searches all the semesters and switches to that semester in order to select the class /// </summary> /// <param name="classId"></param> /// <returns></returns> public async Task <bool> SelectClass(Guid classId) { if (classId == Guid.Empty) { return(false); } // If there's no classes, or none matched, we need to check other semesters if (Classes == null || !Classes.Any(i => i.Identifier == classId)) { var data = await AccountDataStore.Get(CurrentLocalAccountId); // Otherwise we have to see what semester this class might be in... Guid semesterId = await data.GetSemesterIdForClassAsync(classId); if (semesterId == Guid.Empty) { return(false); } await SetCurrentSemester(semesterId); } // Now try selecting the class if (Classes != null) { return(SelectClassWithoutLoading(classId, false)); } return(false); }
private async void SaveAndUpdate() { try { base.IsEnabled = false; Debug.WriteLine("Tasks calendar integration settings changed, saving..."); await AccountsManager.Save(Account); Debug.WriteLine("Tasks calendar integration settings changed, saved."); if (AppointmentsExtension.Current != null) { AppointmentsExtension.Current.ResetAll(Account, await AccountDataStore.Get(Account.LocalAccountId)); // Wait for the calendar integration to complete await AppointmentsExtension.Current.GetTaskForAllCompleted(); } } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); } finally { base.IsEnabled = true; } }
/// <summary> /// Automatically updates display, resets reminders, starts settings sync, and submits changes /// </summary> /// <param name="startsOn"></param> /// <param name="currentWeek"></param> public async System.Threading.Tasks.Task SetWeek(DayOfWeek startsOn, Schedule.Week currentWeek) { if (SetWeekSimple(startsOn, currentWeek)) { // Clear cached schedules on day since they don't subscribe to these changes. // Ideally I would have the lists subscribe to the account, but this will do for now. ViewLists.SchedulesOnDay.ClearCached(); ViewLists.DayScheduleItemsArranger.ClearCached(); NeedsToSyncSettings = true; // Save await SaveOnThread(); //make upcoming update OnPropertyChanged("ShowSchedule"); AccountDataStore data = await AccountDataStore.Get(this.LocalAccountId); var dontWait = RemindersExtension.Current?.ResetReminders(this, data); var dontWaitThread = System.Threading.Tasks.Task.Run(delegate { // Update schedule tile var dontWaitScheduleTile = ScheduleTileExtension.Current?.UpdateScheduleTile(this, data); }); dontWait = Sync.SyncSettings(this, Sync.ChangedSetting.WeekOneStartsOn); } }
private async void ButtonPinToStart_Click(object sender, RoutedEventArgs e) { if ((AppBarButtonPin.Icon as SymbolIcon).Symbol == Symbol.Pin) { try { var currAccount = ViewModel.MainScreenViewModel.CurrentAccount; var currData = await AccountDataStore.Get(currAccount.LocalAccountId); await ScheduleTileHelper.PinTile(currAccount, currData); UpdatePinVisibility(); } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); } } else { try { await ScheduleTileHelper.UnpinTile(ViewModel.MainScreenViewModel.CurrentLocalAccountId); UpdatePinVisibility(); } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); } } }
public static async System.Threading.Tasks.Task UpdatePrimaryTileNotificationsAsync() { try { await _updatePrimaryTileNotificationsWorkQueue.QueueOrMergeAsync(0, async delegate { await System.Threading.Tasks.Task.Run(async delegate { var account = await AccountsManager.GetLastLogin(); AccountDataStore data = null; if (account != null) { data = await AccountDataStore.Get(account.LocalAccountId); } await UpdatePrimaryTileNotificationsBlocking(account, data); }); }); } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); Debug.WriteLine("Failed UpdatePrimaryTileNotificationsAsync"); } }
private async void appBarPin_Click(object sender, RoutedEventArgs e) { try { if (!await PowerPlannerApp.Current.IsFullVersionAsync()) { PowerPlannerApp.Current.PromptPurchase(LocalizedResources.GetString("Settings_Tiles_ClassTile_PromptPremiumFeature")); return; } if (ViewModel.Account == null || ViewModel.Class == null) { return; } if ((appBarPin.Icon as SymbolIcon).Symbol == Symbol.Pin) { var data = await AccountDataStore.Get(ViewModel.Account.LocalAccountId); await ClassTileHelper.PinTileAsync(ViewModel.Account, data, ViewModel.Class.Identifier, ViewModel.Class.Name, ColorTools.GetColor(ViewModel.Class.Color)); } else { await ClassTileHelper.UnpinTile(ViewModel.Account.LocalAccountId, ViewModel.Class.Identifier); } UpdatePinButton(); } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); } }
public static async Task <XmlDocument> GetCurrentTileNotificationContentAsync(AccountDataItem forAccount, Guid classId) { try { ClassTileSettings settings = await forAccount.GetClassTileSettings(classId); if (settings.IsDisabled()) { return(null); } DateTime todayInLocal = DateTime.Today; ClassData data = await LoadDataAsync(await AccountDataStore.Get(forAccount.LocalAccountId), classId, DateTime.SpecifyKind(todayInLocal, DateTimeKind.Utc), settings); // That means the class was deleted, but we'll just return null here if (data == null) { return(null); } List <ItemsOnDay> groupedByDay = GroupByDay(data.AllUpcoming); return(GenerateUpcomingTileNotificationContent(groupedByDay, DateTime.SpecifyKind(todayInLocal, DateTimeKind.Utc), true, UpcomingTileType.ClassTile)); } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); return(null); } }
private static async Task <bool> CheckThatSemesterIsValidBlocking(Guid localAccountId, Guid semesterId) { var dataStore = await AccountDataStore.Get(localAccountId); using (await Locks.LockDataForReadAsync()) { return(dataStore.TableSemesters.Count(i => i.Identifier == semesterId) > 0); } }
/// <summary> /// This can NOT be called while in a data lock, since initializing data store uses a lock /// </summary> /// <returns></returns> protected async Task <AccountDataStore> GetDataStore() { if (_dataStore == null) { _dataStore = await AccountDataStore.Get(LocalAccountId); } return(_dataStore); }
private async void UpdateRealTile() { try { await ClassTileHelper.UpdateTileAsync(ViewModel.Account, await AccountDataStore.Get(ViewModel.Account.LocalAccountId), ViewModel.Class.Identifier); } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); } }
public override async Task <bool> ShouldShowAsync(AccountDataItem account) { // Don't show for offline accounts or for devices that aren't Desktop if (account == null || !account.IsOnlineAccount || InterfacesUWP.DeviceInfo.DeviceFamily != InterfacesUWP.DeviceFamily.Desktop) { return(false); } if (ApplicationData.Current.RoamingSettings.Values.ContainsKey(SETTING_HAS_PROMOTED_ANDROID_AND_IOS)) { return(false); } var dataStore = await AccountDataStore.Get(account.LocalAccountId); // If they actually have some classes bool hasContent; using (await Locks.LockDataForReadAsync()) { hasContent = dataStore.TableClasses.Count() > 1; } if (hasContent) { // Try downloading and then show ShouldSuggestOtherPlatformsResponse response = await account.PostAuthenticatedAsync <ShouldSuggestOtherPlatformsRequest, ShouldSuggestOtherPlatformsResponse>( Website.URL + "shouldsuggestotherplatforms", new ShouldSuggestOtherPlatformsRequest() { CurrentPlatform = "Windows 10" }); if (response.ShouldSuggest) { return(true); } // No need to suggest in the future nor show now MarkShown(account); return(false); } else { // Not enough content to show right now return(false); } }
public async void Handle(BackgroundActivatedEventArgs args) { var taskInstance = args.TaskInstance; taskInstance.Canceled += TaskInstance_Canceled; var deferral = taskInstance.GetDeferral(); try { var accounts = await AccountsManager.GetAllAccounts(); var cancellationToken = _cancellationTokenSource.Token; try { cancellationToken.ThrowIfCancellationRequested(); foreach (var a in accounts) { var data = await AccountDataStore.Get(a.LocalAccountId); cancellationToken.ThrowIfCancellationRequested(); await ClassRemindersExtension.Current?.ResetAllRemindersAsync(a); await RemindersExtension.Current?.ResetReminders(a, data); await TileHelper.UpdateTileNotificationsForAccountAsync(a, data); cancellationToken.ThrowIfCancellationRequested(); } } catch (OperationCanceledException) { } } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); } finally { deferral.Complete(); } }
public async void Run(IBackgroundTaskInstance taskInstance) { SharedInitialization.Initialize(); InitializeUWP.Initialize(); taskInstance.Canceled += TaskInstance_Canceled; var deferral = taskInstance.GetDeferral(); try { var accounts = await AccountsManager.GetAllAccounts(); var cancellationToken = _cancellationTokenSource.Token; try { cancellationToken.ThrowIfCancellationRequested(); foreach (var a in accounts) { var data = await AccountDataStore.Get(a.LocalAccountId); cancellationToken.ThrowIfCancellationRequested(); await TileHelper.UpdateTileNotificationsForAccountAsync(a, data); cancellationToken.ThrowIfCancellationRequested(); } } catch (OperationCanceledException) { } } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); } // TODO: Re-schedule toast notifications? finally { deferral.Complete(); } }
public async System.Threading.Tasks.Task SaveChanges(AccountDataItem account, DataChanges changes) { if (account == null) { throw new NullReferenceException("account was null. Windows: " + Windows.Count); } var dataStore = await AccountDataStore.Get(account.LocalAccountId); await dataStore.ProcessLocalChanges(changes); // Don't await this, we don't want it blocking if (account.IsOnlineAccount) { SyncWithoutBlocking(account); } }
/// <summary> /// Saves changes, then triggers updates to reminders/tiles, and triggers a settings sync /// </summary> /// <param name="schoolTimeZone"></param> /// <returns></returns> public async System.Threading.Tasks.Task SetSchoolTimeZone(TimeZoneInfo schoolTimeZone) { SchoolTimeZone = schoolTimeZone; NeedsToSyncSettings = true; // Save await SaveOnThread(); AccountDataStore data = await AccountDataStore.Get(this.LocalAccountId); var dontWait = RemindersExtension.Current?.ResetReminders(this, data); var dontWaitThread = System.Threading.Tasks.Task.Run(delegate { // Update schedule tile var dontWaitScheduleTile = ScheduleTileExtension.Current?.UpdateScheduleTile(this, data); }); dontWait = Sync.SyncSettings(this, Sync.ChangedSetting.SchoolTimeZone); }
public async System.Threading.Tasks.Task SaveChanges(AccountDataItem account, DataChanges changes, bool waitForSaveAndSyncTasks = false) { if (account == null) { throw new NullReferenceException("account was null. Windows: " + Windows.Count); } var dataStore = await AccountDataStore.Get(account.LocalAccountId); var saveChangeTasks = await dataStore.ProcessLocalChanges(changes); System.Threading.Tasks.Task <SyncResult> syncTask = null; // Don't await this, we don't want it blocking if (account.IsOnlineAccount) { if (waitForSaveAndSyncTasks) { syncTask = Sync.SyncAccountAsync(account); } else { SyncWithoutBlocking(account); } } if (waitForSaveAndSyncTasks) { // Need to wait for the tile/toast tasks to finish await saveChangeTasks.WaitForAllTasksAsync(); if (syncTask != null) { var syncResult = await syncTask; if (syncResult != null && syncResult.SaveChangesTask != null) { await syncResult.SaveChangesTask.WaitForAllTasksAsync(); } } } }
public override async Task <bool> ShouldShowAsync(AccountDataItem account) { if (account == null) { return(false); } // If we've already shown if (Helpers.Settings.HasShownPromoContribute) { return(false); } var dataStore = await AccountDataStore.Get(account.LocalAccountId); // If they actually have lots of tasks using (await Locks.LockDataForReadAsync()) { return(dataStore.ActualTableMegaItems.Count() > 60); } }
/// <summary> /// Automatically updates display, resets reminders, starts settings sync, and submits changes /// </summary> /// <param name="startsOn"></param> /// <param name="currentWeek"></param> public async System.Threading.Tasks.Task SetWeek(DayOfWeek startsOn, Schedule.Week currentWeek) { // Clear cached schedules on day since they don't subscribe to these changes. // Ideally I would have the lists subscribe to the account, but this will do for now. ViewLists.SchedulesOnDay.ClearCached(); ViewLists.DayScheduleItemsArranger.ClearCached(); DateTime today = DateTime.SpecifyKind(DateTime.Today, DateTimeKind.Utc); if (currentWeek == Schedule.Week.WeekTwo) { today = today.AddDays(-7); } DateTime answer = DateTools.Last(startsOn, today); if (answer != WeekOneStartsOn) { WeekOneStartsOn = answer; NeedsToSyncSettings = true; // Save await SaveOnThread(); //make upcoming update OnPropertyChanged("ShowSchedule"); AccountDataStore data = await AccountDataStore.Get(this.LocalAccountId); var dontWait = RemindersExtension.Current?.ResetReminders(this, data); var dontWaitThread = System.Threading.Tasks.Task.Run(delegate { // Update schedule tile var dontWaitScheduleTile = ScheduleTileExtension.Current?.UpdateScheduleTile(this, data); }); dontWait = Sync.SyncSettings(this, Sync.ChangedSetting.WeekOneStartsOn); } }
private async void TryAskingForRatingIfNeeded() { try { // If we haven't asked for rating yet if (!PowerPlannerAppDataLibrary.Helpers.Settings.HasAskedForRating) { if (ViewModel.CurrentAccount != null) { var dataStore = await AccountDataStore.Get(ViewModel.CurrentLocalAccountId); // If they actually have a decent amount of homework if (await System.Threading.Tasks.Task.Run(async delegate { using (await Locks.LockDataForReadAsync()) { return(dataStore.TableMegaItems.Count() > 30 && dataStore.TableMegaItems.Any(i => i.DateCreated < DateTime.Today.AddDays(-60))); } })) { var builder = new Android.App.AlertDialog.Builder(Context); builder .SetTitle("★ Review App ★") .SetMessage("Thanks for using Power Planner! If you love the app, please leave a rating in the Store! If you have any suggestions or issues, please email me!") .SetNeutralButton("Review", delegate { OpenReview(); }) // Neutral is displayed more prominently .SetPositiveButton("Email Dev", delegate { AboutView.EmailDeveloper(Context, base.ViewModel); }) .SetNegativeButton("Close", delegate { }); builder.Create().Show(); PowerPlannerAppDataLibrary.Helpers.Settings.HasAskedForRating = true; } } } } catch { } }
/// <summary> /// Syncs account and updates tiles, without awaiting /// </summary> public async void ExecuteOnLoginTasks() { try { var dataStore = await AccountDataStore.Get(this.LocalAccountId); // Update tiles if (TilesExtension.Current != null) { await TilesExtension.Current.UpdateTileNotificationsForAccountAsync(this, dataStore); } // MainScreenViewModel will start the sync // Update calendar if needed AppointmentsExtension.Current?.ResetAllIfNeeded(this, dataStore); } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); } }
private async void appBarPinClass_Click(object sender, RoutedEventArgs e) { try { if (!(await PowerPlannerApp.Current.IsFullVersionAsync())) { PowerPlannerApp.Current.PromptPurchase(LocalizedResources.GetString("String_PinningClassPremiumFeatureMessage")); return; } if (ViewModel == null || ViewModel.ViewItemsGroupClass.Class == null) { return; } if ((AppBarPinClass.Icon as SymbolIcon).Symbol == Symbol.Pin) { var acct = await AccountsManager.GetOrLoad(ViewModel.MainScreenViewModel.CurrentLocalAccountId); var data = await AccountDataStore.Get(ViewModel.MainScreenViewModel.CurrentLocalAccountId); await ClassTileHelper.PinTileAsync(acct, data, ViewModel.ViewItemsGroupClass.Class.Identifier, ViewModel.ViewItemsGroupClass.Class.Name, ColorTools.GetColor(ViewModel.ViewItemsGroupClass.Class.Color)); } else { await ClassTileHelper.UnpinTile(ViewModel.MainScreenViewModel.CurrentLocalAccountId, ViewModel.ViewItemsGroupClass.Class.Identifier); } UpdatePinButton(); } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); } }
/// <summary> /// Sets current semester and saves changes, also updates primary tile /// </summary> public async System.Threading.Tasks.Task SetCurrentSemesterAsync(Guid currentSemesterId, bool uploadSettings = true) { if (CurrentSemesterId == currentSemesterId) { return; } // If semester is being cleared (going to Years page), ignore this change. // That's to allow easily being able to view overall GPA without losing curr semester. if (currentSemesterId == Guid.Empty) { return; } CurrentSemesterId = currentSemesterId; NeedsToSyncSettings = true; IsAppointmentsUpToDate = false; #if ANDROID DateLastDayBeforeReminderWasSent = DateTime.MinValue; #endif await AccountsManager.Save(this); // Upload their changed setting if (uploadSettings) { var dontWait = Sync.SyncSettings(this, Sync.ChangedSetting.SelectedSemesterId); } var dataStore = await AccountDataStore.Get(this.LocalAccountId); AppointmentsExtension.Current?.ResetAll(this, dataStore); RemindersExtension.Current?.ResetReminders(this, dataStore); TilesExtension.Current?.UpdateTileNotificationsForAccountAsync(this, dataStore); }
private async void appBarPin_Click(object sender, RoutedEventArgs e) { try { if ((appBarPin.Icon as SymbolIcon).Symbol == Symbol.Pin) { var data = await AccountDataStore.Get(ViewModel.Account.LocalAccountId); await ScheduleTileHelper.PinTile(ViewModel.Account, data); } else { await ScheduleTileHelper.UnpinTile(ViewModel.Account.LocalAccountId); } UpdatePinButton(); } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); } }
public async Task HandleViewHolidayActivation(Guid localAccountId, Guid holidayId) { DataItemMegaItem holiday = await Task.Run(async delegate { using (await Locks.LockDataForReadAsync("HandleViewHolidayActivation")) { var dataStore = await AccountDataStore.Get(localAccountId); if (dataStore == null) { return(null); } return(dataStore.TableMegaItems.FirstOrDefault(i => i.MegaItemType == PowerPlannerSending.MegaItemType.Holiday && i.Identifier == holidayId)); } }); if (holiday != null) { var holidayDate = DateTime.SpecifyKind(holiday.Date, DateTimeKind.Local); var desiredDisplayMonth = holidayDate; var mainScreen = GetMainScreenViewModel(); if (mainScreen != null && mainScreen.CurrentAccount != null && mainScreen.CurrentAccount.LocalAccountId == localAccountId && mainScreen.Content is CalendarViewModel) { (mainScreen.Content as CalendarViewModel).DisplayMonth = desiredDisplayMonth; (mainScreen.Content as CalendarViewModel).SelectedDate = holidayDate; } else { NavigationManager.SetDisplayMonth(desiredDisplayMonth); NavigationManager.SetSelectedDate(holidayDate); await HandleSelectMenuItemActivation(localAccountId, NavigationManager.MainMenuSelections.Calendar); } } }
protected virtual async Task InitializeAfterAccount() { DataStore = await AccountDataStore.Get(LocalAccountId); }
private async Task <string[]> SaveImageAttachmentsAsync() { var newImages = ImageAttachments.OfType <EditingNewImageAttachmentViewModel>().ToArray(); if (_removedImageAttachments.Count > 0 || newImages.Length > 0) { var currAccount = Account; if (currAccount == null) { throw new NullReferenceException("Account was null"); } IFolder imagesFolderPortable = await FileHelper.GetOrCreateImagesFolder(currAccount.LocalAccountId); List <string> finalImageNames = ImageAttachments.Select(i => i.ImageAttachment.ImageName).ToList(); // Delete images foreach (var removedImage in _removedImageAttachments) { try { var file = await imagesFolderPortable.GetFileAsync(removedImage.ImageAttachment.ImageName); await file.DeleteAsync(); } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); } } // Add new images foreach (var newImage in newImages) { try { await newImage.TempFile.MoveAsync(Path.Combine(imagesFolderPortable.Path, newImage.TempFile.Name), NameCollisionOption.ReplaceExisting); if (newImage.TempFile is Helpers.TempFile tempFile) { tempFile.DetachTempDisposer(); } } catch (Exception ex) { TelemetryExtension.Current?.TrackException(ex); try { finalImageNames.Remove(newImage.ImageAttachment.ImageName); } catch { } } } // If there were new images, add them to the needing upload list var newImageNames = newImages.Select(i => i.ImageAttachment.ImageName).Intersect(finalImageNames).ToArray(); if (newImageNames.Any()) { var dataStore = await AccountDataStore.Get(currAccount.LocalAccountId); await dataStore.AddImagesToUploadAsync(newImageNames); } return(finalImageNames.ToArray()); } else { return(null); } }
private static async System.Threading.Tasks.Task UpgradeAccount(LoginWin login) { await Store.LoadData(login); AccountWin account = login.Account; AccountDataItem accountUWP = new AccountDataItem(login.LocalAccountId) { AccountId = login.AccountId, AutoLogin = login.AutoLogin, CurrentChangeNumber = account.CurrentChangeNumber, CurrentSemesterId = account.School.ActiveSemesterIdentifier, DeviceId = login.DeviceId, LocalAccountId = login.LocalAccountId, LocalToken = login.Password, PremiumAccountExpiresOn = account.PremiumAccountExpiresOn, RememberPassword = login.RememberPassword, RememberUsername = login.RememberUsername, Username = login.Username, WeekOneStartsOn = account.WeekOneStartsOn, Version = account.Version }; // Save account (need to do this so there's a folder for everything else) await AccountsManager.Save(accountUWP); try { AccountDataStore dataStoreUWP = await AccountDataStore.Get(login.LocalAccountId); // Transfer the Changes PartialChanges existingChanges = await account.GetPartialChanges(); await AccountDataStore.ChangedItems.ImportChangesAsync(login.LocalAccountId, existingChanges.Changes.Keys.ToArray(), existingChanges.Deletes.Keys.ToArray()); try { // Transfer images to upload string[] imagesToUpload = (await account.GetAllImagesToUpload()).ToArray(); await dataStoreUWP.AddImagesToUploadAsync(imagesToUpload); // Transfer stored images StorageFolder oldImagesFolder = await login.GetImagesFolder(); IFolder newImagesFolderPortable = await PowerPlannerAppDataLibrary.DataLayer.FileHelper.GetOrCreateImagesFolder(login.LocalAccountId); StorageFolder newImagesFolder = await StorageFolder.GetFolderFromPathAsync(newImagesFolderPortable.Path); foreach (StorageFile existingImage in await oldImagesFolder.GetFilesAsync()) { await existingImage.MoveAsync(newImagesFolder); } } catch { } // Get all the existing items BaseItem[] syncItems = account.GetAllItemsInSendingFormat(); // Translate them to the universal sync language BaseDataItem[] uwpItems = PowerPlannerAppDataLibrary.SyncLayer.Sync.GetSyncItemsAsDataItems(syncItems); // And then input those into the new database await dataStoreUWP.ImportItemsAsync(uwpItems); } catch (Exception ex) { try { TelemetryExtension.Current?.TrackException(ex); } catch { } await AccountsManager.Delete(login.LocalAccountId); } }
private static async Task UpdateAndScheduleDayOfNotifications(AccountDataItem account, AgendaViewItemsGroup agendaItems, Context context, NotificationManager notificationManager, DateTime now, bool fromForeground) { string tagForAccountStartsWith = account.LocalAccountId.ToString(); List <StatusBarNotification> existingNotifs; if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.M) { existingNotifs = notificationManager.GetActiveNotifications().Where(i => i.Id == NotificationIds.DAY_OF_NOTIFICATIONS && i.Tag != null && i.Tag.StartsWith(tagForAccountStartsWith)).ToList(); } else { // GetActiveNotifications didn't exist before version 23 existingNotifs = new List <StatusBarNotification>(); } // If no current semester, or no items, then just clear if (agendaItems == null || agendaItems.Items.Count == 0) { foreach (var notif in existingNotifs) { notificationManager.Cancel(notif.Tag, NotificationIds.DAY_OF_NOTIFICATIONS); } return; } DateTime nextReminderTime; var itemsThatCouldHaveNotifs = GetItemsThatCouldHaveDayOfNotifications(account, agendaItems, now, out nextReminderTime); // Remove ones that don't exist anymore for (int i = 0; i < existingNotifs.Count; i++) { var existing = existingNotifs[i]; Guid identifier; if (TryGetItemIdFromDayOfTag(existing.Tag, out identifier)) { if (!itemsThatCouldHaveNotifs.Any(x => x.Item1.Identifier == identifier)) { notificationManager.Cancel(existing.Tag, NotificationIds.DAY_OF_NOTIFICATIONS); existingNotifs.RemoveAt(i); i--; } } } foreach (var item in itemsThatCouldHaveNotifs) { UpdateDayOfNotification(account.LocalAccountId, item.Item1, item.Item2, context, notificationManager, existingNotifs, fromForeground); } // Need to mark them as sent Guid[] newlySentHomeworkReminders = itemsThatCouldHaveNotifs.Select(i => i.Item1).OfType <ViewItemHomework>().Where(i => !i.HasSentReminder).Select(i => i.Identifier).ToArray(); Guid[] newlySentExamReminders = itemsThatCouldHaveNotifs.Select(i => i.Item1).OfType <ViewItemExam>().Where(i => !i.HasSentReminder).Select(i => i.Identifier).ToArray(); if (newlySentHomeworkReminders.Length > 0 || newlySentExamReminders.Length > 0) { var dataStore = await AccountDataStore.Get(account.LocalAccountId); if (dataStore != null) { await dataStore.MarkAndroidRemindersSent(newlySentHomeworkReminders, newlySentExamReminders); } } // Schedule the next alarm if (nextReminderTime > now) { AlarmManagerHelper.Schedule( context: context, receiverType: typeof(UpdateDayOfNotificationsReceiver), wakeTime: nextReminderTime, uriData: "powerplanner:?localAccountId=" + account.LocalAccountId, wakeDevice: true); } }