Over a million developers have joined DZone.

Creating an Application with a Local Database for Windows Phone Mango

· Mobile Zone

I was working lately on a new app , ToDo list ( i know , nothing innovative here -_- ) but then I dropped the work till Mango is out,for the very good reason that with Mango I can have a local Database to store and manage my application’s structured data! Clap! Clap!

One of the many new features coming with Windows Phone Mango is the possibility of having local databases- Microsoft SQL Server Compact edition databases(SQL CE)- for your applications.

The database resides in the application’s isolated storage as a file.

In case you are not familiar with the isolated storage,I highly recommend you to read the ” All about WP7 Isolated Storage” articles on the ” WindowsPhone Geek” website.

In order to store and retrieve data in the local database, your Windows Phone application has to use LINQ to SQL.

LINQ to SQL provides an object-oriented approach to working with data and comprises an object model and a runtime.The LINQ to SQL object model is made up primarily by the System.Data.Linq.DataContext object, which acts as a proxy for the local database. The LINQ to SQL runtime is responsible for bridging the world of objects (the DataContext object) with the world of data (the local database). This relationship is summarized in the following image.” MSDN

One more thing to explain is the Data Context . Data Context is the object model that represents the database, each object is a set of entities using the ” plain old CLR object ” (POCO) with attributes.

  • Building the application

My ToDo application looks like this :

As you can see, my main page is a panorama containing :

* Hot list item : where you can find the tasks to be done soon

* Lists: tasks will be sorted , tasks related to work, family, etc…

The other page is a simple Windows Phone page that allows you to add a new task.

In this post we will be working with this user interface.By now you should know how to create a new Windows Phone 7.1 application and how to add pages, so all I have to do is to show you the XAML code :

    <Grid x:Name=”ContentPanel” Grid.Row=”1″ Margin=”12,0″>
                <TextBlock Height=”50″ HorizontalAlignment=”Left” Margin=”10,25,0,0″ Name=”textBlock1″ Text=”Subject:” VerticalAlignment=”Top” Width=”117″ />
                <TextBox Height=”66″ HorizontalAlignment=”Left” Margin=”105,9,0,0″ Name=”textBox1″ Text=”" VerticalAlignment=”Top” Width=”342″ />
                <TextBlock Height=”43″ HorizontalAlignment=”Left” Margin=”10,97,0,0″ Name=”textBlock2″ Text=”Category:” VerticalAlignment=”Top” Width=”103″ />
                <Canvas HorizontalAlignment=”Left” VerticalAlignment=”Top” Width=”345″ Height=”66″ Margin=”111,80,0,0″>
                    <toolkit:ContextMenuService.ContextMenu>
                        <toolkit:ContextMenu>
                            <toolkit:MenuItem Header=”pin to start menu” Click=”MenuItem_Click” Tag=”START_MENU” />
                            <toolkit:MenuItem Header=”delete” Click=”MenuItem_Click” Tag=”DELETE” />
                            <toolkit:MenuItem Header=”share” Click=”MenuItem_Click” Tag=”SHARE” />
                        </toolkit:ContextMenu>
                    </toolkit:ContextMenuService.ContextMenu>
                    <Rectangle Fill=”#FFF4F4F5″ Height=”47″ Stroke=”Black” Width=”319″ Canvas.Left=”6″ Canvas.Top=”6″ />
                    <TextBlock Name=”cat” TextWrapping=”Wrap” Text=” “ Foreground=”Black” Canvas.Left=”71″ Canvas.Top=”27″/>
                </Canvas>
                <TextBlock Height=”50″ HorizontalAlignment=”Left” Margin=”10,179,0,0″ Name=”textBlock3″ Text=”Priority:” VerticalAlignment=”Top” Width=”95″ />
                <RadioButton Content=”Low” Height=”76″ HorizontalAlignment=”Left” Margin=”140,156,0,0″ Name=”radioButton1″ VerticalAlignment=”Top” Width=”134″ />
                <RadioButton Content=”High” Height=”73″ HorizontalAlignment=”Right” Margin=”0,156,33,0″ Name=”radioButton2″ VerticalAlignment=”Top” Width=”126″ />
                <toolkit:DatePicker Header=”Start date:” Margin=”0,234,0,270″ />
                <toolkit:DatePicker Header=”Due date:” Margin=”0,331,0,180″ />
                <CheckBox Content=”Completed” Height=”76″ HorizontalAlignment=”Left” Margin=”6,411,0,0″ Name=”checkBox1″ VerticalAlignment=”Top” Width=”190″ />
                <toolkit:DatePicker Header=”Date completed:” Margin=”2,493,9,21″ />
            </Grid>

