5 -data storage (6t)

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

Upload: neversayloveyou

Post on 21-Jul-2016

32 views

Category:

Documents


4 download

DESCRIPTION

5 -Data Storage (6t)

TRANSCRIPT

Page 1: 5 -Data Storage (6t)

1

DONG NAI UNIVERSITY OF TECHNOLOGY

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

Page 2: 5 -Data Storage (6t)

2

DONG NAI UNIVERSITY OF TECHNOLOGY

1. Read & Write Data to a Local File

ProblemYou want to be able to read and write file data from within a Windows Phone app. SolutionUtilize the StorageFolder and StorageFile classes to perform file and folder management. How It WorksThe 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.

Page 3: 5 -Data Storage (6t)

3

DONG NAI UNIVERSITY OF TECHNOLOGY

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;

Page 4: 5 -Data Storage (6t)

4

DONG NAI UNIVERSITY OF TECHNOLOGY

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;}

Page 5: 5 -Data Storage (6t)

5

DONG NAI UNIVERSITY OF TECHNOLOGY

1. Read & Write Data to a Local File

public async Task<string> LoadFile(string fileName){ //Get the local folder for the current applicationStorageFolder 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;}

Page 6: 5 -Data Storage (6t)

6

DONG NAI UNIVERSITY OF TECHNOLOGY

1. Read & Write Data to a Local File

ProblemYou want to develop an app that will allow the user to read data from an external media card. SolutionLeverage the set of ExternalStorage classes, available within the Microsoft.Phone.Storage APIs. How It WorksThe Microsoft.Phone.Storage namespace includes the following set of classes that can be used to access and read from external storage:

Page 7: 5 -Data Storage (6t)

7

DONG NAI UNIVERSITY OF TECHNOLOGY

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.

Page 8: 5 -Data Storage (6t)

8

DONG NAI UNIVERSITY OF TECHNOLOGY

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>

Page 9: 5 -Data Storage (6t)

9

DONG NAI UNIVERSITY OF TECHNOLOGY

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"); }}

Page 10: 5 -Data Storage (6t)

10

DONG NAI UNIVERSITY OF TECHNOLOGY

3. Encrypt Data

ProblemYou 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. SolutionLeverage the Data Protection API to encrypt/decrypt sensitive file data. How It WorksThe 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.

Page 11: 5 -Data Storage (6t)

11

DONG NAI UNIVERSITY OF TECHNOLOGY

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";

Page 12: 5 -Data Storage (6t)

12

DONG NAI UNIVERSITY OF TECHNOLOGY

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) { }}

Page 13: 5 -Data Storage (6t)

13

DONG NAI UNIVERSITY OF TECHNOLOGY

3. Encrypt Dataprivate 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) { }}

Page 14: 5 -Data Storage (6t)

14

DONG NAI UNIVERSITY OF TECHNOLOGY

4. Store Application Settings

ProblemYou want to include application-specific settings in your Windows Phone application that the users can change from within the app. SolutionStore 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 WorksThe IsolatedStorageSettings class, within the System.IO.IsolatedStorage namespace, can be used to store key-value pairs in the application’s 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.

Page 15: 5 -Data Storage (6t)

15

DONG NAI UNIVERSITY OF TECHNOLOGY

4. Store Application Settings

Method Description Example

Add(key, value) Adds an entry to the IsolatedStorageSettingscollection.

IsolatedStorageSettings.ApplicationSettings.Add(“MyKey”, 1)

Clear() Removes all items from the IsolatedStorageSettingscollection

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

Page 16: 5 -Data Storage (6t)

16

DONG NAI UNIVERSITY OF TECHNOLOGY

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;

Page 17: 5 -Data Storage (6t)

17

DONG NAI UNIVERSITY OF TECHNOLOGY

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:

Page 18: 5 -Data Storage (6t)

18

DONG NAI UNIVERSITY OF TECHNOLOGY

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"];

Page 19: 5 -Data Storage (6t)

19

DONG NAI UNIVERSITY OF TECHNOLOGY

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:

Page 20: 5 -Data Storage (6t)

20

DONG NAI UNIVERSITY OF TECHNOLOGY

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

Page 21: 5 -Data Storage (6t)

21

