Exemple #1
0
        private async void ApplyUpdates()
        {
            try
            {
                // Create default sync parameters.
                OfflineMapSyncParameters parameters = await _offlineMapSyncTask.CreateDefaultOfflineMapSyncParametersAsync();

                // Set the parameters to download all updates for the mobile map packages.
                parameters.PreplannedScheduledUpdatesOption = PreplannedScheduledUpdatesOption.DownloadAllUpdates;

                // Set the map package to rollback to the old state should the sync job fail.
                parameters.RollbackOnFailure = true;

                // Create a sync job using the parameters.
                OfflineMapSyncJob offlineMapSyncJob = _offlineMapSyncTask.SyncOfflineMap(parameters);

                // Get the results of the job.
                offlineMapSyncJob.Start();
                OfflineMapSyncResult result = await offlineMapSyncJob.GetResultAsync();

                // Check if the job succeeded.
                if (offlineMapSyncJob.Status == JobStatus.Succeeded)
                {
                    // Check if the map package needs to be re-opened.
                    if (result.IsMobileMapPackageReopenRequired)
                    {
                        // Re-open the mobile map package.
                        _mobileMapPackage.Close();
                        await _mobileMapPackage.LoadAsync();

                        // Check that the mobile map package was loaded.
                        if (_mobileMapPackage.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded && _mobileMapPackage.Maps.Any())
                        {
                            // Set the mapview to the map from the package.
                            Map offlineMap = _mobileMapPackage.Maps[0];
                            MyMapView.Map = offlineMap;

                            // Create an offline map sync task for the map.
                            _offlineMapSyncTask = await OfflineMapSyncTask.CreateAsync(offlineMap);
                        }
                        else
                        {
                            await Application.Current.MainPage.DisplayAlert("Error", "Failed to load the mobile map package.", "OK");
                        }
                    }

                    // Verify that the map is up to date and change the UI to reflect the update availability status.
                    CheckForScheduledUpdates();
                }
                else
                {
                    await Application.Current.MainPage.DisplayAlert("Error", "Error syncing the offline map.", "OK");
                }
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK");
            }
        }
        private async void ApplyUpdatesClicked(object sender, EventArgs e)
        {
            try
            {
                // Create default sync parameters.
                OfflineMapSyncParameters parameters = await _offlineMapSyncTask.CreateDefaultOfflineMapSyncParametersAsync();

                // Set the parameters to download all updates for the mobile map packages.
                parameters.PreplannedScheduledUpdatesOption = PreplannedScheduledUpdatesOption.DownloadAllUpdates;

                // Create a sync job using the parameters.
                OfflineMapSyncJob offlineMapSyncJob = _offlineMapSyncTask.SyncOfflineMap(parameters);

                // Get the results of the job.
                offlineMapSyncJob.Start();
                OfflineMapSyncResult result = await offlineMapSyncJob.GetResultAsync();

                // Check if the job succeeded.
                if (offlineMapSyncJob.Status == JobStatus.Succeeded)
                {
                    // Check if the map package needs to be re-opened.
                    if (result.IsMobileMapPackageReopenRequired)
                    {
                        // Re-open the mobile map package.
                        _mobileMapPackage.Close();
                        _mobileMapPackage = new MobileMapPackage(_mapPackagePath);
                        await _mobileMapPackage.LoadAsync();

                        // Check that the mobile map package was loaded.
                        if (_mobileMapPackage.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded && _mobileMapPackage.Maps.Any())
                        {
                            // Set the mapview to the map from the package.
                            Map offlineMap = _mobileMapPackage.Maps[0];
                            _myMapView.Map = offlineMap;

                            // Create an offline map sync task for the map.
                            _offlineMapSyncTask = await OfflineMapSyncTask.CreateAsync(offlineMap);
                        }
                        else
                        {
                            new UIAlertView("Error", "Failed to load the mobile map package.", (IUIAlertViewDelegate)null, "OK", null).Show();
                        }
                    }

                    // Verify that the map is up to date and change the UI to reflect the update availability status.
                    CheckForScheduledUpdates();
                }
                else
                {
                    new UIAlertView("Error", "Error syncing the offline map.", (IUIAlertViewDelegate)null, "OK", null).Show();
                }
            }
            catch (Exception ex)
            {
                new UIAlertView("Error", ex.Message, (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }
        /// <summary>
        /// Method that handles syncing the offline and online maps
        /// </summary>
        private async Task SyncMap(Map map)
        {
            var syncTask = await OfflineMapSyncTask.CreateAsync(map);

            // set parameters for sync
            var taskParams = new OfflineMapSyncParameters()
            {
                SyncDirection     = SyncDirection.Bidirectional,
                RollbackOnFailure = true
            };

            try
            {
                // set the job to perform the sync
                OfflineMapSyncJob = syncTask.SyncOfflineMap(taskParams);

                // update the progress property when progress changes
                OfflineMapSyncJob.ProgressChanged +=
                    (s, e) =>
                {
                    Progress = OfflineMapSyncJob.Progress;
                };

                // listen for job changed events
                OfflineMapSyncJob.JobChanged += (s, e) =>
                {
                    // if sync succeeds, raise success message
                    if (OfflineMapSyncJob.Status == JobStatus.Succeeded)
                    {
                        BroadcastMessenger.Instance.RaiseBroadcastMessengerValueChanged(true, Models.BroadcastMessageKey.SyncSucceeded);
                    }
                    else if (OfflineMapSyncJob.Status == JobStatus.Failed)
                    {
                        // if the job failed display the error, unless the user has cancelled it on purpose
                        if (OfflineMapSyncJob.Error != null && OfflineMapSyncJob.Error.Message != "User canceled: Job canceled.")
                        {
                            UserPromptMessenger.Instance.RaiseMessageValueChanged(
                                null, OfflineMapSyncJob.Error.Message, true, OfflineMapSyncJob.Error.StackTrace);
                        }

                        BroadcastMessenger.Instance.RaiseBroadcastMessengerValueChanged(false, Models.BroadcastMessageKey.SyncSucceeded);
                    }
                };

                // begin sync job
                OfflineMapSyncJob.Start();
            }
            catch (Exception ex)
            {
                UserPromptMessenger.Instance.RaiseMessageValueChanged(
                    null, ex.Message, true, ex.StackTrace);

                BroadcastMessenger.Instance.RaiseBroadcastMessengerValueChanged(false, Models.BroadcastMessageKey.SyncSucceeded);
            }
        }
        private async void Initialize()
        {
            try
            {
                // Clear the exiting sample data.
                Directory.Delete(DataManager.GetDataFolder(_itemId, ""), true);
            }
            catch (IOException)
            {
                // Do nothing. Exception happens when sample hasn't been run before and data isn't already present.
            }

            try
            {
                // Token for cancelling the download if the sample is exited early.
                var tokenSource         = new CancellationTokenSource();
                CancellationToken token = tokenSource.Token;

                // Add an event to close the mobile map package when the sample closes.
                Unloaded += (s, e) =>
                {
                    _mobileMapPackage?.Close();
                    tokenSource.Cancel();
                };

                // Download the mobile map package using the sample viewer's data manager.
                await DataManager.DownloadDataItem(_itemId, token);

                // Get the folder path to the mobile map package.
                _mapPackagePath = DataManager.GetDataFolder(_itemId, "");

                // Load the mobile map package.
                _mobileMapPackage = new MobileMapPackage(_mapPackagePath);
                await _mobileMapPackage.LoadAsync();

                // Set the mapview to the map from the package.
                Map offlineMap = _mobileMapPackage.Maps[0];
                MyMapView.Map = offlineMap;

                // Create an offline map sync task for the map.
                _offlineMapSyncTask = await OfflineMapSyncTask.CreateAsync(offlineMap);

                // Check if there are scheduled updates to the preplanned map area.
                CheckForScheduledUpdates();
            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.Message, "Error").ShowAsync();
            }
        }
        private async void UpdateFeatureButton_Clicked(object sender, EventArgs e)
        {
            // Get our point layer
            var featureLayer = (TheMap.Map.AllLayers[3] as FeatureLayer);
            var table        = featureLayer.FeatureTable;
            var features     = await table.QueryFeaturesAsync(new Esri.ArcGISRuntime.Data.QueryParameters {
            });

            // Update a feature
            var feature = features.First();

            feature.SetAttributeValue("Description", "updated");
            await table.UpdateFeatureAsync(feature);

            // Create the sync task
            var syncTask = await OfflineMapSyncTask.CreateAsync(TheMap.Map);

            // Create the job
            var syncDirection = SyncDirection.Upload;
            var job           = syncTask.SyncOfflineMap(new OfflineMapSyncParameters()
            {
                RollbackOnFailure = true,
                SyncDirection     = syncDirection
            });

            job.ProgressChanged += UpdateJob_ProgressChanged;

            // Await result
            var result = await job.GetResultAsync();

            try
            {
                // Here's where we'll get an error trying to access result.LayerResults.
                // It throws a cast exception.
                var error = result.LayerResults;
            }
            catch (Exception ex)
            {
                UpdateStatusLabel.TextColor = Color.Red;
                await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK");
            }
        }
        private async void Initialize()
        {
            try
            {
                // Clear the exiting sample data.
                Directory.Delete(DataManager.GetDataFolder(_itemId, ""), true);
            }
            catch (IOException)
            {
                // Do nothing. Exception happens when sample hasn't been run before and data isn't already present.
            }

            try
            {
                // Download the mobile map package using the sample viewer's data manager.
                await DataManager.DownloadDataItem(_itemId);

                // Get the folder path to the mobile map package.
                _mapPackagePath = DataManager.GetDataFolder(_itemId, "");

                // Load the mobile map package.
                _mobileMapPackage = new MobileMapPackage(_mapPackagePath);
                await _mobileMapPackage.LoadAsync();

                // Set the mapview to the map from the package.
                Map offlineMap = _mobileMapPackage.Maps[0];
                _myMapView.Map = offlineMap;

                // Create an offline map sync task for the map.
                _offlineMapSyncTask = await OfflineMapSyncTask.CreateAsync(offlineMap);

                // Check if there are scheduled updates to the preplanned map area.
                CheckForScheduledUpdates();
            }
            catch (Exception ex)
            {
                new UIAlertView("Error", ex.Message, (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }
        private async void SyncMapArea(string parameter)
        {
            try
            {
                _windowService.SetBusy(true);
                SyncDirection synchronizationMode;
                switch (parameter)
                {
                case "Download":
                    synchronizationMode = SyncDirection.Download;
                    _windowService.SetBusyMessage("Getting latest updates...");
                    break;

                case "Upload":
                    synchronizationMode = SyncDirection.Upload;
                    _windowService.SetBusyMessage("Pushing local changes...");
                    break;

                default:
                    synchronizationMode = SyncDirection.Bidirectional;
                    _windowService.SetBusyMessage("Synchronizing features...");
                    break;
                }

                // Create task that is used to synchronize the offline map
                var task = await OfflineMapSyncTask.CreateAsync(Map);

                // Create parameters
                var parameters = new OfflineMapSyncParameters
                {
                    SyncDirection = synchronizationMode
                };

                // Create job that does the work asynchronously
                var job = task.SyncOfflineMap(parameters);
                job.ProgressChanged += async(s, e) =>
                {
                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        var offlineMapSyncJob = s as OfflineMapSyncJob;
                        _windowService.SetBusyMessage($"Syncing map area...{offlineMapSyncJob.Progress}%");
                    });
                };

                // Run the job and wait the results
                var results = await job.GetResultAsync();

                if (results.HasErrors)
                {
                    // handle nicely
                }

                foreach (string message in job.Messages.Select(x => x.Message))
                {
                    Debug.WriteLine(message);
                }
            }
            catch (Exception ex)
            {
                await _windowService.ShowAlertAsync(ex.Message, "Couldn't sync map area");
            }
            finally
            {
                RefreshCommands();
                _windowService.SetBusy(false);
            }
        }
Exemple #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="map"></param>
        /// <param name="jobHandler"></param>
        /// <param name="progressHandler"></param>
        ///
        /// <returns></returns>
        public async Task <SynchronizeReplicaResult> SynchronizeReplicaAsync(Map map, EventHandler <JobChangedEventArgs> jobHandler,
                                                                             EventHandler <ProgressChangedEventArgs> progressHandler)
        {
            var errors = new List <SyncReplicaErrorResult>();
            var task   = await OfflineMapSyncTask.CreateAsync(map);

            var param = new OfflineMapSyncParameters()
            {
                RollbackOnFailure = true,
                SyncDirection     = SyncDirection.Bidirectional
            };

            var job = task.SyncOfflineMap(param);

            if (jobHandler != null)
            {
                JobChangedEventHandler += jobHandler;
                job.JobChanged         += (o, e) =>
                {
                    if (JobChangedEventHandler != null)
                    {
                        JobChangedEventHandler.Invoke(job, new JobChangedEventArgs()
                        {
                            Messages = job.Messages, Status = job.Status
                        });
                    }
                };
            }
            if (progressHandler != null)
            {
                ProgressChangedEventHandler += progressHandler;
                job.ProgressChanged         += (o, e) =>
                {
                    ProgressChangedEventHandler?.Invoke(job, new ProgressChangedEventArgs()
                    {
                        Progress = job.Progress
                    });
                };
            }

            var result = await job.GetResultAsync();

            if (result.HasErrors)
            {
                errors.AddRange(result.LayerResults
                                .Select(l => new SyncReplicaErrorResult()
                {
                    Name = l.Key.Name, Error = l.Value.Error
                }));
                errors.AddRange(result.TableResults
                                .Select(t => new SyncReplicaErrorResult()
                {
                    Name = t.Key.TableName, Error = t.Value.Error
                }));

                return(new SynchronizeReplicaResult {
                    Synchronized = false, ResultErrors = errors
                });
            }
            else
            {
                return(new SynchronizeReplicaResult {
                    Synchronized = true
                });
            }
        }