Пример #1
0
        public EntryDetailVM(Entry entry)
        {
            if (!Cache.AllItemsLoaded)
            {
                FoodJournalNoSQL.LoadItems(false, null);
            }

            this.entry = entry;
            this.item  = entry.Item;
                        #if WINDOWS_PHONE
            PicturesVM = new PicturesVM(item);
                        #endif
            AmountCollectionVM = new AmountCollectionVM(this);
            PopulateProperties();
        }
Пример #2
0
        private void Requery(string syncID, bool loadCaches)
        {
            using (var log = SessionLog.NewScope("Requerying" + (loadCaches ? " 2" : ""), period.ToString()))
            {
                // Breakfast <- static list of entries

                // Breakfast Items
                // All Items
                // New Item
                // USDA List?
                // - simple
                // - nutrition items
                // - generic items

                List <FoodItem> shown = new List <FoodItem>();

                List <Entry> list = Cache.GetEntryCache(date)[(int)period];

                foreach (Entry e in list)
                {
                    if (e.Item != null)
                    {
                        if (!shown.Contains(e.Item, FoodItemComparer.instance))
                        {
                            shown.Add(e.Item);
                        }
                    }
                }

                var results = new ObservableCollection <SearchResultVM>();
                //results.Clear();

                int cnt = results.Count;

                foreach (var item in Cache.GetRecentCache(period))
                {
                    if (!shown.Contains(item.FlatItem, FoodItemComparer.instance))
                    {
                        shown.Add(item.FlatItem);
                        results.Add(new SearchResultRecentVM(item));
                    }
                }

#if LegacyDB
                var enumerator = new Cache.PeriodEntryEnumerator(period);
                if (loadCaches)
                {
                    enumerator.LoadAllDays();
                }
                enumerator.ShouldLoadDay = () =>
                {
                    if (!loadCaches)
                    {
                        return(false);
                    }
                    if (ShouldStopQuery(syncID))
                    {
                        log.SetState("Aborted"); return(false);
                    }
                    else
                    {
                        return(true);
                    }
                };

                while (enumerator.MoveNext())
                {
                    FoodItem item = enumerator.Current.Item;
                    if (item != null)
                    {
                        if (!shown.Contains(item, FoodItemComparer.instance))
                        {
                            shown.Add(item);
                            results.Add(new SearchResultFoodItemVM(item));
                        }
                    }
                }
#endif

                //" + period.ToString().ToLower() + "
                if (results.Count != cnt)
                {
                    results.Insert(cnt, new SearchResultHeaderVM(Strings.FromEnum("MyRecentItems", period.ToString()), 0));
                }

                cnt = results.Count;

                int i              = 0;
                var enumerator2    = new ResourceRecord2Enumerator(period);
                int MaxCommonItems = AppStats.Current.IncludePremiumItems ? MAXCOMMONITEMSPAID : MAXCOMMONITEMSFREE;
                while (i < MaxCommonItems && enumerator2.MoveNext())
                {
                    FoodItem item = enumerator2.Current;
                    if (!shown.Contains(item, FoodItemComparer.instance))
                    {
                        shown.Add(item);
                        results.Add(new SearchResultFoodItemVM(item));
                        i++;
                    }
                }

                if (results.Count != cnt)
                {
                    results.Insert(cnt, new SearchResultHeaderVM(Strings.FromEnum("CommonItems", period.ToString()), 0));
                }

                cnt = results.Count;

                if (loadCaches || Cache.AllItemsLoaded)
                {
                    if (!Cache.AllItemsLoaded)
                    {
                        if (ShouldStopQuery(syncID))
                        {
                            log.SetState("Aborted"); return;
                        }
                    }

                    if (!Cache.AllItemsLoaded)
                    {
                        FoodJournalNoSQL.LoadItems(false, null);
                    }
                }

                if (loadCaches)
                {
                    //if (HasQuery)
                    System.Threading.Thread.Sleep(500);
                    if (ShouldStopQuery(syncID))
                    {
                        log.SetState("Aborted"); return;
                    }
                }
                else
                {
                    while (results.Count > 12)
                    {
                        results.RemoveAt(12);
                    }
                }

                foreach (var r in results)
                {
                    r.Listener = this;
                }

                // todo: sync instead (how to deal with the removeat 12 though?
                this.ItemList = results;
                NotifyPropertyChanged("ItemList");
            }
        }
