Windows Phone Data Storage

.Data Collection for Custom Control

Custom Control, Own Work

Windows Phone Data Storage

"Goal for every mobile app developer is to create apps that transfer as little data as possible."

  • Windows Phone supports different types of data. The data could be:
    • page-level state data
    • application-level state data
    • static data
    • user-input data
    • data retrieved from files
    • data retrieved from databases
    • data retrieved from the web.
  • The data may have access restrictions (eg static=read-only). In addition the data may have a lifetime: temporary for the current application session, or persisted in storage for all application sessions.
Data Storage Locations

"Typically, if two applications need to access the same dynamic data, the data can not be local to either application. Sharing dynamic data between typical managed-code applications requires remote storage (eg intranet server or in the cloud)."

  • Mobile application data can be stored locally on the device or remotely on a server. Read-only local data can be packaged with the application. Dynamic local data can be managed by application/session/user in isolated storage. Remote data resides on a server and is accessed through a network.
    1. Local Storage - Contains read-only files included with you application package. They can be compiled as Resource or Content files. Examples are a list of state names or a background image.

    2. Isolated Storage - Contains dynamic files which are kept in an application/session/user specific location so NO other managed applications can access the data. Since isolated stores are scoped to particular assemblies, most other managed code will not be able to access your code's data. The .NET framework manages the details of finding the appropriate hidden files that make up isolated storage. Isolated storage is slow, but reliable. Examples are local database files for customer information or files containing the settings for user preferences. The Windows Phone 7 Isolated Storage Explorer from CodePlex is a Beta version app which allows developers to see and explore files in isolated storage. It also allows provides a download function for files that resides in isolated storage. (Note: "highly trusted" managed code, unmanaged code, and administration tools can access ANY isolated storage areas).

      In managed code, there are three ways to use isolated storage:

      1. Key/Value Pairs - the IsolatedStorageSettings class stores key/value pairs in a resource dictionary. Anything that is serializable can be stored, for example: user settings, layout information or application state. Data created with IsolatedStorageSettings persists in storage for all application sessions.

        // Write Key-value Pair to Resouce Dictionary
        public void SaveStringObject()
        {
        var settings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
        settings.Add("key", "value");
        }

      2. File and Folder Access - the IsolatedStorageFile class can create/delete/read/write files and create/delete folders.
        . Working with files in isolated storage is similar to the streams model used for I/O under .NET.

        // Write to a file in Isolated Storage
        IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
        StreamWriter Writer = new StreamWriter(new IsolatedStorageFileStream("TestFile.txt", FileMode.OpenOrCreate, fileStorage));
        Writer.WriteLine(textBox1.Text);
        Writer.Flush();
        Writer.Close();

      3. LINQ to SQL - Language Integrated Query (LINQ, pronounced "link") is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages. LINQ contains query expressions to process data objects. Since LINQ uses query expressions to process data objects, and SQL is used to process relational data ... an "Object-Relational Mapping" is required to convert data between the two forms. The LINQ to SQL component provides a run-time infrastructure for managing relational data as objects.
        • Windows phone can work with the local databases Microsoft SQL Server Compact Edition (SQL CE) and SQLite.
        • Windows phone can work with a backend database such as Microsoft SQL Server or SQLite.
        • Note: SQLite is not simply a lite version of SQL Server. SQLite is an embedded relational database system that does not require a server. The source code for SQLite is in the public domain.

        The LINQ to SQL provider allows LINQ to be used to query Microsoft SQL Server databases, including SQL Server Compact databases.

        • LINQ to SQL does not use the query engine of LINQ. Instead, it converts a LINQ query to a SQL query that is then sent to SQL Server for processing.
        • SQL Server stores the data as relational data and LINQ works with data encapsulated in objects, so the two representations must be mapped to one another.
        • LINQ to SQL defines a mapping framework in which classes are defined that correspond to the tables in the database. The classes contain all or a subset of the columns in the table as data members.
        • The Object Relational Designer (O/R Designer) provides a visual design surface for creating LINQ to SQL entity classes and associations (relationships) that are based on objects in a database.
        An Example of Object-Relational Mapping

        using System.Data.Linq;
        using System.Data.Linq.Mapping;

        namespace PhoneApp4
        {
            [Table(Name = "Customers")]
            public class Customer
            {
                [Column(IsPrimaryKey = true)]
                public int CustID;

                [Column]
                public string CustName;
            }
        }

        An Example LINQ Query

        var CustomersQuery = from customers in northwindDataContext1.Customers
                              where customers.City == CityTextBox.Text
                              select customers;

    3. Remote Storage - Is data residing on a server and is accessed through a network. The client uses Web services to access the data. Different Web protocols can be used to access the remote data. Information about web protocols is in the article Networks and Protocols.



