Windows Phone 8 Data Access - Beginning Windows 8 Data DevelopmentUsing C# and JavaScript (2013)

Beginning Windows 8 Data DevelopmentUsing C# and JavaScript (2013)

10. Windows Phone 8 Data Access

Vinodh Kumar1

(1)

NY, US

Abstract

We end this book by learning the data access options available for Windows Phone apps. This chapter starts by discussing the code sharing techniques between Windows Phone and Windows 8 apps and then introduces you to the Windows Phone built-in database option, SQL Server Compact for Windows Phone, and walk you through the procedure to get started with the Windows Phone app development. We then port the Bill Reminder Windows 8 app that we built in Chapter 6 to a Windows Phone app using the SQLServer Compact database as data storage. Finally we briefly introduce you to the other data storage options that we learned in this book that can be also used in Windows Phone apps.

We end this book by learning the data access options available for Windows Phone apps. This chapter starts by discussing the code sharing techniques between Windows Phone and Windows 8 apps and then introduces you to the Windows Phone built-in database option, SQL Server Compact for Windows Phone, and walk you through the procedure to get started with the Windows Phone app development. We then port the Bill Reminder Windows 8 app that we built in Chapter 6 to a Windows Phone app using the SQLServer Compact database as data storage. Finally we briefly introduce you to the other data storage options that we learned in this book that can be also used in Windows Phone apps.

Sharing the Code

Windows Phone 8 is a major upgrade to Windows Phone 7.x. It replaces the core with the same core as Windows 8, which means the .NET Compact Framework is replaced with the .NET CLR. Apart from this, the Windows Phone API adds Windows Phone Runtime, which has lot in common with WinRT. With this new Windows Phone API, developers will be able to develop apps in VB/C# and C++. Windows Phone 8 also supports native development using Direct3D, xAudio2 Win32, COM, and MF.

Separate UI from App Logic

The strategy to build a successful app that targets both Windows 8 and Windows Phone 8 is to separate the UI from app logic. Model-View-ViewModel (MVVM), which we used extensively in building the various apps in this book, is the only neat approach to separate the UI from the app logic. Using MVVM we can encapsulate one or more ViewModels and on top of that we can have one or more Views that represent Windows Phone Page or Windows 8 Page.

Sharing Portable .NET Code in Portable Class Library

Portable Class Library is one of the important blocks that we can use to share code between Windows 8 and Windows Phone apps written using XAML/VB/C#, as this shares common .NET libraries. In Visual Studio when we create a Portable Class Library a pop-up, shown in Figure 10-1, allows us to select the targeted framework. The project will have set of libraries that shows .NET is currently portable with the platform that we are targeting. Once compiled, these libraries become compatible with the targeted framework and in our case Windows Phone and Windows 8. Apart from creating our own portable libraries, we can also reference some of the common portable libraries like MVVM Light inside our Portable Library project.

A978-1-4302-4993-1_10_Fig1_HTML.jpg

Figure 10-1.

Selecting the targeted frameworks for the Portable Class Library

Using Common Windows Runtime API (Add as Link)

Windows 8 comes with the Common Windows Runtime API, which gives access to sensors, media, and proximity. Along with that we also get Windows Phone 8 Runtime API, which shares a subset of APIs with Windows 8. Whenever we use this set of APIs, we can write once and use it in both Windows 8 and Windows Phone 8 apps using the Add as link functionality available in Visual Studio as shown in Figure 10-2. By doing this the class file will not be copied to the project, and instead will be copied as a link from the source. If we make any changes to the code, therefore, it will be reflected in all the linked references.

Note

Windows Runtime API can't be referenced into the portable libraries while creating portal libraries targeting Windows 8 and Windows Phone 8, as the binary compatibility is not supported and the code has to be compiled for each platform separately.

Using the technique just discussed, we are able to create a compiling app that targets both Windows Phone 8 and Windows 8 by sharing a similar code base.

A978-1-4302-4993-1_10_Fig2_HTML.jpg

Figure 10-2.

Adding an existing file as a link to the Visual Studio Project

SQL Server Compact for Windows Phone

