Skip to content

Instantly share code, notes, and snippets.

@chrisgate
Forked from phenomx2/SyncManager.cs
Created April 23, 2018 23:35
Show Gist options
  • Save chrisgate/955151c4430343d339b57e9f74492f75 to your computer and use it in GitHub Desktop.
Save chrisgate/955151c4430343d339b57e9f74492f75 to your computer and use it in GitHub Desktop.
MobileServiceSQLiteStore Handler
public class SyncManager : IDisposable
{
private readonly MobileServiceClient _client;
private readonly MobileServiceSQLiteStore _store;
public SyncManager()
{
_client = Locator.Current.GetService<MobileServiceClient>();
_store = new MobileServiceSQLiteStore(Constants.OfflineDbPath);
}
private async Task InitializeAsync()
{
if (_client.SyncContext.IsInitialized)
return;
_store.DefineTable<AspNetUser>();
_store.DefineTable<Hall>();
_store.DefineTable<HallBookingEasy>();
_store.DefineTable<News>();
_store.DefineTable<NewsFeed>();
await _client.SyncContext.InitializeAsync(_store);
}
public async Task SyncAsync()
{
await InitializeAsync();
var hallTable = _client.GetSyncTable<Hall>();
var hallBookingTable = _client.GetSyncTable<HallBookingEasy>();
var newsFeedsTable = _client.GetSyncTable<NewsFeed>();
var newsTable = _client.GetSyncTable<News>();
await hallTable.PullAsync("getAllHalls", hallTable.CreateQuery());
await hallBookingTable.PullAsync("getHallBookings", hallBookingTable.CreateQuery());
await newsFeedsTable.PullAsync("getAllNewsFeeds", newsFeedsTable.CreateQuery());
await newsTable.PullAsync("getAllNews", newsTable.CreateQuery());
}
public async Task<IEnumerable<T>> GetAllAsync<T>() where T : TableData
{
await InitializeAsync();
var table = _client.GetSyncTable<T>();
await table.PullAsync(nameof(T), table.CreateQuery());
return await table.ToListAsync();
}
public async Task<T> SingleOrDefaultAsync<T>() where T : TableData
{
await InitializeAsync();
var table = _client.GetSyncTable<T>();
var rows = await table.ToListAsync();
return rows.SingleOrDefault();
}
public async Task<bool> InsertAsync<T>(T toInsert)
{
await InitializeAsync();
var table = _client.GetSyncTable<T>();
await table.InsertAsync(toInsert);
return true;
}
public async Task PurgeTableAsync<T>()
{
await InitializeAsync();
var table = _client.GetSyncTable<T>();
await table.PurgeAsync(true);
}
public void Dispose()
{
_client.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment