SlideShare a Scribd company logo
1 of 60
Download to read offline
Local Database
Files & Storage
Nguyen Tuan | Microsoft Certified Trainer
Agenda
• Local Data Storage: Overview
• Using Isolated Storage
• Using Setting Storage
• File & Protocol Association
• Data serialization
• Local database
• SQLite database
• External Storage(UsingSD Card)
Local Data Storage: Overview



Application
Settings File
App
Application
Files
Package
Manager
Install Folder
Install
DB
Databasefile
DB Database
File (r/o)
Installation folder
• Is a read-only folder
• Contains files of your app package
• APIs to access the installation folder:
• Application.GetResourceStream(Uri) method
• DataContext class
• Package.InstalledLocation property
• StorageFile and StorageFolder classes
Local folder
• Is the root folder of your app’s data store
• Is not altered or updated when you update your app
• Will be removed when the application is uninstalled
• It may be something like this:
C:DataUsersDefAppsAppData{5D93133B-3B39-4ABF-8D61-277D77B9F2AD}Local
Application.GetResourceStream(Uri)
// Get the image stream at the specified URI that
// is relative to the application package root.
Uri uri = new Uri(relativeUriString, UriKind.Relative);
StreamResourceInfo sri = Application.GetResourceStream(uri);
// Convert the stream to an Image object.
BitmapImage bi = new BitmapImage();
bi.SetSource(sri.Stream);
Image img = new Image();
img.Source = bi;
• Use this method to stream files from the installation folder
DataContext class
• To connect to a reference database that is part of the app
package
• is an object representing the database, a proxy, containing Table
objects that represent the tables in the database
Package.InstalledLocation property
• Returns the installation folder as a StorageFolder object
• The Path property to get the full path of the installation folder
Windows.ApplicationModel.Package package = Windows.ApplicationModel.Package.Current;
Windows.Storage.StorageFolder installedLocation = package.InstalledLocation;
String output = String.Format("Installed Location: {0}", installedLocation.Path);
Windows.Storage classes
• StorateFolder
• Represent a store area containing files and folders
• StorageFile
• Represent a file and provide method for manipulating
Saving Data
private async void WriteMessage(String message) {
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.CreateFileAsync("message.dat",
CreationCollisionOption.OpenIfExists);
Stream stream = await file.OpenStreamForWriteAsync();
using (StreamWriter writer = new StreamWriter(stream))
{
await writer.WriteAsync(message);
}
}
Loading Data
private async Task<string> ReadMessageAsync() {
string data = string.Empty;
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.GetFileAsync("message.dat");
Stream stream = await file.OpenStreamForReadAsync();
using (StreamReader reader = new StreamReader(stream))
{
data = await reader.ReadToEndAsync();
}
return data;
}
Isolated Storage Classes
• Isolated Storage is used to store local data
• All I/O operations are restricted to isolated storage
• IsolatedStorageFile
• Represents an isolated storage area containing files and folders
• IsolatedFileStream
• Exposes a file stream access to a file stored within isolated storage
• IsolatedStorageSetting
• Dictionary that stores key-value pairs in isolated storage
Saving Data
private void WriteMessageToIsolatedStorage(string message) {
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
using(IsolatedStorageFileStream stream = new IsolatedStorageFileStream("message.dat",
FileMode.Append, FileAccess.Write, store)){
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine(message);
writer.Close();
}
}
}
Loading Data
private string ReadMessageFromIsolatedStorage() {
string data = string.Empty;
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("message.dat",
FileMode.Open, store)) {
StreamReader reader = new StreamReader(stream);
data = reader.ReadToEnd();
reader.Close();
}
}
return data;
}
Saving Data in Settings
• Is used to store app’s setting in form of key-value.
• It works like a dictionary
private void SaveSetting(string key, string value) {
IsolatedStorageSettings.ApplicationSettings[key] = value;
IsolatedStorageSettings.ApplicationSettings.Save();
}
private string LoadSetting(string key) {
if (IsolatedStorageSettings.ApplicationSettings.Contains(key)) {
return (string)IsolatedStorageSettings.ApplicationSettings[key];
}
return null;
}
Special-use folders in the local folder
• Shared
• Shared/Media
• Shared/ShellContent
• Shared/Transfers
• PlatformData
File & Protocol Association
• File association allows app to launch when the
user want to open a particular file type, via:
• an email attachment
• a website via Internet Explorer
• a text message
• a NFC tag
• another app from the Store
WMAppManifiest.xml
Demo: FilesStorage
Serialization/Deserialization
• Convert an object into a stream of bytes
in order to store the object or transmit it
to memory, a database, or a file
• Binary serialization
• XML serialization
• SOAP serialization
XMLSerializer (1)
• Used to serialize/deserialize bettween objects and xml data
using System.Xml.Serialization;
[XmlRoot(“contact")]
public class Contact
{
[XmlElement("id")]
public int ID{get;set;}
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("email")]
public string Email { get; set; }
}
XMLSerializer (2) - Serialize
using System.Xml.Serialization;
.. .. .. .. ..
private async void SaveContactAsync(Contact contact){
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("contact.xml",
CreationCollisionOption.ReplaceExisting);
var outStream = await file.OpenStreamForWriteAsync();
XmlSerializer serializer = new XmlSerializer(typeof(Contact));
serializer.Serialize(outStream, contact);
await outStream.FlushAsync();
outStream.Close();
}
XMLSerialize (3) – XML File
<?xml version="1.0" encoding="utf-8" ?>
<contact>
<id>1</id>
<name>Maria Rose</name>
<email>rose@live.com</email>
</contact>
Contact contact = new Contact() {
ID = 1,
Name = "Maria Rose",
Email = "rose@live.com"
};
saveContact(contact);
XMLSerializer (4) - Deserialize
using System.Xml.Serialization;
.. .. .. .. ..
private async Task<Contact> LoadContactAsync() {
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("contact.xml");
var inStream = await file.OpenStreamForReadAsync();
XmlSerializer serializer = new XmlSerializer(typeof(Contact));
Contact contact = (Contact)serializer.Deserialize(inStream);
inStream.Close();
return contact;
}
Other Serializers
• DataContractSerializer
• DataContractJsonSerializer
• Third party
Demo: XML Serializer
1.DataStorage
Local database
• App can store relational data in local database
• Resides on app’s Local folder
• Use LINQ to SQL for all database operations
• LINQ provides object-relational mapping capabilites
DataContext
• DataContext is a proxy, represents the database
• Contains Table objects which represent tables on database
• Table objects is made up of entities that correspond to rows of
data in a database
public class TodoDataContext:DataContext
{
public static string DBConnectionString = "Data Source=isostore:/todo.sdf";
public TodoDataContext(string connectionString)
:base(connectionString){
}
public Table<TodoItem> TodoItems;
}
Entity Class
public class TodoItem:INotifyPropertyChanged, INotifyPropertyChanging
{
private int _id;
[Column(IsPrimaryKey=true, IsDbGenerated=true, DbType="INT NOT NULL IDENTITY", CanBeNull=false,
AutoSync=AutoSync.OnInsert)]
public int Id {
get {
return this._id;
}
set {
if (_id != value) {
NotifyPropertyChanging("Id");
this._id = value;
NotifyPropertyChanged("Id");
}
}
}
….
}
Creating database
using (TodoDataContext db = new TodoDataContext(TodoDataContext.DBConnectionString))
{
if (!db.DatabaseExists())
{
db.CreateDatabase();
}
}
Database operation
TodoItem newItem = new TodoItem() { Name = txtItemName.Text };
items.Add(newItem);
db.TodoItems.InsertOnSubmit(newItem);
db.SubmitChanges();
ObservableCollection<TodoItem> items = new ObservableCollection<TodoItem>();
var todoItems = from i in db.TodoItems select i;
foreach (var i in todoItems) {
items.Add(i);
}
Demo: Local Database
SQLite
• Is a SQL database engine
• Is self-contained
• Is serverless
• Is zero-configuration
• Is transactional
Why SQLite?
Worlds’ most popular database
RichFeatures
Reliable
SQLite.org
Documentation
SQL Syntax
C/C++ API Reference
Source and tools download
SQLite for Windows Phone
• SQLite database engine is fully supported on
WP8 platform
• SQLite engine for Windows Phone available as a
Visual Studio extension
Csharp-sqlite
• Is an independent reimplementation of
the SQLite software library
sqlite-net-wp8
• A C++/CX wrapper for SQLite functions that
sqlite-net depends on.
• Can be used as an alternative to csharp-sqlite on
Windows Phone 8
.NET APIs
SQLite-NET
LINQ syntax
Lightweight ORM
Similar to WP8 Local Database (LINQ to SQL)
SQLitePCL
SQL statements
Thin wrapper around the SQLite C API
using (var db = new SQLitePCL.Database("demo.db"))
{
db.Open();
using (var stmt = db.PrepareStatement
("SELECT name, age FROM people"))
{
while (stmt.Step())
{
var name = stmt.GetTextAt(0);
var age = stmt.GetIntAt(1);
}
}
}
var db =
new SQLite.SQLiteAsyncConnection(App.DBPath);
var _customer = await
(from c in db.Table<Customer>()
where c.Id == customerId
select c).FirstOrDefaultAsync();
if (customer != null)
{
var Id = _customer.Id;
var Name = _customer.Name;
}
Installing SQLitePCL to your Solution
1. Add Reference to SQLite extension SDK
2. In ConfigurationManager, change
target platform to X86 or ARM
3. In ‘Manage NuGet Packages’, add
reference to SQLitePCL package
Defining tables
SQLitePCL is really a thin wrapper around the SQLite ‘C’ API
Interact with the database using
SQL statements
Parameterized queries and statements
Create database and tables
private void LoadDatabase()
{
// Get a reference to the SQLite database
conn = new SQLiteConnection("sqlitepcldemo.db");
string sql = @"CREATE TABLE IF NOT EXISTS
Customer (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
Name VARCHAR( 140 ),
City VARCHAR( 140 ),
Contact VARCHAR( 140 )
);";
using (var statement = conn.Prepare(sql))
{
statement.Step();
}
}
Insert
// SqlConnection was opened in App.xaml.cs and exposed through property conn
var db = App.conn;
try
{
using (var custstmt = db.Prepare("INSERT INTO Customer (Name, City, Contact) VALUES (?, ?, ?)"))
{
custstmt.Bind(1, customerName);
custstmt.Bind(2, customerCity);
custstmt.Bind(3, customerContact);
custstmt.Step();
}
}
catch (Exception ex)
{
// TODO: Handle error
}
Select
public Customer GetCustomer(int customerId)
{
Customer customer = null;
using (var statement = dbconn.Prepare("SELECT Id, Name, City, Contact FROM Customer WHERE Id = ?"))
{
statement.Bind(1, customerId);
if (SQLiteResult.DONE == statement.Step())
{
customer = new Customer()
{
Id = (long)statement[0],
Name = (string)statement[1],
City = (string)statement[2],
Contact = (string)statement[3]
};
}
}
return customer;
Update
// See if the customer already exists
var existingCustomer = GetCustomer(customer.Id);
if (existingCustomer != null)
{
using (var custstmt = dbconn.Prepare("UPDATE Customer SET Name = ?, City = ?, Contact = ? WHERE Id=?"))
{
// NOTE when using anonymous parameters the first has an index of 1, not 0.
custstmt.Bind(1, customer.Name);
custstmt.Bind(2, customer.City);
custstmt.Bind(3, customer.Contact);
custstmt.Bind(4, customer.Id);
custstmt.Step();
}
}
Delete
public void DeleteCustomer(int customerId)
{
using (var statement = dbconn.Prepare("DELETE FROM Customer WHERE Id = ?"))
{
statement.Bind(1, customerId);
statement.Step();
}
}
Demo: SQLite
48
The SD Card in Windows Phone
This makes it possible for applicationsto share data amongst themselves
Maps to a local folder on your PC
49
Setting SD card capabilities
Removable Storage
Pictures Library
Videos Library
Music Library
50
Applications and file associations
An image processing program will work with files such as .jpg, .png, etc
A sound processing program will work with .mp3 files
You can add your own custom file types for your particular application if you wish
Note that this is not required for applications accessing files in their own local/roaming/temporary storage
This is the same mechanism used for app-to-app communications through file associations (See Session 10)
51
Setting file associations for your application
This applicationcan only work with .txt
files
52
Getting an SD Card
• These statements get a reference to the SD card on the phone
• They are part of a method that creates a file on the SD card
•This method is part of the demo software we will be running
later
53
var devices = Windows.Storage.KnownFolders.RemovableDevices;
var sdCards = await devices.GetFoldersAsync();
if (sdCards.Count == 0) return;
StorageFolder firstCard = sdCards[0];
Getting an SD Card
• We get a list of SD cards using the KnownFolders API
• There will only be 0 or 1
54
var devices = Windows.Storage.KnownFolders.RemovableDevices;
var sdCards = await devices.GetFoldersAsync();
if (sdCards.Count == 0) return;
StorageFolder firstCard = sdCards[0];
Getting an SD Card
• If there is not one present the value of the Count property will be 0
• This method returns if there are no SD Cards on the device
• Your application must handle this eventuality gracefully
•Not all devices have an SD card slot
•The slot might not have a card fitted into it
55
var devices = Windows.Storage.KnownFolders.RemovableDevices;
var sdCards = await devices.GetFoldersAsync();
if (sdCards.Count == 0) return;
StorageFolder firstCard = sdCards[0];
Getting an SD Card
• The card is exposed as a StorageFolder, so we can use it in the same way the previous
devices we have seen
• We can create folders and files
• But we can only work with files types for which we have declared a file association in the
manifest
56
var devices = Windows.Storage.KnownFolders.RemovableDevices;
var sdCards = await devices.GetFoldersAsync();
if (sdCards.Count == 0) return;
StorageFolder firstCard = sdCards[0];
Inserting an SD card in the emulator
57
SD Cards in the Emulator
58
Ejecting an SD Card from the emulator
There is an option to select this
59
09.Local Database Files and Storage on WP

More Related Content

What's hot

10 sharing files and data in windows phone 8
10   sharing files and data in windows phone 810   sharing files and data in windows phone 8
10 sharing files and data in windows phone 8WindowsPhoneRocks
 
09 data storage, backup and roaming
09   data storage, backup and roaming09   data storage, backup and roaming
09 data storage, backup and roamingWindowsPhoneRocks
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code FirstJames Johnson
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Rebecca Grenier
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android Aakash Ugale
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programmingchhaichivon
 
2001: JNDI Its all in the Context
2001:  JNDI Its all in the Context2001:  JNDI Its all in the Context
2001: JNDI Its all in the ContextRussell Castagnaro
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2Neeraj Mathur
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring DataOliver Gierke
 
Techniques for Cross Platform .NET Development
Techniques for Cross Platform .NET DevelopmentTechniques for Cross Platform .NET Development
Techniques for Cross Platform .NET DevelopmentJeremy Hutchinson
 

What's hot (20)

10 sharing files and data in windows phone 8
10   sharing files and data in windows phone 810   sharing files and data in windows phone 8
10 sharing files and data in windows phone 8
 
09 data storage, backup and roaming
09   data storage, backup and roaming09   data storage, backup and roaming
09 data storage, backup and roaming
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access
 
Android Data Persistence
Android Data PersistenceAndroid Data Persistence
Android Data Persistence
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android
 
JAXP
JAXPJAXP
JAXP
 
Persistences
PersistencesPersistences
Persistences
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
2001: JNDI Its all in the Context
2001:  JNDI Its all in the Context2001:  JNDI Its all in the Context
2001: JNDI Its all in the Context
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2
 
Ajax chap 4
Ajax chap 4Ajax chap 4
Ajax chap 4
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
Ajax chap 5
Ajax chap 5Ajax chap 5
Ajax chap 5
 
Techniques for Cross Platform .NET Development
Techniques for Cross Platform .NET DevelopmentTechniques for Cross Platform .NET Development
Techniques for Cross Platform .NET Development
 
SQLite with UWP
SQLite with UWPSQLite with UWP
SQLite with UWP
 
Android Data Persistence
Android Data PersistenceAndroid Data Persistence
Android Data Persistence
 

Viewers also liked

Les08 (manipulating data)
Les08 (manipulating data)Les08 (manipulating data)
Les08 (manipulating data)Achmad Solichin
 
Sql database object
Sql database objectSql database object
Sql database objectHarry Potter
 
Basic Concept of Database
Basic Concept of DatabaseBasic Concept of Database
Basic Concept of DatabaseMarlon Jamera
 
Modeling Physical Systems with Modern Object Oriented Perl
Modeling Physical Systems with Modern Object Oriented PerlModeling Physical Systems with Modern Object Oriented Perl
Modeling Physical Systems with Modern Object Oriented PerlJoel Berger
 
DB2 10 Universal Table Space - 2012-03-18 - no template
DB2 10 Universal Table Space - 2012-03-18 - no templateDB2 10 Universal Table Space - 2012-03-18 - no template
DB2 10 Universal Table Space - 2012-03-18 - no templateWillie Favero
 
Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - favero
 Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - favero Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - favero
Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - faveroWillie Favero
 
Database, data storage, hosting with Firebase
Database, data storage, hosting with FirebaseDatabase, data storage, hosting with Firebase
Database, data storage, hosting with FirebaseTu Pham
 
Oracle SQL Developer Data Modeler - Version Control Your Designs
Oracle SQL Developer Data Modeler - Version Control Your DesignsOracle SQL Developer Data Modeler - Version Control Your Designs
Oracle SQL Developer Data Modeler - Version Control Your DesignsJeff Smith
 
IBM DB2 for z/OS Administration Basics
IBM DB2 for z/OS Administration BasicsIBM DB2 for z/OS Administration Basics
IBM DB2 for z/OS Administration BasicsIBM
 
Strategies for Distributed Data Storage
Strategies for Distributed Data StorageStrategies for Distributed Data Storage
Strategies for Distributed Data Storagekakugawa
 
Understanding Data Partitioning and Replication in Apache Cassandra
Understanding Data Partitioning and Replication in Apache CassandraUnderstanding Data Partitioning and Replication in Apache Cassandra
Understanding Data Partitioning and Replication in Apache CassandraDataStax
 
5 Data Modeling for NoSQL 1/2
5 Data Modeling for NoSQL 1/25 Data Modeling for NoSQL 1/2
5 Data Modeling for NoSQL 1/2Fabio Fumarola
 
MS Sql Server: Reporting manipulating data
MS Sql Server: Reporting manipulating dataMS Sql Server: Reporting manipulating data
MS Sql Server: Reporting manipulating dataDataminingTools Inc
 

Viewers also liked (20)

Les08 (manipulating data)
Les08 (manipulating data)Les08 (manipulating data)
Les08 (manipulating data)
 
Sql database object
Sql database objectSql database object
Sql database object
 
Basic Concept of Database
Basic Concept of DatabaseBasic Concept of Database
Basic Concept of Database
 
Les09 Manipulating Data
Les09 Manipulating DataLes09 Manipulating Data
Les09 Manipulating Data
 
Physical Modeling and Design for Phase Change Memories
Physical Modeling and Design for Phase Change MemoriesPhysical Modeling and Design for Phase Change Memories
Physical Modeling and Design for Phase Change Memories
 
Modeling Physical Systems with Modern Object Oriented Perl
Modeling Physical Systems with Modern Object Oriented PerlModeling Physical Systems with Modern Object Oriented Perl
Modeling Physical Systems with Modern Object Oriented Perl
 
DB2 10 Universal Table Space - 2012-03-18 - no template
DB2 10 Universal Table Space - 2012-03-18 - no templateDB2 10 Universal Table Space - 2012-03-18 - no template
DB2 10 Universal Table Space - 2012-03-18 - no template
 
Database storage engines
Database storage enginesDatabase storage engines
Database storage engines
 
Partitioning
PartitioningPartitioning
Partitioning
 
Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - favero
 Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - favero Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - favero
Universal Table Spaces for DB2 10 for z/OS - IOD 2010 Seesion 1929 - favero
 
Database, data storage, hosting with Firebase
Database, data storage, hosting with FirebaseDatabase, data storage, hosting with Firebase
Database, data storage, hosting with Firebase
 
Modern PHP Developer
Modern PHP DeveloperModern PHP Developer
Modern PHP Developer
 
Database migration
Database migrationDatabase migration
Database migration
 
Oracle SQL Developer Data Modeler - Version Control Your Designs
Oracle SQL Developer Data Modeler - Version Control Your DesignsOracle SQL Developer Data Modeler - Version Control Your Designs
Oracle SQL Developer Data Modeler - Version Control Your Designs
 
IBM DB2 for z/OS Administration Basics
IBM DB2 for z/OS Administration BasicsIBM DB2 for z/OS Administration Basics
IBM DB2 for z/OS Administration Basics
 
Strategies for Distributed Data Storage
Strategies for Distributed Data StorageStrategies for Distributed Data Storage
Strategies for Distributed Data Storage
 
Understanding Data Partitioning and Replication in Apache Cassandra
Understanding Data Partitioning and Replication in Apache CassandraUnderstanding Data Partitioning and Replication in Apache Cassandra
Understanding Data Partitioning and Replication in Apache Cassandra
 
Access2013 ch09
Access2013 ch09Access2013 ch09
Access2013 ch09
 
5 Data Modeling for NoSQL 1/2
5 Data Modeling for NoSQL 1/25 Data Modeling for NoSQL 1/2
5 Data Modeling for NoSQL 1/2
 
MS Sql Server: Reporting manipulating data
MS Sql Server: Reporting manipulating dataMS Sql Server: Reporting manipulating data
MS Sql Server: Reporting manipulating data
 

Similar to 09.Local Database Files and Storage on WP

React Native Course - Data Storage . pdf
React Native Course - Data Storage . pdfReact Native Course - Data Storage . pdf
React Native Course - Data Storage . pdfAlvianZachryFaturrah
 
Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Nuxeo
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web appsIvano Malavolta
 
Serialization/deserialization
Serialization/deserializationSerialization/deserialization
Serialization/deserializationYoung Alista
 
Get docs from sp doc library
Get docs from sp doc libraryGet docs from sp doc library
Get docs from sp doc librarySudip Sengupta
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and OutputEduardo Bergavera
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12Vince Vo
 
Advance Mobile Application Development class 02-B
Advance Mobile Application Development class 02-BAdvance Mobile Application Development class 02-B
Advance Mobile Application Development class 02-BDr. Mazin Mohamed alkathiri
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...SPTechCon
 
Intoduction on Playframework
Intoduction on PlayframeworkIntoduction on Playframework
Intoduction on PlayframeworkKnoldus Inc.
 
Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Shakir Majeed Khan
 
Android App Development - 09 Storage
Android App Development - 09 StorageAndroid App Development - 09 Storage
Android App Development - 09 StorageDiego Grancini
 
BGOUG 2012 - Drag & drop and other stuff - Using your database as a file server
BGOUG 2012 - Drag & drop and other stuff - Using your database as a file serverBGOUG 2012 - Drag & drop and other stuff - Using your database as a file server
BGOUG 2012 - Drag & drop and other stuff - Using your database as a file serverMarco Gralike
 
Writing Swift code with great testability
Writing Swift code with great testabilityWriting Swift code with great testability
Writing Swift code with great testabilityJohn Sundell
 

Similar to 09.Local Database Files and Storage on WP (20)

React Native Course - Data Storage . pdf
React Native Course - Data Storage . pdfReact Native Course - Data Storage . pdf
React Native Course - Data Storage . pdf
 
Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web apps
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
 
Serialization/deserialization
Serialization/deserializationSerialization/deserialization
Serialization/deserialization
 
5-Hibernate.ppt
5-Hibernate.ppt5-Hibernate.ppt
5-Hibernate.ppt
 
Get docs from sp doc library
Get docs from sp doc libraryGet docs from sp doc library
Get docs from sp doc library
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 
Advance Mobile Application Development class 02-B
Advance Mobile Application Development class 02-BAdvance Mobile Application Development class 02-B
Advance Mobile Application Development class 02-B
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
Android - Saving data
Android - Saving dataAndroid - Saving data
Android - Saving data
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
 
Intoduction on Playframework
Intoduction on PlayframeworkIntoduction on Playframework
Intoduction on Playframework
 
Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...
 
Advance Mobile Application Development class 02
Advance Mobile Application Development class 02Advance Mobile Application Development class 02
Advance Mobile Application Development class 02
 
Lecture 11.pdf
Lecture 11.pdfLecture 11.pdf
Lecture 11.pdf
 
Android App Development - 09 Storage
Android App Development - 09 StorageAndroid App Development - 09 Storage
Android App Development - 09 Storage
 
BGOUG 2012 - Drag & drop and other stuff - Using your database as a file server
BGOUG 2012 - Drag & drop and other stuff - Using your database as a file serverBGOUG 2012 - Drag & drop and other stuff - Using your database as a file server
BGOUG 2012 - Drag & drop and other stuff - Using your database as a file server
 
Writing Swift code with great testability
Writing Swift code with great testabilityWriting Swift code with great testability
Writing Swift code with great testability
 

More from Nguyen Tuan

07.Notifications & Reminder, Contact
07.Notifications & Reminder, Contact07.Notifications & Reminder, Contact
07.Notifications & Reminder, ContactNguyen Tuan
 
12.Maps and Location
12.Maps and Location12.Maps and Location
12.Maps and LocationNguyen Tuan
 
11.Open Data Protocol(ODATA)
11.Open Data Protocol(ODATA) 11.Open Data Protocol(ODATA)
11.Open Data Protocol(ODATA) Nguyen Tuan
 
10.Local Database & LINQ
10.Local Database & LINQ10.Local Database & LINQ
10.Local Database & LINQNguyen Tuan
 
08.Push Notifications
08.Push Notifications 08.Push Notifications
08.Push Notifications Nguyen Tuan
 
13.Windows Phone Store
13.Windows Phone Store13.Windows Phone Store
13.Windows Phone StoreNguyen Tuan
 
06.Programming Media on Windows Phone
06.Programming Media on Windows Phone06.Programming Media on Windows Phone
06.Programming Media on Windows PhoneNguyen Tuan
 
05.Blend Expression, Transformation & Animation
05.Blend Expression, Transformation & Animation05.Blend Expression, Transformation & Animation
05.Blend Expression, Transformation & AnimationNguyen Tuan
 
03.Controls in Windows Phone
03.Controls in Windows Phone03.Controls in Windows Phone
03.Controls in Windows PhoneNguyen Tuan
 
04.Navigation on Windows Phone
04.Navigation on Windows Phone04.Navigation on Windows Phone
04.Navigation on Windows PhoneNguyen Tuan
 
02.Designing Windows Phone Application
02.Designing Windows Phone Application02.Designing Windows Phone Application
02.Designing Windows Phone ApplicationNguyen Tuan
 

More from Nguyen Tuan (11)

07.Notifications & Reminder, Contact
07.Notifications & Reminder, Contact07.Notifications & Reminder, Contact
07.Notifications & Reminder, Contact
 
12.Maps and Location
12.Maps and Location12.Maps and Location
12.Maps and Location
 
11.Open Data Protocol(ODATA)
11.Open Data Protocol(ODATA) 11.Open Data Protocol(ODATA)
11.Open Data Protocol(ODATA)
 
10.Local Database & LINQ
10.Local Database & LINQ10.Local Database & LINQ
10.Local Database & LINQ
 
08.Push Notifications
08.Push Notifications 08.Push Notifications
08.Push Notifications
 
13.Windows Phone Store
13.Windows Phone Store13.Windows Phone Store
13.Windows Phone Store
 
06.Programming Media on Windows Phone
06.Programming Media on Windows Phone06.Programming Media on Windows Phone
06.Programming Media on Windows Phone
 
05.Blend Expression, Transformation & Animation
05.Blend Expression, Transformation & Animation05.Blend Expression, Transformation & Animation
05.Blend Expression, Transformation & Animation
 
03.Controls in Windows Phone
03.Controls in Windows Phone03.Controls in Windows Phone
03.Controls in Windows Phone
 
04.Navigation on Windows Phone
04.Navigation on Windows Phone04.Navigation on Windows Phone
04.Navigation on Windows Phone
 
02.Designing Windows Phone Application
02.Designing Windows Phone Application02.Designing Windows Phone Application
02.Designing Windows Phone Application
 

Recently uploaded

Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Pooja Nehwal
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceanilsa9823
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceanilsa9823
 
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...Niamh verma
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7Pooja Nehwal
 
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...wyqazy
 
Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝soniya singh
 

Recently uploaded (7)

Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
 
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7
 
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
 
Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Shalimar Bagh Delhi reach out to us at 🔝8264348440🔝
 

09.Local Database Files and Storage on WP

  • 1. Local Database Files & Storage Nguyen Tuan | Microsoft Certified Trainer
  • 2. Agenda • Local Data Storage: Overview • Using Isolated Storage • Using Setting Storage • File & Protocol Association • Data serialization • Local database • SQLite database • External Storage(UsingSD Card)
  • 3. Local Data Storage: Overview    Application Settings File App Application Files Package Manager Install Folder Install DB Databasefile DB Database File (r/o)
  • 4. Installation folder • Is a read-only folder • Contains files of your app package • APIs to access the installation folder: • Application.GetResourceStream(Uri) method • DataContext class • Package.InstalledLocation property • StorageFile and StorageFolder classes
  • 5. Local folder • Is the root folder of your app’s data store • Is not altered or updated when you update your app • Will be removed when the application is uninstalled • It may be something like this: C:DataUsersDefAppsAppData{5D93133B-3B39-4ABF-8D61-277D77B9F2AD}Local
  • 6. Application.GetResourceStream(Uri) // Get the image stream at the specified URI that // is relative to the application package root. Uri uri = new Uri(relativeUriString, UriKind.Relative); StreamResourceInfo sri = Application.GetResourceStream(uri); // Convert the stream to an Image object. BitmapImage bi = new BitmapImage(); bi.SetSource(sri.Stream); Image img = new Image(); img.Source = bi; • Use this method to stream files from the installation folder
  • 7. DataContext class • To connect to a reference database that is part of the app package • is an object representing the database, a proxy, containing Table objects that represent the tables in the database
  • 8. Package.InstalledLocation property • Returns the installation folder as a StorageFolder object • The Path property to get the full path of the installation folder Windows.ApplicationModel.Package package = Windows.ApplicationModel.Package.Current; Windows.Storage.StorageFolder installedLocation = package.InstalledLocation; String output = String.Format("Installed Location: {0}", installedLocation.Path);
  • 9. Windows.Storage classes • StorateFolder • Represent a store area containing files and folders • StorageFile • Represent a file and provide method for manipulating
  • 10. Saving Data private async void WriteMessage(String message) { StorageFolder folder = ApplicationData.Current.LocalFolder; StorageFile file = await folder.CreateFileAsync("message.dat", CreationCollisionOption.OpenIfExists); Stream stream = await file.OpenStreamForWriteAsync(); using (StreamWriter writer = new StreamWriter(stream)) { await writer.WriteAsync(message); } }
  • 11. Loading Data private async Task<string> ReadMessageAsync() { string data = string.Empty; StorageFolder folder = ApplicationData.Current.LocalFolder; StorageFile file = await folder.GetFileAsync("message.dat"); Stream stream = await file.OpenStreamForReadAsync(); using (StreamReader reader = new StreamReader(stream)) { data = await reader.ReadToEndAsync(); } return data; }
  • 12. Isolated Storage Classes • Isolated Storage is used to store local data • All I/O operations are restricted to isolated storage • IsolatedStorageFile • Represents an isolated storage area containing files and folders • IsolatedFileStream • Exposes a file stream access to a file stored within isolated storage • IsolatedStorageSetting • Dictionary that stores key-value pairs in isolated storage
  • 13. Saving Data private void WriteMessageToIsolatedStorage(string message) { using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { using(IsolatedStorageFileStream stream = new IsolatedStorageFileStream("message.dat", FileMode.Append, FileAccess.Write, store)){ StreamWriter writer = new StreamWriter(stream); writer.WriteLine(message); writer.Close(); } } }
  • 14. Loading Data private string ReadMessageFromIsolatedStorage() { string data = string.Empty; using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("message.dat", FileMode.Open, store)) { StreamReader reader = new StreamReader(stream); data = reader.ReadToEnd(); reader.Close(); } } return data; }
  • 15. Saving Data in Settings • Is used to store app’s setting in form of key-value. • It works like a dictionary private void SaveSetting(string key, string value) { IsolatedStorageSettings.ApplicationSettings[key] = value; IsolatedStorageSettings.ApplicationSettings.Save(); } private string LoadSetting(string key) { if (IsolatedStorageSettings.ApplicationSettings.Contains(key)) { return (string)IsolatedStorageSettings.ApplicationSettings[key]; } return null; }
  • 16. Special-use folders in the local folder • Shared • Shared/Media • Shared/ShellContent • Shared/Transfers • PlatformData
  • 17. File & Protocol Association • File association allows app to launch when the user want to open a particular file type, via: • an email attachment • a website via Internet Explorer • a text message • a NFC tag • another app from the Store
  • 20. Serialization/Deserialization • Convert an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file • Binary serialization • XML serialization • SOAP serialization
  • 21. XMLSerializer (1) • Used to serialize/deserialize bettween objects and xml data using System.Xml.Serialization; [XmlRoot(“contact")] public class Contact { [XmlElement("id")] public int ID{get;set;} [XmlElement("name")] public string Name { get; set; } [XmlElement("email")] public string Email { get; set; } }
  • 22. XMLSerializer (2) - Serialize using System.Xml.Serialization; .. .. .. .. .. private async void SaveContactAsync(Contact contact){ StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("contact.xml", CreationCollisionOption.ReplaceExisting); var outStream = await file.OpenStreamForWriteAsync(); XmlSerializer serializer = new XmlSerializer(typeof(Contact)); serializer.Serialize(outStream, contact); await outStream.FlushAsync(); outStream.Close(); }
  • 23. XMLSerialize (3) – XML File <?xml version="1.0" encoding="utf-8" ?> <contact> <id>1</id> <name>Maria Rose</name> <email>rose@live.com</email> </contact> Contact contact = new Contact() { ID = 1, Name = "Maria Rose", Email = "rose@live.com" }; saveContact(contact);
  • 24. XMLSerializer (4) - Deserialize using System.Xml.Serialization; .. .. .. .. .. private async Task<Contact> LoadContactAsync() { StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("contact.xml"); var inStream = await file.OpenStreamForReadAsync(); XmlSerializer serializer = new XmlSerializer(typeof(Contact)); Contact contact = (Contact)serializer.Deserialize(inStream); inStream.Close(); return contact; }
  • 25. Other Serializers • DataContractSerializer • DataContractJsonSerializer • Third party
  • 27. Local database • App can store relational data in local database • Resides on app’s Local folder • Use LINQ to SQL for all database operations • LINQ provides object-relational mapping capabilites
  • 28. DataContext • DataContext is a proxy, represents the database • Contains Table objects which represent tables on database • Table objects is made up of entities that correspond to rows of data in a database public class TodoDataContext:DataContext { public static string DBConnectionString = "Data Source=isostore:/todo.sdf"; public TodoDataContext(string connectionString) :base(connectionString){ } public Table<TodoItem> TodoItems; }
  • 29. Entity Class public class TodoItem:INotifyPropertyChanged, INotifyPropertyChanging { private int _id; [Column(IsPrimaryKey=true, IsDbGenerated=true, DbType="INT NOT NULL IDENTITY", CanBeNull=false, AutoSync=AutoSync.OnInsert)] public int Id { get { return this._id; } set { if (_id != value) { NotifyPropertyChanging("Id"); this._id = value; NotifyPropertyChanged("Id"); } } } …. }
  • 30. Creating database using (TodoDataContext db = new TodoDataContext(TodoDataContext.DBConnectionString)) { if (!db.DatabaseExists()) { db.CreateDatabase(); } }
  • 31. Database operation TodoItem newItem = new TodoItem() { Name = txtItemName.Text }; items.Add(newItem); db.TodoItems.InsertOnSubmit(newItem); db.SubmitChanges(); ObservableCollection<TodoItem> items = new ObservableCollection<TodoItem>(); var todoItems = from i in db.TodoItems select i; foreach (var i in todoItems) { items.Add(i); }
  • 33. SQLite • Is a SQL database engine • Is self-contained • Is serverless • Is zero-configuration • Is transactional
  • 34. Why SQLite? Worlds’ most popular database RichFeatures Reliable
  • 35. SQLite.org Documentation SQL Syntax C/C++ API Reference Source and tools download
  • 36. SQLite for Windows Phone • SQLite database engine is fully supported on WP8 platform • SQLite engine for Windows Phone available as a Visual Studio extension
  • 37. Csharp-sqlite • Is an independent reimplementation of the SQLite software library
  • 38. sqlite-net-wp8 • A C++/CX wrapper for SQLite functions that sqlite-net depends on. • Can be used as an alternative to csharp-sqlite on Windows Phone 8
  • 39. .NET APIs SQLite-NET LINQ syntax Lightweight ORM Similar to WP8 Local Database (LINQ to SQL) SQLitePCL SQL statements Thin wrapper around the SQLite C API using (var db = new SQLitePCL.Database("demo.db")) { db.Open(); using (var stmt = db.PrepareStatement ("SELECT name, age FROM people")) { while (stmt.Step()) { var name = stmt.GetTextAt(0); var age = stmt.GetIntAt(1); } } } var db = new SQLite.SQLiteAsyncConnection(App.DBPath); var _customer = await (from c in db.Table<Customer>() where c.Id == customerId select c).FirstOrDefaultAsync(); if (customer != null) { var Id = _customer.Id; var Name = _customer.Name; }
  • 40. Installing SQLitePCL to your Solution 1. Add Reference to SQLite extension SDK 2. In ConfigurationManager, change target platform to X86 or ARM 3. In ‘Manage NuGet Packages’, add reference to SQLitePCL package
  • 41. Defining tables SQLitePCL is really a thin wrapper around the SQLite ‘C’ API Interact with the database using SQL statements Parameterized queries and statements
  • 42. Create database and tables private void LoadDatabase() { // Get a reference to the SQLite database conn = new SQLiteConnection("sqlitepcldemo.db"); string sql = @"CREATE TABLE IF NOT EXISTS Customer (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Name VARCHAR( 140 ), City VARCHAR( 140 ), Contact VARCHAR( 140 ) );"; using (var statement = conn.Prepare(sql)) { statement.Step(); } }
  • 43. Insert // SqlConnection was opened in App.xaml.cs and exposed through property conn var db = App.conn; try { using (var custstmt = db.Prepare("INSERT INTO Customer (Name, City, Contact) VALUES (?, ?, ?)")) { custstmt.Bind(1, customerName); custstmt.Bind(2, customerCity); custstmt.Bind(3, customerContact); custstmt.Step(); } } catch (Exception ex) { // TODO: Handle error }
  • 44. Select public Customer GetCustomer(int customerId) { Customer customer = null; using (var statement = dbconn.Prepare("SELECT Id, Name, City, Contact FROM Customer WHERE Id = ?")) { statement.Bind(1, customerId); if (SQLiteResult.DONE == statement.Step()) { customer = new Customer() { Id = (long)statement[0], Name = (string)statement[1], City = (string)statement[2], Contact = (string)statement[3] }; } } return customer;
  • 45. Update // See if the customer already exists var existingCustomer = GetCustomer(customer.Id); if (existingCustomer != null) { using (var custstmt = dbconn.Prepare("UPDATE Customer SET Name = ?, City = ?, Contact = ? WHERE Id=?")) { // NOTE when using anonymous parameters the first has an index of 1, not 0. custstmt.Bind(1, customer.Name); custstmt.Bind(2, customer.City); custstmt.Bind(3, customer.Contact); custstmt.Bind(4, customer.Id); custstmt.Step(); } }
  • 46. Delete public void DeleteCustomer(int customerId) { using (var statement = dbconn.Prepare("DELETE FROM Customer WHERE Id = ?")) { statement.Bind(1, customerId); statement.Step(); } }
  • 48. 48
  • 49. The SD Card in Windows Phone This makes it possible for applicationsto share data amongst themselves Maps to a local folder on your PC 49
  • 50. Setting SD card capabilities Removable Storage Pictures Library Videos Library Music Library 50
  • 51. Applications and file associations An image processing program will work with files such as .jpg, .png, etc A sound processing program will work with .mp3 files You can add your own custom file types for your particular application if you wish Note that this is not required for applications accessing files in their own local/roaming/temporary storage This is the same mechanism used for app-to-app communications through file associations (See Session 10) 51
  • 52. Setting file associations for your application This applicationcan only work with .txt files 52
  • 53. Getting an SD Card • These statements get a reference to the SD card on the phone • They are part of a method that creates a file on the SD card •This method is part of the demo software we will be running later 53 var devices = Windows.Storage.KnownFolders.RemovableDevices; var sdCards = await devices.GetFoldersAsync(); if (sdCards.Count == 0) return; StorageFolder firstCard = sdCards[0];
  • 54. Getting an SD Card • We get a list of SD cards using the KnownFolders API • There will only be 0 or 1 54 var devices = Windows.Storage.KnownFolders.RemovableDevices; var sdCards = await devices.GetFoldersAsync(); if (sdCards.Count == 0) return; StorageFolder firstCard = sdCards[0];
  • 55. Getting an SD Card • If there is not one present the value of the Count property will be 0 • This method returns if there are no SD Cards on the device • Your application must handle this eventuality gracefully •Not all devices have an SD card slot •The slot might not have a card fitted into it 55 var devices = Windows.Storage.KnownFolders.RemovableDevices; var sdCards = await devices.GetFoldersAsync(); if (sdCards.Count == 0) return; StorageFolder firstCard = sdCards[0];
  • 56. Getting an SD Card • The card is exposed as a StorageFolder, so we can use it in the same way the previous devices we have seen • We can create folders and files • But we can only work with files types for which we have declared a file association in the manifest 56 var devices = Windows.Storage.KnownFolders.RemovableDevices; var sdCards = await devices.GetFoldersAsync(); if (sdCards.Count == 0) return; StorageFolder firstCard = sdCards[0];
  • 57. Inserting an SD card in the emulator 57
  • 58. SD Cards in the Emulator 58
  • 59. Ejecting an SD Card from the emulator There is an option to select this 59