为 Windows 应用启用脱机同步Enable offline sync for your Windows app

Note

Visual Studio App Center 正在投资于对移动应用开发至关重要的新集成服务。Visual Studio App Center is investing in new and integrated services central to mobile app development. 开发人员可以使用生成测试分发服务来设置持续集成和交付管道。Developers can use Build, Test and Distribute services to set up Continuous Integration and Delivery pipeline. 部署应用后,开发人员可以使用分析诊断服务监视其应用的状态和使用情况,并使用推送服务与用户互动。Once the app is deployed, developers can monitor the status and usage of their app using the Analytics and Diagnostics services, and engage with users using the Push service. 开发人员还可以利用 Auth 对用户进行身份验证,利用数据服务在云中持久保存和同步应用数据。Developers can also leverage Auth to authenticate their users and Data service to persist and sync app data in the cloud. 立即查看 App CenterCheck out App Center today.

概述Overview

本教程演示如何使用 Azure 移动应用后端为通用 Windows 平台 (UWP) 应用添加脱机支持。This tutorial shows you how to add offline support to a Universal Windows Platform (UWP) app using an Azure Mobile App backend. 脱机同步允许最终用户与移动应用交互(查看、添加或修改数据),即使在没有网络连接时也是如此。Offline sync allows end users to interact with a mobile app--viewing, adding, or modifying data - even when there is no network connection. 在本地数据库中存储更改。Changes are stored in a local database. 设备重新联机后,这些更改会与远程后端同步。Once the device is back online, these changes are synced with the remote backend.

本教程会更新创建 Windows 应用 教程中的 UWP 应用项目,支持 Azure 移动应用的脱机功能。In this tutorial, you update the UWP app project from the tutorial Create a Windows app to support the offline features of Azure Mobile Apps. 如果不使用下载的快速入门服务器项目,必须将数据访问扩展包添加到项目。If you do not use the downloaded quick start server project, you must add the data access extension packages to your project. 有关服务器扩展包的详细信息,请参阅使用适用于 Azure 移动应用的 .NET 后端服务器 SDKFor more information about server extension packages, see Work with the .NET backend server SDK for Azure Mobile Apps.

若要了解有关脱机同步功能的详细信息,请参阅主题 Azure 移动应用中的脱机数据同步To learn more about the offline sync feature, see the topic Offline Data Sync in Azure Mobile Apps.

要求Requirements

本教程需要的内容以下先决条件:This tutorial requires the following pre-requisites:

更新客户端应用以支持脱机功能Update the client app to support offline features

脱机情况下,可使用 Azure 移动应用脱机功能与本地数据库交互。Azure Mobile App offline features allow you to interact with a local database when you are in an offline scenario. 若要在应用中使用这些功能,请初始化 SyncContext to a local store. Then reference your table through the IMobileServiceSyncTable 接口。To use these features in your app, you initialize a SyncContext to a local store. Then reference your table through the IMobileServiceSyncTable interface. SQLite 在设备上用作本地存储。SQLite is used as the local store on the device.

  1. 安装 适用于通用 Windows 平台的 SQLite 运行时Install the SQLite runtime for the Universal Windows Platform.

  2. 在 Visual Studio 中,打开在 创建 Windows 应用 教程中完成的 UWP 应用项目的 NuGet 包管理器。In Visual Studio, open the NuGet package manager for the UWP app project that you completed in the Create a Windows app tutorial. 搜索并安装 Microsoft.Azure.Mobile.Client.SQLiteStore NuGet 包。Search for and install the Microsoft.Azure.Mobile.Client.SQLiteStore NuGet package.

  3. 在解决方案资源管理器中,右键单击“引用”>“添加引用...” >“通用 Windows”>“扩展”,并同时启用“适用于通用 Windows 平台的 SQLite”和“适用于通用 Windows 平台应用的 Visual C++ 2015 运行时” 。In Solution Explorer, right-click References > Add Reference... > Universal Windows > Extensions, then enable both SQLite for Universal Windows Platform and Visual C++ 2015 Runtime for Universal Windows Platform apps.

    添加 SQLite UWP 引用

  4. 打开 MainPage.xaml.cs 文件,并取消注释 #define OFFLINE_SYNC_ENABLED 定义。Open the MainPage.xaml.cs file and uncomment the #define OFFLINE_SYNC_ENABLED definition.

  5. 在 Visual Studio 中,按 F5 键重新生成并运行客户端应用。In Visual Studio, press the F5 key to rebuild and run the client app. 应用的工作方式与启用脱机同步之前一样。但是,本地数据库中现在填充了可以在脱机方案中使用的数据。The app works the same as it did before you enabled offline sync. However, the local database is now populated with data that can be used in an offline scenario.

更新应用以与后端断开连接Update the app to disconnect from the backend

本部分断开与移动应用后端的连接,以模拟脱机情况。In this section, you break the connection to your Mobile App backend to simulate an offline situation. 添加数据项时,异常处理程序会指示该应用处于脱机模式。When you add data items, your exception handler tells you that the app is in offline mode. 在此状态下,新项会添加到本地存储,下次以连接状态运行推送时,这些新项将同步到移动应用后端。In this state, new items added in the local store and will be synced to the mobile app backend when push is next run in a connected state.

  1. 编辑共享项目中的 App.xaml.cs。Edit App.xaml.cs in the shared project. 注释掉 MobileServiceClient 的初始化并添加使用无效移动应用 URL 的以下行:Comment out the initialization of the MobileServiceClient and add the following line, which uses an invalid mobile app URL:

     public static MobileServiceClient MobileService = new MobileServiceClient("https://your-service.azurewebsites.fail");
    

    还可以通过在设备上禁用 wifi 和手机网络或使用飞行模式来演示脱机行为。You can also demonstrate offline behavior by disabling wifi and cellular networks on the device or use airplane mode.

  2. F5 生成并运行应用。Press F5 to build and run the app. 请注意,在应用启动时,同步刷新将失败。Notice your sync failed on refresh when the app launched.

  3. 输入新项,并注意每次单击 保存 时,推送将失败,并显示 CancelledByNetworkError状态。Enter new items and notice that push fails with a CancelledByNetworkError status each time you click Save. 但是,新的待办事项在可被推送到移动应用后端之前,将存在于本地存储中。However, the new todo items exist in the local store until they can be pushed to the mobile app backend. 在生产应用中,如果取消显示这些异常,客户端应用的行为将会像它仍连接到移动应用后端时一样。In a production app, if you suppress these exceptions the client app behaves as if it's still connected to the mobile app backend.

  4. 关闭应用程序并重新启动它,以验证你创建的新项目是否已永久保存到本地存储中。Close the app and restart it to verify that the new items you created are persisted to the local store.

  5. (可选)在 Visual Studio 中,打开“服务器资源管理器” 。(Optional) In Visual Studio, open Server Explorer. 导航到“Azure” ->“SQL 数据库” 中的数据库。Navigate to your database in Azure->SQL Databases. 右键单击数据库并选择“在 SQL Server 对象资源管理器中打开” 。Right-click your database and select Open in SQL Server Object Explorer. 现在便可以浏览 SQL 数据库表及其内容。Now you can browse to your SQL database table and its contents. 验证确认后端数据库中的数据未更改。Verify that the data in the backend database has not changed.

  6. (可选)通过 Fiddler 或 Postman 之类的 REST 工具使用 https://<your-mobile-app-backend-name>.chinacloudsites.cn/tables/TodoItem 格式的 GET 查询,查询移动后端。(Optional) Use a REST tool such as Fiddler or Postman to query your mobile backend, using a GET query in the form https://<your-mobile-app-backend-name>.chinacloudsites.cn/tables/TodoItem.

更新应用以重新连接移动应用后端Update the app to reconnect your Mobile App backend

在本部分中,会将应用重新连接到移动应用后端。In this section, you reconnect the app to the mobile app backend. 这些更改可模拟应用上的网络重新连接。These changes simulate a network reconnection on the app.

