Windows 8 Modern App Data Access Options - Beginning Windows 8 Data DevelopmentUsing C# and JavaScript (2013)

Beginning Windows 8 Data DevelopmentUsing C# and JavaScript (2013)

3. Windows 8 Modern App Data Access Options

Vinodh Kumar1

(1)

NY, US

Abstract

The Windows 8 platform redefines the way apps access and manipulate data, as there is no direct way to access a local or remote database server as we do with .NET using ADO.NET, Linq2SQL, or the Entity framework. WinRT APIs do not provide any of the following options for security and platform-related reasons.

The Windows 8 platform redefines the way apps access and manipulate data, as there is no direct way to access a local or remote database server as we do with .NET using ADO.NET, Linq2SQL, or the Entity framework. WinRT APIs do not provide any of the following options for security and platform-related reasons.

· Built-in local databases like SQLCE

· Connection to SQL Express Instances

· Accessing databases using ODBC or OLEDB providers

· Direct access to the disk

With these limitations, managing data becomes a critical part in developing a Windows 8 app. In this chapter we take a look at various data storage options that can be considered when building Windows Store apps, along with the various WinRT APIs that can be used.

Data Storage Options

Most of the applications, irrespective of platform, need to store data pertaining to the application in a location within a predefined format. Location and format of the data depend on various factors like platform, application, and pricing. As for Windows 8 Store apps, data can be stored either locally or remotely.

Local storage is where data is stored locally within a device. In Windows 8 Store apps, data stored within an app cannot be shared with another app, as each app is restricted to a sandbox. There are various options for storing data locally and the following are some of the options that are discussed in detail in this chapter.

· Application data

· Using built-in File Picker contracts

· IndexedDB

· JET API

· SQLite

Application Data

Every app installed in Windows 8/RT will be allocated space for storing application data. This application storage can be used to store an app’s settings, preferences, context, app status, and files. This storage cannot be accessed by other apps and can be only accessed using the APIs provided in WinRT.

For storing and retrieving application data, use the ApplicationData class, which is a part of the Windows.Store namespace and this data can be stored in three different ways:

· Local application data: Stores the data locally. Use local storage only if you have good reason not to roam the setting to the cloud.

· Roaming application data: Data will be synced across all the devices on which the user has installed the app. If we use roaming and there is no Microsoft account, it will be stored locally.

· Temporary application data: Data is stored temporarily during an application session and can be removed any time by a system maintenance task.

We learn more about application data in Chapter 5.

File System

Databases based on a file system in Windows 8 using WinRT provide another way to store information. There are many open source options available and WinRT File Based Database is one of the popular file-based databases found in www.codeplex.com .

WinRT File Based Database is a file-system-based database written using the WinRT framework. This API allows users to create tables based on classes. Each database consists of many tables and these tables are serialized and stored in Application Data Storage. We learn about this in detail in Chapter 5.

File Picker Contracts

File Picker contracts can be used to store and retrieve the data as files from the device hard disk in a format that is understood by the Windows 8 Store app. File Picker is the only way for an app to gain access to files and folders located in any part of the system. Unlike .NET APIs, WinRT doesn’t provide an option to manage files without user intervention. That is, the app cannot gain access to a file in the system without the user explicitly acting on the files or folder using the File Picker contract.

There are three types of File Picker contracts.

· FileOpenPicker: After calling this class, the user will be presented with a UI to pick a file.

· FileSavePicker: This class helps to save a file.

· FolderPicker: This class is used to pick a folder.

To open a file using the FileOpenPicker class, we have to add at least one file extension to the FileTypeFilter collection, to indicate what file types are supported by the app. The FileTypeFilter will throw an Unspecified error exception if it is empty. Apart from FileTypeFilter, all other properties are optional, including ViewMode and SuggestedStartLocation. In Listing 3-1 we use FileOpenPicker to open a picture from the Pictures Library as a stream.

Listing 3-1. Using FileOpenPicker to Open a File from the Picture Library

string selectedFileName=null;

string photoStream=null;

FileOpenPicker openPicker = new FileOpenPicker();

openPicker.ViewMode = PickerViewMode.Thumbnail;

openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;

openPicker.FileTypeFilter.Add(".jpg");

openPicker.FileTypeFilter.Add(".jpeg");

openPicker.FileTypeFilter.Add(".png");

StorageFile file = await openPicker.PickSingleFileAsync();

if (file != null)

{

selectedFileName = file.Name;

photoStream = await file.OpenReadAsync();

}

