Exemple #1
0
        /// <summary>
        /// Method that handles downloading the map into an offline map package
        /// </summary>
        private async Task DownloadPackageAsync(Envelope extent)
        {
            var syncTask = await OfflineMapTask.CreateAsync(_map);

            try
            {
                // set extent based on screen
                var parameters = await syncTask.CreateDefaultGenerateOfflineMapParametersAsync(extent);

                // set the job to generate the offline map
                GenerateOfflineMapJob = syncTask.GenerateOfflineMap(parameters, _downloadPath);

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

                // listen for job changed events
                GenerateOfflineMapJob.JobChanged += GenerateOfflineMapJob_JobChanged;

                // begin download job
                GenerateOfflineMapJob.Start();
            }
            catch (Exception ex)
            {
                UserPromptMessenger.Instance.RaiseMessageValueChanged(
                    null, ex.Message, true, ex.StackTrace);
            }
        }
Exemple #2
0
        private static async Task DownloadMapAsync(PortalItem portalItem)
        {
            Map onlineMap          = new Map(portalItem);
            var takeMapOfflineTask = await OfflineMapTask.CreateAsync(onlineMap);

            // Create the job to generate an offline map, pass in the parameters and a path to
            //store the map package.
            var parameters = new GenerateOfflineMapParameters()
            {
                MaxScale       = 5000,
                IncludeBasemap = true,
            };
            var path = MapAreaManager.GetOfflineMapPath("reference_base_map", true);

            GenerateOfflineMapJob generateMapJob =
                takeMapOfflineTask.GenerateOfflineMap(parameters, path);

            // Generate the offline map and download it.
            GenerateOfflineMapResult offlineMapResult = await generateMapJob.GetResultAsync();

            if (!offlineMapResult.HasErrors)
            {
                // Job completed successfully and all content was generated.
                Debug.WriteLine("Map " +
                                offlineMapResult.MobileMapPackage.Item.Title +
                                " was saved to " +
                                offlineMapResult.MobileMapPackage.Path);
            }
            else
            {
                // Job is finished but one or more layers or tables had errors.
                if (offlineMapResult.LayerErrors.Count > 0)
                {
                    // Show layer errors.
                    foreach (var layerError in offlineMapResult.LayerErrors)
                    {
                        Debug.WriteLine("Error occurred when taking " +
                                        layerError.Key.Name +
                                        " offline. Error : " +
                                        layerError.Value.Message);
                    }
                }
                if (offlineMapResult.TableErrors.Count > 0)
                {
                    // Show table errors.
                    foreach (var tableError in offlineMapResult.TableErrors)
                    {
                        Debug.WriteLine("Error occurred when taking " +
                                        tableError.Key.TableName +
                                        " offline. Error : " +
                                        tableError.Value.Message);
                    }
                }
            }
        }
Exemple #3
0
        public async void generateOfflineMap()
        {
            OfflineMapTask task = await OfflineMapTask.CreateAsync(mapView.Map);

            Envelope initialLocation = new Envelope(375474, 120000, 422020, 152000, new SpatialReference(26985));
            GenerateOfflineMapParameters parameters =
                await task.CreateDefaultGenerateOfflineMapParametersAsync(initialLocation);


            GenerateOfflineMapJob    generateMapJob = task.GenerateOfflineMap(parameters, "C:\\RuntimeArcgis");
            GenerateOfflineMapResult results        = await generateMapJob.GetResultAsync();
        }
        // Show changes in job progress.
        private void OfflineMapJob_ProgressChanged(object sender, EventArgs e)
        {
            // Get the job.
            GenerateOfflineMapJob job = sender as GenerateOfflineMapJob;

            // Dispatch to the UI thread.
            InvokeOnMainThread(() =>
            {
                // Show the percent complete and update the progress bar.
                _statusLabel.Text = $"Taking map offline ({job.Progress}%) ...";
            });
        }