首次运行该应用程序时,OnNavigatedTo 事件处理程序将调用 InitLocalStoreAsyncWhen you first run the application, the OnNavigatedTo event handler calls InitLocalStoreAsync. 而此方法又将调用 SyncAsync,将本地存储与后端数据库同步。This method in turn calls SyncAsync to sync your local store with the backend database. 应用会尝试在启动时同步。The app attempts to sync on startup.

  1. 在共享项目中,打开 App.xaml.cs,并取消注释 MobileServiceClient 之前的初始化,以使用正确的移动应用 URL。Open App.xaml.cs in the shared project, and uncomment your previous initialization of MobileServiceClient to use the correct the mobile app URL.

  2. F5 键重新生成并运行应用。Press the F5 key to rebuild and run the app. 执行 OnNavigatedTo 事件处理程序时,该应用将使用推送和拉取操作将本地更改与 Azure 移动应用后端进行同步。The app syncs your local changes with the Azure Mobile App backend using push and pull operations when the OnNavigatedTo event handler executes.

  3. (可选)使用 SQL Server 对象资源管理器或 Fiddler 之类的 REST 工具查看更新后的数据。(Optional) View the updated data using either SQL Server Object Explorer or a REST tool like Fiddler. 请注意,数据已在 Azure 移动应用后端数据库和本地存储之间进行同步。Notice the data has been synchronized between the Azure Mobile App backend database and the local store.

  4. 在应用程序中,单击要在本地存储区中完成的几个项旁边的复选框。In the app, click the check box beside a few items to complete them in the local store.

    UpdateCheckedTodoItem 调用 SyncAsync,将每个已完成项与移动应用后端同步。UpdateCheckedTodoItem calls SyncAsync to sync each completed item with the Mobile App backend. SyncAsync 同时调用推送和拉取操作。SyncAsync calls both push and pull. 但是, 针对客户端已更改的表执行拉取操作时,始终会自动执行推送操作However, whenever you execute a pull against a table that the client has made changes to, a push is always executed automatically. 此行为可确保本地存储中的所有表以及关系都保持一致。This behavior ensures all tables in the local store along with relationships remain consistent. 此行为可能会导致意外的推送。This behavior may result in an unexpected push. 有关此行为的详细信息,请参阅 Azure 移动应用中的脱机数据同步For more information on this behavior, see Offline Data Sync in Azure Mobile Apps.

API 摘要API Summary

为了支持移动服务的脱机功能,我们使用了 IMobileServiceSyncTable 接口,并使用本地 SQLite 数据库初始化了 MobileServiceClient.SyncContextTo support the offline features of mobile services, we used the IMobileServiceSyncTable interface and initialized MobileServiceClient.SyncContext with a local SQLite database. 脱机时,移动应用的普通 CRUD 操作执行起来就像此应用仍处于连接状态一样,但操作针对本地存储进行。When offline, the normal CRUD operations for Mobile Apps work as if the app is still connected while the operations occur against the local store. 以下方法用于将本地存储与服务器进行同步:The following methods are used to synchronize the local store with the server:

  • PushAsync 由于此方法是 IMobileServicesSyncContext 的成员,因此对所有表进行的更改将推送到后端。PushAsync Because this method is a member of IMobileServicesSyncContext, changes across all tables are pushed to the backend. 只有具有本地更改的记录才会被发送到服务器。Only records with local changes are sent to the server.
  • PullAsyncIMobileServiceSyncTable 启动拉取操作。PullAsync A pull is started from a IMobileServiceSyncTable. 当表中存在被跟踪的更改时,会执行隐式推送操作以确保本地存储中的所有表以及关系都保持一致。When there are tracked changes in the table, an implicit push is run to make sure that all tables in the local store along with relationships remain consistent. PushOtherTables 参数控制在隐式推送操作中是否推送上下文中的其他表。The pushOtherTables parameter controls whether other tables in the context are pushed in an implicit push. query 参数使用 IMobileServiceTableQuery<T> 或 OData 查询字符串来筛选返回的数据。The query parameter takes an IMobileServiceTableQuery<T> or OData query string to filter the returned data. queryId 参数用于定义增量同步。有关详细信息,请参阅 Azure 移动应用中的脱机数据同步The queryId parameter is used to define incremental sync. For more information, see Offline Data Sync in Azure Mobile Apps.
  • PurgeAsync 应用应定期调用此方法,从本地存储中清除过时数据。PurgeAsync Your app should periodically call this method to purge stale data from the local store. 需要清除尚未同步的任何更改时,请使用 force 参数。Use the force parameter when you need to purge any changes that have not yet been synced.

有关这些概念的详细信息,请参阅 Azure 移动应用中的脱机数据同步For more information about these concepts, see Offline Data Sync in Azure Mobile Apps.

更多信息More info

以下主题提供有关移动应用的脱机同步功能的更多背景信息:The following topics provide additional background information on the offline sync feature of Mobile Apps: