0
[DataContract]
class UserData
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public int ID { get; set; }

    [DataMember]
    public int phoneNumber { get; set; }

    [DataMember]
    public string Course { get; set; }
    [DataMember]
    public Uri Image { get; set; }
}

[DataContract]
class UserItems
{
    [DataMember]
    static ObservableCollection<UserData> _items = new ObservableCollection<UserData>();
    [DataMember]
    public static ObservableCollection<UserData> Items
    {
        get { return _items; }
    }

and this is the AppDataManager class

class AppDataManager
{
    public static async Task SaveAsync<T>(T data, string fileName)
    {

        StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, 
            CreationCollisionOption.GenerateUniqueName);


        var stream = await file.OpenStreamForWriteAsync();
        var serializer = new DataContractSerializer(typeof(T));

        serializer.WriteObject(stream ,data);
        await stream.FlushAsync();
    }

    public static async Task<T> RestoreAsync<T>(string fileName)
    {
        try
        {
            var file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);

            var instream = await file.OpenStreamForReadAsync();
            var serializer = new DataContractSerializer(typeof(T));
            return (T)serializer.ReadObject(instream);
        }
        catch (Exception)
        {
            return default(T);
        }
    }
}
}

I tried to save one object and it worked, but the collection is my problem, the app im working with is to save the user data every time he entered the data.

The question is : How to save the collection of data and how to retrieve it as a collection of data?

mipe34
  • 5,596
  • 3
  • 26
  • 38
Ibraheem Al-Saady
  • 854
  • 3
  • 14
  • 30
  • this post may help: http://stackoverflow.com/questions/13923600/how-to-save-observablecollection-in-windows-store-app – Jim O'Neil Jan 19 '13 at 17:31
  • 1
    UserItems._items is private and UserItems.Items has no setter. Better to mark the property only as a DataMember and give it a setter. If it is RestoreAsync only that was failing, then you have you answer – kindasimple Jan 20 '13 at 02:56

1 Answers1

0

Check this link, it's about the Windows Phone environment but i think it's also applicable in your case: http://geekswithblogs.net/mikebmcl/archive/2010/12/29/datacontractserializer-type-is-not-serializable-because-it-is-not-public.aspx. Decorating your _items private member with the DataMember attribute might be the issue.

If not that, maybe ObservableCollection<T> doesn't play nicely with the DataContractSerializer, so instead you could use a regular List<T> backing up the observable collection and marking that list instead as a DataMember.

Gabriel S.
  • 1,347
  • 11
  • 31