Synchronizing in a Background Task

Now that we have implementations for IDataService and ISyncService I can update the backgounrd task for the Windows platform applications to perform synchronization in the background. To begin with I need to reference the Autofac libraries (including the Microsoft common service locator and extensions libraries) by adding the RealEstateInspector.Background in NuGet package manager

image

 

The next thing is to update the Run method of the background task so that it looks for a current access token and uses it to initialise the data service.

public async void Run(IBackgroundTaskInstance taskInstance)
{
    try
    {
        var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;

        var authContext = new AuthenticationContext(Constants.ADAuthority);
        if (authContext.TokenCache.ReadItems().Count() > 0)
        {
            authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
        }

        var authResult =
            await
                authContext.AcquireTokenSilentAsync(Constants.MobileServiceAppIdUri,
                Constants.ADNativeClientApplicationClientId);
        if (authResult != null && !string.IsNullOrWhiteSpace(authResult.AccessToken))
        {
            var dataService = ServiceLocator.Current.GetInstance<IDataService>();
            var syncService = ServiceLocator.Current.GetInstance<ISyncService>();

            await dataService.Initialize(authResult.AccessToken);

            if (cost == BackgroundWorkCostValue.High)
            {
                await syncService.ForceUpload();
            }
            else
            {
                await syncService.Synchronise(true);
            }
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
    finally
    {
        if (deferral != null)
        {
            deferral.Complete();
        }
    }
}

Depending on the cost of the background task I either want the task to force an upload of pending updates (if high cost), or do a full synchronisation.

Leave a comment