Exemple #5
0
        private async void ConfigurationContinuation()
        {
            // Hide the configuration UI.
            _overridesVC.DismissViewController(true, null);

            // Create the job with the parameters and output location.
            _generateOfflineMapJob = _takeMapOfflineTask.GenerateOfflineMap(_parameters, _packagePath, _overrides);

            // Handle the progress changed event for the job.
            _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

            // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
            GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

            // Check for job failure (writing the output was denied, e.g.).
            if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
            {
                // Report failure to the user.
                UIAlertController messageAlert = UIAlertController.Create("Error", "Failed to take the map offline.", UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }

            // Check for errors with individual layers.
            if (results.LayerErrors.Any())
            {
                // Build a string to show all layer errors.
                System.Text.StringBuilder errorBuilder = new System.Text.StringBuilder();
                foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                {
                    errorBuilder.AppendLine($"{layerError.Key.Id} : {layerError.Value.Message}");
                }

                // Show layer errors.
                UIAlertController messageAlert = UIAlertController.Create("Error", errorBuilder.ToString(), UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }

            // Display the offline map.
            _myMapView.Map = results.OfflineMap;

            // Apply the original viewpoint for the offline map.
            _myMapView.SetViewpoint(new Viewpoint(_areaOfInterest));

            // Enable map interaction so the user can explore the offline data.
            _myMapView.InteractionOptions.IsEnabled = true;

            // Change the title and disable the "Take map offline" button.
            _statusLabel.Text             = "Map is offline";
            _takeMapOfflineButton.Enabled = false;
        }
Exemple #6
0
        // Show changes in job progress.
        private void OfflineMapJob_ProgressChanged(object sender, EventArgs e)
        {
            // Get the job.
            GenerateOfflineMapJob job = sender as GenerateOfflineMapJob;

            // Dispatch to the UI thread.
            Device.BeginInvokeOnMainThread(() =>
            {
                // Show the percent complete and update the progress bar.
                Percentage.Text      = job.Progress > 0 ? job.Progress.ToString() + " %" : string.Empty;
                progressBar.Progress = job.Progress / 100.0;
            });
        }
Exemple #7
0
        // Show changes in job progress.
        private async void OfflineMapJob_ProgressChanged(object sender, EventArgs e)
        {
            // Get the job.
            GenerateOfflineMapJob job = sender as GenerateOfflineMapJob;

            // Dispatch to the UI thread.
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                // Show the percent complete and update the progress bar.
                Percentage.Text   = job.Progress > 0 ? job.Progress.ToString() + " %" : string.Empty;
                ProgressBar.Value = job.Progress;
            });
        }
        // Show changes in job progress.
        private void OfflineMapJob_ProgressChanged(object sender, EventArgs e)
        {
            // Get the job.
            GenerateOfflineMapJob job = sender as GenerateOfflineMapJob;

            // Dispatch to the UI thread.
            DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () =>
            {
                // Show the percent complete and update the progress bar.
                Percentage.Text   = job.Progress > 0 ? job.Progress.ToString() + " %" : string.Empty;
                ProgressBar.Value = job.Progress;
            });
        }
        // Show changes in job progress.
        private void OfflineMapJob_ProgressChanged(object sender, EventArgs e)
        {
            // Get the job.
            GenerateOfflineMapJob job = sender as GenerateOfflineMapJob;

            // Dispatch to the UI thread.
            Dispatcher.Invoke(() =>
            {
                // Show the percent complete and update the progress bar.
                Percentage.Text   = job.Progress > 0 ? job.Progress.ToString() + " %" : string.Empty;
                ProgressBar.Value = job.Progress;
            });
        }
        // Show changes in job progress.
        private void OfflineMapJob_ProgressChanged(object sender, EventArgs e)
        {
            // Get the job.
            GenerateOfflineMapJob job = sender as GenerateOfflineMapJob;

            // Dispatch to the UI thread.
            InvokeOnMainThread(() =>
            {
                // Show the percent complete and update the progress bar.
                string percentText = job.Progress > 0 ? job.Progress.ToString() + " %" : string.Empty;
                _loadingOverlay.UpdateProgress(job.Progress);
                _loadingOverlay.UpdateLabel("Taking map offline (" + percentText + ") ...");
            });
        }
Exemple #11
0
        // Show changes in job progress.
        private void OfflineMapJob_ProgressChanged(object sender, EventArgs e)
        {
            // Get the job.
            GenerateOfflineMapJob job = sender as GenerateOfflineMapJob;

            // Dispatch to the UI thread.
            RunOnUiThread(() =>
            {
                // Show the percent complete and update the progress bar.
                string percentText          = job.Progress > 0 ? job.Progress.ToString() + " %" : string.Empty;
                _progressIndicator.Progress = job.Progress;
                _alertDialog.SetMessage($"Taking map offline ({percentText}) ...");
            });
        }
        private async void GenerateOfflineMap(OfflineMapTask task, GenerateOfflineMapParameters parameters)
        {
            string pathToOutputPackage = @"C:\My Documents\Readiness\Trainings\Runtime 100.1\Demos\OfflineMap";
            // Create a job and provide needed parameters
            GenerateOfflineMapJob job = task.GenerateOfflineMap(parameters, pathToOutputPackage);


            // Generate the offline map and download it
            GenerateOfflineMapResult results = await job.GetResultAsync();


            if (!results.HasErrors)
            {
                // Job is finished and all content was generated
                Debug.WriteLine("Map " + results.MobileMapPackage.Item.Title + " saved to " + results.MobileMapPackage.Path);


                // Show offline map in a MapView
                MyMapView.Map = results.OfflineMap;
            }
            else
            {
                // Job is finished but some of the layers/tables had errors
                if (results.LayerErrors.Count > 0)
                {
                    foreach (var layerError in results.LayerErrors)
                    {
                        Debug.WriteLine("Error occurred when taking " + layerError.Key.Name + " offline. Error : " + layerError.Value.Message);
                    }
                }
                if (results.TableErrors.Count > 0)
                {
                    foreach (var tableError in results.TableErrors)
                    {
                        Debug.WriteLine("Error occurred when taking " + tableError.Key.TableName + " offline. Error : " + tableError.Value.Message);
                    }
                }
            }
        }
