You are on page 1of 71

DONG NAI UNIVERSITY OF TECHNOLOGY

1
6. Serializing Objects
5. Consuming XML
3. Encrypt Data
2. Read Data from an SD Card
1. Read & Write Data to a Local File
7. Consuming Web Resources
4. Store Application Settings
8. Using a Local Database
DONG NAI UNIVERSITY OF TECHNOLOGY
2
1. Read & Write Data to a Local File
Problem
You want to be able to read and write file data from within a
Windows Phone app.
Solution
Utilize the StorageFolder and StorageFile classes to perform
file and folder management.
How It Works
The StorageFolder and StorageFile classes, which belong to the
Windows. Storage namespace.
The StorageFile class represents a local file and contains
information about the file and its content.
The StorageFolder class can be used to read from and write
to a local file. This class also contains methods to obtain the
list of files or subfolders within a local folder, as well as to
create, rename, or delete folders.
DONG NAI UNIVERSITY OF TECHNOLOGY
3
1. Read & Write Data to a Local File
To be able to perform any type of file or folder management, we
first need to obtain a handle to a local storage folder. This can
be accomplished by accessing the LocalFolder property for the
current application data store instance.
using System.Threading.Tasks;
using System.IO;
using Windows.Storage;
using Windows.Storage.Streams;
using System.Text;
DONG NAI UNIVERSITY OF TECHNOLOGY
4
1. Read & Write Data to a Local File
public async Task<bool> SaveFile(string fileName,string content) {
try {//Convert the file text to a byte array
byte[] fileBytes = Encoding.UTF8.GetBytes(content.ToCharArray());
//Get the local folder for the current application
StorageFolder local = ApplicationData.Current.LocalFolder;
if (local != null) {//Create a new file, or update file if one
already exists with the same name
StorageFile file = await local.CreateFileAsync(fileName,
CreationCollisionOption.ReplaceExisting);
//Write the file contents
Stream fileStream = await file.OpenStreamForWriteAsync();
fileStream.Write(fileBytes, 0, fileBytes.Length);
fileStream.Flush();
fileStream.Close();
}
} catch (Exception ex) {
return false; }
return true;
}
DONG NAI UNIVERSITY OF TECHNOLOGY
5
1. Read & Write Data to a Local File
public async Task<string> LoadFile(string fileName){
//Get the local folder for the current application
StorageFolder local =
Windows.Storage.ApplicationData.Current.LocalFolder;
string contents = "";
if (local != null) {
try { //Load the specified file
Stream file = await local.OpenStreamForReadAsync(fileName);
//Read the entire file into the FileText property
using (StreamReader streamReader = new StreamReader(file)) {
contents = streamReader.ReadToEnd();
}
file.Close();
}
catch (FileNotFoundException ex) {
//file doesn't exist
return contents; }
}
return contents;
}
DONG NAI UNIVERSITY OF TECHNOLOGY
6
1. Read & Write Data to a Local File
Problem
You want to develop an app that will allow the user to read data
from an external media card.
Solution
Leverage the set of ExternalStorage classes, available within
the Microsoft.Phone.Storage APIs.
How It Works
The Microsoft.Phone.Storage namespace includes the
following set of classes that can be used to access and read from
external storage:
DONG NAI UNIVERSITY OF TECHNOLOGY
7
2. Read Data from an SD Card
ExternalStorage: A static class that is used to obtain a handle to
an external media card, if one is available on the device. It contains
only a single method, GetExternalStorageDevicesAsync, which
returns an ExternalStorageDevice object.

ExternalStorageDevice: Exposes a property, RootFolder, which
provides a handle to the root folder on the SD media card, which is
an ExternalStorageFolder object.

ExternalStorageFolder: Used to obtain the list of files or
subfolders within a folder on the media card.

