TodoItemManager.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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 = InitializeDatabase();
  22. var store = new MobileServiceSQLiteStore(path);
  23. store.DefineTable<TodoItem>();
  24. //Initializes the SyncContext using the default IMobileServiceSyncHandler.
  25. await client.SyncContext.InitializeAsync(store);
  26. todoTable = client.GetSyncTable<TodoItem>();
  27. }
  28. private string InitializeDatabase()
  29. {
  30. #if __ANDROID__ || __IOS__
  31. CurrentPlatform.Init();
  32. #endif
  33. SQLitePCL.Batteries.Init();
  34. var path = "localstore.db";
  35. #if __ANDROID__
  36. path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), path);
  37. if (!File.Exists(path))
  38. {
  39. File.Create(path).Dispose();
  40. }
  41. #endif
  42. return path;
  43. }
  44. public static TodoItemManager DefaultManager
  45. {
  46. get
  47. {
  48. return defaultInstance;
  49. }
  50. private set
  51. {
  52. defaultInstance = value;
  53. }
  54. }
  55. public MobileServiceClient CurrentClient
  56. {
  57. get { return client; }
  58. }
  59. public async Task<ObservableCollection<TodoItem>> GetTodoItemsAsync(bool syncItems = false)
  60. {
  61. try
  62. {
  63. await Initialize();
  64. if (syncItems)
  65. {
  66. await SyncAsync();
  67. }
  68. var items = await todoTable
  69. .Where(todoItem => !todoItem.Done)
  70. .OrderBy(todoItem => todoItem.Name)
  71. .ToEnumerableAsync();
  72. return new ObservableCollection<TodoItem>(items);
  73. }
  74. catch (MobileServiceInvalidOperationException msioe)
  75. {
  76. Debug.WriteLine(@"Invalid sync operation: {0}", msioe.Message);
  77. throw;
  78. }
  79. catch (Exception e)
  80. {
  81. Debug.WriteLine(@"Sync error: {0}", e.Message);
  82. throw;
  83. }
  84. return null;
  85. }
  86. public async Task SaveTaskAsync(TodoItem item)
  87. {
  88. await Initialize();
  89. if (item.Id == null)
  90. {
  91. await todoTable.InsertAsync(item);
  92. }
  93. else
  94. {
  95. await todoTable.UpdateAsync(item);
  96. }
  97. }
  98. public async Task SyncAsync()
  99. {
  100. await Initialize();
  101. ReadOnlyCollection<MobileServiceTableOperationError> syncErrors = null;
  102. try
  103. {
  104. await client.SyncContext.PushAsync();
  105. await todoTable.PullAsync(
  106. //The first parameter is a query name that is used internally by the client SDK to implement incremental sync.
  107. //Use a different query name for each unique query in your program
  108. "allTodoItems",
  109. todoTable.CreateQuery());
  110. }
  111. catch (MobileServicePushFailedException exc)
  112. {
  113. if (exc.PushResult != null)
  114. {
  115. syncErrors = exc.PushResult.Errors;
  116. }
  117. }
  118. // Simple error/conflict handling. A real application would handle the various errors like network conditions,
  119. // server conflicts and others via the IMobileServiceSyncHandler.
  120. if (syncErrors != null)
  121. {
  122. foreach (var error in syncErrors)
  123. {
  124. if (error.OperationKind == MobileServiceTableOperationKind.Update && error.Result != null)
  125. {
  126. //Update failed, reverting to server's copy.
  127. await error.CancelAndUpdateItemAsync(error.Result);
  128. }
  129. else if(error.OperationKind != MobileServiceTableOperationKind.Update)
  130. {
  131. // Discard local change.
  132. await error.CancelAndDiscardItemAsync();
  133. }
  134. Debug.WriteLine(@"Error executing sync operation. Item: {0} ({1}). Operation discarded.", error.TableName, error.Item["id"]);
  135. }
  136. }
  137. }
  138. }
  139. }