Exemple #13
0
        private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
        {
            // Clean up any previous outputs in the temp directory.
            string tempPath = $"{Path.GetTempPath()}";

            string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");

            // Loop through the folder names and delete them.
            foreach (string dir in outputFolders)
            {
                try
                {
                    // Delete the folder.
                    Directory.Delete(dir, true);
                }
                catch (Exception)
                {
                    // Ignore exceptions (files might be locked, for example).
                }
            }

            // Create a new folder for the output mobile map.
            string packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork");
            int    num         = 1;

            while (Directory.Exists(packagePath))
            {
                packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num.ToString());
                num++;
            }

            // Create the output directory.
            Directory.CreateDirectory(packagePath);

            try
            {
                // Show the progress indicator while the job is running.
                busyIndicator.IsVisible = true;

                // Create an offline map task with the current (online) map.
                OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(MyMapView.Map);

                // Create the default parameters for the task, pass in the area of interest.
                GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);

                // Create the job with the parameters and output location.
                _generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, packagePath);

                // Handle the progress changed event for the job.
                _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

                // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
                GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

                // Check for job failure (writing the output was denied, e.g.).
                if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
                {
                    await((Page)Parent).DisplayAlert("Alert", "Generate offline map package failed.", "OK");
                    busyIndicator.IsVisible = false;
                }

                // Check for errors with individual layers.
                if (results.LayerErrors.Any())
                {
                    // Build a string to show all layer errors.
                    System.Text.StringBuilder errorBuilder = new System.Text.StringBuilder();
                    foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                    {
                        errorBuilder.AppendLine(string.Format("{0} : {1}", layerError.Key.Id, layerError.Value.Message));
                    }

                    // Show layer errors.
                    string errorText = errorBuilder.ToString();
                    await((Page)Parent).DisplayAlert("Alert", errorText, "OK");
                }

                // Display the offline map.
                MyMapView.Map = results.OfflineMap;

                // Apply the original viewpoint for the offline map.
                MyMapView.SetViewpoint(new Viewpoint(_areaOfInterest));

                // Enable map interaction so the user can explore the offline data.
                MyMapView.InteractionOptions.IsEnabled = true;

                // Hide the "Take map offline" button.
                takeOfflineArea.IsVisible = false;

                // Show a message that the map is offline.
                messageArea.IsVisible = true;
            }
            catch (TaskCanceledException)
            {
                // Generate offline map task was canceled.
                await((Page)Parent).DisplayAlert("Alert", "Taking map offline was canceled", "OK");
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                await((Page)Parent).DisplayAlert("Alert", ex.Message, "OK");
            }
            finally
            {
                // Hide the activity indicator when the job is done.
                busyIndicator.IsVisible = false;
            }
        }