ExternalStorageFile: Used to open a stream to read the contents
of the current file through the method OpenForReadAsync.
DONG NAI UNIVERSITY OF TECHNOLOGY
8
2. Read Data from an SD Card
The APIs currently allow only read-only access to files.
To read a file from an SD card, the app must incorporate the
following modifications in the app manifest file:
1. Include the ID_CAP_REMOVABLE_STORAGE capability.
2. Register for a file association to declare what file types the
app can handle, example:
<Extensions>
<FileTypeAssociation TaskID="_default" Name="txt"
NavUriFragment="fileToken=%s">
<SupportedFileTypes>
<FileType ContentType="application/txt">.txt</FileType>
</SupportedFileTypes>
</FileTypeAssociation>
</Extensions>
DONG NAI UNIVERSITY OF TECHNOLOGY
9
2. Read Data from an SD Card
private async void btnSDCard_Click(object sender, RoutedEventArgs e)
{ ExternalStorageDevice sdCard = (await ExternalStorage.
GetExternalStorageDevicesAsync()).FirstOrDefault();
if (sdCard != null) {
IEnumerable<ExternalStorageFile> files = await
sdCard.RootFolder.GetFilesAsync();
ExternalStorageFile SelectedFile = files.Where(f =>
f.Name.EndsWith(".txt")).FirstOrDefault();
System.IO.Stream fileStream = await
SelectedFile.OpenForReadAsync();
//Read the entire file into the FileText property
using (StreamReader streamReader = new StreamReader(fileStream)){
txtContent.Text = streamReader.ReadToEnd();
}
fileStream.Close();
}
else {
MessageBox.Show("An SD card was not detected");
}
}
DONG NAI UNIVERSITY OF TECHNOLOGY
10
3. Encrypt Data
Problem
You are developing an app that will store sensitive data within
a file that will be saved to isolated storage. You want to ensure
the file data is encrypted as an additional security measure.
Solution
Leverage the Data Protection API to encrypt/decrypt sensitive
file data.
How It Works
The Windows Phone Data Protection API provides a
mechanism to encrypt and decrypt sensitive data using a
unique decryption key that is created when the app is run for
the first time. Cryptographic key generation is built into the
API and removes the need for a developer to explicitly define a
key for this purpose.
DONG NAI UNIVERSITY OF TECHNOLOGY
11
3. Encrypt Data
The Data Protection API includes the ProtectedData class
(part of the System.Security.Cryptography namespace),
which contains two methods:
Protect: Encrypts the data that is passed into the method.
The data must be passed in as a byte array. The encrypted data
is returned as a byte array.
Unprotect: Decrypts the data that is passed into the method.
The data must be passed in as a byte array. The decrypted data
is returned as a byte array.
string filePath = "mydata.txt";
DONG NAI UNIVERSITY OF TECHNOLOGY
12
3. Encrypt Data
private void btnProtect_Click(object sender, RoutedEventArgs e) {
try {
byte[] InfoByteArray = Encoding.UTF8.GetBytes(txtProtect.Text);
byte[] encryptedInfoByteArray =
ProtectedData.Protect(InfoByteArray, null);
// Create a file in the application's isolated storage.
IsolatedStorageFile file =
IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream writestream = new
IsolatedStorageFileStream(filePath, FileMode.Create,
FileAccess.Write, file);
Stream writer = new StreamWriter(writestream).BaseStream;
writer.Write(encryptedInfoByteArray, 0,
encryptedInfoByteArray.Length);
writer.Close();
writestream.Close();
}
catch(Exception ex) {
}
}
DONG NAI UNIVERSITY OF TECHNOLOGY
13
3. Encrypt Data
private void btnUnprotect_Click(object sender, RoutedEventArgs e) {
try { IsolatedStorageFile file =
IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream readstream = new
IsolatedStorageFileStream(filePath, FileMode.Open,
FileAccess.Read, file);
if (readstream != null) {
Stream reader = new StreamReader(readstream).BaseStream;
byte[] encryptedInfoByteArray = new byte[reader.Length];
reader.Read(encryptedInfoByteArray,0,encryptedInfoByteArray.Length);
reader.Close();
readstream.Close();
byte[]InfoByteArray=ProtectedData.Unprotect(encryptedInfoByteArray,null);
string content = Encoding.UTF8.GetString(InfoByteArray , 0,
InfoByteArray .Length);
txtUnprotect.Text = content;
}
}
catch (Exception ex) { }
}
DONG NAI UNIVERSITY OF TECHNOLOGY
14
4. Store Application Settings
Problem
You want to include application-specific settings in your
Windows Phone application that the users can change from
within the app.
Solution
Store the values of each setting within isolated storage and
provide a UI that will allow the user to change these settings
from within the application.
How It Works
The IsolatedStorageSettings class, within the
System.IO.IsolatedStorage namespace, can be used to store
key-value pairs in the applications isolated storage. The
ApplicationSettings property retrieves the current instance
of the IsolatedStorageSettings dictionary for the application,
or it creates a new one if one does not yet exist.
DONG NAI UNIVERSITY OF TECHNOLOGY
15
4. Store Application Settings
Method Description Example
Add(key, value) Adds an entry to the
IsolatedStorageSettings
collection.
IsolatedStorageSettings.
ApplicationSettings.
Add(MyKey, 1)
Clear() Removes all items from the
IsolatedStorageSettingscoll
ection
IsolatedStorageSettings.
ApplicationSettings.
Clear()
Contains(key) Conducts a check to
determine whether an
element exists in the
collection for the specified
key. Returns true if an
element is found.
bool itemExists =
IsolatedStorageSettings.
ApplicationSettings.
Contains(MyKey)
IsolatedStorageSettings Methods
DONG NAI UNIVERSITY OF TECHNOLOGY
16
4. Store Application Settings
Method Description Example
Remove(key) Removes the item
associated to the specified
key from the dictionary.
IsolatedStorageSettings.
ApplicationSettings.
Remove("MyKey");
Save() Saves the changes made
within the collection to
isolated storage.
IsolatedStorageSettings.
ApplicationSettings.
Save()
IsolatedStorageSettings Methods
using System.IO.IsolatedStorage;
DONG NAI UNIVERSITY OF TECHNOLOGY
17
4. Store Application Settings
System.IO.IsolatedStorage.IsolatedStorageSettings
isoStoreSettings = System.IO.IsolatedStorage.
IsolatedStorageSettings.ApplicationSettings;
isoStoreSettings["IntegerValue"] = 113;
isoStoreSettings["StringValue"] = Dr Thanh;
isoStoreSettings["DateValue"] = datePicker.Value.Value;
isoStoreSettings["BoolValue"] = (bool)toggleSwitch.IsChecked;

