Miszka.info
Miszka.info

Reputation: 35

Preloaded Database on Windows Phone 7.5 Mango Application

Im creating an App in visual studio for Windows Phone Mango in which I need a dictionary database. I know how to create it, how to insert, update and delete.

I have a 300k xml file of data which I want to preload in that database (parse and insert - thats not the problem) into the application. The problem is that I don't want to do it when the app is being installed. I want the database file preinstalled in the isolated data storage. I also need that system on-board because the xml contents could change every 3 months. But processing a 300k xml file on a phone - every time when the app is installed - sounds quite... stupid when I can make the database preinstalled...

PS. Is there any decent XML helpers in linq? For caching xml files for example..

Upvotes: 2

Views: 1035

Answers (1)

Chris Koenig
Chris Koenig

Reputation: 2748

This doesn't address your situation with XML helpers for Linq, but a good way to handle this is to create the database separately (like in a Console Application project) and load it up with the data you need. Next, copy the SDF file into your Windows Phone project as Content. Lastly, when you deploy your application, copy the database out of the deployment location into isolated storage. That way, you don't have to deal with XML files, or anything like that. It is a simple matter to copy from the deployment location to Isolated Storage. I am working on a (quite long) blog post that talks all about this, but the core code you need is this:

// Obtain the virtual store for the application.
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();

// Create a stream for the file in the installation folder.
using (Stream input = Application.GetResourceStream(new Uri("ReferenceDB.sdf", UriKind.Relative)).Stream)
{
    // Create a stream for the new file in isolated storage.
    using (IsolatedStorageFileStream output = iso.CreateFile("ApplicationDB.sdf"))
    {
        // Initialize the buffer.
        byte[] readBuffer = new byte[4096];
        int bytesRead = -1;

        // Copy the file from the installation folder to isolated storage.
        while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
        {
            output.Write(readBuffer, 0, bytesRead);
        }
    }
}

Then you can connect to the database as normal and read/write data all day long:

var db = new MyDataContext("Data Source = 'isostore:/ApplicationDB.sdf';");

You can download some sample code from my GitHub repository at https://github.com/ChrisKoenig/ReferenceDatabase

-Chris

Upvotes: 6

Related Questions