Microsoft.Azure.Mobile Client - Handling Server Error using custom IMobileServiceSyncHandler - Xamarin Forms

前端 未结 2 1266
挽巷
挽巷 2021-01-28 22:52

I have implemented the Azure - Offline Sync based on the documentation / Sample provided by Microsoft Sample in my Xamarin Forms Application.

In the sample / documentati

相关标签:
2条回答
  • 2021-01-28 23:10

    The exception carries with it a copy of the server version. In my implementation of IMobileServiceSyncHandler I therefore just return error.Value and this seems to work.

    A more extensive example of this kind of logic can be found in this MSDN blog.

    The same author has another example where he shows how you can resolve the conflict in favour of the server copy or the client copy, here.

    0 讨论(0)
  • 2021-01-28 23:18

    You say you aren't trying to resolve conflicts, but you need to resolve them one way or another (without telling the user what's going on, perhaps) by accepting the server version of the object or updating the client operation. Otherwise it will just keep telling you about the same conflict each time it retries the operation.

    You need to have a subclass of the Microsoft.WindowsAzure.MobileServices.Sync.MobileServiceSyncHandler class, which overrides OnPushCompleteAsync() in order to handle conflicts and other errors. Let's call the class SyncHandler:

    public class SyncHandler : MobileServiceSyncHandler
    {
        public override async Task OnPushCompleteAsync(MobileServicePushCompletionResult result)
        {
            foreach (var error in result.Errors)
            {
                await ResolveConflictAsync(error);
            }
            await base.OnPushCompleteAsync(result);
        }
    
        private static async Task ResolveConflictAsync(MobileServiceTableOperationError error)
        {
            Debug.WriteLine($"Resolve Conflict for Item: {error.Item} vs serverItem: {error.Result}");
    
            var serverItem = error.Result;
            var localItem = error.Item;
    
            if (Equals(serverItem, localItem))
            {
                // Items are the same, so ignore the conflict
                await error.CancelAndUpdateItemAsync(serverItem);
            }
            else // check server item and local item or the error for criteria you care about
            {
                // Cancels the table operation and discards the local instance of the item.
                await error.CancelAndDiscardItemAsync();
            }
        }
    }
    

    Include an instance of this SyncHandler() when you initialize your MobileServiceClient:

    await MobileServiceClient.SyncContext.InitializeAsync(store, new SyncHandler()).ConfigureAwait(false);
    

    Read up on the MobileServiceTableOperationError to see other conflicts you can handle as well as its methods to allow resolving them.

    0 讨论(0)
提交回复
热议问题