isoStoreSettings.Save();
Write settings:
DONG NAI UNIVERSITY OF TECHNOLOGY
18
4. Store Application Settings
Read settings:
System.IO.IsolatedStorage.IsolatedStorageSettings
isoStoreSettings = System.IO.IsolatedStorage.
IsolatedStorageSettings.ApplicationSettings;

int intValue= (int)isoStoreSettings["IntegerValue"];
string stringValue = (string)isoStoreSettings["StringValue"];
DateTime dateValue =
((DateTime)isoStoreSettings["DateValue"]).Date;
bool boolValue= (bool)isoStoreSettings["BoolValue"];
DONG NAI UNIVERSITY OF TECHNOLOGY
19
4. Store Application Settings
Person p = new Person();
p.FirstName = firstNameTextBox.Text;
p.LastName = lastNameTextBox.Text;
IsolatedStorageSettings isoStoreSettings =
IsolatedStorageSettings.ApplicationSettings;

Write custom settings:
Person p;
if(isoStoreSettings.TryGetValue("Person", out p))
{
}
isoStoreSettings["Person"] = p;
isoStoreSettings.Save();
Read custom settings:
DONG NAI UNIVERSITY OF TECHNOLOGY
20
There are multiple methods to load and parse XML. In this
document we will focus on the XDocument object from the
System.Xml.Linq namespace.
5. Consuming XML
DONG NAI UNIVERSITY OF TECHNOLOGY
21
<?xml version="1.0" encoding="utf-8" ?>
<persons>
<person>
<name>Trn Duy Thanh</name>
<address>S 3 ng 6, Khu Dn C
Gia Ha, p 5, Phong Ph, Bnh Chnh,
Tp.HCM</address>
</person>
<person>
<name>Phm Th Xun Diu</name>
<address>Ph vang, Bnh i, Bn
Tre</address>
</person>
<person>
<name>Nguyn Vn Hng</name>
<address>S 15 Nguyn Vn V, Qun
Tn Bnh, TP.HCM</address>
</person>
</persons>
5. Consuming XML
DONG NAI UNIVERSITY OF TECHNOLOGY
22
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="PersonListBox"
ItemsSource="{Binding}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"
HorizontalAlignment="Stretch"
Style="{StaticResource PhoneTextAccentStyle}" />
<TextBlock Text="{Binding Address}"
TextWrapping="Wrap"
HorizontalAlignment="Stretch" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
MainPage.xaml
5. Consuming XML
DONG NAI UNIVERSITY OF TECHNOLOGY
23
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
}
loadXMLData("Data/person_data_source.xml");
5. Consuming XML
DONG NAI UNIVERSITY OF TECHNOLOGY
24
public void loadXMLData(string fileName) {
XDocument document = XDocument.Load(fileName,
LoadOptions.None);
XElement root = document.Element("persons");
IEnumerable<XElement> listElement=root.Elements("person");
var listPerson = listElement.Select (

p => new Person()
{
Name=p.Element("name").Value,
Address = p.Element("address").Value,
});
PersonListBox.DataContext = listPerson;
}
5. Consuming XML
DONG NAI UNIVERSITY OF TECHNOLOGY
25
6. Serializing Objects
6.1 XMLSerializer
6.2 DataContractSerializer
6.3 DataContractJsonSerializer
DONG NAI UNIVERSITY OF TECHNOLOGY
26
6.1 XMLSerializer
The XmlSerializer class takes care of
serializing objects into XML, then re-
hydrating the XML back into object
form.
The serialized objects can be saved to
the database, local storage, or passed
to some other process.
To use XmlSerializer, add the
System.Xml.Serialization assembly
to the References node of your project
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
}
DONG NAI UNIVERSITY OF TECHNOLOGY
27
6.1 XMLSerializer
public void XmlSerialize() {
// Create the Person object with user data
var person = new Person() {
FirstName = txtFirtName1.Text,
LastName = txtLastName1.Text };
// create an XmlSerializer for the Person type
var serializer = new XmlSerializer(typeof(Person));
// serialize the Person object to XML stored in a stream
var stream = new MemoryStream();
serializer.Serialize(stream, person);
// extract the XML and display in the textbox
stream.Position = 0;
var reader = new StreamReader(stream);
txtData1.Text = reader.ReadToEnd();
}
DONG NAI UNIVERSITY OF TECHNOLOGY
28
6.1 XMLSerializer
public void XmlDeserialize()
{
// create the XmlSerializer for the Person type
var serializer = new XmlSerializer(typeof(Person));
// place the XML text into a stream
var stream = new
MemoryStream(Encoding.UTF8.GetBytes(txtData1.Text));
// deserialize the stream containing XML to the Person object
var person = serializer.Deserialize(stream) as Person;
// Display the reconstituded object in the text boxes
txtFirtName1.Text = person.FirstName;
txtLastName1.Text = person.LastName;
}
DONG NAI UNIVERSITY OF TECHNOLOGY
29
6.2 DataContractSerializer
DataContractSerializer is faster than
XmlSerializer, but has fewer options
for tweaking the XML output. If you
dont need control over the XML
format, DataContractSerializer can
be swapped for XmlSerializer with
only a few changes.
You must mark classes and members
to be serialized with attributes from
the System.Runtime.Serialization
namespace.
DONG NAI UNIVERSITY OF TECHNOLOGY
30
6.2 DataContractSerializer
using System.Runtime.Serialization;
namespace LearnXMlSerialization
{
[DataContract]
public class ContractPerson
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
}
}
DONG NAI UNIVERSITY OF TECHNOLOGY
31
6.2 DataContractSerializer
private void SerializeWith_DataContractSerializer() {
// Create the Person object with user data
var person = new ContractPerson() {
FirstName = txtFirtName2.Text,
LastName = txtLastName2.Text
};
// create an DataContractSerializer( for the Person type
var serializer = new
DataContractSerializer(typeof(ContractPerson));
// serialize the Person object to XML stored in a stream
var stream = new MemoryStream();
serializer.WriteObject(stream, person);
// extract the XML and display in the textbox
stream.Position = 0;
var reader = new StreamReader(stream);
txtData2.Text = reader.ReadToEnd();
}
DONG NAI UNIVERSITY OF TECHNOLOGY
32
6.2 DataContractSerializer
private void DeserializeWith_DataContractSerializer() {
// create the DataContractSerializer for the Person type
var serializer = new
DataContractSerializer(typeof(ContractPerson));
// place the XML text into a stream
var stream = new
MemoryStream(Encoding.UTF8.GetBytes(txtData2.Text));
// deserialize the stream containing XML to the Person object
var person = serializer.ReadObject(stream) as
ContractPerson;
// Display the reconstituded object in the text boxes
txtFirtName2.Text = person.FirstName;
txtLastName2.Text = person.LastName;
}
DONG NAI UNIVERSITY OF TECHNOLOGY
33
6.3 DataContractJsonSerializer
JavaScript Object Notation (JSON) is
the other big player in the data
serialization space. Its simplicity and
lighter weight makes it a pervasive
choice among web services.
JSON serialization is like the previous
XML serialization examples except that
DataContractJsonSerializer from the
System.Runtime.Serialization.Json
namespace performs the heavy lifting
DONG NAI UNIVERSITY OF TECHNOLOGY
34
6.3 DataContractJsonSerializer
public void JsonSerialization() {
// Create the Person object with user data
Person person = new Person() {
FirstName = txtFirtName3.Text,
LastName = txtLastName3.Text
};
// serialize the object to Json form
var serializer = new DataContractJsonSerializer(typeof(Person));
var stream = new MemoryStream();
serializer.WriteObject(stream, person);
// write the Json out to a textbox
stream.Position = 0;
var reader = new StreamReader(stream);
txtData3.Text = reader.ReadToEnd();
}
DONG NAI UNIVERSITY OF TECHNOLOGY
35
6.3 DataContractJsonSerializer
public void JsonDeSerialization() {
// create the DataContractJsonSerializer for the Person type
var serializer = new
DataContractJsonSerializer(typeof(Person));
// place the XML text into a stream
var stream = new
MemoryStream(Encoding.UTF8.GetBytes(txtData3.Text));
// deserialize the stream containing XML to the Person object
var person = serializer.ReadObject(stream) as Person;
// Display the reconstituded object in the text boxes
txtFirtName3.Text = person.FirstName;
txtLastName3.Text = person.LastName;
}
DONG NAI UNIVERSITY OF TECHNOLOGY
36
7. Consuming Web Resources
WebClient and HttpRequest objects retrieve XML or JSON
data from remote locations on the web, RSS feeds, and web
services.
WebClient is the simpler of the two to use and is handy for
one time access to web services or for downloading remote
resources.
HttpRequest is slightly more complex but designed for
greater control over content type, headers, cookies and
credentials.
DONG NAI UNIVERSITY OF TECHNOLOGY
37
7. Consuming Web Resources
WebClient
Use the WebClient method DownloadStringAsync() to bring
down a string of text or OpenReadAsync() to retrieve a stream
of binary data. In both cases, set up a handler for the completion
of the operation and call the appropriate asynchronous method.
Before we can call either method, we need to set up the objects
and methods that will parse and store the data.
In the example that follows, we will pull data from the Flickr API.
1. Login : www.flickr.com
2. Get API Key: http://www.flickr.com/services/apps/create/
DONG NAI UNIVERSITY OF TECHNOLOGY
38
7. Consuming Web Resources
WebClient
1. Login : www.flickr.com
1. Get API Key:
http://www.flickr.com/serv
ices/apps/create/
DONG NAI UNIVERSITY OF TECHNOLOGY
39
7. Consuming Web Resources
WebClient
<Grid x:Name="LayoutRoot" >
<ListBox x:Name="FlickrListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Stretch="UniformToFill" Width="100"
Height="100"
Source="{Binding Uri}" />
<TextBlock Grid.Column="1" Margin="10,0,0,0"
Text="{Binding Title}"
HorizontalAlignment="Stretch" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
MainPage.Xaml
DONG NAI UNIVERSITY OF TECHNOLOGY
40
7. Consuming Web Resources
WebClient
private const string BaseUrl =
"http://ycpi.api.flickr.com/services/rest/";
private const string QueryStrings =

