Пример #1
0
        protected override async Task InitializeAfterAccount()
        {
            DataChanges changes = new DataChanges();

            changes.Add(new DataItemYear()
            {
                Identifier = Guid.NewGuid(),
                Name       = "Freshman"
            });

            changes.Add(new DataItemYear()
            {
                Identifier = Guid.NewGuid(),
                Name       = "Sophomore"
            });

            changes.Add(new DataItemYear()
            {
                Identifier = Guid.NewGuid(),
                Name       = "Junior"
            });

            changes.Add(new DataItemYear()
            {
                Identifier = Guid.NewGuid(),
                Name       = "Senior"
            });

            await DataStore.ProcessLocalChanges(changes);

            await InitializeAfterYears();
        }
Пример #2
0
        public async Task TestAdding_DateCreated()
        {
            DataChanges changes = new DataChanges();

            // Add multiple at once
            changes.Add(new DataItemYear()
            {
                Identifier = Guid.NewGuid(),
                Name       = "Freshman"
            });

            changes.Add(new DataItemYear()
            {
                Identifier = Guid.NewGuid(),
                Name       = "Sophomore"
            });

            await DataStore.ProcessLocalChanges(changes);


            ViewModelYearsAndSemesters viewModel = await ViewModelYearsAndSemesters.LoadAsync(LocalAccountId);

            var freshman  = viewModel.School.Years[0];
            var sophomore = viewModel.School.Years[1];

            Assert.AreEqual("Freshman", freshman.Name);
            Assert.AreEqual("Sophomore", sophomore.Name);

            // Make sure the second item is 1 tick after the first
            Assert.AreEqual(freshman.DateCreated.AddTicks(1), sophomore.DateCreated);
        }
Пример #3
0
        public async Task TestCascadeDeleteYear()
        {
            Guid freshmanId = Guid.NewGuid();
            Guid tempId;

            DataChanges changes = new DataChanges();

            changes.Add(new DataItemYear()
            {
                Identifier = freshmanId,
                Name       = "Freshman"
            });

            changes.Add(new DataItemSemester()
            {
                Identifier      = Guid.NewGuid(),
                UpperIdentifier = changes.EditedItems.OfType <DataItemYear>().First().Identifier,
                Name            = "Fall"
            });

            changes.Add(new DataItemSemester()
            {
                Identifier      = Guid.NewGuid(),
                UpperIdentifier = changes.EditedItems.OfType <DataItemYear>().First().Identifier,
                Name            = "Spring"
            });

            changes.Add(new DataItemYear()
            {
                Identifier = Guid.NewGuid(),
                Name       = "Sophomore"
            });

            changes.Add(new DataItemSemester()
            {
                Identifier      = Guid.NewGuid(),
                UpperIdentifier = changes.EditedItems.OfType <DataItemYear>().First(i => i.Name.Equals("Sophomore")).Identifier,
                Name            = "Fall - Sophomore"
            });

            await DataStore.ProcessLocalChanges(changes);

            Assert.AreEqual(2, DataStore.TableYears.Count(), "Database count of years incorrect");
            Assert.AreEqual(3, DataStore.TableSemesters.Count(), "Database count of semesters incorrect");


            changes = new DataChanges();

            changes.DeleteItem(freshmanId);

            await DataStore.ProcessLocalChanges(changes);

            Assert.AreEqual(1, DataStore.TableYears.Count(), "Database count of years incorrect");
            Assert.AreEqual(1, DataStore.TableSemesters.Count(), "Database count of semesters incorrect");
        }
        protected override async Task InitializeAfterSemesters()
        {
            DataChanges changes = new DataChanges();

            changes.Add(new DataItemClass()
            {
                Credits         = 3,
                Details         = "Some details about Math class",
                Identifier      = Guid.NewGuid(),
                Name            = "Math",
                RawColor        = ColorTools.GetArray(Colors.Blue, 3),
                UpperIdentifier = CurrentSemesterId
            });

            CurrentClassId = Guid.NewGuid();

            changes.Add(new DataItemClass()
            {
                Name            = "English",
                Details         = "The class where you write essays in.",
                Identifier      = CurrentClassId,
                Credits         = 4,
                RawColor        = ColorTools.GetArray(Colors.Red, 3),
                UpperIdentifier = CurrentSemesterId
            });

            changes.Add(new DataItemClass()
            {
                Name            = "Spanish",
                Details         = "Learn a foreign language",
                Identifier      = Guid.NewGuid(),
                Credits         = 4,
                RawColor        = ColorTools.GetArray(Colors.Green, 3),
                UpperIdentifier = base.CurrentSemesterId
            });

            changes.Add(new DataItemClass()
            {
                Name            = "Science",
                Details         = "Perform experiments",
                Identifier      = Guid.NewGuid(),
                Credits         = 4,
                RawColor        = ColorTools.GetArray(Colors.Purple, 3),
                UpperIdentifier = base.CurrentSemesterId
            });

            await DataStore.ProcessLocalChanges(changes);
        }