.Azure Cloud Services

Azure Cloud Services, Fair Use



Cloud Computing

"Resources for working with Azure include Code Samples, Toolkits, and Accelerators."

  • Microsoft's cloud computing is called Windows Azure and provides the following capabilities:
    • Allows you to offer Web service login with authentication.
    • Access databases stored on Azure.
    • Manage user permissions.
    • Send push notifications to client devices.
    • Support for both standard Web protocols SOAP and REST.
    • Resources for working with Azure, including Windows Azure Code Samples, Toolkits, and Accelerators.
NIST Definition of Cloud Computing
  • In the document The NIST Definition of Cloud Computing the National Institute of Standards and Technology defines cloud computing as follows:
    • "Cloud computing is a model for enabling ubiquitous, convenient, on-demand network access to a shared pool of configurable computing resources (e.g., networks, servers, storage, applications, and services) that can be rapidly provisioned and released with minimal management effort or service provider interaction. This cloud model is composed of five essential characteristics, three service models, and four deployment models.
      • Essential Characteristics:
        1. On-demand self-service. A consumer can unilaterally provision computing capabilities, such as server time and network storage, as needed automatically without requiring human interaction with each service provider.

        2. Broad network access. Capabilities are available over the network and accessed through standard mechanisms that promote use by heterogeneous thin or thick client platforms (e.g., mobile phones, tablets, laptops, and workstations).

        3. Resource pooling. The provider’s computing resources are pooled to serve multiple consumers using a multi-tenant model, with different physical and virtual resources dynamically assigned and reassigned according to consumer demand. There is a sense of location independence in that the customer generally has no control or knowledge over the exact location of the provided resources but may be able to specify location at a higher level of abstraction (e.g., country, state, or datacenter). Examples of resources include storage, processing, memory, and network bandwidth.

        4. Rapid elasticity. Capabilities can be elastically provisioned and released, in some cases automatically, to scale rapidly outward and inward commensurate with demand. To the consumer, the capabilities available for provisioning often appear to be unlimited and can be appropriated in any quantity at any time.

        5. Measured service. Cloud systems automatically control and optimize resource use by leveraging a metering capability at some level of abstraction appropriate to the type of service (e.g., storage, processing, bandwidth, and active user accounts). Resource usage can be monitored, controlled, and reported, providing transparency for both the provider and consumer of the utilized service.

      • Service Models:
        1. Software as a Service (SaaS). The capability provided to the consumer is to use the provider’s applications running on a cloud infrastructure. The applications are accessible from various client devices through either a thin client interface, such as a web browser (e.g., web-based email), or a program interface. The consumer does not manage or control the underlying cloud infrastructure including network, servers, operating systems, storage, or even individual application capabilities, with the possible exception of limited user-specific application configuration settings.

        2. Platform as a Service (PaaS). The capability provided to the consumer is to deploy onto the cloud infrastructure consumer-created or acquired applications created using programming languages, libraries, services, and tools supported by the provider. The consumer does not manage or control the underlying cloud infrastructure including network, servers, operating systems, or storage, but has control over the deployed applications and possibly configuration settings for the application-hosting environment.

        3. Infrastructure as a Service (IaaS). The capability provided to the consumer is to provision processing, storage, networks, and other fundamental computing resources where the consumer is able to deploy and run arbitrary software, which can include operating systems and applications. The consumer does not manage or control the underlying cloud infrastructure but has control over operating systems, storage, and deployed applications; and possibly limited control of select networking components (e.g., host firewalls).

      • Deployment Models:
        1. Private cloud. The cloud infrastructure is provisioned for exclusive use by a single organization comprising multiple consumers (e.g., business units). It may be owned, managed, and operated by the organization, a third party, or some combination of them, and it may exist on or off premises.

        2. Community cloud. The cloud infrastructure is provisioned for exclusive use by a specific community of consumers from organizations that have shared concerns (e.g., mission, security requirements, policy, and compliance considerations). It may be owned, managed, and operated by one or more of the organizations in the community, a third party, or some combination of them, and it may exist on or off premises.

        3. Public cloud. The cloud infrastructure is provisioned for open use by the general public. It may be owned, managed, and operated by a business, academic, or government organization, or some combination of them. It exists on the premises of the cloud provider.

        4. Hybrid cloud. The cloud infrastructure is a composition of two or more distinct cloud infrastructures (private, community, or public) that remain unique entities, but are bound together by standardized or proprietary technology that enables data and application portability (e.g., cloud bursting for load balancing between clouds)."
.Microsoft Sync Framework

Microsoft Sync Framework, Fair Use


Synchronizing Data

"Synchronizing data between a local database and a server database can be configured for a down-load only synchronization or a bidirectional sychronization."

  • Microsoft Sync Framework or SQL Server Replication can be used to synchronize data between a mobile device and a remote server:
    1. Microsoft Sync Framework (MSF) is a platform for synchronizing data across multiple data stores. MSF is available for both managed and unmanaged code. MSF handles many of challenges involved in synchronizing data, such as:
      1. Conflict Detection
      2. Connectivity Loss
      3. Change Tracking

      MSF has defined components for different types of synchronizing providers:

      1. Database Synchronizing Provider (formerly know as ADO.NET Sync). - were built to allow developers who were familiar with the concepts of ADO.NET to apply that knowledge to data synchronization through a very similar set of APIs.

      2. File Synchronization Provider (formerly known as File Systems Sync) - is a generic, reusable component used for synchronizing files and folders between NTFS or FAT formatted file volumes. It includes support for removable media such as flash drives.

      3. Web Synchronizing Components (formerly known as FeedSync) - designed for Atom (Atom syndication format, created as an alternative to RSS) and RSS (Rich Site Summary, aka Really Simple Syndication), requires a flat collection of items to be synchronized. Contains a set of algorithms followed by all endpoints to create, update, merge, and conflict resolve all items.
    2. SQL Server Replication - Unlike Sync Framework, which is targeted towards developers, SQL Server Replication is targeted at IT and database administrators:
      1. Transactional replication is typically used in server-to-server scenarios that require high throughput, including: improving scalability and availability; data warehousing and reporting; integrating data from multiple sites; integrating heterogeneous data; and offloading batch processing.

      2. Merge replication is primarily designed for mobile applications or distributed server applications that have possible data conflicts.


.Occasionally Connected Application

Computer Clip Art, Public Domain

Occasionally Connected Applications

"The Occasionally Connected Application model can improve application performance because the speed of the network is no longer a limiting factor when retrieving data. A user can now access the data at the speed of the local computer."

  • An Occasionally Connected Applications (OCA) is an application that synchronizes a local database with a remote database when an active connection exists.
    • OCA allows users to work with data offline. This can improve application performance because the speed of the network is no longer a limiting factor when retrieving data, a user can now access the data at the speed of the local computer.

    • OCA can use a local database cache to store the data on the client computer. The Local Database Cache was introduced in Visual Studio 2008. This feature enables you to easily download to a local SQL Server Compact database an initial dataset, and later make changes to that dataset.

    • By default the Local Database Cache provides download-only sychronization. However code can be added enable bidirectional sychronization.

    • Between synchronizations, if a row is changed by both the client and the server -- the row is in conflict. The sync framework allows for the detection, resolution, and review of the conflicts.

    • The following components must be installed to perform database synchronizations:
      • Sync Framework
      • SQL Server Compact
      • A version of SQL Server other than SQL Server Compact to act as the server database.
    • To include data synchronization in a Visual Studio project:
      • Use Local Database Cache as a new project item template.
      • In addition to using the Local Database Cache template, you can also use the Data Source Configuration Wizard to configure the desired type of synchronization.
.Data Encryption

Computer Clip Art, Public Domain

Data Encryption

"Encrypting the data will not increase the security if the decryption key resides on the phone, no matter how well the key is hidden."

  • The ProtectedData class provides methods for encrypting and decrypting data. This class cannot be inherited.
    • The ProtectedData class provides access to the Data Protection API (DPAPI) available in Microsoft Windows 2000 and later operating systems. This is a service that is provided by the operating system and does not require additional libraries.

    • The ProtectedData class has two methods:
      1. Protect - encrypts the data in a specified byte array and returns a byte array that contains the encrypted data.

      2. Unprotect - decrypts the data in a specified byte array and returns a byte array that contains the decrypted data.
    Windows Phone Encrypt and Decrypt Example Code

    using System.Text;
    using System.Security.Cryptography;

    namespace PhoneApp3
    {
        public partial class MainPage : PhoneApplicationPage
        {
            // Constructor
            public MainPage()
            {
                InitializeComponent();

                string myPassword = "Kevin's34!Password";

                // Encrypt - convert string to byte array, call Protect           
                byte[] secretData = Encoding.UTF8.GetBytes(myPassword);
                string secretDataString = Encoding.UTF8.GetString(secretData, 0, secretData.Length);
                MessageBox.Show("Unencrypted password is: " + secretDataString);
                byte[] encryptedSecretData = ProtectedData.Protect(secretData, null);

                // Decrypt - call Unprotect, covert byte array to string
                byte[] decryptedSecretData = ProtectedData.Unprotect(encryptedSecretData, null);
                string secretDataDecryptedString = Encoding.UTF8.GetString(decryptedSecretData, 0, decryptedSecretData.Length);
                MessageBox.Show("Decrypted password is: " + secretDataDecryptedString);
            }
        }
    }

Reference Articles