Unlike Windows 8, Windows Phone provides built-in support for SQL Server Compact as a local database. This database resides in the Isolated Storage of the app and is an in-memory relational database. The following are the some of the features of SQL Server Compact.

· SQL Server Compact database runs within the Windows Phone application’s process. Unlike SQL Server, the database doesn’t run continuously in the background; instead, an instance is created only when the app is in use.

· As the database is stored in the app’s Isolated Storage, this database can only be accessed by that app and can’t be shared with any other apps.

· Transaction SQL is not supported. Instead, LINQ to SQL is used as the ORM engine.

· Because SQL Server Compact database is part of the Windows Phone Runtime, no DLLs corresponding to the SQL Server Compact database need to be packaged as part of the app.

With this brief introduction about the built-in SQL Server compact database, we next port the Bill Reminder Windows 8 app that we built in Chapter 6 using Windows 8 XAML/C#, SQLite, MVVM Light Framework to a Windows Phone app using SQL Server Compact as the database instead of SQLite to store data, along with the MVVM Light Framework.

Porting Bill Reminder Windows 8 App to Windows Phone

Porting the Bill Reminder app for Windows Phone is quite simple and straightforward. The project structure is shown in Figure 10-3, and most parts of the code remain unchanged, apart from the layout that adapts to a smaller screen.

A978-1-4302-4993-1_10_Fig3_HTML.jpg

Figure 10-3.

BillReminder Windows Phone app project structure, which looks similar to the BillReminder Windows 8 app

Setting Up the Windows Phone 8 Development Environment

Windows Phone SDK 8.0 can be downloaded from http://go.microsoft.com/fwlink/?LinkId=259416 . This SDK includes all the necessary tools like Visual Studio Express 2012 for Windows Phone, project templates for creating new Windows Phone apps, and the Windows Phone emulator for testing. After installing the SDK, we create a new Windows Phone app as shown in Figure 10-4.

A978-1-4302-4993-1_10_Fig4_HTML.jpg

Figure 10-4.

Windows Phone app project template

After creating the app, we are prompted to select the targeted Windows Phone OS version as shown in Figure 10-5. Select the Windows Phone OS 8.0, but you can always go for Windows Phone OS 7.1 to support both versions, as Windows Phone 8 OS provided backward compatibility of the app developed targeting Windows Phone 7.1.

A978-1-4302-4993-1_10_Fig5_HTML.jpg

Figure 10-5.

Selecting the Windows Phone platform that we want to target, in this case Windows Phone OS 8.0

We add project references to the MVVM Light Framework and Windows Phone Toolkit using the NuGet package. Windows Phone Toolkit provides a collection of controls, animation framework, and extension methods to make Windows Phone development easier. We use the DatePicker and ListPicker controls from the Windows Phone Toolkit in our project.

Creating the Database Table

As mentioned in Chapter 6, the main function of the Bill Reminder app is to help keep track of bills. For this, we create three tables via Category, Bill, and PaidBill, similar to the ones we did for the Windows 8 app. Like the SQLite wrapper sqlite-net, SQL Server Compact is also an ORM-based database, so we copy the class files that map to the three tables into the Windows Phone app Model folder as shown in Figure 10-3. These classes define our object model and its mapping to the schema of the database.

Next, to access the data stored in the database using LINQ to SQL, we have to decorate this class with the [Table] attribute as shown in Listing 10-1. Basically we can use this attribute to designate a class as an entity class that is associated with a database table or view.

In addition to associating classes with tables, we need to denote each field or property that we intend to associate with a database column.

Listing 10-1. Category, Bill, and PaidBill Classes

[Table]

public class Category

{

[Column(IsPrimaryKey = true, IsDbGenerated = true)]

public int CategoryID { get; internal set; }

[Column(CanBeNull = false)]

public string Name { get; internal set; }

}

[Table]

public class Bill