Now that the user interface is ready, we will build the Data Context.

First thing to do is to add the reference System.Data.Linq to be able to work with LINQ to SQL.

Then add a new class, I’ll call it task.

    [Table]
        public class task : INotifyPropertyChanged, INotifyPropertyChanging
        {
            private string _subject;
            [Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
            public string Subject
            {
                get
                {
                    return _subject;
                }
                set
                {
                    if (_subject != value)
                    {
                        NotifyPropertyChanging(“Subject”);
                        _subject = value;
                        NotifyPropertyChanged(“Subject”);
                    }
                }
            }
            private string _category;
            public string Category
            {
                get
                {
                    return _category;
                }
                set
                {
                    if (_category != value)
                    {
                        NotifyPropertyChanging(“Category”);
                        _category = value;
                        NotifyPropertyChanged(“Category”);
                    }
                }
            }
            private bool _completed;
            [Column]
            public bool Completed
            {
                get
                {
                    return _completed;
                }
                set
                {
                    if (_completed != value)
                    {
                        NotifyPropertyChanging(“Completed”);
                        _completed = value;
                        NotifyPropertyChanged(“Completed”);
                    }
                }
            }
            private bool _priority;
            [Column]
            public bool Priority
            {
                get
                {
                    return _priority;
                }
                set
                {
                    if (_priority != value)
                    {
                        NotifyPropertyChanging(“Priority”);
                        _priority = value;
                        NotifyPropertyChanged(“Priority”);
                    }
                }
            }
            private DateTime _startDate;
            [Column]
            public DateTime StartDate
            {
                get
                {
                    return _startDate;
                }
                set
                {
                    if (_startDate != value)
                    {
                        NotifyPropertyChanging(“StartDate”);
                        _startDate = value;
                        NotifyPropertyChanged(“StartDate”);
                    }
                }
            }
            private DateTime _dueDate;
            [Column]
            public DateTime DuetDate
            {
                get
                {
                    return _dueDate;
                }
                set
                {
                    if (_dueDate != value)
                    {
                        NotifyPropertyChanging(“DuetDate”);
                        _dueDate = value;
                        NotifyPropertyChanged(“DuetDate”);
                    }
                }
            }
            private DateTime _dateCompleted;
            [Column]
            public DateTime DateCompleted
            {
                get
                {
                    return _dateCompleted;
                }
                set
                {
                    if (_dateCompleted != value)
                    {
                        NotifyPropertyChanging(“DateCompleted”);
                        _dateCompleted = value;
                        NotifyPropertyChanged(“DateCompleted”);
                    }
                }
            }
            public event PropertyChangedEventHandler PropertyChanged;
            private void NotifyPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
            public event PropertyChangingEventHandler PropertyChanging;
            private void NotifyPropertyChanging(string propertyName)
            {
                if (PropertyChanging != null)
                {
                    PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
                }
            }
        }

Add another class called TaskDataContext that derives from DataContext:

    namespace task
    {
        public class TaskDataContext: DataContext
        {
            public TaskDataContext(string connectionString): base(connectionString)    {    }
            public Table<task> tasks { get { return this.GetTable<task>(); } }
        }
    }

Notice that we have to check if the database exists , if not we need to create it .

In the MainPage.xaml.cs add the following code:

    using (TaskDataContext context = new TaskDataContext(connectionString))
                {
                    if (!context.DatabaseExists())
                    {
                    context.CreateDatabase();
                    }
                }

To sum up, in order to use local database, we need to specify the data context then create the database if it doesn’t exist.

In the coming post , we will learn how to query the database. Stay Tuned!

 

Topics:

Published at DZone with permission of Rabeb Othmani, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}