(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .

WP7 for iPhone and Android Developers - Local Data Storage

(4 votes)
Kevin Hoffman
>
Kevin Hoffman
Joined Feb 01, 2011
Articles:   10
Comments:   1
More Articles
1 comments   /   posted on Jul 04, 2011
Tags:   windows-phone-7 , android , iphone , ios , data-storage , kevin-hoffman
Categories:   Data Access , Windows Phone

This is the 8th article in a series of articles that introduce Windows Phone 7 development to developers of other mobile platforms such as iOS and Android. In this article, we’ll talk about some of the various options for storing and retrieving application-specific data on the phone.

When mobile developers build applications, one of the first things they need to decide is how they plan on storing data on the device. When you build a desktop application, this is rarely a concern. Mobile developers typically have less options because the devices have limited resources and, in many cases, the platform SDKs restrict the ways in which the developer can interact with the underlying file system.

For example, when you’re building an application for a mobile device, you can’t simply create and fill random directories wherever you like. In most cases, your application is restricted to operating within a sandbox. In addition to process isolation, this sandbox provides private file storage that is often limited by a maximum storage quota.

iOS developers are lucky in that they get access to Core Data, a framework for storing and querying relational data. Developers can visually model their database and generate Objective-C entity classes which they can use as parent classes for derived functionality. With iOS, Core Data can read and write SQLite database files. With the current version of Windows Phone 7, we have no such luxuries and are limited to using lower level facilities. However, when the “Mango” release of WP7 is made available (currently in Beta 2), developers will be able to build code-first LINQ to SQL database models that are backed by a compact, file-based SQL engine that runs on the phone.

Windows Phone 7 developers can access a private, sandboxed file store called Isolated Storage to read and write arbitrary files, so long as the app doesn’t exceed its allotted quota. In addition to arbitrary files, there is also an API designed to make it easier for developers to read and write configuration settings within the application’s Isolated Storage folder.

Reading and Writing Application Settings

If the information you plan on storing and retrieving can be reduced to a relatively small amount of key-value pairs then you can probably avoid the complexity of working directly with files and instead make use of the IsolatedStorageSettings class. This class provides a wrapper around a file that the SDK can maintain for you, which in turn contains key-value pairs.

To access your application’s settings, you use the ApplicationSettings property of the IsolatedStorageSettings class. Manipulating settings looks very much like adding and removing keys from a dictionary:

 1: var appSettings = IsolatedStorageSettings.ApplicationSettings;
 2: settings.Add("ZombieKillCount", 21);
 3:  
 4: // later on, retrieve a setting
 5: viewModel.ZombieKillCount = (int)appSettings["ZombieKillCount");

You’ll find the IsolatedStorageSettins class in the namespace System.IO.IsolatedStorage. You don’t need to manually save the application settings to isolated storage because they will be saved when the application terminates normally through any of the standard means. If you want to manually save the data to isolated storage then just call the Save() method on the ApplicationSettings object.

You don’t have to just store primitive types like integers and strings. If you really want to, you can store virtually any type of object. However, I won’t even show the sample code for doing so because it is generally considered bad practice. You should keep the settings stored using this API as primitive as possible. If you need to store more complicated data, you should do so using an Isolated Storage File, which we’ll talk about next.

Using Isolated Storage

As mentioned earlier, Windows Phone 7 applications all have their own private sandboxes in which their AppDomain runs in a way that cannot negatively impact other applications. In addition, any storage access made by that application has to go through Isolated Storage. On Windows desktop machines, Isolated Storage provides a means for storing disk without giving applications destructive privilege and the same principle is behind the fact that its use is mandatory (as in, it’s the only option) on WP7. Even in the upcoming “Mango” release, the local SQL databases available to developers are still files stored in Isolated Storage.

In the current version of WP7, the WP7 device emulator has a quirky behavior where it will wipe the contents of isolated storage between application executions. If you run into this behavior, debugging and testing your application can become painful and tedious – at this point you might want to switch to writing against the “Mango” beta, whose simulator appears to be free of such quirks.

Isolated Storage provides an API that looks like a file folder structure. When you obtain a reference to an existing or newly created file in an isolated store, your only option for interacting with that file via Streams. Many of the existing .NET desktop classes and methods for accessing files are just wrappers around the lower level streams API.

The easiest way of reading and writing file-backed data with Isolated Storage is to use binary serialization of object instances and to store and retrieve the binary version of those objects as files. For example, let’s say you have a file that you want to use to store a player’s profile for your game. You might create a class that looks something like this for representing the data:

 1: using System.Runtime.Serialization;
 2:  
 3: namespace MyAwesomeGame.Models
 4: {
 5:     [DataContract]
 6:     public class Gamer
 7:     {
 8:         [DataMember]
 9:         public string Name { get; set; }
 10:  
 11:         [DataMember]
 12:         public string Description { get; set; }
 13:  
 14:         [DataMember]
 15:         public int KillCount { get; set; }
 16:     }
 17: }

Standard object serialization is not available in the current version of WP7. However, because a full implementation of WCF is available (including the binary protocol formats), we do have access to the WCF data contract serializer, which can convert any object into an array of bytes – exactly what we need to talk to an isolated storage file.

Next, we just need to write the code that creates an isolated storage file, converts an object instance into an array of bytes, and stores those bytes in a file. Here are some utility methods in a helper class that read and write object graphs from isolated storage:

 1: namespace IsolatedStorageDemo
 2: {
 3:     public static class IsoStoreHelper
 4:     {
 5:         public static void WriteGraphToFile<T>(string filename, T sourceObject)
 6:         {
 7:             using (IsolatedStorageFile isf =
 8:                 IsolatedStorageFile.GetUserStoreForApplication())
 9:             {
 10:                 using (IsolatedStorageFileStream stream =
 11:                   new IsolatedStorageFileStream(filename, FileMode.Create, isf))
 12:                 {
 13:                     DataContractSerializer dcs = new DataContractSerializer(typeof(T));
 14:                     dcs.WriteObject(stream, sourceObject);
 15:                     stream.Close();
 16:                 }
 17:             }
 18:         }
 19:  
 20:         public static T ReadGraphFromFile<T>(string filename) where T:class
 21:         {
 22:             T result = null;
 23:             using (IsolatedStorageFile isf = 
 24:                 IsolatedStorageFile.GetUserStoreForApplication())
 25:             {
 26:                 using (IsolatedStorageFileStream stream =
 27:                     new IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, isf))
 28:                 {
 29:                     if (stream.Length > 0)
 30:                     {
 31:                         DataContractSerializer dcs = new DataContractSerializer(typeof(T));
 32:                         result = dcs.ReadObject(stream) as T;
 33:                     }
 34:                 }
 35:             }
 36:  
 37:             return result;
 38:         }
 39:     }
 40: }

Again, you’ve got to keep in mind that even though you can seemingly write unlimited amount of data to the storage file, this is still a mobile device with a limited amount of disk space and each application is only allocated a certain amount of storage. If you find your application needs access to a much larger volume of data, consider storing that data in the cloud and accessing it via web services, which is the topic of the next article in this series.

Summary

Windows Phone 7 represents a fantastic opportunity for developers of all  backgrounds to take advantage of an incredibly powerful mobile development platform. In this article, I talked about the two main ways WP7 developers persist data locally on the device – via application settings and via files. Both of these options are backed by Isolated Storage, .NET’s secure, sandboxed, quota-limited storage area.


Subscribe

Comments

  • JonBonning

    Re: WP7 for iPhone and Android Developers - Local Data Storage


    posted by JonBonning on Apr 19, 2012 15:52

    Just wondering if/when WP7 will be moving to a core data access platform similar to that of iOS? It really is much more convenient for application development and in my experience makes for faster loading and running applications.

Add Comment

Login to comment:
  *      *       

From this series