static public async Task UpdateWatchedToasts(List <WhirlMonData.WhirlPoolAPIData.WATCHED> watched) { try { ToastedDictionary toasted = await ReadToasted(); // debug // toasted.Clear(); // Remove obsoleted toasts - iterate over toasted List <int> keysToRemove = new List <int>(); foreach (var id in toasted.Keys) { // Find var w = watched.Find(x => x.ID == id); if (w == null) { ClearWatchedToast(id); keysToRemove.Add(id); } } foreach (var id in keysToRemove) { toasted.Remove(id); } // add/update Toasts foreach (var w in watched) { String last; if (toasted.TryGetValue(w.ID, out last)) { // see if updated if (w.LAST_DATE != last) { ShowWatchedToast(w); toasted[w.ID] = w.LAST_DATE; } } else { // new ShowWatchedToast(w); toasted[w.ID] = w.LAST_DATE; } } await WriteToasted(toasted); } catch (Exception x) { ShowErrorToast("UpdateWatchedToasts", x); } }
static private async Task WriteToasted(ToastedDictionary toasted) { try { // Convert to json MemoryStream ms = new MemoryStream(); var serializer = new DataContractJsonSerializer(typeof(ToastedDictionary)); serializer.WriteObject(ms, toasted); ms.Flush(); ms.Position = 0; var sr = new StreamReader(ms); String json = sr.ReadToEnd(); using (Semaphore semFile = new Semaphore(1, 1, TOASTED_SEM)) { if (!semFile.WaitOne(2000)) { throw new Exception("Failed to accquire toast access Semaphore"); } try { // Write To File Windows.Storage.StorageFolder temporaryFolder = ApplicationData.Current.TemporaryFolder; StorageFile toastedFile = await temporaryFolder.CreateFileAsync("toasted.json", CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(toastedFile, json); } finally { semFile.Release(); } } } catch (Exception x) { ShowToast("WriteToasted:" + x.Message); } }
static private async Task <ToastedDictionary> ReadToasted() { try { String json = null; using (Semaphore semFile = new Semaphore(1, 1, TOASTED_SEM)) { if (!semFile.WaitOne(2000)) { throw new Exception("Failed to accquire toast access Semaphore"); } try { Windows.Storage.StorageFolder temporaryFolder = ApplicationData.Current.TemporaryFolder; StorageFile toastedFile = await temporaryFolder.GetFileAsync("toasted.json"); if (!toastedFile.IsAvailable) { return(new ToastedDictionary()); } json = await FileIO.ReadTextAsync(toastedFile); } finally { semFile.Release(); } } // Sanity checks if (json == null) { return(new ToastedDictionary()); } json = json.Trim(); if (String.IsNullOrEmpty(json)) { return(new ToastedDictionary()); } // parse using (MemoryStream ms = new MemoryStream()) { using (StreamWriter wr = new StreamWriter(ms)) { wr.Write(json); wr.Flush(); ms.Position = 0; var serializer = new DataContractJsonSerializer(typeof(ToastedDictionary)); ToastedDictionary td = (ToastedDictionary)serializer.ReadObject(ms); return(td); } } } catch (FileNotFoundException) { return(new ToastedDictionary()); } catch (Exception x) { ShowToast("ReadToasted:" + x.Message); return(new ToastedDictionary()); } }