TodoItemManager.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. // To add offline sync support: add the NuGet package Microsoft.Azure.Mobile.Client.SQLiteStore
  2. // to all projects in the solution and uncomment the symbol definition OFFLINE_SYNC_ENABLED
  3. // For Xamarin.iOS, also edit AppDelegate.cs and uncomment the call to SQLitePCL.CurrentPlatform.Init()
  4. // For more information, see: http://go.microsoft.com/fwlink/?LinkId=620342
  5. #define OFFLINE_SYNC_ENABLED
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Collections.ObjectModel;
  9. using System.Diagnostics;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using Microsoft.WindowsAzure.MobileServices;
  14. #if OFFLINE_SYNC_ENABLED
  15. using Microsoft.WindowsAzure.MobileServices.SQLiteStore;
  16. using Microsoft.WindowsAzure.MobileServices.Sync;
  17. #endif
  18. namespace DevDaysTasks
  19. {
  20. public partial class TodoItemManager
  21. {
  22. static TodoItemManager defaultInstance = new TodoItemManager();
  23. MobileServiceClient client;
  24. IMobileServiceSyncTable<TodoItem> todoTable;
  25. private TodoItemManager()
  26. {
  27. this.client = new MobileServiceClient(Constants.ApplicationURL);
  28. var store = new MobileServiceSQLiteStore("localstore.db");
  29. store.DefineTable<TodoItem>();
  30. //Initializes the SyncContext using the default IMobileServiceSyncHandler.
  31. this.client.SyncContext.InitializeAsync(store);
  32. this.todoTable = client.GetSyncTable<TodoItem>();
  33. }
  34. public static TodoItemManager DefaultManager
  35. {
  36. get
  37. {
  38. return defaultInstance;
  39. }
  40. private set
  41. {
  42. defaultInstance = value;
  43. }
  44. }
  45. public MobileServiceClient CurrentClient
  46. {
  47. get { return client; }
  48. }
  49. public bool IsOfflineEnabled
  50. {
  51. get { return todoTable is Microsoft.WindowsAzure.MobileServices.Sync.IMobileServiceSyncTable<TodoItem>; }
  52. }
  53. public async Task<ObservableCollection<TodoItem>> GetTodoItemsAsync(bool syncItems = true)
  54. {
  55. try
  56. {
  57. if (syncItems)
  58. {
  59. await this.SyncAsync();
  60. }
  61. var items = await todoTable
  62. .Where(todoItem => !todoItem.Done)
  63. .ToEnumerableAsync();
  64. return new ObservableCollection<TodoItem>(items);
  65. }
  66. catch (MobileServiceInvalidOperationException msioe)
  67. {
  68. Debug.WriteLine(@"Invalid sync operation: {0}", msioe.Message);
  69. }
  70. catch (Exception e)
  71. {
  72. Debug.WriteLine(@"Sync error: {0}", e.Message);
  73. }
  74. return null;
  75. }
  76. public async Task SaveTaskAsync(TodoItem item)
  77. {
  78. if (item.Id == null)
  79. {
  80. await todoTable.InsertAsync(item);
  81. }
  82. else
  83. {
  84. await todoTable.UpdateAsync(item);
  85. }
  86. }
  87. public async Task SyncAsync()
  88. {
  89. ReadOnlyCollection<MobileServiceTableOperationError> syncErrors = null;
  90. try
  91. {
  92. await this.client.SyncContext.PushAsync();
  93. await this.todoTable.PullAsync(
  94. //The first parameter is a query name that is used internally by the client SDK to implement incremental sync.
  95. //Use a different query name for each unique query in your program
  96. "allTodoItems",
  97. this.todoTable.CreateQuery());
  98. }
  99. catch (MobileServicePushFailedException exc)
  100. {
  101. if (exc.PushResult != null)
  102. {
  103. syncErrors = exc.PushResult.Errors;
  104. }
  105. }
  106. // Simple error/conflict handling. A real application would handle the various errors like network conditions,
  107. // server conflicts and others via the IMobileServiceSyncHandler.
  108. if (syncErrors != null)
  109. {
  110. foreach (var error in syncErrors)
  111. {
  112. if (error.OperationKind == MobileServiceTableOperationKind.Update && error.Result != null)
  113. {
  114. //Update failed, reverting to server's copy.
  115. await error.CancelAndUpdateItemAsync(error.Result);
  116. }
  117. else
  118. {
  119. // Discard local change.
  120. await error.CancelAndDiscardItemAsync();
  121. }
  122. Debug.WriteLine(@"Error executing sync operation. Item: {0} ({1}). Operation discarded.", error.TableName, error.Item["id"]);
  123. }
  124. }
  125. }
  126. }
  127. }