4

I am trying to store a list of objects I created in the isolated storage and be able to display them in a list by auto generating a title for them. So far the code works but once I tombstone the app and start it up all my data is saved except for the list of objects. I think my problem may be with how I initialize the list in the first place, or possibly how I am displaying the names. Any help is appreciated.

this code is in my App.xaml.cs:

public partial class App : Application
    {
      public List<my_type> testList = new List<my_type>();

        void loadvalues()
        {
         IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
         List<my_Type> L;
         if (settings.TryGetValue<List<DrinkSesh>>("Storage", out L))
         { testList = L; }
        }

        void savevalues()
        {
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
        settings["Storage"] = testList;
        settings.Save();
        }
     }

This code is on my mainPage to add the items to the list:

(Application.Current as App).testList.Add(new my_type());

and this code is to implement the titles onto the screen on a different page:

 public different_class()
{
        {
                InitializeComponent();
                for (i = 0; i < (Application.Current as App).testList.Count; i++)
                {
                    CreateATextBlock((Application.Current as    App).testList[i].Title_ToString(), i);
                }
        }

        private void CreateATextBlock(String title,int num)
        {
            testblockname = new TextBlock();
            testblockname.Text = (num + 1) + ". " + title;
            DrList.Children.Add(testblockname);
        }
}

Thank you in advance!

2 Answers 2

7

Here is the code I use to save and load lists of objects from isolated storage.

public class IsoStoreHelper
{
    private static IsolatedStorageFile _isoStore;
    public static IsolatedStorageFile IsoStore 
    { 
        get { return _isoStore ?? (_isoStore = IsolatedStorageFile.GetUserStoreForApplication()); }
    }

    public static void SaveList<T>(string folderName, string dataName, ObservableCollection<T> dataList) where T : class
    {
        if (!IsoStore.DirectoryExists(folderName))
        {
            IsoStore.CreateDirectory(folderName);
        }

        string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);

        using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileStreamName, FileMode.Create, IsoStore))
        {
            DataContractSerializer dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
            dcs.WriteObject(stream, dataList);
        }
    }

    public static ObservableCollection<T> LoadList<T>(string folderName, string dataName) where T : class
    {
        ObservableCollection<T> retval = new ObservableCollection<T>();

        if (!IsoStore.DirectoryExists(folderName))
        {
            IsoStore.CreateDirectory(folderName);
        }

        string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);

        using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileStreamName, FileMode.OpenOrCreate, IsoStore))
        {
            if (stream.Length > 0)
            {
                DataContractSerializer dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
                retval = dcs.ReadObject(stream) as ObservableCollection<T>;
            }
        }

        return retval;
    }
}
5
  • Thanks for the example Steve, but I am getting this error when I implement it: "Operation not permitted on IsolatedStorageFileStream" I think it is how I have my folderName expressed. here is my load usage: testList = IsoStoreHelper.LoadList<DrinkSesh>("Storage/", "Storage");
    – RJDubz
    Feb 23, 2011 at 3:25
  • Remove the slash from the end of the first parameter. If that doesn't work try changing the name Storage to something else eg ("Session", "DrinkSesh") Feb 23, 2011 at 7:32
  • I have tried that however I still get the error. It seems to only fail with the load method not the save. I still am confused on where to declare my list. right now it is just at the top of the App class like so: public ObservableCollection<DrinkSesh> testList=new ObservableCollection<DrinkSesh>(); I'm sorry for my stupidity with silverlight I just feel like I am doing something fundamentally wrong here because it will create new instances of the list each time it opens or activates the app am I wrong?
    – RJDubz
    Feb 23, 2011 at 21:12
  • 1
    Actually I just fixed it! Been working on that problem for about a week. Turns out I was doing something fundamentally wrong...I was declaring my variables in the DrinkSesh class as private not public. I did not realize this was necessary, but then it worked with my original saving code. I will continue to fiddle with your method because it is a better way, but now at least its functioning! Thanks for all your help.
    – RJDubz
    Feb 23, 2011 at 21:34
  • @SteveChadbourne I am getting System.NullReferenceException in line - retval = dcs.ReadObject(stream) as List<MyContact>; of LoadList<T> method. Don't know why!! Oct 9, 2013 at 19:56
2

By simply adding your collection (List) to your IsolatedStorageSettings you are relying on the built in serializer (the DataContractSerializer) to serialize your object for persisting to disk.

Are you sure your object can be correctly serialized and deserialized?

Doing this yourself is probably the easiest way to do this.

If you do this yourself, not that: - DataContractSerializer is slow - DataContractJsonSerializer is faster - Json.net is faster still - Binary serialization is fastest.

When serializing yourself you should also save in an IsolatedStorageFile rahter than in the settings. This can help with performance and also adds flexibility which can aid debugging and testing.

2
  • Thanks for the tip Matt. Is DataContractJsonSerializer built into WP7 API's? Seem to remember it's not? Any egs on Binary Serialization? Feb 23, 2011 at 7:37
  • @SteveChadbourne DataContractJsonSerializer is in the System.ServiceModel.Web.dll assembly.
    – Matt Lacey
    Feb 23, 2011 at 9:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.