{

[Column(IsPrimaryKey = true

, IsDbGenerated = true

, DbType = "INT NOT NULL Identity"

, CanBeNull = false

, AutoSync = AutoSync.OnInsert)]

public int BillID { get; internal set; }

[Column(CanBeNull = false)]

public string Name { get; internal set; }

[Column(CanBeNull = false)]

public DateTime DueDate { get; internal set; }

[Column(CanBeNull = false)]

public bool IsRecurring { get; internal set; }

[Column(CanBeNull = true, UpdateCheck = UpdateCheck.Never)]

public int CategoryID{get; internal set; }

private EntityRef<Category> category;

[Association(Storage = "category"

, ThisKey = "CategoryID"

, OtherKey = "CategoryID"

, IsForeignKey = true)]

public Category Category

{

get { return category.Entity; }

set

{

if (value != null)

{

CategoryID = value.CategoryID;

}

category.Entity = value;

}

}

[Column(CanBeNull = false)]

public Decimal Amount { get; internal set; }

}

[Table]

public class PaidBill

{

[Column(IsPrimaryKey = true, IsDbGenerated = false)]

public int PaidBillID { get; internal set; }

[Column(CanBeNull = false, UpdateCheck = UpdateCheck.Never)]

public int BillID { get; internal set; }

private EntityRef<Bill> bill;

[Association(Storage = "bill"

, ThisKey = "BillID"

, OtherKey = "BillID"

, IsForeignKey = true)]

public Bill Bill

{

get { return bill.Entity; }

set

{

if (value != null)

{

BillID = value.BillID;

}

bill.Entity = value;

}

}

[Column(CanBeNull = true)]

public DateTime PaidDate { get; internal set; }

[Column(CanBeNull = true)]

public Decimal Amount { get; internal set; }

}

Creating the DataContext Class

The DataContext class inherits from System.Data.Linq.DataContext and is used to expose the database to the rest of the code through properties of type Table<TEntity> as shown in Listing 10-2.

Listing 10-2. BillReminderDataContext Class Exposes the Database

using System.Data.Linq;

namespace BillReminder.Model

{

public class BillReminderDataContext : DataContext

{

public BillReminderDataContext(string connectionString)

: base(connectionString)

{

}

public Table<Bill> Bills

{

get

{

return this.GetTable<Bill>();

}

}

public Table<Category> Categories

{

get

{

return this.GetTable<Category>();

}

}

public Table<PaidBill> PaidBills

{

get

{

return this.GetTable<PaidBill>();

}

}

}

}

Next we create the database using the DataContext object at the App initialization in App.xaml.cs. The DataContext object is initialized by passing the connection string, which basically tells the app how to connect to the database. Once the app is initialized, we check if the database exists; if it doesn’t we create the database by calling the CreateDatabase() method of the DataContext. We also add some default value to the Category table by adding the Category object to the data context using the InsertOnSubmit method and calling the data context SubmitChanges method to permanently add the data as a row in the database (see Listing 10-3).

Listing 10-3. Creating the Database in App Initialization Using DataContext

public partial class App : Application