Exemple #14
0
        private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
        {
            // Create a path for the output mobile map.
            string tempPath = $"{Path.GetTempPath()}";

            string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");

            // Loop through the folder names and delete them.
            foreach (string dir in outputFolders)
            {
                try
                {
                    // Delete the folder.
                    Directory.Delete(dir, true);
                }
                catch (Exception)
                {
                    // Ignore exceptions (files might be locked, for example).
                }
            }

            // Create a new folder for the output mobile map.
            string packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork");
            int    num         = 1;

            while (Directory.Exists(packagePath))
            {
                packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num.ToString());
                num++;
            }

            // Create the output directory.
            Directory.CreateDirectory(packagePath);

            // Show the progress dialog while the job is running.
            _alertDialog.Show();

            // Create an offline map task with the current (online) map.
            OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(_mapView.Map);

            // Create the default parameters for the task, pass in the area of interest.
            GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);

            // Configure basemap settings for the job.
            ConfigureOfflineJobForBasemap(parameters, async() =>
            {
                try
                {
                    // Create the job with the parameters and output location.
                    _generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, packagePath);

                    // Handle the progress changed event for the job.
                    _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

                    // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
                    GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

                    // Check for job failure (writing the output was denied, e.g.).
                    if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
                    {
                        // Report failure to the user.
                        ShowStatusMessage("Failed to take the map offline.");
                    }

                    // Check for errors with individual layers.
                    if (results.LayerErrors.Any())
                    {
                        // Build a string to show all layer errors.
                        StringBuilder errorBuilder = new StringBuilder();
                        foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                        {
                            errorBuilder.AppendLine($"{layerError.Key.Id} : {layerError.Value.Message}");
                        }

                        // Show layer errors.
                        ShowStatusMessage(errorBuilder.ToString());
                    }

                    // Display the offline map.
                    _mapView.Map = results.OfflineMap;

                    // Apply the original viewpoint for the offline map.
                    _mapView.SetViewpoint(new Viewpoint(_areaOfInterest));

                    // Enable map interaction so the user can explore the offline data.
                    _mapView.InteractionOptions.IsEnabled = true;

                    // Change the title and disable the "Take map offline" button.
                    _takeMapOfflineButton.Text    = "Map is offline";
                    _takeMapOfflineButton.Enabled = false;
                }
                catch (TaskCanceledException)
                {
                    // Generate offline map task was canceled.
                    ShowStatusMessage("Taking map offline was canceled");
                }
                catch (Exception ex)
                {
                    // Exception while taking the map offline.
                    ShowStatusMessage(ex.Message);
                }
                finally
                {
                    // Hide the loading overlay when the job is done.
                    _alertDialog.Dismiss();
                }
            });
        }
        private async void GenerateOnDemand()
        {
            ArcGISPortal portal = await ArcGISPortal.CreateAsync();

            // Get a web map item using its ID.
            PortalItem webmapItem = await PortalItem.CreateAsync(portal, "dba73588a56d476484b8d0fa1c480c9b");

            // Create a map from the web map item.
            Map onlineMap = new Map(webmapItem);

            // Create an OfflineMapTask from the map ...
            OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(onlineMap);

            // ... or a web map portal item.
            takeMapOfflineTask = await OfflineMapTask.CreateAsync(webmapItem);

            await onlineMap.LoadAsync();

            // Create default parameters for the task.
            Envelope areaOfInterest = GetAreaOfInterest();
            GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(areaOfInterest);

            // Limit the maximum scale to 5000 but take all the scales above (use default of 0 as the MinScale).
            parameters.MaxScale = 5000;

            // Set attachment options.
            parameters.AttachmentSyncDirection     = AttachmentSyncDirection.Upload;
            parameters.ReturnLayerAttachmentOption = ReturnLayerAttachmentOption.EditableLayers;

            // Request the table schema only (existing features won’t be included).
            parameters.ReturnSchemaOnlyForEditableLayers = true;

            // Update the map title to contain the region.
            parameters.ItemInfo.Title = parameters.ItemInfo.Title + " (Central)";

            // Override the thumbnail with a new image based on the extent.
            RuntimeImage thumbnail = await MyMapView.ExportImageAsync();

            parameters.ItemInfo.Thumbnail = thumbnail;

            // Create the job to generate an offline map, pass in the parameters and a path to store the map package.
            GenerateOfflineMapJob generateMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, pathToOutputPackage);

            // Generate the offline map and download it.
            GenerateOfflineMapResult offlineMapResult = await generateMapJob.GetResultAsync();

            if (!offlineMapResult.HasErrors)
            {
                // Job completed successfully and all content was generated.
                Debug.WriteLine("Map " +
                                offlineMapResult.MobileMapPackage.Item.Title +
                                " was saved to " +
                                offlineMapResult.MobileMapPackage.Path);

                // Show the offline map in a MapView.
                MyMapView.Map = offlineMapResult.OfflineMap;
            }
            else
            {
                // Job is finished but one or more layers or tables had errors.
                if (offlineMapResult.LayerErrors.Count > 0)
                {
                    // Show layer errors.
                    foreach (var layerError in offlineMapResult.LayerErrors)
                    {
                        Debug.WriteLine("Error occurred when taking " +
                                        layerError.Key.Name +
                                        " offline. Error : " +
                                        layerError.Value.Message);
                    }
                }
                if (offlineMapResult.TableErrors.Count > 0)
                {
                    // Show table errors.
                    foreach (var tableError in offlineMapResult.TableErrors)
                    {
                        Debug.WriteLine("Error occurred when taking " +
                                        tableError.Key.TableName +
                                        " offline. Error : " +
                                        tableError.Value.Message);
                    }
                }
            }

            OfflineMapCapabilities results = await takeMapOfflineTask.GetOfflineMapCapabilitiesAsync(parameters);

            if (results.HasErrors)
            {
                // Handle possible errors with layers
                foreach (var layerCapability in results.LayerCapabilities)
                {
                    if (!layerCapability.Value.SupportsOffline)
                    {
                        Debug.WriteLine(layerCapability.Key.Name + " cannot be taken offline. Error : " + layerCapability.Value.Error.Message);
                    }
                }

                // Handle possible errors with tables
                foreach (var tableCapability in results.TableCapabilities)
                {
                    if (!tableCapability.Value.SupportsOffline)
                    {
                        Debug.WriteLine(tableCapability.Key.TableName + " cannot be taken offline. Error : " + tableCapability.Value.Error.Message);
                    }
                }
            }
            else
            {
                // All layers and tables can be taken offline!
                MessageBox.Show("All layers are good to go!");
            }

            // Create a mobile map package from an unpacked map package folder.
            MobileMapPackage offlineMapPackage = await MobileMapPackage.OpenAsync(pathToOutputPackage);

            // Set the title from the package metadata to the UI


            // Get the map from the package and set it to the MapView
            var map = offlineMapPackage.Maps.First();

            MyMapView.Map = map;
        }
