1

I am creating Windows Store App based on Split App template. What is the best way to save data from SampleDataSource for later use?

I tried:

Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
roamingSettings.Values["Data"] = AllGroups;

It throws exception: 'Data of this type is not supported'.

Jim O'Neil
  • 23,344
  • 7
  • 42
  • 67
Jacob Jedryszek
  • 6,365
  • 10
  • 34
  • 39

1 Answers1

5

RoamingSettings only supports the runtime data types (with exception of Uri); additionally, there's a limitation as to how much data you can save per setting and in total.

You'd be better off using RoamingFolder (or perhaps LocalFolder) for the storage aspects.

For the serialization aspect you might try the DataContractSerializer. If you have a class like:

public class MyData
{
    public int Prop1 { get; set; }
    public int Prop2 { get; set; }
}
public ObservableCollection<MyData> coll;

then write as follows

var f = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("data.txt");
using ( var st = await f.OpenStreamForWriteAsync())
{
    var s = new DataContractSerializer(typeof(ObservableCollection<MyData>), 
                                       new Type[] { typeof(MyData) });
    s.WriteObject(st, coll);

and read like this

using (var st = await Windows.Storage.ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("data.txt"))
{
    var t = new DataContractSerializer(typeof(ObservableCollection<MyData>), 
                                       new Type[] { typeof(MyData) });
    var col2 = t.ReadObject(st) as ObservableCollection<MyData>;

}
Jim O'Neil
  • 23,344
  • 7
  • 42
  • 67
  • During write i get following error: "Type 'MyData' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types." – Jacob Jedryszek Jan 13 '13 at 05:04
  • with your own version of "MyData"? The code that's exactly above should work fine, and does for me. What does your MyData look like? – Jim O'Neil Jan 13 '13 at 05:31
  • It's my own. It's based on default SplitApp template: https://jj09.snipt.net/my-collection-for-save-in-win8/ (MyData=GtdDataGroup) – Jacob Jedryszek Jan 13 '13 at 15:45
  • ok, your scenario is definitely more complex, with collection members, and private fields. The recommendation is sound regarding marking properties with attributes. You may run into some cyclic issues as well with serialization (see IsReference), but with some tweaking I can get your class structure to serialize at least in a quick test. Start decorating your classes with the attributes, and you'll get there! – Jim O'Neil Jan 13 '13 at 17:39