Work with data in mobile applications. We implement offline storage and data synchronization using Microsoft Azure and SQLite

    image

    Now on the market there are a huge number of applications that are not adapted to work offline, which creates inconvenience for users.
    Some time ago, the new Microsoft Azure Mobile Services SQLiteStore SDK 1.0 alpha , which provides an API for creating applications that work in the absence of the Internet and takes care of all the data synchronization between the local database and the Azure database, was made available to C # developers . SQLite is created and used as a local database.

    So, we have the following popular ways to organize offline storage:
    • Serialization in XML, JSON or other NoSQL.
    • SQLite or other third-party databases.

    Synchronization Mechanisms:
    • Each time the local copy of the database is updated completely.
    • Only changes are transmitted over the network.

    Means of synchronization:

    Azure Mobile Services SDK for synchronization


    The functionality of the new Microsoft Azure Mobile Services SQLiteStore SDK 1.0 alpha for data synchronization is not identical to the Sync Framework or Azure Data Sync.

    From the point of view of the client side, while there is an opportunity to work only with SQLite , but the creators promise that the opportunities will develop and other client databases will be added later.

    The server side supports the following databases: SQL Database, MongoDB and Azure Table Storage.

    The SDK supports the following operations: Push (sending to the server), Pull (downloading from the server), Purge (cleaning the local storage).

    Today we will focus on how to create a backend for your application usingMicrosoft Azure Mobile Services SQLiteStore SDK 1.0 alpha .

    For work, we need:

    Our task will consist of the following items:
    • Creation of a mobile service and a mobile database in Microsoft Azure;
    • Creating an application project. We will make a universal application in Visual Studio.
    • Creating a local application database.
    • Implement data synchronization.

    Let's get started ...

    Configure Azure Mobile Services


    1. To create an Azure Mobile Service for your project, you need to open the Microsoft Azure Portal and go to the Mobile Services - New menu.



    Creating a cloud service, you can choose in which language you will write the service code. In C # or JavaScript.



    2. When the mobile service is created, on the main page of the service, you can find instructions on how to use it in applications for many popular platforms and frameworks, such as Windows, Windows Phone, IOS, Android, Xamarin.



    3. You can download the cloud service project template, modify its code, for example, by adjusting the data model as in the screenshot below.



    4. Then, publish to the cloud from Visual Studio.



    How to develop and publish a cloud service is written in sufficient detail here .

    Create an application project


    1. I will use the universal application project for Windows and Windows Phone.



    2. After creating the project, we will connect the necessary libraries. Since we have a project for both Windows and Windows Phone, we need to install WindowsAzure.MobileServices for both projects.







    3. In the general project ( Shared ), open App.xaml.cs and add the announcement of the mobile service there:

    public static MobileServiceClient MobileService = new MobileServiceClient("https://demo-backend.azure-mobile.net/", "ZDgibxPOCWSwOvbYJvAAipjAybMIJO51"); 
    

    4. Now we can work with data through a cloud service and save data in the database.

    Creating a local database and synchronization


    Now we need to create a local SQLite data store.

    1. Install SQLite for Windows 8.1 and SQLite for Windows Phone 8.1

    2. Add SQLite as the used library for our Windows and Windows Phone applications.





    3. Install and add the WindowsAzure.MobileServices.SQLiteStore package to References 4. Open the Shared project and create a new empty class with the data model there. In my case, it turned out like this: 5. Create an auxiliary class that will create a local database for us, be able to fill it with data and send data to the cloud service.









    MobileServicesSync.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.WindowsAzure.MobileServices.Sync;
    using Microsoft.WindowsAzure.MobileServices.SQLiteStore;
    using System.Threading;
    namespace DemoApp
    {    
        public static class MobileServicesSync
        {
            public static async void InitSQLiteStore()
            {
                if (!App.MobileService.SyncContext.IsInitialized)
                {
                    var store = new MobileServiceSQLiteStore("DemoAppSync.db");
                    store.DefineTable();
                    await App.MobileService.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());
                }
            }
            public static async void InsertItem(MyAppItem item)
            {
                IMobileServiceSyncTable table = App.MobileService.GetSyncTable();
                await table.InsertAsync(item);
            }
            public static async void Push()
            {
                string errorString = null;
                try
                {
                    CancellationToken token = new CancellationToken();
                    await App.MobileService.SyncContext.PushAsync(token);
                }
                catch (MobileServicePushFailedException ex)
                {
                    errorString = "Push failed because of sync errors: " + ex.PushResult.Errors.Count() + ", message: " + ex.Message;
                }
                catch (Exception ex)
                {
                    errorString = "Push failed: " + ex.Message;
                }
            }
        }
    }
    


    Application interface


    1. Open MainPage.xaml and add buttons there to fill the table with data and synchronization.

    MainPage.xaml


    2. Add code to handle events in MainPage.xaml.cs .

    MainPage.xaml.cs
        	 public MainPage()
            {
                this.InitializeComponent();
                MobileServicesSync.InitSQLiteStore();
            }
            private void addBtn_Click(object sender, RoutedEventArgs e)
            {
                MobileServicesSync.InsertItem(new MyAppItem { Text="Ура!" });
            }
            private void syncBtn_Click(object sender, RoutedEventArgs e)
            {
                MobileServicesSync.Push();
            }
    


    Launch and check


    1. Run the application and see how it works.



    2. As soon as we started the application, we already created a local SQLite database. We can find it in the application folder and see. For this I will use SQLite Browser .

    My database is here: C: \ Users \ [username] \ AppData \ Local \ Packages \ [app id] \ LocalState



    As you can see, now it is empty.

    3. Add an element to it by clicking on the Add Item button of our application.

    4. The data in the database will be updated and a record will be added there, but our cloud database is still empty.



    5. Now click on the Sync button in the application to synchronize databases and see the result.



    The synchronization worked and the data from the local application database appeared in the cloud database.



    Note: for those who have not earned
    It may turn out that creating a local database will fail with an error. Then find and add the assembly SQLitePCL.Ext.dll to the References . For some reason, it itself is not always installed by NuGet.



    Conclusion


    The new Microsoft Azure Mobile Services and its SDK has many new useful features for application developers. One of them is support for offline work and data synchronization for applications. Following this instruction, you can configure data synchronization for your Phone or Windows application without spending a lot of time on complex algorithms and writing libraries.

    useful links




    Also popular now: