8/2/2019 WP7 Tpa 8 Data Base
1/27
TPA - Windows Phone
Isolated Storage, Local Database
part 1
Prepared by: Kamil Kowalski
8/2/2019 WP7 Tpa 8 Data Base
2/27
Agenda
Isolated Storage
Settings vs. Files
IsolatedStorageSettings, IsolatedStorageFile
Local Database (part 1) Introduction
LINQ to SQL
Database mapping
Attributes DataContext, Connection String
Q & A
8/2/2019 WP7 Tpa 8 Data Base
3/27
Isolated Storage
Isolated storage is a space provided to store the locally, onlocal file system data or files.
Each application can have their own space (storage) so that
other application data cannot be shared with in the
application which gives more security to the data. Applications will not have the ability to share, call, or interact
with other applications on the device.
If you have two applications, and you want to share data between
them, youd better have some kind of cloud-based service that can
share that data for you.
8/2/2019 WP7 Tpa 8 Data Base
4/27
Isolated StorageSettings vs. Files
There are three ways to
store your data locally:
The first is through a library of
name/value pairs. This is
calledIsolatedStorageSettings
The second way is through
actual file and folder
creation. This is called
IsolatedStorageFile.
Last way is the local database
using relational data.
8/2/2019 WP7 Tpa 8 Data Base
5/27
Isolated StorageIsolatedStorageSettings
IsolatedStorageSettings class uses the methods listedbelow to store and retrieve the:
Add we can make use of this method to store the data in the
dictionary as key value pair.
Remove we can make use of this method to remove/delete the
data with a specified key.
Contains we can make use of this method to check if particular data
is available or not using the specified key.
This data is persisted across application stop/start, powering
the phone off, etc. The data is there until you remove it, or the user uninstalls
your application.
8/2/2019 WP7 Tpa 8 Data Base
6/27
Isolated StorageIsolatedStorageSettings
Few things to remember: Trying to retrieve a value from IsolatedStorageSettings will throw an
error, if it hasnt already been created. Make sure you initialize your
settings, or ALWAYS check the .Contains property first.
You can save anything you want in the Settings: a boolean value for
example, but Customer object as well, or any other else you can comeup with.
Remember that you have to explicitly cast your data when you
retrieve it. Youre saving the object, but the storage does NOT save
the type.
Setting a value is the same as adding a value to the library.
8/2/2019 WP7 Tpa 8 Data Base
7/27
Isolated StorageIsolatedStorageFile
IsolatedStorageFile is the mechanism you can use forstoring actual FILES on the users device.
We have the ability to create and delete folders, subfolders,
and files.
This is going to seem like a TON more code, but its actuallypretty simple:
were creating a new IsolatedStorageFile object, and then writing it to
the drive using an IsolatedStorageFileStream.
8/2/2019 WP7 Tpa 8 Data Base
8/27
Local Database
Local database in Windows Phone 7.1 is an implementationof SQL Compact for Mango. It is an in memory/embedded
relational database management system (RDB MS).
Local Database is stored in application's Isolated Storage, so
one database can be used only from one application and cannot be shared between several applications.
8/2/2019 WP7 Tpa 8 Data Base
9/27
Local Database
A local database offers the following advantages: the ability to make complex queries to the database which are
performed efficiently and quickly
allows only data that is necessary at a particular moment to be
loaded in memory
you can do all operations like : adding , removing, inserting, deleting,
etc. and all this operations are handled efficiently by the SQL
Compact runtime.
The following scenarios are perfect for local database usage:
Relatively many related tables/entities containing a moderate amountof records
A few tables containing large amounts of records/data
Local cache of data that comes from the cloud
8/2/2019 WP7 Tpa 8 Data Base
10/27
Local Database
Here is the Process that you need to follow in order to use aLocal Database in Windows Phone:
1. Implement all database classes: tables, columns, relations,
datacontext, etc.
2. Create a new database (,sdf) file in Isolated Storage(by default the
database is empty).
3. Populate the database stored in the Isolated Storage with data
8/2/2019 WP7 Tpa 8 Data Base
11/27
Local DatabaseLINQ to SQL
LINQ to SQL is the glue between application and LocalDatabase.
LINQ to SQL is an ORM (object relational mapping)
framework which comes as a part of the .NET Framework.
It allows you to: map your business objects (model classes) to tables in the database
Query the database using LINQ
Insert data to the database
Update data to the database
Delete data to the database
8/2/2019 WP7 Tpa 8 Data Base
12/27
Local DatabaseLINQ to SQL
How does it work: LINQ is a set of extension methods thatenable you to write queries against data in a local database inC# using special Query syntax.
Basically Query syntaxis a convenient declarative shorthandfor expressing queries using the standard LINQ query
operator.1. Usually LINQ to SQL query expression in begins with a "from" clauseand ends with a "select" clause.
2. The "from" clause indicates what data you want to query (usually youquery data from a collection/datacontext)
3. The "select" clause indicates what data you want returned and inwhat format it should be in.
4. Whenever you want to filter data you can use "where" clause.
5. For ordering data the clause is "orderby"
8/2/2019 WP7 Tpa 8 Data Base
13/27
Local DatabaseLINQ to SQL
While Windows Phone supports most LINQ to SQL features, thereare some limitations.
You can take a look at MSDN for reference: LINQ to SQL Support forWindows Phone.
Here are some of them:
ExecuteCommand is not supported: Windows Phone does not supportexecuting "raw" Transact-SQL, Data Definition Language (DDL), or DataModeling Language (DML) statements.
ADO.NET Objects (such as DataReader) are not supported: All data from aLINQ to SQL query is returned in an object collection of type specified bythe data context.
Only Microsoft SQL Server Compact Edition (SQL CE) data types aresupported: SQL CE is the underlying database technology for a localdatabase. For a full list of SQL CE data types, see Data Types (SQL ServerCompact).
http://msdn.microsoft.com/en-us/library/hh202872(v=vs.92).aspxhttp://msdn.microsoft.com/en-us/library/hh202872(v=vs.92).aspxhttp://go.microsoft.com/fwlink/?LinkId=217712http://go.microsoft.com/fwlink/?LinkId=217712http://go.microsoft.com/fwlink/?LinkId=217712http://go.microsoft.com/fwlink/?LinkId=217712http://msdn.microsoft.com/en-us/library/hh202872(v=vs.92).aspxhttp://msdn.microsoft.com/en-us/library/hh202872(v=vs.92).aspxhttp://msdn.microsoft.com/en-us/library/hh202872(v=vs.92).aspx8/2/2019 WP7 Tpa 8 Data Base
14/27
Local DatabaseLINQ to SQL
Table.IListSource.GetList Method is not supported: To bind to allcontents in a table, query the entire table and bind to the query.
Handle inserts and deletes with business logic.
Take() requires a constant value in LINQ queries: SQL CE does not
support the use of queried values within the Transact-SQL TOP
statement. If you want to use a variable value within the Takemethod, calculate that value in a different query than the one that
the Take method is used in.
Skip() and Take() require an ordered list: These methods depend on
ordering to return results in a consistent manner.
BinaryFormatter is not supported: To convert custom types to a SQLServer Binary or VarBinary data type, your data context property can
implement a LINQ to SQL CustomType or be of type byte[] or
System.Data.Linq.Binary.
A good tutorial for LINQ to SQL is here and here.
http://msdn.microsoft.com/en-us/library/bb308959.aspxhttp://msdn.microsoft.com/en-us/library/bb425822.aspxhttp://msdn.microsoft.com/en-us/library/bb425822.aspxhttp://msdn.microsoft.com/en-us/library/bb308959.aspx8/2/2019 WP7 Tpa 8 Data Base
15/27
Local DatabaseDatabase mapping
To create a local database, you must first define the entityclasses. These classes define your object model and its
mapping to the schema of the database.
The object-relational capabilities of LINQ to SQL depend on
these mapping details to create a relational database thatmaps to the corresponding data context.
For each entity, mapping details are specified by using LINQ
to SQL mapping attributes.
These attributes specify database-specific features such astables, columns, primary keys, and indexes.
8/2/2019 WP7 Tpa 8 Data Base
16/27
Local DatabaseDatabase mapping
Mapping types to tables and properties to columns in thedatabase schema is done using attributes:
Entity classes are attributed with a [Table] attribute, in order to map
them to tables in the database
The [Index] attribute can be used (on classes) to define an index
Entity properties are attributed with a [Column] attribute, in order to
map them to columns in the database
[Column( IsPrimaryKey = true )] is used to specify the primary key
property
8/2/2019 WP7 Tpa 8 Data Base
17/27
Local DatabaseDatabase mapping
Associations are specified using the [Association] attribute,which allows you to configure a relation between two entities/ tables in the database mapping. The Association attributehas the following important properties:
OtherKey- the name of the property that corresponds to the id of the
object at the other end of the association ThisKey- the name of the property that corresponds to the primary
key for this type
Storage - the backing variable for the property
The code-first approach to defining the database schema is
preferred. There is no visual designer that can help in mapping and configuring
classes to work with the database.
Or at least it is not supported officially. You may try to use SQL Metal
http://sqlmetalosui.codeplex.com/http://sqlmetalosui.codeplex.com/8/2/2019 WP7 Tpa 8 Data Base
18/27
Local Database[Table] attribute
You can use this attribute to designate a class as an entityclass that is associated with a database table or view.
LINQ to SQL treats classes that have this attribute as persistent
classes.
You can use the Name property of the TableAttribute
attribute to specify a name for the table.
You can optionally use the schema name to qualify a table name.
If you do not specify a name by using the Name property, the table
name is assumed to be the same as the class name.
LINQ to SQL supports only single-table mapping. Entity class must be mapped to exactly one database table, and you
cannot map a database table to multiple classes at the same time.
8/2/2019 WP7 Tpa 8 Data Base
19/27
Local Database[Table] attribute
[Column] attribute
In addition to associating classes to tables (by [Table] attribute) youwill need to denote each field or property you intend to associatewith a database column.
[Column] attribute has a variety of properties you can use tocustomize the exact mapping between your fields / properties andthe database columns.
The most important property is the IsPrimaryKey. It tells LINQ toSQL that the database column is part of the primary key in thetable.
8/2/2019 WP7 Tpa 8 Data Base
20/27
Local Database[Column] attribute
Only fields and properties declared as columns will bepersisted to, or retrieved from the database.
Others will be considered as transient parts of your application logic.
8/2/2019 WP7 Tpa 8 Data Base
21/27
Local Database[Association] attribute
Associations between entity classes in LINQ to SQL areanalogous to relationships between tables in a database.
[Association] attribute is used to designate a property to
represent an association in the database, such as a foreign
key to primary key relationship. You can also represent one-to-one and many-to-many relationships as well.
One-to-one: Represent this kind of relationship by including
properties of type EntitySet on both sides.
Many-to-many: In many-to-many relationships, the primary key of the
link table (also named the junction table) is often formed by acomposite of the foreign keys from the other two tables.
8/2/2019 WP7 Tpa 8 Data Base
22/27
Local Database[Association] attribute
Association are specified using the [Association] attribute,which allows you to configure a relation between two types
in the database mapping.
The Association attribute has the following important
properties: OtherKey- the name of the property that corresponds to the id of the
object at the other end of the association
ThisKey- the name of the property that corresponds to the primary
key for this type
Storage - the backing variable for the property
8/2/2019 WP7 Tpa 8 Data Base
23/27
Local Database[Index] attribute
[Index] attribute specifies an additional index on a localdatabase table. Written at the table level, designatesadditional indexes on the table.
Each index can cover one or more columns.
[Index] attribute is used internally by the database engine.
This means that, except for defining an index, you do not have towrite your LINQ to SQL queries or do anything else differently in orderto use an index.
[Index] attribute has the following important properties:
Columns: Gets or sets the columns on which the index is based.
IsUnique: Gets or sets a value that indicates whether the index isunique, in which no two rows are permitted to have the same indexkey value.
Name: Gets or sets the name of the index.
8/2/2019 WP7 Tpa 8 Data Base
24/27
8/2/2019 WP7 Tpa 8 Data Base
25/27
Local DatabaseDataContext
The purpose of the data context is to expose the database tothe rest of your code in an object oriented manner.
A data context has three important characteristics:
It inherits from the "System.Data.Linq.DataContext" class
The data context constructor must call the base(connectionString)constructor
The data context exposes the tables from the database through
properties of type Table (ex: Table).
The Table class implements IQueriable and enables you to
write LINQ queries against the database.
8/2/2019 WP7 Tpa 8 Data Base
26/27
Local DatabaseConnection String
Before we can actually use a database at all, we need tospecify a connection string, which basically tells the
application how to connect to the database.
A connection string can be used to specify database
configuration values. In a connection string, individualparameters are separated by semicolons and parameter
values are placed within single quotes.
Some parameters are applicable only to creating the database; after
the database has been created, those parameters are ignored.
A special format of the connection string must be used:"Data Source='isostore:/DIRECTORY/FILE.sdf'";
8/2/2019 WP7 Tpa 8 Data Base
27/27
Q & A
??