TodoItemManager.cs 4.6 KB

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