Knowledge is power. We love to share it.

News related to Mono products, services and latest developments in our community.

ivan-cagalj

Storing data in Windows Phone 7

06/29/2012

Data persistance is one of the most important aspects of any application. In my last post, I have described data binding with a simple book list application, but I didn’t implement the persistance mechanism for the list that were created. In this simple scenario, when you navigate from the main page, a list is deleted from the memory and all work is lost. Of course, this cannot happen in the real world app. Windows Phone 7 framework provides us with several methods for saving data. You can use them to preserve application state or to save processed content.

When writing application for Windows Phone, we must consider application lifetime defined in the execution model. Limited hardware resources, mostly CPU and RAM, are to blame when smartphone starts to act slow and nonresponsive. To overcome this problem, Windows Phone 7 application lifecycle is shortened  and optimized to insure that application runs smoothly. Only one application is allowed to run in foreground and has the highest priority, while other applications can run in background or can be in suspended state to minimize the resources used.

There are two types of data we are usually saving:

  • Page and application settings
  • Application data

 

User interface

First, create a new Windows Phone project. Open MainPage.xaml in design mode and add one text box to the content panel. Name it txtNote and resize it to fill the free space on the content panel. Find property TextWrapping and set it to Wrap, and clean the default text. When finished, It should look like this.

image

 

Page and application settings

Windows Phone 7 users can navigate forward or backwards through the stack of running applications. They can start application from a tile on Start, and go backwards using the Back button. Other than that, applications can be interrupted by Launchers or Choosers. Launchers are APIs that applications can use to enable tasks such as making phone calls or sending emails. Choosers are APIs that applications can use to launch built-in applications, which return some data to the calling application. When the user presses the Back button, the application is terminated. However, when the user presses the Start button (or start via launcher or chooser) the application is not terminated, but put into suspended state, where the system is maintaining application state. If the user returns, the application is resurrected and the application state is restored. This is called tombstoning.  With Mango, Microsoft introduced Dormant as a new state of the application. If there is enough memory left, the Windows Phone leaves the process of your application in memory. User can than use the new fast switch function and return to the switched application. 

Preserve and Restore Page State

While in Dormant state, application’s data is preserved in the phone memory. When application is tombstoned, Windows Phone OS frees occupied memory by terminating all processes but a static dictionary State object in PhoneApplicationPage class. If the user navigates back, application can use the data stored in that object to restore application state so that it appears to be in the same state as it was when the user navigated away. This technique can be used only for user interface restoration since it doesn’t permanently save data and state is destroyed when application is terminated.

Code example:

   1: public partial class MainPage : PhoneApplicationPage
   2: {
   3:     bool _isNewPageInstance = false;
   4:     public MainPage()
   5:     {
   6:         InitializeComponent();
   7:         _isNewPageInstance = true;
   8:     }
   9:     protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
  10:     {
  11:         if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
  12:         {
  13:             PhoneApplicationService.Current.State.Clear();
  14:             PhoneApplicationService.Current.State.Add("AppNote", txtNote.Text);
  15:         }
  16:     }
  17:     protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
  18:     {
  19:         if (_isNewPageInstance)
  20:         {
  21:             if (PhoneApplicationService.Current.State.ContainsKey("AppNote"))
  22:                 txtNote.Text = PhoneApplicationService.Current.State["AppNote"] as string;
  23:         }
  24:         _isNewPageInstance = false;
  25:     }
  26: }
_isNewPageInstance flag makes sure that saved note is restored only if the new application instance is created. This means that application was tombstoned and removed from memory.
 

Preserve and Restore Application State

Application state is used for persistent data, required between different runs of the application. It can be used both when the application is tombstoned or completely terminated, and it provides a simple way to restore the user interface or to preserve the application settings.

