0

So, I'm developing a contact management system and I'm trying to add a contact. Instead of jumping between ViewModels(the contact and main contact page are separate), I've decided to take in data from the view, create a contact, add it to a list then serialize that list. Then, when I get back to the main page, I deserialize that list.

This works fine(no optimization, this is just a simple college project) as the data is added to the JSON file. My problem is- when I navigate back to the main page- the list doesn't update due to an UnauthorisedAccessException on my stream. The deserialization method is:

             private async void buildMyListWithJsonAsync(){
            ObservableCollection<Contact> list = new ObservableCollection<Contact>();
            try
            {
                string JSONFILENAME = "contacts.json";
                string content = " ";
                StorageFile File = await ApplicationData.Current.LocalFolder.GetFileAsync(JSONFILENAME);
                using (IRandomAccessStream testStream = await File.OpenAsync(FileAccessMode.Read)){
                    using (DataReader dreader = new DataReader(testStream)){
                        uint length = (uint)testStream.Size;
                        await dreader.LoadAsync(length);
                        content = dreader.ReadString(length);
                        list = JsonConvert.DeserializeObject<ObservableCollection<Contact>>(content);
                    }


                }
                contactlist = new ObservableCollection<Contact>();
                foreach (Contact c in list)
                 contactlist.Add(c); 

            }
            catch (Exception e)
            { e.ToString(); }
        }

Any help or aid would be appreciated.

Adam
  • 23
  • 1
  • 7

1 Answers1

0

I'd hazard an educated guess that the issue is around threading and your ObservableCollection. ObservableCollections aren't threadsafe and involve raising events on the UI thread they're created on typically & StorageFile API is all async thread based. Have a shot at pulling the string back from the async thread and doing the Serialization and Deserialization on the main UI thread instead and that may well resolve it.

mcr
  • 762
  • 5
  • 19
  • I'm sorry, I'm not entirely sure about what you're suggesting I do. The stream excepts when I return... But, when I use the same stream to display the list on app start, it runs through without an error. – Adam Mar 19 '15 at 18:02
  • 1
    I think I misread your original post as the exception being raised by the Deserialize (or at least by its use), whereas it sounds like it's a file permission thing the 2nd time you try to access the file whereas the first time works fine? If so, it sounds like the file is being held onto by the previous access and needs some explicit releasing. Does this questions answer work for you : http://stackoverflow.com/a/11243593/4670514 – mcr Mar 19 '15 at 22:58