DONG NAI UNIVERSITY OF TECHNOLOGY

<?xml version="1.0" encoding="utf-8" ?><persons> <person> <name>TrầCn Duy Thanh</name> <address>Số 3 đường 6, Khu Dân Cư Gia Hòa, Ấp 5, Phong Phú, Bình Chánh, Tp.HCM</address> </person> <person> <name>Phạm Thị Xuần Diệu</name> <address>Phú vang, Bình Đại, BếLn Tre</address> </person> <person> <name>NguyếMn Văn Hùng</name> <address>SốL 15 NguyếMn Văn Vĩ, Quận Tần Bình, TP.HCM</address> </person></persons>

5. Consuming XML

Page 22: 5 -Data Storage (6t)

22

DONG NAI UNIVERSITY OF TECHNOLOGY

<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

Page 23: 5 -Data Storage (6t)

23

DONG NAI UNIVERSITY OF TECHNOLOGY

public class Person { public string Name { get; set; } public string Address { get; set; } }

loadXMLData("Data/person_data_source.xml");

5. Consuming XML

Page 24: 5 -Data Storage (6t)

24

DONG NAI UNIVERSITY OF TECHNOLOGY

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

Page 25: 5 -Data Storage (6t)

25

DONG NAI UNIVERSITY OF TECHNOLOGY

6. Serializing Objects

6.1 XMLSerializer

6.2 DataContractSerializer

6.3 DataContractJsonSerializer

Page 26: 5 -Data Storage (6t)

26

DONG NAI UNIVERSITY OF TECHNOLOGY

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; } }

Page 27: 5 -Data Storage (6t)

27

DONG NAI UNIVERSITY OF TECHNOLOGY

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();}

Page 28: 5 -Data Storage (6t)

28

DONG NAI UNIVERSITY OF TECHNOLOGY

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 streamvar 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;}

Page 29: 5 -Data Storage (6t)

29

DONG NAI UNIVERSITY OF TECHNOLOGY

6.2 DataContractSerializer

DataContractSerializer is faster than XmlSerializer, but has fewer options for tweaking the XML output. If you don’t 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.

Page 30: 5 -Data Storage (6t)

30

DONG NAI UNIVERSITY OF TECHNOLOGY

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; } }}

Page 31: 5 -Data Storage (6t)

31

DONG NAI UNIVERSITY OF TECHNOLOGY

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();}

Page 32: 5 -Data Storage (6t)

32

DONG NAI UNIVERSITY OF TECHNOLOGY

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;}

Page 33: 5 -Data Storage (6t)

33

DONG NAI UNIVERSITY OF TECHNOLOGY

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

Page 34: 5 -Data Storage (6t)

34

DONG NAI UNIVERSITY OF TECHNOLOGY

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(); }

Page 35: 5 -Data Storage (6t)

35

DONG NAI UNIVERSITY OF TECHNOLOGY

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;}

Page 36: 5 -Data Storage (6t)

36

DONG NAI UNIVERSITY OF TECHNOLOGY

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.

Page 37: 5 -Data Storage (6t)

37

DONG NAI UNIVERSITY OF TECHNOLOGY

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/

Page 38: 5 -Data Storage (6t)

38

DONG NAI UNIVERSITY OF TECHNOLOGY

7. Consuming Web Resources

WebClient

1. Login : www.flickr.com

1. Get API Key: http://www.flickr.com/services/apps/create/

Page 39: 5 -Data Storage (6t)

39

DONG NAI UNIVERSITY OF TECHNOLOGY

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

Page 40: 5 -Data Storage (6t)

40

DONG NAI UNIVERSITY OF TECHNOLOGY

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=json&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);

Page 41: 5 -Data Storage (6t)

41

DONG NAI UNIVERSITY OF TECHNOLOGY

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

Page 42: 5 -Data Storage (6t)

42

DONG NAI UNIVERSITY OF TECHNOLOGY

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;}

Page 43: 5 -Data Storage (6t)

43

DONG NAI UNIVERSITY OF TECHNOLOGY

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; } }

Page 44: 5 -Data Storage (6t)

44

DONG NAI UNIVERSITY OF TECHNOLOGY

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; } }

Page 45: 5 -Data Storage (6t)