{

public static PhoneApplicationFrame RootFrame { get; private set; }

public App()

{

UnhandledException += Application_UnhandledException;

InitializeComponent();

InitializePhoneApplication();

InitializeLanguage();

if (Debugger.IsAttached)

{

Application.Current.Host.Settings.EnableFrameRateCounter = false;

PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;

}

try

{

app = this;

DB = new BillReminderDataContext("isostore:/BillReminder.sdf");

InitializeDatabase();

}

catch(Exception ex)

{

Debug.WriteLine(ex.Message);

}

}

private static App app;

public static App CurrentApp

{

get { return app; }

}

public BillReminderDataContext DB { get; set; }

private void InitializeDatabase()

{

if (DB.DatabaseExists()) return;

DB.CreateDatabase();

if (!App.CurrentApp.DB.Categories.Any())

{

DB.Categories.InsertOnSubmit(new Category()

{

Name = "Credit Card"

});

DB.Categories.InsertOnSubmit(new Category()

{

Name = "Loan"

});

DB.Categories.InsertOnSubmit(new Category()

{

Name = "Utilities"

});

DB.SubmitChanges();

}

}

Updating the Model

Apart from the new DataContext class BillReminderDataContext all of the other classes inside the Model folder will be carried from the Windows 8 Bill Reminder app with a few minor changes to the DataService class. Here we replace the code that references the SQLite database to refer to the SQL Server Compact database, but all within the same methods as shown in Listing 10-4.

Listing 10-4. Methods to Retrieve Bill Details and Add, Update, and Delete Bills

using System;

using System.Collections.Generic;

using System.Collections.ObjectModel;

using System.Linq;

namespace BillReminder.Model

{

public class DataService : IDataService

{

public void AddBill(Bill bill)

{

App.CurrentApp.DB.Bills.InsertOnSubmit(bill);

App.CurrentApp.DB.SubmitChanges();

}

public Bill GetBillByID(int billId)

{

return App.CurrentApp.DB.Bills.First(b => b.BillID == billId);

}

public ObservableCollection<Billtem> GetBills(DateTime month)

{

var bills = new ObservableCollection<Billtem>();

var fromDate = new DateTime(month.Year, month.Month, 1); //first day of the month

var toDate = fromDate.AddMonths(1).AddDays(-1); // last day of the month

var query = from bill in App.CurrentApp.DB.Bills

join cat in App.CurrentApp.DB.Categories on bill.CategoryID equals

cat.CategoryID

join paid in App.CurrentApp.DB.PaidBills on bill.BillID equals paid.BillID into

pp

from paid in pp.DefaultIfEmpty()

where (bill.IsRecurring || (bill.DueDate >= fromDate && bill.DueDate <= toDate))

select new Billtem(this)

{

BillID = bill.BillID

,

Name = bill.Name

,

Category = cat.Name

,

DueDate = bill.DueDate

,

Amount = bill.Amount

,

PaidAmount = paid.Amount

,

PaidDate = paid.PaidDate

};

foreach (var item in query)

{

item.IsPaid = (item.PaidAmount > 0 && item.PaidDate > DateTime.MinValue);

bills.Add(item);

}

return bills;

}

public IList<Category> GetCategories()

{

return App.CurrentApp.DB.Categories.ToList();

}

public Category GetCategoryByID(int categoryId)

{

return App.CurrentApp.DB.Categories.First(c => c.CategoryID == categoryId);

}

public void MarkPaid(int billId, decimal amount)

{

PaidBill paidBill;

if (App.CurrentApp.DB.PaidBills.Count() > 0)

{

paidBill = App.CurrentApp.DB.PaidBills.First(b => b.BillID == billId);

}

else

{

paidBill= new PaidBill();

paidBill.BillID = billId;

App.CurrentApp.DB.PaidBills.InsertOnSubmit(paidBill);

}

paidBill.Amount = amount;

paidBill.PaidDate = DateTime.Now;

App.CurrentApp.DB.SubmitChanges();

}

public void UpdateBill(Bill bill)

{

App.CurrentApp.DB.SubmitChanges();

}

}

}

No Update to the ViewModel

Apart from minor framework-level changes that we have to make for navigating between pages, we have not made any changes to the ViewModel from the one we used with the Windows 8 Bill Reminder app.

Views

Because the Phone form factor is not the same as a tablet devices on which our Windows 8 app runs, we have to make changes to the layout of the Views as shown in Figure 10-6 to suit the smaller devices. Similar to the Windows 8 app, MainPage.xaml (see Listing 10-5) is the starting page of the Bill Reminder Windows Phone app. This view has a LongListSelector control and two app bar buttons for navigating to the Bill.xaml page, again similar to the navigation of the Windows 8 app. The LongListSelector control is similar to Windows 8 GridView Xaml control, which binds to the Bill property in the MainViewModel and displays the recent bills as a list using a DataTemplate. The displayed bill information two modes, depending on the status of the Bill object’s IsPaid property. If the IsPaid property is false, then we display a Textbox for entering the bill amount and a Button to mark the bill as paid. This button command is bound to the PaidCommand in the MainViewModel. But if the bill is paid instead, then both these controls’ Visibility property is set to Collapsed using a ValueConverter VisibilityConverter.

A978-1-4302-4993-1_10_Fig6_HTML.jpg

Figure 10-6.

Bill Reminder app displaying recent bills

Listing 10-5. MainPage.xaml Includes a LongListSelector with Data Template to Display Recent Bills

<phone:PhoneApplicationPage

x:Class="BillReminder.MainPage"

xmlns=" http://schemas.microsoft.com/winfx/2006/xaml/presentation "

xmlns:x=" http://schemas.microsoft.com/winfx/2006/xaml "

xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d=" http://schemas.microsoft.com/expression/blend/2008 "

xmlns:mc=" http://schemas.openxmlformats.org/markup-compatibility/2006 "

mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Portrait" Orientation="Portrait"

shell:SystemTray.IsVisible="True"

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

xmlns:ec="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"

xmlns:abu="clr-namespace:AppBarUtils;assembly=AppBarUtils"

xmlns:converters="clr-namespace:BillReminder.Converters"

DataContext="{Binding Main, Source={StaticResource Locator}}">

<phone:PhoneApplicationPage.ApplicationBar>

<shell:ApplicationBar

IsVisible="True"

IsMenuEnabled="True"

Opacity="0.99">

<shell:ApplicationBarIconButton

x:Name="addBill"

IconUri="/Assets/AppBar/new.png"

Text="new" />

<shell:ApplicationBarIconButton

x:Name="editBill"

IconUri="/Assets/AppBar/edit.png"

Text="edit" />

</shell:ApplicationBar>

</phone:PhoneApplicationPage.ApplicationBar>

<i:Interaction.Behaviors>

<abu:AppBarItemCommand Id="new" Command="{Binding AddCommand, Mode=OneWay}"/>

<abu:AppBarItemCommand Id="edit" Command="{Binding EditCommand, Mode=OneWay}"/>

</i:Interaction.Behaviors>

<!--LayoutRoot is the root grid where all page content is placed-->

<Grid x:Name="LayoutRoot" Background="Transparent">

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

<RowDefinition Height="*"/>

</Grid.RowDefinitions>

<StackPanel x:Name="TitlePanel"

Grid.Row="0"

Margin="12,17,0,28">

<TextBlock Text="Bill Reminder"

Style="{StaticResource PhoneTextNormalStyle}"

Margin="12,0"/>

<TextBlock Text="Recent Bills"

Margin="9,-7,0,0"

Style="{StaticResource PhoneTextTitle1Style}"/>

</StackPanel>

<!--ContentPanel - place additional content here-->

<Grid x:Name="ContentPanel"

Grid.Row="1" Margin="12,0,12,0">

<phone:LongListSelector ItemsSource="{Binding Bills}"

SelectedItem ="{Binding SelectedBill, Mode=TwoWay}"

ItemTemplate="{StaticResource DataTemplate}">

</phone:LongListSelector>

</Grid>

</Grid>

</phone:PhoneApplicationPage>

BillView.xaml as shown in Figure 10-7 is used to create and edit a bill. This page has controls like TextBox, ListPicker, DatePicker, and CheckBox that bind to the properties of the BillViewModel. ListPicker and DatePicker are not part of the Windows Phone default control set, but instead they can be included by referencing the Windows Phone toolkit from NuGet packages. Also on the page we have two app bar buttons. The Save button is used to save the Bill object to the database and this button’s command property is bound to the BillViewModel’s SaveCommand.BackButton is used to navigate back to the MainPage.xaml. The ListPicker control allows the user to pick a bill category. This ListPicker is bound to the Categories property of the ViewModel, and the SelectedItem is bound two-way to the SelectedCategory property (see Listing 10-6).

A978-1-4302-4993-1_10_Fig7_HTML.jpg

Figure 10-7.

Bill Detail page for adding and editing a bill

Listing 10-6. BillView.xaml Has Controls to Input Bill Information

<phone:PhoneApplicationPage

xmlns=" http://schemas.microsoft.com/winfx/2006/xaml/presentation "

xmlns:x=" http://schemas.microsoft.com/winfx/2006/xaml "

xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:d=" http://schemas.microsoft.com/expression/blend/2008 "

xmlns:mc=" http://schemas.openxmlformats.org/markup-compatibility/2006 "

xmlns:converters="clr-namespace:BillReminder.Converters"

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

xmlns:abu="clr-namespace:AppBarUtils;assembly=AppBarUtils"

xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

x:Class="BillReminder.BillView"

mc:Ignorable="d"

SupportedOrientations="Portrait" Orientation="Portrait"

shell:SystemTray.IsVisible="True"

>

<phone:PhoneApplicationPage.Resources>

<converters:DateTimeToStringConverter x:Key="DateTimeToStringConverter"/>

<converters:DecimalToStringConverter x:Key="DecimalToStringConverter"/>

</phone:PhoneApplicationPage.Resources>

<phone:PhoneApplicationPage.FontFamily>

<StaticResource ResourceKey="PhoneFontFamilyNormal"/>

</phone:PhoneApplicationPage.FontFamily>

<phone:PhoneApplicationPage.FontSize>

<StaticResource ResourceKey="PhoneFontSizeNormal"/>

</phone:PhoneApplicationPage.FontSize>

<phone:PhoneApplicationPage.Foreground>

<StaticResource ResourceKey="PhoneForegroundBrush"/>

</phone:PhoneApplicationPage.Foreground>

<phone:PhoneApplicationPage.DataContext>

<Binding Path="Bill" Source="{StaticResource Locator}"/>

</phone:PhoneApplicationPage.DataContext>

<phone:PhoneApplicationPage.ApplicationBar>

<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True" Opacity="0.99">

<shell:ApplicationBarIconButton x:Name="save"

IconUri="/Assets/AppBar/save.png"

Text="save" />

</shell:ApplicationBar>

</phone:PhoneApplicationPage.ApplicationBar>

<i:Interaction.Behaviors>

<abu:AppBarItemCommand Id="save"

Command="{Binding SaveCommand, Mode=OneWay}"/>

</i:Interaction.Behaviors>

<!--LayoutRoot is the root grid where all page content is placed-->

<Grid x:Name="LayoutRoot" Background="Transparent">

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

<RowDefinition Height="*"/>

</Grid.RowDefinitions>

<StackPanel x:Name="TitlePanel"

Grid.Row="0"

Margin="12,17,0,28">

<TextBlock Text="Bill Reminder"

Style="{StaticResource PhoneTextNormalStyle}"

Margin="12,0"/>

<TextBlock Text="{Binding Title}"

Margin="9,-7,0,0"

Style="{StaticResource PhoneTextTitle1Style}"/>

</StackPanel>

<!--ContentPanel - place additional content here-->

<Grid x:Name="ContentPanel"

Grid.Row="1"

Margin="12,0,12,0">

<StackPanel Grid.Row="1">

<StackPanel HorizontalAlignment="Left"

VerticalAlignment="Top"

Width="383"

Orientation="Horizontal"

Margin="5">

<TextBlock TextWrapping="Wrap"

Text="Bill Name"

Margin="10,0,30,0"

FontSize="16"

Width="100"

VerticalAlignment="Center"/>

<TextBox TextWrapping="Wrap"

Margin="0,0,0,-2"

Width="283"

Text="{Binding Name, Mode=TwoWay}"/>

</StackPanel>

<StackPanel HorizontalAlignment="Left"

VerticalAlignment="Top"

Width="383"

Orientation="Horizontal"

Margin="5">

<TextBlock TextWrapping="Wrap"

Text="Category"

Margin="10,0,30,0"

FontSize="16"

Width="100"

VerticalAlignment="Center"/>

<toolkit:ListPicker Width="229"

ItemsSource="{Binding Categories}"

DisplayMemberPath="Name"

SelectedItem="{Binding SelectedCategory, Mode=TwoWay}"

Margin="12,6,6,6"/>

</StackPanel>

<StackPanel HorizontalAlignment="Left"

VerticalAlignment="Top"

Width="383"

Orientation="Horizontal"

Margin="5">

<TextBlock TextWrapping="Wrap"

Text="Due Date"

Margin="10,0,30,0"

FontSize="16"

Width="100"

VerticalAlignment="Center"/>

<toolkit:DatePicker Value= "{Binding DueDate, Mode=TwoWay}" />

</StackPanel>

<StackPanel HorizontalAlignment="Left"

VerticalAlignment="Top"

Width="383"

Orientation="Horizontal"

Margin="5">

<TextBlock TextWrapping="Wrap"

Text="Amount"

Margin="10,0,30,0"

FontSize="16"

Width="100" VerticalAlignment="Center"/>

<TextBox TextWrapping="Wrap"

Margin="0,0,0,-2"

Width="283"

Text="{Binding Amount, Converter={StaticResource DecimalToStringConverter}, Mode=TwoWay}"/>

</StackPanel>

<StackPanel HorizontalAlignment="Left"

VerticalAlignment="Top"

Width="383"

Orientation="Horizontal"

Margin="5">

<TextBlock TextWrapping="Wrap"

Text="Recurring?"

Margin="10,0,30,0"

FontSize="16" Width="100"

VerticalAlignment="Center"/>

<CheckBox VerticalAlignment="Stretch"

IsChecked="{Binding IsRecurring, Mode=TwoWay}"/>

</StackPanel>

</StackPanel>

</Grid>

</Grid>

</phone:PhoneApplicationPage>

Other Data Storage Options

Apart from the SQL Server Compact, we can use many different data storage options as we did for Windows 8 apps. Let’s briefly look at some of these options.

File-Based Data Storage

Similar to Windows 8 apps, Windows Phone apps also have app-specific isolated storage. We can use this storage to build a file-based storage solution for Windows Phone apps. Like the WinRT File Based Database we saw in Chapter 5, there are many similar libraries like SterlingDB that we can use for Windows Phone. Sterling can be referred in a project by using NuGet package. Sterling is a lightweight NoSQL object-oriented database that can be used in .NET 4.0, Silverlight, and Windows Phone that works with our existing class structures. Also using Sterling DB we can quickly sterilize objects with support for LINQ to Object.

SQLite

We can also use SQLite as a data storage option for a Windows Phone app and the steps to integrate this are very similar those by which we integrated SQLite in a Windows 8 app, as detailed in Chapter 6.

Windows Azure Mobile Services

Another interesting option that is familiar to readers is Windows Azure Mobile Services, which we saw in detail in Chapter 9. The Windows Azure Mobile Services SDK provides the necessary library to integrate it inside a Windows Phone app; in fact, the Windows Azure Mobile service start screen generates a sample app for Windows Phone (see Figure 10-8) that can be downloaded. This app is preconfigured to access the back end and is ready to run.

A978-1-4302-4993-1_10_Fig8_HTML.jpg

Figure 10-8.

Windows Azure Mobile Services sample Windows Phone 8 project that we can download from the Windows Azure Management portal

Similarly we can create a service layer using ASP.NET Web API or WCF to access any back end like SQL Server from Windows Phone.

Conclusion

In this chapter we ported the Bill Reminder Windows 8 app to Windows Phone. By doing so we used the Windows Phone built-in data access option SQL Server Compact database as the data strorage. The intention of this chapter is to highlight the options available for you as a developer to build apps that can target both Windows 8 and Windows Phone apps. We did so by detailing various techniques that we can use to share code between the two platforms. Also at the end of the chapter, we briefly looked at the various other data storage options that can be used in developing a Windows Phone app.

With this chapter, we have completed this book and I hope it has helped you learn various data access options for developing Windows 8 apps. This book has provided an overview of the Windows 8 app framework, and you have also learned to use various development tools and libraries that can be incorporated into many Windows 8 apps. In each chapter of this book we built a Windows 8 app using different data access techniques, and we also provided ideas for improving the app. I hope this will be a good starting point for you to add additional features to the apps to make them fully functional. Perhaps you will even submit them to the Windows app stores, so that millions of people can download them and appreciate your efforts. Happy app developing!

Vinodh KumarBeginning Windows 8 Data DevelopmentUsing C# and JavaScript10.1007/978-1-4302-4993-1© Apress 2013