"?method={0}&api_key={1}&user_id={2}&format=j
son&nojsoncallback=1";
private const string FlickrMethod =
"flickr.people.getPublicPhotos";
private const string YourApiKey =
"dcd6a32705ef1615f2a652247bf5df95";
private const string
LibraryOfCongressKey = "8623220@N02";
private string FlickrPhotosUrl =
BaseUrl +
String.Format(QueryStrings,
FlickrMethod, YourApiKey,
LibraryOfCongressKey);
DONG NAI UNIVERSITY OF TECHNOLOGY
41
7. Consuming Web Resources
WebClient
private void UseWebClient()
{
var uri = new Uri(FlickrPhotosUrl);
var client = new WebClient();
client.DownloadStringCompleted += (sender, e) =>
{
var photos = GetFlickrPhotos(e.Result);
Dispatcher.BeginInvoke(() =>
{
FlickrListBox.DataContext = photos;
});
};
client.DownloadStringAsync(uri);
}
Call UseWebClient() Method in OnNavigatedTo
DONG NAI UNIVERSITY OF TECHNOLOGY
42
7. Consuming Web Resources
private static List<FlickrPhoto> GetFlickrPhotos(string json) {
const string baseUrl =
"http://farm{0}.staticflickr.com/{1}/{2}_{3}_s.jpg";
List<FlickrPhoto> FlickrPhotos = null;
var serializer = new DataContractJsonSerializer(typeof(RootObject));
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json))) {
var root = serializer.ReadObject(stream) as RootObject;
if (root.photos != null) {
FlickrPhotos = (from photo in root.photos.photo
select new FlickrPhoto {
Title = photo.title,
Uri = new Uri(String.Format(baseUrl,
photo.farm, photo.server, photo.id, photo.secret))
}).ToList();
}
}
return FlickrPhotos;
}
DONG NAI UNIVERSITY OF TECHNOLOGY
43
7. Consuming Web Resources
public class Photo
{
public string id { get; set; }
public string owner { get; set; }
public string secret { get; set; }
public string server { get; set; }
public int farm { get; set; }
public string title { get; set; }
public int ispublic { get; set; }
public int isfriend { get; set; }
public int isfamily { get; set; }
}
public class Photos
{
public int page { get; set; }
public int pages { get; set; }
public int perpage { get; set; }
public string total { get; set; }
public List<Photo> photo { get; set; }
}
DONG NAI UNIVERSITY OF TECHNOLOGY
44
7. Consuming Web Resources
public class RootObject
{
public Photos photos { get; set; }
public string stat { get; set; }
}
public class FlickrPhoto
{
public string Title { get; set; }
public Uri Uri { get; set; }
}
DONG NAI UNIVERSITY OF TECHNOLOGY
45
7. Consuming Web Resources
HttpWebRequest
private void Button_Click(object sender,
RoutedEventArgs e)
{
System.Uri targetUri = new
System.Uri(TextBlockTargetUri.Text);
HttpWebRequest request =
(HttpWebRequest)HttpWebRequest.Create
(targetUri);
request.BeginGetResponse(new
AsyncCallback(ReadWebRequestCallback),
request);
}
DONG NAI UNIVERSITY OF TECHNOLOGY
46
7. Consuming Web Resources
private void ReadWebRequestCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse myResponse =
(HttpWebResponse)myRequest.EndGetResponse(callbackResult);
using (StreamReader httpwebStreamReader = new
StreamReader(myResponse.GetResponseStream()))
{
string results = httpwebStreamReader.ReadToEnd();
//TextBlockResults.Text = results; //-- on another thread!
Dispatcher.BeginInvoke(() => TextBlockResults.Text = results);
}
myResponse.Close();
}
DONG NAI UNIVERSITY OF TECHNOLOGY
47
8. Using a Local Database
8.2 LINQ-to-SQL
8.3 SQLite
DONG NAI UNIVERSITY OF TECHNOLOGY
48
8.1 LINQ-to-SQL
The Windows Phone 7.1 SDK added support for local
databases in Windows Phone Store apps by using the LINQ-
to-SQL API and the SQL Server Compact Edition (SQLCE)
database engine.
The primary advantage of a database is that it makes it
possible for you to perform complex queries on potentially
large data sets without requiring that you load all that data
into memory
DONG NAI UNIVERSITY OF TECHNOLOGY
49
8.1 LINQ-to-SQL
LINQ-to-SQL is an object-relational mapping (ORM) API
based on the Language-Integrated Query (LINQ) framework.
It makes it possible for apps to perform queries and create,
read, update, and delete (CRUD) operations on strongly
typed managed objects, just as it would on data stored in
memory, while taking advantage of the underlying database
engine to load only the data thats required.
DONG NAI UNIVERSITY OF TECHNOLOGY
50
8.1 LINQ-to-SQL
DONG NAI UNIVERSITY OF TECHNOLOGY
51
8.1 LINQ-to-SQL
DONG NAI UNIVERSITY OF TECHNOLOGY
52
8.1 LINQ-to-SQL
DONG NAI UNIVERSITY OF TECHNOLOGY
53
8.2 SQLite
Windows Phone 8 adds support for the popular open-source
database engine, SQLite. SQLite offers several key advantages
over LINQ-to-SQL and SQLCE, such as the following:
SQLite is accessible from native code.
It is supported on most modern operating systems, allowing
for code reuse across platforms.
It provides higher performance for certain types of
operations.
DONG NAI UNIVERSITY OF TECHNOLOGY
54
8.2 SQLite
Acquiring SQLite for Windows Phone
On the Tools menu, choose Extension
And Updates to open the Extensions
And Updates dialog box. Use the search
box in the upper-right corner of the
dialog box to search for SQLite
1
DONG NAI UNIVERSITY OF TECHNOLOGY
55
8.2 SQLite
After youve installed that, the native sqlite3 dlls are installed
into a folder under C:\Program Files (x86)\Microsoft
SDKs\Windows Phone\v8.0\ExtensionSDKs\SQLite.WP80\.
Thats just for your information you should never have to
manually copy the sqlite3.dll from there in order to use the
database.
This location: It is important to fix some errors
DONG NAI UNIVERSITY OF TECHNOLOGY
56
8.2 SQLite
Inside C:\Program Files (x86)\Microsoft SDKs\Windows
Phone\v8.0\ExtensionSDKs\SQLite.WP80\3.8.3.1
DONG NAI UNIVERSITY OF TECHNOLOGY
57
8.2 SQLite
Download SQLiteWinRTPhone:
https://sqlwinrt.codeplex.com/SourceControl/latest
2
DONG NAI UNIVERSITY OF TECHNOLOGY
58
8.2 SQLite
Make the same version 3.8.3.1
Inside SQLiteWinRTPhone
3
DONG NAI UNIVERSITY OF TECHNOLOGY
59
8.2 SQLite
4
Include Existing Project
DONG NAI UNIVERSITY OF TECHNOLOGY
60
8.2 SQLite
5
Add Reference Project
DONG NAI UNIVERSITY OF TECHNOLOGY
61
8.2 SQLite
Create Database & Table
Insert one row
Select one row
Select Multi rows
Update row
Delete Row
Demo
(Take yourself GUI)
DONG NAI UNIVERSITY OF TECHNOLOGY
62
8.2 SQLite
using Windows.Storage;
using SQLiteWinRT;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
static Database db;
static ManualResetEvent DBLoaded = new ManualResetEvent(false);
public static Task<Database> GetDatabaseAsync()
{
return Task.Run(() =>
{
DBLoaded.WaitOne();
return db;
});
}
MainPage coding
DONG NAI UNIVERSITY OF TECHNOLOGY
63
8.2 SQLite
private async void LoadDatabase()
{
// Get a reference to the SQLite database
db = new Database
(ApplicationData.Current.LocalFolder, "books.db");

await db.OpenAsync();

string sql = @"CREATE TABLE IF NOT EXISTS
Sach (Ma VARCHAR(10),
Ten NVARCHAR( 150 ),
Trang INTEGER
);";
string description = "Create Sach table";
await ExecuteSQLStatement(db, sql, description);

DBLoaded.Set();
}
Create Database & Table
DONG NAI UNIVERSITY OF TECHNOLOGY
64
8.2 SQLite
private static async Task ExecuteSQLStatement
(Database db, string sql, string description)
{
try
{
await db.ExecuteStatementAsync(sql);
Debug.WriteLine(description + " executed OK");
}
catch (Exception ex)
{
}
}
DONG NAI UNIVERSITY OF TECHNOLOGY
65
8.2 SQLite
private async void InsertData()
{
try
{
// Connection already opened in app.xaml.cs - get reference
Database db = await GetDatabaseAsync();
var custstmt = await db.PrepareStatementAsync
("INSERT INTO Sach (Ma, Ten, Trang) VALUES (@Ma, @Ten, @Trang)");
// NOTE that named parameters have a leading "@",":" or "$".
custstmt.BindTextParameterWithName("@Ma", txtMaSach.Text);
custstmt.BindTextParameterWithName("@Ten", txtTenSach.Text);
custstmt.BindIntParameterWithName("@Trang", int.Parse(txtSoTrang.Text));
// Use StepAsync to execute a prepared statement
await custstmt.StepAsync();
}
catch (System.Runtime.InteropServices.COMException ex)
{
throw new ApplicationException(ex.Message );
}
}
Insert one row
DONG NAI UNIVERSITY OF TECHNOLOGY
66
8.2 SQLite
Select one row
public async void GetData(string ma)
{
var db = await GetDatabaseAsync();
var readstmt = await db.PrepareStatementAsync(
"SELECT * FROM Sach WHERE Ma = @ma");
readstmt.BindTextParameterWithName("@ma", ma);
if (await readstmt.StepAsync() == true)
{
txtMaSach.Text= readstmt.GetTextAt(0);
txtTenSach.Text=readstmt.GetTextAt(1);
txtSoTrang.Text=readstmt.GetIntAt(2)+"";
}
}
DONG NAI UNIVERSITY OF TECHNOLOGY
67
8.2 SQLite
Select Multi rows
public async void GetData() {
var db = await GetDatabaseAsync();
var readstmt = await db.PrepareStatementAsync
("SELECT Ma,Ten,Trang FROM Sach");
List<string> dsTen = new List<string>();
while(await readstmt.StepAsync() == true) {
string ma = readstmt.GetTextAt(0);
string ten = readstmt.GetTextAt(1);
int trang = readstmt.GetIntAt(2);
dsTen.Add(ma+" - "+ten +" - page = "+trang);
}
longlistSelector1.ItemsSource = null;
longlistSelector1.ItemsSource = dsTen;
}
DONG NAI UNIVERSITY OF TECHNOLOGY
68
8.2 SQLite
Update Row
public async void UpdateData(string ma)
{
// See if the customer already exists
var custstmt = await db.PrepareStatementAsync
("UPDATE Sach SET Ten = ?, Trang = ? WHERE Ma=?");
{
// NOTE when using anonymous parameters the first has an
index of 1, not 0.
custstmt.BindTextParameterAt(1, txtTenSach.Text);
custstmt.BindIntParameterAt(2, int.Parse( txtSoTrang.Text));
custstmt.BindTextParameterAt(3, txtMaSach.Text);
await custstmt.StepAsync();
}

}
DONG NAI UNIVERSITY OF TECHNOLOGY
69
8.2 SQLite
Delete Row
public async void DeleteData(string ma)
{
string sql = @"DELETE FROM Sach WHERE Ma=@ma";
var custstmt = await db.PrepareStatementAsync(sql);
custstmt.BindTextParameterWithName("@ma", ma);

await custstmt.StepAsync();
}
DONG NAI UNIVERSITY OF TECHNOLOGY
70
8.2 SQLite
Exercise: Create Database as the same picture below, and
then input some data foreach table to test
How to Enable foreign key constraints???
DONG NAI UNIVERSITY OF TECHNOLOGY
END
71

You might also like