Пример #3
0
        public static void StartLoad()
        {
            //#if DEBUG
            //if (FoodJournal.ViewModels.ScreenshotVM.InScreenshot)
            //	return;
            //#endif

            if (Loading)
            {
                return;
            }

            Loading = true;

            // save after 1 second
            BackgroundTask.Start(1000, async() => {
                bool GoAgain = false;

                try {
                    LoadState();

                    List <DateTime> ChangedDates = new List <DateTime> ();

                    String LastSync = "";
                    foreach (var app in state.GetApps())
                    {
                        if (app.InstanceGuid != AppStats.Current.AppInstance)
                        {
                            if (LastSync.Length > 0)
                            {
                                LastSync += "|";
                            }
                            LastSync += app.InstanceGuid + "=" + app.LastestChange.ToString("s");
                        }
                    }


                    List <Package> changes = await SyncService.Get(state.Skip, LastSync);
                    foreach (var change in changes)
                    {
                        if (change.Type == "Continuation")
                        {
                            GoAgain = true;
                        }
                        else
                        {
                            state.Skip++;
                        }

                        try {
                            System.Diagnostics.Debug.WriteLine(string.Format("Applying remote changes {0} {1} {2}", change.Type, change.Key, change.ClientTime));

                            switch (change.Type)
                            {
                            case ("Recent"):
                                // this should get re-calculated so skip
                                break;

                            case ("Continuation"):
                                // no work here
                                break;

                            case ("Day"):

                                DateTime date = DateTime.Parse(change.Key);

                                FoodJournalNoSQL.LoadDay(date, change.Contents);

                                if (!ChangedDates.Contains(date))
                                {
                                    ChangedDates.Add(date);
                                }

                                break;

                            case ("Items"):

                                FoodJournalNoSQL.LoadItems(true, change.Contents);
                                break;

                            case ("UserSettings"):

                                UserSettings.ReplaceWith(change.Contents);

                                break;

                            case ("AppStats"):

                                //if (change.Contents.Contains("<InstalledProductKind>Paid</InstalledProductKind>"))
                                //	AppStats.Current.RegisterPurchase("Reinstall");

                                break;

                            default:
                                System.Diagnostics.Debug.WriteLine(string.Format("Not applying remote changes {0} {1} {2}", change.Type, change.Key, change.ClientTime));
                                break;
                            }
                        } catch (Exception ex) {
                            LittleWatson.ReportException(ex, string.Format("Applying changes {0} {1} {2}", change.Type, change.Key, change.ClientTime));
                        }

                        bool found = false;
                        foreach (var app in state.Apps)
                        {
                            if (app.InstanceGuid == change.AppInstance)
                            {
                                found       = true;
                                app.SetDate = change.ClientTime;
                            }
                        }

                        if (!found)
                        {
                            state.Apps.Add(new ConnectedApp()
                            {
                                InstanceGuid = change.AppInstance, LastestChange = DateTime.MinValue, SetDate = change.ClientTime
                            });
                        }
                    }

                    if (changes.Count == 0 || !GoAgain)
                    {
                        state.Skip = 0;
                        foreach (var app in state.Apps)
                        {
                            app.LastestChange = app.SetDate;
                        }
                    }
                    foreach (DateTime date in ChangedDates)
                    {
                        FoodJournalNoSQL.StartSaveDayFull(date);
                    }

                    SaveState();
                } catch (Exception ex) {
                    LittleWatson.ReportException(ex, "Saving state");
                } finally {
                    Loading = false;
                }

                if (GoAgain)
                {
                    StartLoad();
                }
            }
                                 );
        }