Code example:

   1: public partial class MainPage : PhoneApplicationPage
   2: {
   3:     bool _isNewPageInstance = false;
   4:     public MainPage()
   5:     {
   6:         InitializeComponent();
   7:         _isNewPageInstance = true;
   8:     }
   9:     protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
  10:     {
  11:         IsolatedStorageSettings.ApplicationSettings.Clear();
  12:         IsolatedStorageSettings.ApplicationSettings.Add("AppNote", txtNote.Text);
  13:     }
  14:     protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
  15:     {
  16:         if (_isNewPageInstance)
  17:         {
  18:             if (IsolatedStorageSettings.ApplicationSettings.Contains("AppNote"))
  19:                 txtNote.Text = IsolatedStorageSettings.ApplicationSettings["AppNote"] as string;
  20:         }
  21:         _isNewPageInstance = false;
  22:     }
  23: }

 

Application Data

All previously described methods are excellent when you want to create simple application with small memory footprint like in our example. If you want to work with files (pictures, music….) you must use Isolated Storage. In Windows Phone 7, every installed application gets isolated storage space for its needs. Isolated means that this space is exclusively reserved for your application and other applications don’t have access to it. Sharing data between applications is possible only by using another storage resource like network share or cloud services. Isolated storage management is implemented in System.IO.IsolatedStorage namespace, in the IsolatedStorageFile class.  

Isolated storage file

When instanced, IsolatedStorageFile object has methods for file and folder manipulation. Most of them are similar to their System.IO namespace counterparts, so you should be familiar with their functionality. IsolatedStorageFileStream is a class that exposes file in the isolated storage and allows file content manipulation.

Code example:

   1: public partial class MainPage : PhoneApplicationPage
   2: {
   3:     bool _isNewPageInstance = false;
   4:  
   5:     public MainPage()
   6:     {
   7:         InitializeComponent();
   8:         _isNewPageInstance = true;
   9:  
  10:     }
  11:  
  12:     protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
  13:     {
  14:         IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
  15:         FileMode mode = FileMode.CreateNew;
  16:  
  17:         if (store.FileExists("appNote.txt"))
  18:             mode = FileMode.Truncate;
  19:  
  20:  
  21:         using (var stream = new IsolatedStorageFileStream("appNote.txt", mode, store))
  22:         {
  23:             using (var fileWriter = new StreamWriter(stream))
  24:             {
  25:                 fileWriter.Write(txtNote.Text);
  26:             }
  27:         }
  28:     }
  29:  
  30:     protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
  31:     {
  32:         if (_isNewPageInstance)
  33:         {
  34:             IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
  35:             if (store.FileExists("appNote.txt"))
  36:             {
  37:                 using (var stream = new IsolatedStorageFileStream("appNote.txt", FileMode.Open, store))
  38:                 {
  39:                     using (var fileReader = new StreamReader(stream))
  40:                     {
  41:                         txtNote.Text = fileReader.ReadToEnd();
  42:                     }
  43:                 }
  44:             }
  45:         }
  46:  
  47:         _isNewPageInstance = false;
  48:     }
  49: }

 

Database

Windows Phone 7 supports SQL CE database for storing relational data. The database file is actually stored in application’s isolated storage container, and to store and retrieve data in a local database application uses LINQ to SQL. This will be covered in our future posts.

Rated 2.00, 8 vote(s). 
Can you tell me how to Windows Phone 7 supports SQL CE database for storing relational data.and how cam i store data on permently with example.I hope you will sure help me.thanks in advance .please help me.
ivan-cagalj
Hi,
I am currently involved in some other projects, so I took a brake from Windows Phone development. Since you have shown an interest to this topic I decided to write an article about using SQL CE database on Windows Phone. It will be done in month or two so stay tuned. In the meantime, I will post a list of links just to get you started.
Kind regards,
Ivan
ivan-cagalj
There are some links I promised:
http://www.fiveminutes.eu/storing-local-data-on-windows-phone-7/
http://dotnet.dzone.com/articles/resources-using-sql-server
http://www.codeproject.com/Articles/249208/Extracting-a-SQL-CE-DB-from-Isolated-Storage-in-WP
http://www.codeproject.com/Articles/230380/LINQ-to-SQL-Advanced-Concepts-and-Features
http://msdn.microsoft.com/en-us/data/jj193542.aspx

hope you will find it useful.
Bye