Пример #5
0
        public async System.Threading.Tasks.Task TestDeletingClassSchedule()
        {
            DataChanges changes = new DataChanges();

            changes.Add(new DataItemSchedule()
            {
                Identifier      = Guid.NewGuid(),
                UpperIdentifier = base.CurrentClassId,
                StartTime       = new DateTime(2015, 1, 1, 8, 00, 00, DateTimeKind.Utc),
                EndTime         = new DateTime(2015, 1, 1, 8, 50, 00, DateTimeKind.Utc),
                Room            = "Modern Languages 201",
                ScheduleWeek    = Schedule.Week.BothWeeks,
                ScheduleType    = Schedule.Type.Normal,
                DayOfWeek       = DayOfWeek.Monday
            });

            await DataStore.ProcessLocalChanges(changes);

            var viewModel = await ViewModelClass.LoadAsync(base.LocalAccountId, base.CurrentClassId, new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            Assert.AreEqual(1, viewModel.Class.Schedules.Count);

            var schedule = viewModel.Class.Schedules[0];


            changes = new DataChanges();

            changes.DeleteItem(schedule.Identifier);

            await DataStore.ProcessLocalChanges(changes);

            viewModel = await ViewModelClass.LoadAsync(base.LocalAccountId, base.CurrentClassId, new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            Assert.AreEqual(0, viewModel.Class.Schedules.Count);
        }
Пример #6
0
        public async Task TestAddingClass_Defaults()
        {
            DataItemClass c = new DataItemClass()
            {
                Identifier      = Guid.NewGuid(),
                UpperIdentifier = base.CurrentSemesterId,
                Credits         = 3,
                Name            = "Math",
                Details         = "",
                RawColor        = ColorTools.GetArray(Colors.Red, 3)
            };

            DataChanges changes = new DataChanges();

            changes.Add(c);

            await base.DataStore.ProcessLocalChanges(changes);

            var viewModel = await ViewModelClass.LoadAsync(base.LocalAccountId, c.Identifier, DateTime.Today);

            var viewClass = viewModel.Class;

            Assert.AreEqual("Math", viewClass.Name);
            Assert.AreEqual(3, viewClass.Credits);
            Assert.AreEqual("", viewClass.Details);
            Assert.AreEqual(Colors.Red, viewClass.Color);
        }
Пример #7
0
        public void Delete()
        {
            TryStartDataOperationAndThenNavigate(async delegate
            {
                if (IsInWhatIfMode)
                {
                    Grade.WeightCategory.Remove(Grade);
                    Grade.WeightCategory.Class.ResetDream();
                }
                else
                {
                    // Tasks/events don't actually get deleted, just excluded from grades
                    if (Grade is ViewItemTaskOrEvent taskOrEvent)
                    {
                        var dataItem = taskOrEvent.CreateBlankDataItem();
                        dataItem.WeightCategoryIdentifier = PowerPlannerSending.BaseHomeworkExam.WEIGHT_CATEGORY_EXCLUDED;

                        DataChanges changes = new DataChanges();
                        changes.Add(dataItem);

                        await PowerPlannerApp.Current.SaveChanges(changes);
                    }
                    else
                    {
                        await MainScreenViewModel.DeleteItem(Grade);
                    }
                }
            }, delegate
Пример #8
0
        public async Task TestAddingSemester()
        {
            ViewModelYearsAndSemesters viewModel = await ViewModelYearsAndSemesters.LoadAsync(LocalAccountId);

            var years = viewModel.School.Years;

            var freshman  = viewModel.School.Years[0];
            var sophomore = viewModel.School.Years[1];
            var junior    = viewModel.School.Years[2];
            var senior    = viewModel.School.Years[3];

            DataChanges changes = new DataChanges();

            changes.Add(new DataItemSemester()
            {
                Identifier      = Guid.NewGuid(),
                UpperIdentifier = freshman.Identifier,
                Name            = "Fall (Freshman)"
            });

            await DataStore.ProcessLocalChanges(changes);

            Assert.AreEqual(1, freshman.Semesters.Count);
            Assert.AreEqual(freshman.Identifier, freshman.Semesters.First().Year.Identifier);
            Assert.AreEqual("Fall (Freshman)", freshman.Semesters.First().Name);
        }
        public async void UndropGrade()
        {
            try
            {
                if (IsInWhatIfMode)
                {
                    Grade.IsDropped  = false;
                    Grade.WasChanged = true;
                    Grade.WeightCategory.Class.ResetDream();
                }
                else
                {
                    var g = Grade.CreateBlankDataItem();
                    g.IsDropped = false;

                    DataChanges changes = new DataChanges();
                    changes.Add(g);

                    await PowerPlannerApp.Current.SaveChanges(changes);
                }
            }
            catch (Exception ex)
            {
                TelemetryExtension.Current?.TrackException(ex);
            }
        }
Пример #10
0
        private async void Save()
        {
            try
            {
                IsEnabled = false;

                var changes = new DataChanges();

                // Class changes
                var c = new DataItemClass()
                {
                    Identifier        = Class.Identifier,
                    DoesRoundGradesUp = RoundGradesUp
                };

                changes.Add(c);

                await TryHandleUserInteractionAsync("Save", async delegate
                {
                    await PowerPlannerApp.Current.SaveChanges(changes);
                }, "Failed to save. Your error has been reported.");
            }

            catch (Exception ex)
            {
                TelemetryExtension.Current?.TrackException(ex);
                await new PortableMessageDialog("Error encountered while saving. Your error report has been sent to the developer.", "Error").ShowAsync();
            }

            finally
            {
                IsEnabled = true;
            }
        }
        public void SetPercentComplete(double percentComplete)
        {
            ViewItemHomework homework = Item as ViewItemHomework;

            if (homework == null || homework.PercentComplete == percentComplete)
            {
                return;
            }

            TryStartDataOperationAndThenNavigate(delegate
            {
                DataChanges changes = new DataChanges();

                changes.Add(new DataItemMegaItem()
                {
                    Identifier      = homework.Identifier,
                    PercentComplete = percentComplete
                });

                return(PowerPlannerApp.Current.SaveChanges(changes));
            }, delegate
            {
                // Go back immediately before
                if (percentComplete == 1)
                {
                    this.GoBack();
                }
            });
        }
Пример #12
0
        public async Task TestViewModelCalendar_EdgeCase()
        {
            DataChanges changes = new DataChanges();

            changes.Add(new DataItemHomework()
            {
                Name            = "New Year 2016",
                Date            = new DateTime(2016, 1, 1, 0, 0, 0, DateTimeKind.Utc),
                Identifier      = Guid.NewGuid(),
                UpperIdentifier = base.CurrentClassId,
                Details         = ""
            });

            await base.DataStore.ProcessLocalChanges(changes);

            // TODO
            //var viewModel = await ViewModelCalendar.LoadAsync(base.LocalAccountId, base.CurrentSemesterId);

            //Assert.AreEqual(0, viewModel.Items.Count, "Should start empty");

            //await viewModel.ApplyFilterAsync(new DateTime(2015, 10, 1, 0, 0, 0, DateTimeKind.Utc), new DateTime(2016, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            //Assert.AreEqual(1, viewModel.Items.Count, "After first filter");

            //await viewModel.ApplyFilterAsync(new DateTime(2015, 11, 1, 0, 0, 0, DateTimeKind.Utc), new DateTime(2016, 2, 1, 0, 0, 0, DateTimeKind.Utc));

            //Assert.AreEqual(1, viewModel.Items.Count, "After second filter");
        }
        public void DropGrade()
        {
            TryStartDataOperationAndThenNavigate(async delegate
            {
                if (IsInWhatIfMode)
                {
                    Grade.IsDropped  = true;
                    Grade.WasChanged = true;
                    Grade.WeightCategory.Class.ResetDream();
                }
                else
                {
                    var g       = Grade.CreateBlankDataItem();
                    g.IsDropped = true;

                    DataChanges changes = new DataChanges();
                    changes.Add(g);

                    await PowerPlannerApp.Current.SaveChanges(changes);
                }
            }, delegate
            {
                this.RemoveViewModel();
            });
        }
Пример #14
0
        public async Task TestViewModelCalendar_Normal()
        {
            DataChanges changes = new DataChanges();

            changes.Add(new DataItemHomework()
            {
                Name            = "New Year 2016",
                Date            = new DateTime(2016, 1, 1, 0, 0, 0, DateTimeKind.Utc),
                Identifier      = Guid.NewGuid(),
                UpperIdentifier = base.CurrentClassId,
                Details         = ""
            });

            changes.Add(new DataItemHomework()
            {
                Identifier      = Guid.NewGuid(),
                Name            = "Birthday 2015",
                Date            = new DateTime(2015, 9, 25, 0, 0, 0, DateTimeKind.Utc),
                Details         = "Congrats!",
                UpperIdentifier = base.CurrentClassId
            });

            changes.Add(new DataItemHomework()
            {
                Identifier      = Guid.NewGuid(),
                Name            = "Afterparty 2015",
                Date            = new DateTime(2015, 9, 25, 0, 0, 0, DateTimeKind.Utc),
                Details         = "Celebrate!",
                UpperIdentifier = base.CurrentClassId
            });

            await base.DataStore.ProcessLocalChanges(changes);

            // TODO: Needs updating
            Assert.Fail("Needs updating");
            //var viewModel = await ViewModelCalendar.LoadAsync(base.LocalAccountId, base.CurrentSemesterId);

            //Assert.AreEqual(0, viewModel.Items.Count, "Should start empty");

            //await viewModel.ApplyFilterAsync(new DateTime(2015, 7, 1, 0, 0, 0, DateTimeKind.Utc), new DateTime(2015, 11, 1, 0, 0, 0, DateTimeKind.Utc));

            //Assert.AreEqual(2, viewModel.Items.Count, "After first filter");
            //Assert.IsTrue(viewModel.Items.Any(i => i.Name.Equals("Birthday 2015")));
            //Assert.IsTrue(viewModel.Items.Any(i => i.Name.Equals("Afterparty 2015")));
        }
Пример #15
0
        public void TestHomeworkExamSortingAll()
        {
            DataChanges changes = new DataChanges();

            changes.Add(new DataItemExam()
            {
                Name            = "Second item",
                Date            = new DateTime(2015, 1, 2, 0, 0, 0, DateTimeKind.Utc),
                UpperIdentifier = base.CurrentClassId
            });

            changes.Add(new DataItemHomework()
            {
                Name            = "First item",
                Date            = new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc),
                UpperIdentifier = base.CurrentClassId
            });
        }
Пример #16
0
        public static async System.Threading.Tasks.Task <AccountDataItem> CreateAndInitializeAccountAsync(string username, string localToken, string token, long accountId, int deviceId)
        {
            var account = await CreateAccountHelper.CreateAccountLocally(username, localToken, token, accountId, deviceId, needsInitialSync : false);

            if (account != null)
            {
                AccountsManager.SetLastLoginIdentifier(account.LocalAccountId);

                // Add the default year/semester
                try
                {
                    DataItemYear year = new DataItemYear()
                    {
                        Identifier = Guid.NewGuid(),
                        Name       = PowerPlannerResources.GetString("DummyFirstYear")
                    };

                    DataItemSemester semester = new DataItemSemester()
                    {
                        Identifier      = Guid.NewGuid(),
                        UpperIdentifier = year.Identifier,
                        Name            = PowerPlannerResources.GetString("DummyFirstSemester")
                    };

                    DataChanges changes = new DataChanges();
                    changes.Add(year);
                    changes.Add(semester);

                    await PowerPlannerApp.Current.SaveChanges(account, changes);

                    await account.SetCurrentSemesterAsync(semester.Identifier);

                    NavigationManager.MainMenuSelection = NavigationManager.MainMenuSelections.Schedule;

                    return(account);
                }
                catch (Exception ex)
                {
                    TelemetryExtension.Current?.TrackException(ex);
                }
            }

            return(null);
        }
Пример #17
0
        private void FlagFieldAsChanged(string fieldName, object previousValue)
        {
            if (fieldName.Equals("SuppressErrorNotification", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            if (!DataChanges.ContainsKey(fieldName))
            {
                DataChanges.Add(fieldName, previousValue);
                HasUnsavedChanges = true;
            }
        }
Пример #18
0
        public void Save()
        {
            TryStartDataOperationAndThenNavigate(delegate
            {
                string details = Details.Trim();

                DataItemClass c = new DataItemClass()
                {
                    Identifier = Class.Identifier,
                    Details    = details
                };

                DataChanges editChanges = new DataChanges();
                editChanges.Add(c);
                return(PowerPlannerApp.Current.SaveChanges(editChanges));
            }, delegate
            {
                this.GoBack();
            });
        }
        public async void Save()
        {
            try
            {
                if (!AreScalesValid())
                {
                    await new PortableMessageDialog(PowerPlannerResources.GetString("String_InvalidGradeScalesMessageBody"), PowerPlannerResources.GetString("String_InvalidGradeScalesMessageHeader")).ShowAsync();
                    return;
                }

                GradeScale[] newScales = GradeScales.ToArray();

                DataChanges changes = new DataChanges();

                // Class changes
                {
                    var c = new DataItemClass()
                    {
                        Identifier = Class.Identifier
                    };

                    c.SetGradeScales(newScales);

                    changes.Add(c);
                }

                TryStartDataOperationAndThenNavigate(delegate
                {
                    return(PowerPlannerApp.Current.SaveChanges(changes));
                }, delegate
                {
                    this.RemoveViewModel();
                });
            }

            catch (Exception ex)
            {
                TelemetryExtension.Current?.TrackException(ex);
                await new PortableMessageDialog("Error encountered while saving. Your error report has been sent to the developer.", "Error").ShowAsync();
            }
        }
        public void Save()
        {
            TryStartDataOperationAndThenNavigate(delegate
            {
                DataChanges changes = new DataChanges();

                // Class changes
                var c = new DataItemClass()
                {
                    Identifier   = Class.Identifier,
                    PassingGrade = PassingGrade / 100
                };

                changes.Add(c);

                return(PowerPlannerApp.Current.SaveChanges(changes));
            }, delegate
            {
                this.RemoveViewModel();
            });
        }
        public async Task MoveItem(BaseViewItemHomeworkExam item, DateTime toDate)
        {
            try
            {
                if (item.Date.Date == toDate.Date)
                {
                    return;
                }

                DataChanges changes = new DataChanges();

                var editedDataItem = item.CreateBlankDataItem();
                editedDataItem.Date = DateTime.SpecifyKind(toDate.Date.Add(item.Date.TimeOfDay), DateTimeKind.Utc);
                changes.Add(editedDataItem);

                await PowerPlannerApp.Current.SaveChanges(changes);
            }
            catch (Exception ex)
            {
                TelemetryExtension.Current?.TrackException(ex);
            }
        }
Пример #22
0
        public void Save()
        {
            TryStartDataOperationAndThenNavigate(async delegate
            {
                string name = Name;

                if (string.IsNullOrWhiteSpace(name))
                {
                    new PortableMessageDialog(PowerPlannerResources.GetString("AddYearPage_MessageNoName_Body"), PowerPlannerResources.GetString("AddYearPage_MessageNoName_Title")).Show();
                    return;
                }

                DataItemYear year;

                if (YearToEdit != null)
                {
                    year = new DataItemYear()
                    {
                        Identifier = YearToEdit.Identifier
                    }
                }
                ;

                else
                {
                    year = new DataItemYear()
                    {
                        Identifier = Guid.NewGuid()
                    }
                };

                year.Name = name;

                DataChanges changes = new DataChanges();
                changes.Add(year);

                await PowerPlannerApp.Current.SaveChanges(changes);
            }, delegate
        public void Delete()
        {
            TryStartDataOperationAndThenNavigate(delegate
            {
                if (IsUnassigedMode)
                {
                    var changedItem = Item.CreateBlankDataItem();
                    changedItem.WeightCategoryIdentifier = PowerPlannerSending.BaseHomeworkExam.WEIGHT_CATEGORY_EXCLUDED;

                    var changes = new DataChanges();
                    changes.Add(changedItem);

                    return(PowerPlannerApp.Current.SaveChanges(changes));
                }
                else
                {
                    return(MainScreenViewModel.DeleteItem(Item));
                }
            }, delegate
            {
                this.GoBack();
            });
        }
        public void Save()
        {
            TryStartDataOperationAndThenNavigate(async delegate
            {
                string name = Name;

                if (string.IsNullOrWhiteSpace(name))
                {
                    new PortableMessageDialog(PowerPlannerResources.GetStringNoNameMessageBody(), PowerPlannerResources.GetStringNoNameMessageHeader()).Show();
                    return;
                }

                DataItemSemester semester;

                if (SemesterToEdit != null)
                {
                    semester = new DataItemSemester()
                    {
                        Identifier = SemesterToEdit.Identifier
                    }
                }
                ;

                else if (AddParams != null)
                {
                    semester = new DataItemSemester()
                    {
                        Identifier      = Guid.NewGuid(),
                        UpperIdentifier = AddParams.YearIdentifier
                    }
                }
                ;

                else
                {
                    throw new NullReferenceException("Either editing semester or add semester param must be initialized.");
                }

                semester.Name = name;

                if (SupportsStartEnd)
                {
                    if (StartDate != null)
                    {
                        semester.Start = DateTime.SpecifyKind(StartDate.Value.Date, DateTimeKind.Utc);

                        if (!SqlDate.IsValid(semester.Start))
                        {
                            semester.Start = DateTime.Today;
                        }
                    }

                    else
                    {
                        semester.Start = PowerPlannerSending.DateValues.UNASSIGNED;
                    }

                    if (EndDate != null)
                    {
                        semester.End = DateTime.SpecifyKind(EndDate.Value.Date, DateTimeKind.Utc);

                        if (!SqlDate.IsValid(semester.End))
                        {
                            semester.End = DateTime.Today;
                        }
                    }

                    else
                    {
                        semester.End = PowerPlannerSending.DateValues.UNASSIGNED;
                    }


                    if (!PowerPlannerSending.DateValues.IsUnassigned(semester.Start) &&
                        !PowerPlannerSending.DateValues.IsUnassigned(semester.End) &&
                        semester.Start > semester.End)
                    {
                        new PortableMessageDialog(PowerPlannerResources.GetString("EditSemesterPage_String_StartDateGreaterThanEndExplanation"), PowerPlannerResources.GetString("EditSemesterPage_String_InvalidStartDate")).Show();
                        return;
                    }
                }

                DataChanges changes = new DataChanges();
                changes.Add(semester);

                await PowerPlannerApp.Current.SaveChanges(changes);
            }, delegate
Пример #25
0
        public async void Handle(BackgroundActivatedEventArgs args)
        {
            var taskInstance = args.TaskInstance;

            taskInstance.Canceled += TaskInstance_Canceled;

            var deferral = taskInstance.GetDeferral();

            try
            {
                var toastActionTrigger = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail;

                var toastArgs = ArgumentsHelper.Parse(toastActionTrigger.Argument);

                if (toastArgs is BaseArgumentsWithAccount toastArgsWithAccount)
                {
                    Guid localAccountId = toastArgsWithAccount.LocalAccountId;

                    if (localAccountId == Guid.Empty)
                    {
                        return;
                    }

                    AccountDataItem account = await AccountsManager.GetOrLoad(localAccountId);

                    if (account == null)
                    {
                        return;
                    }

                    var cancellationToken = _cancellationTokenSource.Token;

                    try
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        if (toastArgs is MarkTasksCompleteArguments markCompleteArgs)
                        {
                            TelemetryExtension.Current?.TrackEvent("ToastMarkedCompleted");

                            DataChanges changes = new DataChanges();

                            foreach (var id in markCompleteArgs.ItemIds)
                            {
                                changes.Add(new DataItemMegaItem()
                                {
                                    Identifier      = id,
                                    PercentComplete = 1
                                }, onlyEdit: true);
                            }

                            // Need to wait for all tile/toast tasks to complete before returning and completing deferral
                            await PowerPlannerApp.Current.SaveChanges(account, changes, waitForSaveAndSyncTasks : true);
                        }
                    }

                    catch (OperationCanceledException) { }

                    // Wait for the calendar integration to complete
                    await AppointmentsExtension.Current?.GetTaskForAllCompleted();
                }
            }

            catch (Exception ex)
            {
                TelemetryExtension.Current?.TrackException(ex);
            }

            finally
            {
                deferral.Complete();
            }
        }
Пример #26
0
        public async System.Threading.Tasks.Task TestViewModelAgenda_Normal()
        {
            DataChanges changes = new DataChanges();

            changes.Add(new DataItemHomework()
            {
                Name            = "New Year 2016",
                Date            = new DateTime(2016, 1, 1, 0, 0, 0, DateTimeKind.Utc),
                Identifier      = Guid.NewGuid(),
                UpperIdentifier = base.CurrentClassId,
                Details         = ""
            });

            changes.Add(new DataItemHomework()
            {
                Identifier      = Guid.NewGuid(),
                Name            = "Birthday 2015",
                Date            = new DateTime(2015, 9, 25, 0, 0, 0, DateTimeKind.Utc),
                Details         = "Congrats!",
                UpperIdentifier = base.CurrentClassId,
                PercentComplete = 0.3
            });

            changes.Add(new DataItemHomework()
            {
                Identifier      = Guid.NewGuid(),
                Name            = "Afterparty 2015",
                Date            = new DateTime(2015, 9, 25, 0, 0, 0, DateTimeKind.Utc),
                Details         = "Celebrate!",
                UpperIdentifier = base.CurrentClassId
            });

            changes.Add(new DataItemHomework()
            {
                Identifier      = Guid.NewGuid(),
                Name            = "Recovery",
                Date            = new DateTime(2015, 9, 26, 0, 0, 0, DateTimeKind.Utc),
                Details         = "",
                UpperIdentifier = base.CurrentClassId
            });

            // SHOULDN'T BE INCLUDED
            changes.Add(new DataItemHomework()
            {
                Identifier      = Guid.NewGuid(),
                Name            = "Completed in the future",
                Date            = new DateTime(2015, 9, 28, 0, 0, 0, DateTimeKind.Utc),
                Details         = "",
                UpperIdentifier = base.CurrentClassId,
                PercentComplete = 1
            });

            changes.Add(new DataItemHomework()
            {
                Identifier      = Guid.NewGuid(),
                Name            = "In the past",
                Date            = new DateTime(2015, 9, 23, 0, 0, 0, DateTimeKind.Utc),
                Details         = "",
                UpperIdentifier = base.CurrentClassId
            });

            // SHOULDN'T BE INCLUDED
            changes.Add(new DataItemHomework()
            {
                Identifier      = Guid.NewGuid(),
                Name            = "Completed in the past",
                Date            = new DateTime(2015, 9, 24, 0, 0, 0, DateTimeKind.Utc),
                Details         = "",
                UpperIdentifier = base.CurrentClassId,
                PercentComplete = 1
            });

            // SHOULDN'T BE INCLUDED
            changes.Add(new DataItemExam()
            {
                Identifier      = Guid.NewGuid(),
                Name            = "Exam in the past",
                Date            = new DateTime(2015, 9, 24, 0, 0, 0, DateTimeKind.Utc),
                Details         = "",
                UpperIdentifier = base.CurrentClassId
            });

            changes.Add(new DataItemExam()
            {
                Identifier      = Guid.NewGuid(),
                Name            = "Exam in the future",
                Date            = new DateTime(2015, 9, 28, 0, 0, 0, DateTimeKind.Utc),
                Details         = "",
                UpperIdentifier = base.CurrentClassId
            });

            changes.Add(new DataItemExam()
            {
                Identifier      = Guid.NewGuid(),
                Name            = "Exam today",
                Date            = new DateTime(2015, 9, 25, 0, 0, 0, DateTimeKind.Utc),
                Details         = "",
                UpperIdentifier = base.CurrentClassId
            });

            await base.DataStore.ProcessLocalChanges(changes);


            //var viewModel = await ViewModelAgenda.LoadAsync(base.LocalAccountId, base.CurrentSemesterId, new DateTime(2015, 9, 25));


            //Assert.AreEqual(7, viewModel.Items.Count);
            //Assert.IsTrue(viewModel.Items.Any(i => i.Name.Equals("New Year 2016")));
            //Assert.IsTrue(viewModel.Items.Any(i => i.Name.Equals("Birthday 2015")));
            //Assert.IsTrue(viewModel.Items.Any(i => i.Name.Equals("Afterparty 2015")));
            //Assert.IsTrue(viewModel.Items.Any(i => i.Name.Equals("Recovery")));
            //Assert.IsTrue(viewModel.Items.Any(i => i.Name.Equals("In the past")));
            //Assert.IsTrue(viewModel.Items.Any(i => i.Name.Equals("Exam in the future")));
            //Assert.IsTrue(viewModel.Items.Any(i => i.Name.Equals("Exam today")));
        }
        public async void Save()
        {
            try
            {
                string name = Name;

                if (string.IsNullOrWhiteSpace(name))
                {
                    await new PortableMessageDialog(PowerPlannerResources.GetStringNoNameMessageBody(), PowerPlannerResources.GetStringNoNameMessageHeader()).ShowAsync();
                    return;
                }

                DataItemMegaItem holiday;

                if (HolidayToEdit != null)
                {
                    holiday = new DataItemMegaItem()
                    {
                        Identifier = HolidayToEdit.Identifier
                    }
                }
                ;

                else if (AddParams != null)
                {
                    holiday = new DataItemMegaItem()
                    {
                        Identifier      = Guid.NewGuid(),
                        UpperIdentifier = AddParams.SemesterIdentifier,
                        MegaItemType    = PowerPlannerSending.MegaItemType.Holiday
                    }
                }
                ;

                else
                {
                    throw new NullReferenceException("Either editing holiday or add holiday param must be initialized.");
                }

                holiday.Name = name;

                holiday.Date = DateTime.SpecifyKind(StartDate.Date, DateTimeKind.Utc);

                if (!SqlDate.IsValid(holiday.Date))
                {
                    holiday.Date = DateTime.Today;
                }

                holiday.EndTime = DateTime.SpecifyKind(EndDate.Date, DateTimeKind.Utc);
                holiday.EndTime = holiday.EndTime.AddDays(1).AddSeconds(-1);

                if (!SqlDate.IsValid(holiday.EndTime))
                {
                    holiday.EndTime = DateTime.Today;
                }



                if (holiday.Date > holiday.EndTime)
                {
                    await new PortableMessageDialog(PowerPlannerResources.GetString("EditSemesterPage_String_StartDateGreaterThanEndExplanation"), PowerPlannerResources.GetString("EditSemesterPage_String_InvalidStartDate")).ShowAsync();
                    return;
                }

                DataChanges changes = new DataChanges();
                changes.Add(holiday);

                TryStartDataOperationAndThenNavigate(async delegate
                {
                    await PowerPlannerApp.Current.SaveChanges(changes);
                }, delegate
                {
                    this.RemoveViewModel();
                });
            }

            catch (Exception ex)
            {
                TelemetryExtension.Current?.TrackException(ex);
            }
        }
Пример #28
0
        public async void Save()
        {
            try
            {
                if (!AreWeightsValid())
                {
                    await new PortableMessageDialog(PowerPlannerResources.GetString("String_InvalidWeightCategoriesMessageBody"), PowerPlannerResources.GetString("String_InvalidWeightCategoriesMessageHeader")).ShowAsync();
                    return;
                }

                DataChanges changes = new DataChanges();

                // Process weight category changes
                List <EditingWeightCategoryViewModel> newWeights = new List <EditingWeightCategoryViewModel>(WeightCategories);

                List <BaseViewItemMegaItem> lostGrades = new List <BaseViewItemMegaItem>();

                //handle weights that were deleted
                foreach (ViewItemWeightCategory existing in Class.WeightCategories)
                {
                    //if that existing weight isn't in the new weights list
                    if (!newWeights.Any(i => i.Identifier == existing.Identifier))
                    {
                        //mark it for deletion
                        changes.DeleteItem(existing.Identifier);

                        //add all of its grades to the lost grades
                        lostGrades.AddRange(existing.Grades);
                    }
                }

                //if there aren't any weights, need to add the default All Grades
                if (newWeights.Count == 0)
                {
                    newWeights.Add(new EditingWeightCategoryViewModel()
                    {
                        Name   = PowerPlannerResources.GetString("WeightCategory_AllGrades"),
                        Weight = 100
                    });
                }

                Guid firstCategory = newWeights.First().Identifier;

                //strip away any existing weight categories that didn't change
                foreach (EditingWeightCategoryViewModel newWeight in newWeights.ToArray())
                {
                    ViewItemWeightCategory existing = Class.WeightCategories.FirstOrDefault(i => i.Identifier == newWeight.Identifier);

                    if (existing != null)
                    {
                        //if the name and/or value didn't change, we'll remove it from the main list
                        if (existing.Name.Equals(newWeight.Name) && existing.WeightValue == newWeight.Weight)
                        {
                            newWeights.Remove(newWeight);
                        }
                    }
                }

                //and now process the new/changed weights
                foreach (EditingWeightCategoryViewModel changed in newWeights)
                {
                    DataItemWeightCategory w;

                    ViewItemWeightCategory existing = Class.WeightCategories.FirstOrDefault(i => i.Identifier == changed.Identifier);

                    //if existing, serialize
                    if (existing != null)
                    {
                        w = new DataItemWeightCategory()
                        {
                            Identifier = existing.Identifier
                        }
                    }
                    ;

                    else
                    {
                        w = new DataItemWeightCategory()
                        {
                            Identifier      = Guid.NewGuid(),
                            UpperIdentifier = Class.Identifier
                        };

                        //if we didn't have a first category yet
                        if (firstCategory == Guid.Empty)
                        {
                            firstCategory = w.Identifier;
                        }
                    }

                    w.Name        = changed.Name;
                    w.WeightValue = changed.Weight;

                    changes.Add(w);
                }

                // And then move the lost grades into the first available weight category
                foreach (var lostGrade in lostGrades.OfType <ViewItemGrade>())
                {
                    DataItemGrade g = new DataItemGrade()
                    {
                        Identifier = lostGrade.Identifier
                    };

                    g.UpperIdentifier = firstCategory;

                    changes.Add(g);
                }
                foreach (var lostGrade in lostGrades.OfType <ViewItemTaskOrEvent>())
                {
                    DataItemMegaItem g = new DataItemMegaItem()
                    {
                        Identifier = lostGrade.Identifier
                    };

                    g.WeightCategoryIdentifier = firstCategory;

                    changes.Add(g);
                }

                TryStartDataOperationAndThenNavigate(delegate
                {
                    return(PowerPlannerApp.Current.SaveChanges(changes));
                }, delegate
                {
                    this.RemoveViewModel();
                });
            }

            catch (Exception ex)
            {
                TelemetryExtension.Current?.TrackException(ex);
                await new PortableMessageDialog("Error encountered while saving. Your error report has been sent to the developer.", "Error").ShowAsync();
            }
        }
Пример #29
0
        public async void Save()
        {
            try
            {
                string name = Name.Trim();
                if (string.IsNullOrWhiteSpace(name))
                {
                    await new PortableMessageDialog(PowerPlannerResources.GetStringNoNameMessageBody(), PowerPlannerResources.GetStringNoNameMessageHeader()).ShowAsync();
                    return;
                }

                if (Class == null)
                {
                    await new PortableMessageDialog(PowerPlannerResources.GetStringNoClassMessageBody(), PowerPlannerResources.GetStringNoClassMessageHeader()).ShowAsync();
                    return;
                }

                if (IsEndTimePickerVisible && EndTime <= StartTime)
                {
                    new PortableMessageDialog(PowerPlannerResources.GetString("EditingClassScheduleItemView_LowEndTime.Content"), PowerPlannerResources.GetString("EditingClassScheduleItemView_InvalidEndTime.Title")).Show();
                    return;
                }

                List <DataItemMegaItem> bulkEntry = null;

                if (Repeats && IsRepeatingEntryEnabled)
                {
                    if (RecurrenceControlViewModel.ShowErrorIfInvalid())
                    {
                        return;
                    }

                    if (RecurrenceControlViewModel.EndDate.Date <= Date.Date)
                    {
                        TelemetryExtension.Current?.TrackEvent("UserError_InvalidRecurrence", new Dictionary <string, string>()
                        {
                            { "Error", "EndDateNotGreaterThanStart" },
                            { "UserData", "Start: " + Date.ToString("d") + " End: " + RecurrenceControlViewModel.EndDate.ToString("d") }
                        });

                        await new PortableMessageDialog("Your end date must be greater than the date that this series starts on.", "Repeating occurrence invalid").ShowAsync();
                        return;
                    }

                    bulkEntry = new List <DataItemMegaItem>();

                    foreach (var currDate in RecurrenceControlViewModel.GetEnumerableDates(Date.Date))
                    {
                        if (bulkEntry.Count >= 50)
                        {
                            TelemetryExtension.Current?.TrackEvent("UserError_TooManyOccurrences", new Dictionary <string, string>()
                            {
                                { "Error", "EndDateTooFarOut" },
                                { "UserData", $"Date: {Date.ToString("d")} {RecurrenceControlViewModel}" }
                            });

                            await new PortableMessageDialog("The repeating end date you selected is too far into the future such that greater than 50 occurrences would be created. Please select a closer end date.", "Repeating occurrence invalid").ShowAsync();
                            return;
                        }

                        bulkEntry.Add(CreateDataItem(currDate));
                    }
                }

                DataChanges changes = new DataChanges();

                // If we're adding
                if (AddParams != null)
                {
                    try
                    {
                        if (Class.IsNoClassClass)
                        {
                            // Save into a single shared storage object (the semester overrides the data item and facilitates storing these properly)
                            PopulateClassSavedInfo(Class.DataItem);
                        }
                        else
                        {
                            // Save into the class itself
                            changes.Add(CreateClassSavedInfoDataItem());

                            // And ignore updating calendar integration on that class edit, since it doesn't affect calendar integration
                            changes.IgnoreEditedClassIdentifierFromCalendarIntegration(Class.Identifier);
                        }
                    }
                    catch (Exception ex)
                    {
                        TelemetryExtension.Current?.TrackException(ex);
                    }
                }

                DataItemMegaItem dataItem;
                bool             repeating = false;
                if (bulkEntry != null && bulkEntry.Count > 0)
                {
                    dataItem = bulkEntry[0];

                    foreach (var item in bulkEntry)
                    {
                        changes.Add(item);
                    }

                    repeating = true;
                }

                // Otherwise not repeating, create item as normal
                else
                {
                    dataItem = CreateDataItem(Date.Date);
                    changes.Add(dataItem);
                }

                TryStartDataOperationAndThenNavigate(async delegate
                {
                    if (!repeating)
                    {
                        string[] updatedImageNames = await SaveImageAttachmentsAsync();
                        if (updatedImageNames != null)
                        {
                            dataItem.ImageNames = updatedImageNames;
                        }
                    }

                    await PowerPlannerApp.Current.SaveChanges(changes);

                    // Non-critical code
                    try
                    {
                        // Perfect time to ask for permission to send notifications
                        RemindersExtension.Current?.RequestReminderPermission();

                        NavigationManager.SetPreviousAddItemClass(dataItem.UpperIdentifier);

                        if (!Class.IsNoClassClass)
                        {
                            NavigationManager.SelectedWeightCategoryIdentifier = dataItem.WeightCategoryIdentifier;
                        }

                        NavigationManager.SetPreviousAddItemDate(Date.Date);

                        if (SelectedTimeOption == TimeOption_AllDay)
                        {
                            TrackTimeOption("AllDay");
                        }
                        else if (SelectedTimeOption == TimeOption_BeforeClass)
                        {
                            TrackTimeOption("BeforeClass");
                        }
                        else if (SelectedTimeOption == TimeOption_Custom)
                        {
                            TrackTimeOption("Custom");
                        }
                        else if (SelectedTimeOption == TimeOption_DuringClass)
                        {
                            TrackTimeOption("DuringClass");
                        }
                        else if (SelectedTimeOption == TimeOption_EndOfClass)
                        {
                            TrackTimeOption("EndOfClass");
                        }
                        else if (SelectedTimeOption == TimeOption_StartOfClass)
                        {
                            TrackTimeOption("StartOfClass");
                        }

                        if (_userChangedSelectedTimeOption)
                        {
                            TelemetryExtension.Current?.TrackEvent("Action_CustomizedTimeOption");
                        }

                        if (bulkEntry != null && RecurrenceControlViewModel != null)
                        {
                            if (!Account.HasAddedRepeating)
                            {
                                Account.HasAddedRepeating = true;
                                await AccountsManager.Save(Account);
                            }

                            TelemetryExtension.Current?.TrackEvent("Action_RecurringBulkEntry", new Dictionary <string, string>()
                            {
                                { "RepeatInterval", RecurrenceControlViewModel.GetRepeatIntervalAsNumber().ToString() },
                                { "RepeatType", RecurrenceControlViewModel.SelectedRepeatOption.ToString() },
                                { "EndType", RecurrenceControlViewModel.SelectedEndOption.ToString() },
                                { "Occurrences", bulkEntry.Count.ToString() }
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        // Non-critical exception
                        TelemetryExtension.Current?.TrackException(ex);
                    }
                }, delegate
                {
                    this.RemoveViewModel();
                });
            }

            catch (Exception ex)
            {
                TelemetryExtension.Current?.TrackException(ex);
            }
        }
        public async void Save()
        {
            // First we block user interaction on checking if full version, since don't want to dismiss the UI
            // before prompting that they need the full version (otherwise they'd lose data)
            await TryHandleUserInteractionAsync("SaveCheckingIfAllowed", async (cancellationToken) =>
            {
                Guid identifierToIgnore = _editingGrade == null ? Guid.Empty : _editingGrade.Identifier;
                // For free version, block assigning grade if number of graded items exceeds 5
                if (SelectedWeightCategory != null &&
                    (_editingGrade == null || _editingGrade.GradeReceived == PowerPlannerSending.Grade.UNGRADED) &&
                    SelectedWeightCategory.Class.WeightCategories.SelectMany(i => i.Grades).Where(i => i.Identifier != identifierToIgnore && i.GradeReceived != PowerPlannerSending.Grade.UNGRADED).Count() >= 5 &&
                    !await PowerPlannerApp.Current.IsFullVersionAsync())
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    PowerPlannerApp.Current.PromptPurchase(PowerPlannerResources.GetString("MessageFreeGradesLimitReached"));
                    return;
                }

                // And then we perform the data operation which doesn't need any UI interaction blocks
                TryStartDataOperationAndThenNavigate(async delegate
                {
                    string name = Name;
                    if (name.Length == 0)
                    {
                        new PortableMessageDialog(PowerPlannerResources.GetString("String_NoNameMessageBody"), PowerPlannerResources.GetString("String_NoNameMessageHeader")).Show();
                        return;
                    }

                    ViewItemWeightCategory weightCategory = SelectedWeightCategory;
                    if (weightCategory == null)
                    {
                        new PortableMessageDialog(PowerPlannerResources.GetString("EditGradePage_MessageNoWeightCategoryBody"), PowerPlannerResources.GetString("EditGradePage_MessageNoWeightCategoryHeader")).Show();
                        return;
                    }

                    //// What If mode
                    if (State == OperationState.AddingWhatIf || State == OperationState.EditingWhatIf)
                    {
                        BaseViewItemHomeworkExamGrade whatIfGrade;

                        // New
                        if (_editingGrade == null)
                        {
                            whatIfGrade = new ViewItemGrade(null)
                            {
                                DateCreated = DateTime.UtcNow,
                                Updated     = DateTime.UtcNow
                            }
                        }
                        ;

                        // Existing
                        else
                        {
                            whatIfGrade         = _editingGrade;
                            whatIfGrade.Updated = DateTime.UtcNow;
                        }

                        whatIfGrade.Name          = name;
                        whatIfGrade.Details       = Details;
                        whatIfGrade.Date          = DateTime.SpecifyKind(Date, DateTimeKind.Utc).Date.Add(_originalDateOffset);
                        whatIfGrade.GradeReceived = GradeReceived;
                        whatIfGrade.GradeTotal    = GradeTotal;

                        if (UsesIsDropped)
                        {
                            whatIfGrade.IsDropped = IsDropped;
                        }

                        whatIfGrade.WasChanged = true;

                        whatIfGrade.CanBeUsedForAchievingDesiredGrade = whatIfGrade.GradeReceived == PowerPlannerSending.Grade.UNGRADED;

                        if (whatIfGrade.WeightCategory != null)
                        {
                            whatIfGrade.WeightCategory.Remove(whatIfGrade);
                        }

                        weightCategory.Add(whatIfGrade);

                        weightCategory.Class.ResetDream();
                    }

                    else
                    {
                        BaseDataItemHomeworkExamGrade g;
                        if (State == OperationState.Adding)
                        {
                            g = new DataItemGrade()
                            {
                                Identifier = Guid.NewGuid()
                            }
                        }
                        ;
                        else
                        {
                            g = _editingGrade.CreateBlankDataItem();
                        }

                        g.Name = name;

                        if (g is DataItemGrade)
                        {
                            g.UpperIdentifier = weightCategory.Identifier;
                        }
                        else if (g is DataItemMegaItem)
                        {
                            (g as DataItemMegaItem).WeightCategoryIdentifier = weightCategory.Identifier;
                        }

                        g.Details       = Details;
                        g.Date          = DateTime.SpecifyKind(Date, DateTimeKind.Utc).Date.Add(_originalDateOffset);
                        g.GradeReceived = GradeReceived;
                        g.GradeTotal    = GradeTotal;

                        if (UsesIsDropped)
                        {
                            g.IsDropped = IsDropped;
                        }

                        DataChanges changes = new DataChanges();
                        changes.Add(g);
                        await PowerPlannerApp.Current.SaveChanges(changes);
                        // We don't cancel here since we need the following to occur, and removing the view model is fine regardless
                    }

                    NavigationManager.SetPreviousAddItemDate(Date);
                    NavigationManager.SelectedWeightCategoryIdentifier = weightCategory.Identifier;
                }, delegate
                {
                    _onSaved?.Invoke();
                    this.RemoveViewModel();
                });
            });