Пример #4
0
        public static void Migrate()
        {
            try
            {
                                #if WINDOWS_PHONE
                FoodJournalDB db = new FoodJournalDB(false);
                                #else
                FoodJournalDB db = new FoodJournalDB(true);
                                #endif

                if (!db.DatabaseExists())
                {
                    return;
                }

                if (db.Table <FoodItemDO>().Count() == 0 && db.Table <EntryDO>().Count() == 0)
                {
#if !WINDOWS_PHONE
                    db.Close();
#endif
                    Logging.SessionLog.RecordMilestone("Deleting Legacy FoodItem DB", "");
                    db.DeleteDatabase();
                    return;
                }

                                #if !WINDOWS_PHONE
                if (System.IO.File.Exists(DatabaseFilePath))
                {
                    db.Close();
                    System.IO.File.Copy(DatabaseFilePath, DatabaseFilePath.Replace(".db3", ".bak"));
                    db = new FoodJournalDB(true);
                }
                                #endif

                DateTime start = DateTime.Now;

                int ExceptionCount            = 0;
                Dictionary <int, int> itemmap = new Dictionary <int, int>();

                Logging.SessionLog.RecordTraceValue("Database migration - item count", db.Table <FoodItemDO>().Count().ToString());
                Logging.SessionLog.RecordTraceValue("Database migration - selection count", db.Table <EntryDO>().Count().ToString());

                var AllItems      = db.Table <FoodItemDO>().ToList();
                var AllSelections = db.Table <EntryDO>().ToList();

                List <FoodItemDO> ToDeleteItems      = new List <FoodItemDO>();
                List <EntryDO>    ToDeleteSelections = new List <EntryDO>();

                Dictionary <int, String> items     = new Dictionary <int, string>();
                List <DateTime>          savedates = new List <DateTime>();

                foreach (FoodItemDO item in AllItems)
                {
                    try
                    {
                        items.Add(item.Id, item.TextDB);

                        var NewItem = new FoodJournal.Model.FoodItem(item.TextDB, false);

                        NewItem.Culture        = item.Culture;
                        NewItem.DescriptionDB  = item.DescriptionDB;
                        NewItem.LastAmountDB   = item.LastAmountDB;
                        NewItem.NutritionDB    = item.NutritionDB;
                        NewItem.ServingSizesDB = item.ServingSizesDB;
                        NewItem.SourceID       = item.SourceID;

                        Cache.MergeItem(NewItem);

                        ToDeleteItems.Add(item);
                    }
                    catch (Exception ex) { ExceptionCount++; LittleWatson.ReportException(ex); }
                }

                foreach (EntryDO entry in AllSelections)
                {
                    try
                    {
                        var entryDate = DateTime.Parse(entry.Date);

                        var NewSelection = new FoodJournal.Model.Entry(entryDate, entry.Period, items[entry.FoodItemId]);
                        NewSelection.AmountScaleDB    = entry.AmountScaleDB;
                        NewSelection.AmountSelectedDB = entry.AmountSelectedDB;

                        Cache.AddEntry(NewSelection);

                        ToDeleteSelections.Add(entry);

                        if (!savedates.Contains(entryDate))
                        {
                            savedates.Add(entryDate);
                        }
                    }
                    catch (Exception ex) { ExceptionCount++; LittleWatson.ReportException(ex); }
                }

                foreach (Period period in PeriodList.All)
                {
                    foreach (DateTime date in savedates)
                    {
                        FoodJournalNoSQL.StartSaveDay(date, period);
                    }
                }

                int i = 120;
                while (i-- > 0 && FoodJournalNoSQL.IsSaving())
                {
                    System.Threading.Thread.Sleep(500);
                }

                if (i == 0)
                {
                    SessionLog.RecordMilestone("Upgrade failed in 1 minute", AllSelections.Count.ToString());
                    throw new Exception("Upgrade failed in 1 minute");
                }

                foreach (EntryDO Selection in ToDeleteSelections)
                {
                    try
                    {
                                                #if WINDOWS_PHONE
                        db.Table <EntryDO>().DeleteOnSubmit(Selection);
                        db.SubmitChanges();
                                                #else
                        db.Delete <EntryDO>(Selection.Id);
                                                #endif
                    }
                    catch (Exception ex) { db = new FoodJournalDB(false); ExceptionCount++; LittleWatson.ReportException(ex); }
                }

                foreach (FoodItemDO Item in ToDeleteItems)
                {
                    try
                    {
                                                #if WINDOWS_PHONE
                        db.Table <FoodItemDO>().DeleteOnSubmit(Item);
                        db.SubmitChanges();
                                                #else
                        db.Delete <FoodItemDO>(Item.Id);
                                                #endif
                    }
                    catch (Exception ex) { db = new FoodJournalDB(false); ExceptionCount++; LittleWatson.ReportException(ex); }
                }

                Logging.SessionLog.RecordMilestone("Database migration - exception count", ExceptionCount.ToString());
                Logging.SessionLog.RecordMilestone("Database migration - duration", string.Format("{0} s", DateTime.Now.Subtract(start).TotalSeconds));
            }
            catch (Exception ex) { LittleWatson.ReportException(ex); }
        }