Using Isolated Storage on Windows Phone

On a Windows Phone application, or actually in any application, you will sometimes want to keep information around from one session to another. On a Windows Phone it is sometimes especially important as it is a little difficult to type on these small devices. If you need the user to login, fill in their name and email, or enter other information each time they use the application, then you might want to store that data on the phone and retrieve it each time they come back in to the application. Isolated storage is the place where you are can store this information for your application.

This article assumes that you have VS.NET 2010 and the Windows Phone tools installed along with it. The Windows Phone tools must be downloaded separately and installed with VS.NET 2010. You may also download the free VS.NET 2010 Express for Windows Phone developer environment.

Store Data On Your Phone 

Figure 1: Store Data on your Phone

The LastUser Class

For this example, I will be taking the data from the screen and putting it into a class called “LastUser”. This class is shown in the code below:

public class LastUser : INotifyPropertyChanged {
  #region INotifyPropertyChanged Event
  public event PropertyChangedEventHandler PropertyChanged;

  protected void RaisePropertyChanged(string propertyName)  {
    if (PropertyChanged != null)
      PropertyChanged(this,
        new PropertyChangedEventArgs(propertyName));
  }

  private string mFirstName = string.Empty;
  private string mLastName = string.Empty;
  private string mEmail = string.Empty;

  public string FirstName  {
    get { return mFirstName; }
    set {
      mFirstName = value;
      RaisePropertyChanged("FirstName");
    }
  }

  public string LastName  {
    get { return mLastName; }
    set {
      mLastName = value;
      RaisePropertyChanged("LastName");
    }
  }

  public string Email  {
    get { return mEmail; }
    set {
      mEmail = value;
      RaisePropertyChanged("Email");
    }
  }
}

This class implements the INotifyPropertyChanged interface as I want the user interface to automatically update when I load this data into an instance of this class.

Hooking up this Class to the Page

In the sample page (shown in Figure 1) you will need to bind the LastUser class to the DataContext of this page. In the page class create an instance of the LastUser class like the shown here:

private LastUser _User = new LastUser();

In the Loaded event procedure for the page you will set the DataContext of the page to the _User variable as shown here:

private void PhoneApplicationPage_Loaded(object sender,
 RoutedEventArgs e)
{
  this.DataContext = _User;
}

The first time in, this user class will be completely blank. All of the text boxes on the XAML page that are bound to each of the properties in the LastUser class will also be blank. Later you will add two additional lines of code to the Loaded event procedure to retrieve user data stored, but first let’s learn to store a user into isolated storage.

Storing Data into Isolated Storage

After the user has filled in some information on this phone page and click the Submit button you will save the data from the LastUser class into isolated storage. After you save the user data you will then redirect back to the main page.

private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
  SaveUser();
  NavigationService.Navigate(new Uri("/MainPage.xaml",
     UriKind.Relative));
}

The SaveUser Method

The SaveUser method will take the data from the _User variable and serialize it as an XML string so it can be stored into isolated storage. The process for serializing an object into XML is the same on Windows Phone as in any other .NET application.

You create an instance of the XmlSerializer class passing in the Type of LastUser. You call the Serialize method on the XmlSerializer object to convert all the properties of the LastUser object to Xml and store the result into a MemoryStream. Next, use a StreamReader class to read the MemoryStream and convert that memory stream into an XML string (stored in the “xml” variable). Finally you use the IsolatedStorageSettings.ApplicationSettings to create a new key (in this case a constant USER_KEY defined as “LastUser”) and store the data in the “xml” variable into storage.

private void SaveUser()
{
  string xml = string.Empty;

  using (MemoryStream ms = new MemoryStream())
  {
    XmlSerializer serializer = new XmlSerializer(typeof(LastUser));
    serializer.Serialize(ms, _User);
    ms.Position = 0;

    using (StreamReader reader = new StreamReader(ms))
      xml = reader.ReadToEnd();
  }

  // Store user in Isolated Storage
  IsolatedStorageSettings.ApplicationSettings[USER_KEY] = xml;
}

NOTE: The USER_KEY is a constant defined in the page class as shown below:

private const string USER_KEY = "LastUser";

Checking if Data Exists

The next time you come into this phone page, after storing the user data, you will want to retrieve that data and fill it into the _User variable. You will now add two more lines to the Loaded event procedure to detect if the data has been stored into isolated storage with the key name of USER_KEY (“LastUser”). For this you use the ApplicationSettings.Contains method to check to see if the USER_KEY key name is in isolated storage. If the key exists, you will call the GetUser method to retrieve the data.

private void PhoneApplicationPage_Loaded(object sender,
  RoutedEventArgs e)
{
  if (IsolatedStorageSettings.ApplicationSettings.
        Contains(USER_KEY))
    GetUser();

  this.DataContext = _User;
}

The GetUser Method

The GetUser method is just the opposite of the SaveUser method. This method will use the IsolatedStorageSettings.ApplicationSettings to retrieve the data as a string from the key USER_KEY. You now need to take the string and convert it into a stream. I am using a MemoryStream object in the code below and calling the GetBytes method on the Unicode object to convert the string into a byte array. Once in the byte array, you create an instance of the XmlSerializer and use the Deserialize method to convert the byte array in the memory stream back into an instance of the LastUser class.

private void GetUser()
{
  string xml;

  xml =
  IsolatedStorageSettings.ApplicationSettings[USER_KEY].ToString();
  using (MemoryStream ms = new
          MemoryStream(Encoding.Unicode.GetBytes(xml)))
  {
    XmlSerializer serializer = new XmlSerializer(typeof(LastUser));
    _User = (LastUser)serializer.Deserialize(ms);
  }
}

After you have deserialized the data from isolated storage and placed it into the _User variable, the data will automatically display in the bound text boxes on the page.

Summary

You have now seen how easy it is to store data from one invocation of your phone app to another. I added two pages within the phone application so you can see that the data does indeed stick around in between calls to the pages. You need to do this because on the emulator you can’t save the data in isolated storage because it is wiped out each time you stop and start your project in VS.NET. However, on a real Windows Phone, the storage will stay around in between each instance of running the application.

NOTE: You can download the complete sample code at my website. http://www.pdsa.com/downloads. Choose Tips & Tricks, then "Using Isolated Storage on Windows Phone" from the drop-down.

Good Luck with your Coding,
Paul Sheriff

** SPECIAL OFFER FOR MY BLOG READERS **
Visit http://www.pdsa.com/Event/Blog for a free video on Silverlight entitled Silverlight XAML for the Complete Novice - Part 1.

 

Past Blog Content

Blog Archive

No Comments