As a user of mobile applications you certainly have used their ability to store local data. Of course you don’t want to re-enter your name, location or profile picture every time you start the application, but instead you tell the application to remember it. As you can see, your name, location and picture are different types of data and Windows Phone 7 platform provides different mechanisms to store local data. In this blog post we`ll discuss those mechanism and provide examples for developers.

Windows Phone 7 doesn’t allow direct access to the OS file system, but instead every application gets the space for its data. This space is accessible only by that application, hence the name Isolated Storage. There are three ways in which application can use its space based on the type of data it needs to save:

1. Settings
Persisting user settings can be done using IsolatedStorageSettings class. This is simple dictionary of key-value pairs where key is of type String and value is of type Object. This way you can save any type of data and access it by its given name. Here is the code example for storing and getting data in the isolated storage:

// Getting the settings object itself
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

// If the key exists
if (settings.Contains("key"))
{
    // Store the new value
    settings["key"] = value;
}
// Otherwise create the key.
else
{
    settings.Add("key", value);
}
// If the key exists, retrieve the value.
if (settings.Contains("key"))
{
    value = (T)settings["key"];
}

2. Files and folders
In case you need to save files there’s IsolatedStorageFile class. The following code will show you how to create and delete folders and read or write files in isolated storage.

// Get the isolated storage object, create and delete folder
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
myStore.CreateDirectory("NewFolder");
myStore.DeleteDirectory("NewFolder");

Creating and writing to a file can be done with following lines:

StreamWriter writer = new StreamWriter(new IsolatedStorageFileStream("NewFolderSomeFile.txt", FileMode.CreateNew, myStore));
writer.Write("some new text");
writer.Close()

Opening existing file and reading from it can be done in this way:

IsolatedStorageFileStream fileStream = myStore.OpenFile("SomeFile.txt", FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fileStream))
{
    String fromFile = reader.ReadLine();
}

3. Database
In case your application have anything more complex than settings and files, you would want to use relational database for data persistence. Since the Windows Phone 7.1 Mango update this is possible using SQL Server Compact. It is an embedded relational database management system which means all benefits from relational model can be used while it is adapted for use in a mobile device. Manipulating the data in the database can be done using LINQ to SQL object relational mapping framework which is standard part of .NET framework.

But, before we’re ready to populate the database, we need to create domain classes, map them to database tables and create database itself. Currently in WP 7.1 Mango there is no designer or wizard that will do this for you. That is why the recommended approach at the moment is “code-first”, which means write all domain classes on your own and then create the database during runtime. This means that you need to write all the code that will define which class is mapped to which table and which class member is mapped to which attribute in the table. It surely is a lot of boring work for a developer, not to mention specifying data types, primary and foreign keys, constraints…

Fortunately there is this tool called SqlMetal which can generate all the mappings and save you a lot of time. It’s a command line tool which comes with Visual Studio and usually you won’t use it any more than executing one command. For using it, you will need valid .sdf database file. You can create one from Visual Studio and make sure you have all necessary tables and attributes. When you have database, fire up SqlMetal and execute the following command:

sqlmetal c:tempMyDatabase.sdf /code:"c:tempMyDataClasses.cs" /namespace:MyData /context:MyDataContext

SqlMetal will take the database and create C# class MyDataClasses.cs which contains all the code you need to access
the database. For example:

string ConnectionString = @"isostore:/MyDatabase.sdf';
using (MyDataContext context = new MyDataContext(ConnectionString))
{
    if (!context.DatabaseExists())
    {
        // create database if it does not exist
        context.CreateDatabase();
    }
}
// create a new country and add it to the context
Country country = new Country();
country.Name = "Spain";
// add the new country to the context
context.Countries1.InsertOnSubmit(country);

// save changes to the database
context.SubmitChanges()

And that’s it, your data is now persisted in the database.

0 comments