45

DONG NAI UNIVERSITY OF TECHNOLOGY

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); }

Page 46: 5 -Data Storage (6t)

46

DONG NAI UNIVERSITY OF TECHNOLOGY

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();}

Page 47: 5 -Data Storage (6t)

47

DONG NAI UNIVERSITY OF TECHNOLOGY

8. Using a Local Database

8.2 LINQ-to-SQL

8.3 SQLite

Page 48: 5 -Data Storage (6t)

48

DONG NAI UNIVERSITY OF TECHNOLOGY

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

Page 49: 5 -Data Storage (6t)

49

DONG NAI UNIVERSITY OF TECHNOLOGY

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 that’s required.

Page 50: 5 -Data Storage (6t)

50

DONG NAI UNIVERSITY OF TECHNOLOGY

8.1 LINQ-to-SQL

Page 51: 5 -Data Storage (6t)

51

DONG NAI UNIVERSITY OF TECHNOLOGY

8.1 LINQ-to-SQL

Page 52: 5 -Data Storage (6t)

52

DONG NAI UNIVERSITY OF TECHNOLOGY

8.1 LINQ-to-SQL

Page 53: 5 -Data Storage (6t)

53

DONG NAI UNIVERSITY OF TECHNOLOGY

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.

Page 54: 5 -Data Storage (6t)

54

DONG NAI UNIVERSITY OF TECHNOLOGY

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

Page 55: 5 -Data Storage (6t)

55

DONG NAI UNIVERSITY OF TECHNOLOGY

8.2 SQLite

After you’ve 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\. That’s 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

Page 56: 5 -Data Storage (6t)

56

DONG NAI UNIVERSITY OF TECHNOLOGY

8.2 SQLite

Inside “C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\ExtensionSDKs\SQLite.WP80\3.8.3.1”

Page 57: 5 -Data Storage (6t)

57

DONG NAI UNIVERSITY OF TECHNOLOGY

8.2 SQLite

Download SQLiteWinRTPhone: https://sqlwinrt.codeplex.com/SourceControl/latest

2

Page 58: 5 -Data Storage (6t)

58

DONG NAI UNIVERSITY OF TECHNOLOGY

8.2 SQLiteMake the same version 3.8.3.1

Inside SQLiteWinRTPhone

3

Page 59: 5 -Data Storage (6t)

59

DONG NAI UNIVERSITY OF TECHNOLOGY

8.2 SQLite

4

Include Existing Project

Page 60: 5 -Data Storage (6t)

60

DONG NAI UNIVERSITY OF TECHNOLOGY

8.2 SQLite5Add Reference Project

Page 61: 5 -Data Storage (6t)

61

DONG NAI UNIVERSITY OF TECHNOLOGY

8.2 SQLite

Create Database & Table Insert one row Select one row Select Multi rows Update row Delete Row

Demo(Take yourself GUI)

Page 62: 5 -Data Storage (6t)

62

DONG NAI UNIVERSITY OF TECHNOLOGY

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

Page 63: 5 -Data Storage (6t)

63

DONG NAI UNIVERSITY OF TECHNOLOGY

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

Page 64: 5 -Data Storage (6t)

64

DONG NAI UNIVERSITY OF TECHNOLOGY

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) {

} }

Page 65: 5 -Data Storage (6t)

65

DONG NAI UNIVERSITY OF TECHNOLOGY

8.2 SQLiteprivate 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

Page 66: 5 -Data Storage (6t)

66

DONG NAI UNIVERSITY OF TECHNOLOGY

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)+""; } }

Page 67: 5 -Data Storage (6t)

67

DONG NAI UNIVERSITY OF TECHNOLOGY

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; }

Page 68: 5 -Data Storage (6t)

68

DONG NAI UNIVERSITY OF TECHNOLOGY

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(); } }

Page 69: 5 -Data Storage (6t)

69

DONG NAI UNIVERSITY OF TECHNOLOGY

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(); }

Page 70: 5 -Data Storage (6t)

70

DONG NAI UNIVERSITY OF TECHNOLOGY

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???

Page 71: 5 -Data Storage (6t)

71

DONG NAI UNIVERSITY OF TECHNOLOGY

END