AzureService.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 = "syncstore.db";
  29. path = Path.Combine(MobileServiceClient.DefaultDatabasePath, path);
  30. //setup our local sqlite store and intialize our table
  31. var store = new MobileServiceSQLiteStore(path);
  32. //Define table
  33. store.DefineTable<Speaker>();
  34. //Initialize SyncContext
  35. await Client.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());
  36. //Get our sync table that will call out to azure
  37. table = Client.GetSyncTable<Speaker>();
  38. }
  39. public async Task<IEnumerable<Speaker>> GetSpeakers()
  40. {
  41. await Initialize();
  42. await SyncSpeakers();
  43. return await table.OrderBy(s => s.Name).ToEnumerableAsync();
  44. }
  45. public async Task SyncSpeakers()
  46. {
  47. try
  48. {
  49. await Client.SyncContext.PushAsync();
  50. await table.PullAsync("allSpeakers", table.CreateQuery());
  51. }
  52. catch (Exception ex)
  53. {
  54. Debug.WriteLine("Unable to sync speakers, that is alright as we have offline capabilities: " + ex);
  55. }
  56. }
  57. }
  58. }