Exemple #16
0
        /// <summary>
        /// Handles download job status changes when download succeeds or fails
        /// </summary>
        private async void GenerateOfflineMapJob_JobChanged(object sender, EventArgs e)
        {
            // If the job succeeded, check for layer and table errors
            // if job fails, get the error
            if (GenerateOfflineMapJob.Status == JobStatus.Succeeded)
            {
                // remove event handler so it doesn't fire multiple times
                GenerateOfflineMapJob.JobChanged -= GenerateOfflineMapJob_JobChanged;

                try
                {
                    var result = await GenerateOfflineMapJob.GetResultAsync();

                    // download has succeeded and there were no errors, return
                    if (result.LayerErrors.Count == 0 && result.TableErrors.Count == 0)
                    {
                        BroadcastMessenger.Instance.RaiseBroadcastMessengerValueChanged(true, BroadcastMessageKey.SyncSucceeded);
                    }
                    else
                    {
                        // if there were errors, create the error message to display to the user
                        var stringBuilder = new StringBuilder();

                        foreach (var error in result.LayerErrors)
                        {
                            stringBuilder.AppendLine(error.Value.Message);
                        }

                        foreach (var error in result.TableErrors)
                        {
                            stringBuilder.AppendLine(error.Value.Message);
                        }

                        UserPromptMessenger.Instance.RaiseMessageValueChanged(
                            Resources.GetString("DownloadWithErrors_Title"), stringBuilder.ToString()
                            , true, null);
                        BroadcastMessenger.Instance.RaiseBroadcastMessengerValueChanged(true, BroadcastMessageKey.SyncSucceeded);
                    }
                }
                catch (Exception ex)
                {
                    UserPromptMessenger.Instance.RaiseMessageValueChanged(
                        Resources.GetString("GenericError_Title"),
                        ex.Message,
                        true,
                        ex.StackTrace);
                }
            }
            else if (GenerateOfflineMapJob.Status == JobStatus.Failed)
            {
                // remove event handler so it doesn't fire multiple times
                GenerateOfflineMapJob.JobChanged -= GenerateOfflineMapJob_JobChanged;

                // if the job failed but not due to user cancellation, display the error
                if (GenerateOfflineMapJob.Error != null &&
                    GenerateOfflineMapJob.Error.Message != "User canceled: Job canceled.")
                {
                    UserPromptMessenger.Instance.RaiseMessageValueChanged(
                        Properties.Resources.GetString("DownloadFailed_Title"), GenerateOfflineMapJob.Error.Message, true, GenerateOfflineMapJob.Error.StackTrace);
                }
                BroadcastMessenger.Instance.RaiseBroadcastMessengerValueChanged(false, BroadcastMessageKey.SyncSucceeded);
            }
        }
        private async void ConfigurationContinuation(object sender, EventArgs e)
        {
            try
            {
                // Show the progress dialog while the job is running.
                _alertDialog.Show();

                // Create the job with the parameters and output location.
                _generateOfflineMapJob = _takeMapOfflineTask.GenerateOfflineMap(_parameters, _packagePath, _overrides);

                // Handle the progress changed event for the job.
                _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

                // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
                GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

                // Check for job failure (writing the output was denied, e.g.).
                if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
                {
                    // Report failure to the user.
                    ShowStatusMessage("Failed to take the map offline.");
                }

                // Check for errors with individual layers.
                if (results.LayerErrors.Any())
                {
                    // Build a string to show all layer errors.
                    System.Text.StringBuilder errorBuilder = new System.Text.StringBuilder();
                    foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                    {
                        errorBuilder.AppendLine($"{layerError.Key.Id} : {layerError.Value.Message}");
                    }

                    // Show layer errors.
                    ShowStatusMessage(errorBuilder.ToString());
                }

                // Display the offline map.
                _mapView.Map = results.OfflineMap;

                // Apply the original viewpoint for the offline map.
                _mapView.SetViewpoint(new Viewpoint(_areaOfInterest));

                // Enable map interaction so the user can explore the offline data.
                _mapView.InteractionOptions.IsEnabled = true;

                // Change the title and disable the "Take map offline" button.
                _takeMapOfflineButton.Text    = "Map is offline";
                _takeMapOfflineButton.Enabled = false;
            }
            catch (TaskCanceledException)
            {
                // Generate offline map task was canceled.
                ShowStatusMessage("Taking map offline was canceled");
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                ShowStatusMessage(ex.Message);
            }
            finally
            {
                _alertDialog.Dismiss();
            }
        }
        private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
        {
            // Make sure the user is logged in.

            /*
             * bool loggedIn = await EnsureLoggedInAsync();
             * if (!loggedIn)
             * {
             *  return;
             * }
             */

            // Disable the button to prevent errors.
            _takeMapOfflineButton.Enabled = false;

            // Show the loading indicator.
            _loadingIndicator.StartAnimating();

            // Create a path for the output mobile map.
            string tempPath = $"{Path.GetTempPath()}";

            string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");

            // Loop through the folder names and delete them.
            foreach (string dir in outputFolders)
            {
                try
                {
                    // Delete the folder.
                    Directory.Delete(dir, true);
                }
                catch (Exception ex)
                {
                    // Ignore exceptions (files might be locked, for example).
                    Debug.WriteLine(ex);
                }
            }

            // Create a new folder for the output mobile map.
            string packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork");
            int    num         = 1;

            while (Directory.Exists(packagePath))
            {
                packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num);
                num++;
            }

            // Create the output directory.
            Directory.CreateDirectory(packagePath);

            try
            {
                // Show the loading overlay while the job is running.
                _statusLabel.Text = "Taking map offline...";

                // Create an offline map task with the current (online) map.
                OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(_myMapView.Map);

                // Create the default parameters for the task, pass in the area of interest.
                GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);

                // Generate parameter overrides for more in-depth control of the job.
                GenerateOfflineMapParameterOverrides overrides = await takeMapOfflineTask.CreateGenerateOfflineMapParameterOverridesAsync(parameters);

                // Show the configuration window.
                ShowConfigurationWindow(overrides);

                // Finish work once the user has configured the override.
                _overridesVC.FinishedConfiguring += async() =>
                {
                    // Hide the configuration UI.
                    _overridesVC.DismissViewController(true, null);

                    // Create the job with the parameters and output location.
                    _generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, packagePath, overrides);

                    // Handle the progress changed event for the job.
                    _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

                    // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
                    GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

                    // Check for job failure (writing the output was denied, e.g.).
                    if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
                    {
                        // Report failure to the user.
                        UIAlertController messageAlert = UIAlertController.Create("Error", "Failed to take the map offline.", UIAlertControllerStyle.Alert);
                        messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                        PresentViewController(messageAlert, true, null);
                    }

                    // Check for errors with individual layers.
                    if (results.LayerErrors.Any())
                    {
                        // Build a string to show all layer errors.
                        System.Text.StringBuilder errorBuilder = new System.Text.StringBuilder();
                        foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                        {
                            errorBuilder.AppendLine($"{layerError.Key.Id} : {layerError.Value.Message}");
                        }

                        // Show layer errors.
                        UIAlertController messageAlert = UIAlertController.Create("Error", errorBuilder.ToString(), UIAlertControllerStyle.Alert);
                        messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                        PresentViewController(messageAlert, true, null);
                    }

                    // Display the offline map.
                    _myMapView.Map = results.OfflineMap;

                    // Apply the original viewpoint for the offline map.
                    _myMapView.SetViewpoint(new Viewpoint(_areaOfInterest));

                    // Enable map interaction so the user can explore the offline data.
                    _myMapView.InteractionOptions.IsEnabled = true;

                    // Change the title and disable the "Take map offline" button.
                    _statusLabel.Text             = "Map is offline";
                    _takeMapOfflineButton.Enabled = false;
                };
            }
            catch (TaskCanceledException)
            {
                // Generate offline map task was canceled.
                UIAlertController messageAlert = UIAlertController.Create("Canceled", "Taking map offline was canceled", UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                UIAlertController messageAlert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }
            finally
            {
                // Hide the loading overlay when the job is done.
                _loadingIndicator.StopAnimating();
            }
        }
        private async void TakeMapOfflineButton_Click(object sender, RoutedEventArgs e)
        {
            // Create a new folder for the output mobile map.
            string packagePath = Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), @"NapervilleWaterNetwork");
            int    num         = 1;

            while (Directory.Exists(packagePath))
            {
                packagePath = Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), @"NapervilleWaterNetwork" + num.ToString());
                num++;
            }

            // Create the output directory.
            Directory.CreateDirectory(packagePath);

            try
            {
                // Show the progress indicator while the job is running.
                BusyIndicator.Visibility = Visibility.Visible;

                // Create an offline map task with the current (online) map.
                OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(MyMapView.Map);

                // Create the default parameters for the task, pass in the area of interest.
                GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);

                #region overrides

                // Generate parameter overrides for more in-depth control of the job.
                GenerateOfflineMapParameterOverrides overrides = await takeMapOfflineTask.CreateGenerateOfflineMapParameterOverridesAsync(parameters);

                // Configure the overrides using helper methods.
                ConfigureTileLayerOverrides(overrides);
                ConfigureLayerExclusion(overrides);
                CropWaterPipes(overrides);
                ApplyFeatureFilter(overrides);

                // Create the job with the parameters and output location.
                _generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, packagePath, overrides);

                #endregion overrides

                // Handle the progress changed event for the job.
                _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

                // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
                GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

                // Check for job failure (writing the output was denied, e.g.).
                if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
                {
                    MessageBox.Show("Generate offline map package failed.", "Job status");
                    BusyIndicator.Visibility = Visibility.Collapsed;
                }

                // Check for errors with individual layers.
                if (results.LayerErrors.Any())
                {
                    // Build a string to show all layer errors.
                    System.Text.StringBuilder errorBuilder = new System.Text.StringBuilder();
                    foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                    {
                        errorBuilder.AppendLine(string.Format("{0} : {1}", layerError.Key.Id, layerError.Value.Message));
                    }

                    // Show layer errors.
                    string errorText = errorBuilder.ToString();
                    MessageBox.Show(errorText, "Layer errors");
                }

                // Display the offline map.
                MyMapView.Map = results.OfflineMap;

                // Apply the original viewpoint for the offline map.
                MyMapView.SetViewpoint(new Viewpoint(_areaOfInterest));

                // Enable map interaction so the user can explore the offline data.
                MyMapView.InteractionOptions.IsEnabled = true;

                // Hide the "Take map offline" button.
                takeOfflineArea.Visibility = Visibility.Collapsed;

                // Show a message that the map is offline.
                MessageArea.Visibility = Visibility.Visible;
            }
            catch (TaskCanceledException)
            {
                // Generate offline map task was canceled.
                MessageBox.Show("Taking map offline was canceled");
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                MessageBox.Show(ex.Message, "Offline map error");
            }
            finally
            {
                // Hide the activity indicator when the job is done.
                BusyIndicator.Visibility = Visibility.Collapsed;
            }
        }
        private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
        {
            // Create a path for the output mobile map.
            string tempPath = $"{Path.GetTempPath()}";

            string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");

            // Loop through the folder names and delete them.
            foreach (string dir in outputFolders)
            {
                try
                {
                    // Delete the folder.
                    Directory.Delete(dir, true);
                }
                catch (Exception)
                {
                    // Ignore exceptions (files might be locked, for example).
                }
            }

            // Create a new folder for the output mobile map.
            string packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork");
            int    num         = 1;

            while (Directory.Exists(packagePath))
            {
                packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num.ToString());
                num++;
            }

            // Create the output directory.
            Directory.CreateDirectory(packagePath);

            try
            {
                // Show the loading overlay while the job is running.
                CGRect bounds = View.Bounds;
                _loadingOverlay = new LoadingMapOverlay(bounds, true);
                _loadingOverlay.UpdateLabel("Taking map offine ...");
                _loadingOverlay.OnCanceled += (s, evt) =>
                {
                    // The user canceled the job.
                    _generateOfflineMapJob.Cancel();
                };
                this.ParentViewController.View.Add(_loadingOverlay);

                // Create an offline map task with the current (online) map.
                OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(_myMapView.Map);

                // Create the default parameters for the task, pass in the area of interest.
                GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);

                // Create the job with the parameters and output location.
                _generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, packagePath);

                // Handle the progress changed event for the job.
                _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

                // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
                GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

                // Check for job failure (writing the output was denied, e.g.).
                if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
                {
                    // Report failure to the user.
                    UIAlertController messageAlert = UIAlertController.Create("Error", "Failed to take the map offline.", UIAlertControllerStyle.Alert);
                    messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                    PresentViewController(messageAlert, true, null);
                }

                // Check for errors with individual layers.
                if (results.LayerErrors.Any())
                {
                    // Build a string to show all layer errors.
                    System.Text.StringBuilder errorBuilder = new System.Text.StringBuilder();
                    foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                    {
                        errorBuilder.AppendLine(string.Format("{0} : {1}", layerError.Key.Id, layerError.Value.Message));
                    }

                    // Show layer errors.
                    UIAlertController messageAlert = UIAlertController.Create("Error", errorBuilder.ToString(), UIAlertControllerStyle.Alert);
                    messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                    PresentViewController(messageAlert, true, null);
                }

                // Display the offline map.
                _myMapView.Map = results.OfflineMap;

                // Apply the original viewpoint for the offline map.
                _myMapView.SetViewpoint(new Viewpoint(_areaOfInterest));

                // Enable map interaction so the user can explore the offline data.
                _myMapView.InteractionOptions.IsEnabled = true;

                // Change the title and disable the "Take map offline" button.
                _takeMapOfflineButton.SetTitle("Map is offline", UIControlState.Normal);
                _takeMapOfflineButton.Enabled = false;
            }
            catch (TaskCanceledException)
            {
                // Generate offline map task was canceled.
                UIAlertController messageAlert = UIAlertController.Create("Canceled", "Taking map offline was canceled", UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                UIAlertController messageAlert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }
            finally
            {
                // Hide the loading overlay when the job is done.
                if (_loadingOverlay != null)
                {
                    _loadingOverlay.Hide();
                }
            }
        }
