AzureService.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using DevDaysSpeakers.Services;
  2. using DevDaysSpeakers.Model;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using System.IO;
  7. using Xamarin.Forms;
  8. using Microsoft.WindowsAzure.MobileServices;
  9. using Microsoft.WindowsAzure.MobileServices.Sync;
  10. using System.Threading.Tasks;
  11. using Microsoft.WindowsAzure.MobileServices.SQLiteStore;
  12. using System.Diagnostics;
  13. [assembly: Dependency(typeof(AzureService))]
  14. namespace DevDaysSpeakers.Services
  15. {
  16. public class AzureService
  17. {
  18. public MobileServiceClient Client { get; set; } = null;
  19. IMobileServiceSyncTable<Speaker> table;
  20. public async Task Initialize()
  21. {
  22. if (Client?.SyncContext?.IsInitialized ?? false)
  23. return;
  24. var appUrl = "https://montemagnospeakers.azurewebsites.net";
  25. //Create our client
  26. Client = new MobileServiceClient(appUrl);
  27. //InitialzeDatabase for path
  28. var path = InitializeDatabase();
  29. //setup our local sqlite store and intialize our table
  30. var store = new MobileServiceSQLiteStore(path);
  31. //Define table
  32. store.DefineTable<Speaker>();
  33. //Initialize SyncContext
  34. await Client.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());
  35. //Get our sync table that will call out to azure
  36. table = Client.GetSyncTable<Speaker>();
  37. }
  38. private string InitializeDatabase()
  39. {
  40. #if __ANDROID__ || __IOS__
  41. Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
  42. #endif
  43. SQLitePCL.Batteries.Init();
  44. var path = "syncstore.db";
  45. #if __ANDROID__
  46. path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), path);
  47. if (!File.Exists(path))
  48. {
  49. File.Create(path).Dispose();
  50. }
  51. #endif
  52. return path;
  53. }
  54. public async Task<IEnumerable<Speaker>> GetSpeakers()
  55. {
  56. await Initialize();
  57. await SyncSpeakers();
  58. return await table.OrderBy(s => s.Name).ToEnumerableAsync();
  59. }
  60. public async Task SyncSpeakers()
  61. {
  62. try
  63. {
  64. await Client.SyncContext.PushAsync();
  65. await table.PullAsync("allSpeakers", table.CreateQuery());
  66. }
  67. catch (Exception ex)
  68. {
  69. Debug.WriteLine("Unable to sync speakers, that is alright as we have offline capabilities: " + ex);
  70. }
  71. }
  72. }
  73. }