Windows Phone 7 – Simple database example

Today when I start to play around with developing on Windows Phone 7, I would like to write a first small database application because Windows Phone does not support SQL Server any more. Therefore I must use either LINQ over XML or store the database somewhere on server/Windows Azure and provide services so that the client can access and make query to get and update data. In this small example, I would like to work with LINQ To XML to create a database and update it.

My data object (data entity) is a class of Student with his first name, last name and email built by appending first name and last name as describing below

public class Student
{
	public string EMail { get; set; }
	public string FirstName { get; set; }
	public string LastName { get; set; }

	public Student(string FirstName, string LastName)
	{
		this.FirstName = FirstName;
		this.LastName = LastName;
		EMail = FirstName + "@" + LastName + ".com";
	}

	public Student(XElement xElement)
	{
		EMail = xElement.Attribute("EMail").Value;
		FirstName = xElement.Element("FirstName").Value;
		LastName = xElement.Element("LastName").Value;
	}

	public XElement Information
	{
		get
		{
			return new XElement("Student",
					new XAttribute("EMail", EMail),
					new XElement("FirstName", FirstName),
					new XElement("LastName", LastName));
		}
	}
}

Then I create a sample database with some predefined students

<?xml version="1.0" encoding="utf-8" ?>
<Students>
  <Student EMail="Lewis@Franklin.com">
    <FirstName>Lewis</FirstName>
    <LastName>Franklin</LastName>
  </Student>
  <Student EMail="Whitcomb@Donald.com">
    <FirstName>Whitcomb</FirstName>
    <LastName>Donald</LastName>
  </Student>
  <Student EMail="Kadi@Wadad.com">
    <FirstName>Kadi</FirstName>
    <LastName>Wadad</LastName>
  </Student>
</Students>

This database will be loaded into a list of student. Everytime when I add a new student, the new one will be added in this list and the list will be flushed back into XML database. However the predefined database locates outside the management field of application therefore we have no right to write data back. To write data back to XML file, I must store it in isolated storage of application and work with this replication.

public class StudentList : List<Student>
{
	public void Load(string strXMLFile)
	{
		IsolatedStorageFile isfData = IsolatedStorageFile.GetUserStoreForApplication();
		XDocument doc = null;
		IsolatedStorageFileStream isfStream = null;
		if (isfData.FileExists(strXMLFile))
		{
			isfStream = new IsolatedStorageFileStream(strXMLFile, FileMode.Open, isfData);
			doc = XDocument.Load(isfStream);
			isfStream.Close();
		}
		else
		{
			doc = XDocument.Load(strXMLFile);
			isfStream = new IsolatedStorageFileStream(strXMLFile, FileMode.CreateNew, isfData);
			doc.Save(isfStream);
			isfStream.Close();
		}

		var vStudent = from s in doc.Descendants("Student")
					   select new Student(s);
		this.Clear();
		AddRange(vStudent);
	}

	public void Save(string strXMLFile)
	{
		try
		{
			XElement xml = new XElement("Students",
							from p in this
							select p.Information);

			IsolatedStorageFileStream isfStream = new IsolatedStorageFileStream(strXMLFile, FileMode.Open, IsolatedStorageFile.GetUserStoreForApplication());
			xml.Save(isfStream);
			isfStream.Close();
		}
		catch (Exception ex)
		{
			MessageBox.Show(ex.Message);
		}
	}
}

To work with the database we just need to initialize an object of StudentList and call its methods to manipulate data

private void LoadDatabase()
{
	m_dbList = new StudentList();
	m_dbList.Load("Database.xml");
	lvData.ItemsSource = m_dbList;
}

The complete source code of this example you can download here “Windows Phone Database Example

17 thoughts on “Windows Phone 7 – Simple database example”

  1. Hi~ thanks for the tutorial.

    However I encoutered problems while compiling this sample.

    The error msg looks like

    \The tag ‘PhoneApplicationFrame’ does not exist in XML namespace ‘clrnamespace…Microsoft.Phone.Controls.Navigation’\

    Do I need to check out something?

    Thanks for the help.

  2. Thanks for the tutorial!

    Ive managed to implement it, but was hoping to implement an alphabetical sorting-function. Could I make a copy of the Load()-function and somehow edit these lines of code for that purpose?


    var vStudent = from s in doc.Descendants("Student")
    orderby s.Element("FirstName") ascending // Test, did not work
    select new Word(s);

  3. Great job, just what I needed! Now do you have any similar examples on manipulating just ONE student instead of the whole list? For example, a sample which allows you to click a student from the list, and takes you to a new page with just that student where you can update their info. A true “add student” function would be a good one too, where a new page is provided for the user to enter info.
    Thanks!!!

  4. Hi,

    could you help me with manipulating single student? Example once user logged in the mainpage will only display the logged in user info.

    Thanks!
    Leigh

  5. EzTools has just released FileDb version 1.0, a new simple database for Windows Phone 7 / Silverlight / .NET. It is a NoSql database, supporting one table per file with an embedded index. It supports common .NET datatypes, e.g. String, Boolean, Int, UInt DateTime, Float, Double and arrays of the same. And it supports powerful RegEx searches. Also available is a database explorer tools which allows you to visualize and edit your data. Find out more and download at http://www.eztools-software.com/tools/filedb

  6. After I changed to new version of CTP, and it has a error “There were deployment errors. Continue?”. After I click yes, it has error
    “Zune software is not launched. Retry after making sure that Zune software is launched.” Anyone know what happened?

  7. After I removed the styles in the app.xaml, then the problem is gone. 🙂 Have no idea about the messages.

Leave a Reply

Your email address will not be published. Required fields are marked *