Exemple #21
0
        /// <summary>
        /// Method that handles downloading the map into an offline map package
        /// </summary>
        private async Task DownloadPackageAsync(Envelope extent)
        {
            var syncTask = await OfflineMapTask.CreateAsync(Map);

            try
            {
                // set extent based on screen
                var parameters = await syncTask.CreateDefaultGenerateOfflineMapParametersAsync(extent);

                // set the job to generate the offline map
                GenerateOfflineMapJob = syncTask.GenerateOfflineMap(parameters, DownloadPath);

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

                // listen for job changed events
                GenerateOfflineMapJob.JobChanged +=
                    async(sender, args) =>
                {
                    // If the job succeeded, check for layer and table errors
                    // if job fails, get the error
                    if (GenerateOfflineMapJob.Status == JobStatus.Succeeded)
                    {
                        var result = await GenerateOfflineMapJob.GetResultAsync();

                        // download has succeeded and there were no errors, return
                        if (result.LayerErrors.Count == 0 && result.TableErrors.Count == 0)
                        {
                            BroadcastMessenger.Instance.RaiseBroadcastMessengerValueChanged(true, BroadcastMessageKey.SyncSucceeded);
                        }
                        else
                        {
                            // if there were errors, create the error message to display to the user
                            var stringBuilder = new StringBuilder();

                            foreach (var error in result.LayerErrors)
                            {
                                stringBuilder.AppendLine(error.Value.Message);
                            }

                            foreach (var error in result.TableErrors)
                            {
                                stringBuilder.AppendLine(error.Value.Message);
                            }

                            UserPromptMessenger.Instance.RaiseMessageValueChanged(
                                Properties.Resources.GetString("DownloadWithErrors_Title"), stringBuilder.ToString()
                                , true, null);
                            BroadcastMessenger.Instance.RaiseBroadcastMessengerValueChanged(true, BroadcastMessageKey.SyncSucceeded);
                        }
                    }
                    else if (GenerateOfflineMapJob.Status == JobStatus.Failed)
                    {
                        // if the job failed but not due to user cancellation, display the error
                        if (GenerateOfflineMapJob.Error != null &&
                            GenerateOfflineMapJob.Error.Message != "User canceled: Job canceled.")
                        {
                            UserPromptMessenger.Instance.RaiseMessageValueChanged(
                                Properties.Resources.GetString("DownloadFailed_Title"), GenerateOfflineMapJob.Error.Message, true, GenerateOfflineMapJob.Error.StackTrace);
                        }
                        BroadcastMessenger.Instance.RaiseBroadcastMessengerValueChanged(false, BroadcastMessageKey.SyncSucceeded);
                    }
                };

                // begin download job
                GenerateOfflineMapJob.Start();
            }
            catch (Exception ex)
            {
                UserPromptMessenger.Instance.RaiseMessageValueChanged(
                    null, ex.Message, true, ex.StackTrace);
            }
        }
        private async void GenerateMapArea()
        {
            try
            {
                _windowService.SetBusyMessage("Taking map offline");
                _windowService.SetBusy(true);

                string offlineDataFolder = OfflineDataStorageHelper.GetDataFolderForMap(Map);

                // If temporary data folder exists remove it
                try
                {
                    if (Directory.Exists(offlineDataFolder))
                    {
                        Directory.Delete(offlineDataFolder, true);
                    }
                }
                catch (Exception)
                {
                    // If folder can't be deleted, open a new one.
                    offlineDataFolder = Path.Combine(offlineDataFolder, DateTime.Now.Ticks.ToString());
                }

                // If temporary data folder doesn't exists, create it
                if (!Directory.Exists(offlineDataFolder))
                {
                    Directory.CreateDirectory(offlineDataFolder);
                }

                // Get area of interest as a envelope from the map view
                var areaOfInterest =
                    _mapViewService.GetCurrentViewpoint(ViewpointType.BoundingGeometry)
                    .TargetGeometry as Envelope;

                // Step 1 : Create task with the map that is taken offline
                var task = await OfflineMapTask.CreateAsync(Map);

                // Step 2 : Create parameters based on selections
                var parameters = await task.CreateDefaultGenerateOfflineMapParametersAsync(
                    areaOfInterest);

                parameters.MaxScale       = _levelsOfDetail[SelectedLevelOfDetail].Scale;
                parameters.MinScale       = 0;
                parameters.IncludeBasemap = IncludeBasemap;
                parameters.ReturnLayerAttachmentOption = ReturnLayerAttachmentOption.None;

                // Step 3 : Create job that does the work asynchronously and
                //          set progress indication
                _job = task.GenerateOfflineMap(parameters, offlineDataFolder);
                _job.ProgressChanged += GenerateOfflineMap_ProgressChanged;

                // Step 4 : Run the job and wait the results
                var results = await _job.GetResultAsync();

                if (results.HasErrors)
                {
                    string errorString = "";
                    // If one or more layers fails, layer errors are populated with corresponding errors.
                    foreach (var(key, value) in results.LayerErrors)
                    {
                        errorString += $"Error occurred on {key.Name} : {value.Message}\r\n";
                    }
                    foreach (var(key, value) in results.TableErrors)
                    {
                        errorString += $"Error occurred on {key.TableName} : {value.Message}\r\n";
                    }
                    OfflineDataStorageHelper.FlushLogToDisk(errorString, Map);
                }

                // Step 5 : Use results
                Map = results.OfflineMap;

                RefreshCommands();
            }
            catch (Exception ex)
            {
                await _windowService.ShowAlertAsync(ex.Message, "Error generating offline map");
            }
            finally
            {
                _windowService.SetBusy(false);
            }
        }