Quantcast
Channel: かずきのBlog@hatena
Viewing all articles
Browse latest Browse all 1388

Azure Mobile AppsでUWPを作ってみよう「同期編」

$
0
0

過去記事

あらすじ

すべて手組で最初からやってみた。今度はオフライン同期というものをやってみようと思う。

オフライン同期

オフライン同期を使うと、ネットワークにつながってないときはオフラインのDBに書き込んで、任意のタイミングで、オフラインDBとリモートのテーブルを同期したりできるみたいですね。 SQLiteが必要になるので、拡張機能でSQLite for Universal Windows Platformをインストールして、プロジェクトの参照に追加しておきます。

f:id:okazuki:20160909083028p:plain

次にNuGetで以下のパッケージを追加します。

  • Microsoft.Azure.Mobile.Client.SQLiteStore

そして、OnNavigatedToメソッドで初期化処理を行います。

protectedoverride async void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    if (!this.Client.SyncContext.IsInitialized)
    {
        var sqlite = new MobileServiceSQLiteStore("local.db");
        sqlite.DefineTable<TodoItem>();
        await this.Client.SyncContext.InitializeAsync(sqlite);
    }
}

そして、リフレッシュボタンあたりで以下のように同期をとるようにします。

private async void ButtonRefresh_Click(object sender, RoutedEventArgs e)
{
    await this.Client.SyncContext.PushAsync();
    var table = this.Client.GetSyncTable<TodoItem>();
    await table.PullAsync("todoItem", table.CreateQuery());
    var items = await table.CreateQuery().ToListAsync();
    this.ListViewTodos.ItemsSource = items;
}

名前のとおりですね。PushAsyncがサーバーへの送信。PullAsyncがクエリの内容をサーバーから取得です。注意点はGetTableじゃなくてGetSyncTableを使うところでしょうか。

GetSyncTableを使うようにデータ保存のところも書き換えます。

private async void ButtonAdd_Click(object sender, RoutedEventArgs e)
{
    var table = this.Client.GetSyncTable<TodoItem>();
    await table.InsertAsync(new TodoItem { Text = this.TextBoxInput.Text });
    this.TextBoxInput.Text = "";
}

いくつかデータを保存してみて、SQL Databaseにデータがいってないことが確認できます。

同期前

f:id:okazuki:20160909084256p:plain

同期後

f:id:okazuki:20160909084409p:plain

とりあえず単純なケースですがローカルとの同期うまくいってるみたいですね。 設計段階で単純なテーブル単位のPullとかでまかなえるような感じにしておかないといけないっぽいですね。


Viewing all articles
Browse latest Browse all 1388

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>