Similar to FileOpenPicker we have to add at least one file type to the FileTypeChoices collection and the rest of the properties are optional. As shown in Listing 3-2, apart from providing the options to save the files in various types by adding to the FileTypeChoices collection we also used the DefaultFileExtension property to define a preferred format in which the file can be stored.

Listing 3-2. Using FileSavePicker to Save a File within a Device File System

var fileSavePicker = new FileSavePicker();

fileSavePicker.FileTypeChoices.Add("Raw Images", new List<string> { ".raw", ".dat" });

fileSavePicker.FileTypeChoices.Add(".jpg Image", new List<string> { ".jpg" });

fileSavePicker.DefaultFileExtension = ".jpg";

fileSavePicker.SuggestedFileName = "NewImage1.jpg";

var fileToSave = await fileSavePicker.PickSaveFileAsync();

The FolderPicker is very similar to the FileOpenPicker with resembling properties as shown in Listing 3-3.

Listing 3-3. Using FolderPicker to Pick a Folder from the Picture Library

var folderPicker = new FolderPicker();

folderPicker.FileTypeFilter.Add(".jpg");

folderPicker.ViewMode = PickerViewMode.Thumbnail;

folderPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;

folderPicker.SettingsIdentifier = "FolderPicker";

var folder = await folderPicker.PickSingleFolderAsync();

IndexedDB

IndexedDB is a nonrelational data store, designed to store structured objects in collections known as an Object Store. The Object Store holds records as key/value pairs. Each record in the Object Store has a single key, which can be configured to autoincrement or can be provided by the application. This key is like the primary key in a relational database table, where no two records within an Object Store can be identified by the same key.

Internet Explorer 10 and Windows Store apps using JavaScript support the Indexed Database API defined by the World Wide Web Consortium (W3C) Indexed Database API specification, so applications written using HTML5 and JavaScript will be able to use IndexedDB as a local storage option. The following are some of the common IndexedDB contracts.

· Database: A database consists of one or more object stores that hold the data stored in the database. It also contains indexes and is used to manage transactions. There can be multiple databases in an application.

· Object Store: An object store is a primary storage solution used for storing data in a database. It’s a collection of JavaScript objects where attributes have key/value pairs.

· Key: A key is used to uniquely identify an object within a database. It has values of type float, date, string, and array. It’s very similar to the primary key columns in a relational database table. It also imposes an ascending sort order on the associated objects.

· Value: A value is a JavaScript object that associated with a given key. Every record is associated with a value. It can be a complex object that has no schematization requirements.

· Key Path: A key path is a string that defines a way to extract a key from a value. A key path is said to be valid when it has either an empty string or a multiple JavaScript separated by periods.

· Index: An index is an alternative method to retrieve records in an object store rather than using a key. It’s a specialized storage solution that supports searching objects in the store by attribute values.

· Transaction: This is used to read or write data into the database. Transactions are always operated in one of three modes: read-only, readwrite, or versionchange.

· Request: A request is used to perform a read or write operation on a database. It’s analogous to a SQL statement.

· Key Range: The key range is used to retrieve records from object stores and indexes.

· Cursor: A cursor is a brief mechanism used to iterate over multiple records in a database. They are bidirectional, and can skip duplicate records in a nonunique index.

Even though IndexedDB concepts looks similar to relational database management elements, one key difference is that there is no relational semantics, which mean we will not be able to use joins. In Chapter 4 we will learn in detail about using IndexedDB as a storage option for a Movie Collection and Inventory Windows Store app.

ESENT/JET API

Extensible Storage Engine (ESENT), also known as JET API, is an Indexed Sequential Access Method (ISAM) data storage technology from Microsoft. The ESENT runtime has been a part of Windows since Windows 2000 and has been used in products like Microsoft Exchange, Active Directory, Windows Update, and Desktop Search. This application stores and retrieves data from tables using indexed or sequential cursor navigation.

We can use ESENT for applications that need reliable, high-performance, low-overhead storage of structured or semistructured data. The ESENT engine can help with data needs ranging from something as simple as a hash table that is too large to store in memory to something more complex, such as an application with tables, columns, and indexes.

ESENT incorporates all the benefits of the ISAM data storage technique, including the following.

· ACID transaction

· Snapshot isolation

· Concurrent access storage

· Cursor navigation

· Advanced indexing: Indexing over multivalued columns, sparse, and tuple

· Fixed, variable, and tagged columns

· Data integrity and consistency

· Column size ranging from 1 bit to 2 GB

We will be learning in detail about using JET API in Chapter 5. We will build a Windows Store Password Manager app that stores data using JET API.

SQLite

SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. It’s a file-based database that can be used without any need for a database engine like SQLServer, Oracle, and so on. SQLite is a relational database management system that is contained in a small C programming library. SQLite is the most widely deployed SQL database engine in the world and its source code exists in the public domain. It is free for use for both private and commercial purposes.

SQLite is very similar to the SQL Server compact in characteristics. It’s an embedded database that should be included explicitly with in the app and run in-process within the app unlike SQL Serve Compact, which in most cases will be part of the OS (Windows Phone OS, Windows Mobile OS). We will learn in detail about using SQLite in Windows 8 projects in Chapter 6.

Remote Data

Not all Windows 8 Store apps store data locally. Many l ine of b usiness (LOB) app s store data in a central repository like Windows Azure, SQL Server, Oracle , and so on. WinRT doesn t provide the necessary APIs to directly access this data, so we have to access it in a way that is similar to a cc essing data in Silverlight applications ; that is, build ing a service layer that exposes the entities, in a format like XML, JSON, and binary using transfer protocols like HTTP, HTTPS , and TCP.

In the next part of this chapter we look in to some of the data transfer techniques that can be used to access data remotely.

Windows Communication Framework

The Windows Communication Framework (WCF) is widely used as a service layer in enterprise applications. This service can be leveraged with minimum changes when porting an existing application to WinRT or building a companion Windows 8 Store app to an existing LOB application, as WinRT provides the necessary APIs to consume WCF services. WCF provides different options for consuming data.

· WCF Web Services: WCF Web Services is based on the Simple Object Access Protocol (SOAP), which returns data in XML format. Consuming WCF Web Services is very similar to how we do that with .NET.

· WCF Data Services: WCF Data Services is based on the oData protocol, which returns XML or JSON data, using REST queries. We learn more about this in Chapter 8.

Apart from these two straightforward techniques, we can also use the more complex and powerful WCF HTTP/.NET TCP. Using this technique, we can implement our own protocol, format, and query method that is supported by WinRT, as WinRT support is not as broad as that for .NET.

ASP.NET Web API

The ASP.NET Web API introduced with ASP.NET MVC 4.0 and .NET Framework 4.5 is a new addition to the ASP.NET stack that allows us to create a RESTful and AJAX API that helps to build web or HTTP-based client or server endpoints.Why Should We Use Web API?

ASP.NET Web API is Microsoft’s answer to a modern programming landscape for building a service layer that can be easily consumed by most clients. Web API is an ideal platform for building pure HTTP-based services that can be useful when building multiplatform applications like apps for desktop application, HTML5, iOS, Android, Windows 8, and Windows Phone, as all these clients can make GET, PUT, POST, and DELETE requests and get the Web API response.

In Chapter 7 we learn to set up a CRUD ASP.NET Web API Rest service and consume this service from a Windows Store JavaScript app by building a Party Planner app.

Windows Azure Mobile Web Services

WCF and ASP.NET Web APIs are ideal for enterprise apps in which the data are stored in a datacenter of that enterprise. But if you are looking to store the data in a cloud and if you like to use Windows Azure as a scalable cloud back end, then Windows Azure Mobile Web Services is the way to go.

Windows Azure Mobile Services allows users to quickly connect any mobile client like Windows 8, Windows Phone, iOS, Android, or HTML5 apps to a cloud-based back end hosted on Windows Azure. Windows Azure Mobile Services also offer built-in functionality to authenticate users via Microsoft, Google, Facebook, or Twitter credentials, and send push notifications. Windows Azure Mobile Services can be easily integrated into a Windows 8 Store app as Microsoft provides the necessary tools and SDKs to do so. In Chapter 9 we learn to uses Windows Azure Mobile Services as a back-end storage option by building an Instagram-inspired application, Instashot.

Conclusion

This chapter gave a brief introduction to some of the data options that can be used along with Windows 8 Store apps. In the coming chapters we will be learning about some of these in greater detail.

Apart from this, WinRT provides APIs to interact with public data applications like Facebook, Twitter, and LinkedIn. As mentioned in Chapter 2, we can use WebAuthenticationBroker for authenticating the user against user authentication providers like Facebook, Twitter, Google, and Microsoft. The WebAuthenticationBroker class provides the necessary infrastructure for apps to use Internet authentication and authorization protocols such as OAuth and OpenID. Furthermore, WinRT provides built in APIs to query RSS, oData, and more.

Vinodh KumarBeginning Windows 8 Data DevelopmentUsing C# and JavaScript10.1007/978-1-4302-4993-1_4

© Vinodh Kumar 2013