// Generate / download and display layers from a generated geodatabase
        private async void GenerateGeodatabaseButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                panelUI.IsEnabled = false;
                panelStatus.Visibility = Visibility.Visible;

                ReportStatus("Creating GeodatabaseSyncTask...");
                var syncTask = new GeodatabaseSyncTask(new Uri(BASE_URL));

                // Get current viewpoints extent from the MapView
                var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
                var viewpointExtent = currentViewpoint.TargetGeometry.Extent;

                var options = new GenerateGeodatabaseParameters(new int[] { 0, 1, 2 }, viewpointExtent)
                {
                    GeodatabasePrefixName = GDB_PREFIX,
                    ReturnAttachments = false,
                    OutSpatialReference = MyMapView.SpatialReference,
                    SyncModel = SyncModel.PerLayer
                };

                var tcs = new TaskCompletionSource<GeodatabaseStatusInfo>();
                Action<GeodatabaseStatusInfo, Exception> completionAction = (info, ex) =>
                {
                    if (ex != null)
                        tcs.SetException(ex);
                    tcs.SetResult(info);
                };

                var generationProgress = new Progress<GeodatabaseStatusInfo>();
                generationProgress.ProgressChanged += (sndr, sts) => { ReportStatus(sts.Status.ToString()); };

                ReportStatus("Starting GenerateGeodatabase...");
                var result = await syncTask.GenerateGeodatabaseAsync(options, completionAction,
                    TimeSpan.FromSeconds(3), generationProgress, CancellationToken.None);

                ReportStatus("Waiting on geodatabase from server...");
                var statusResult = await tcs.Task;

                ReportStatus("Downloading Geodatabase...");
                var gdbPath = await DownloadGeodatabase(statusResult);

                ReportStatus("Create local feature layers...");
                await CreateFeatureLayersAsync(gdbPath);

                MyMapView.Map.Layers["wildfireGroup"].IsVisible = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Sample Error");
            }
            finally
            {
                panelStatus.Visibility = Visibility.Collapsed;
                panelUI.IsEnabled = true;
            }
        }
예제 #2
0
파일: TaskExt.cs 프로젝트: fjkish/DotNet
        /// <summary>
        /// Extension method to generate new geodatabase from target service.
        /// </summary>
        /// <param name="task">Task used.</param>
        /// <param name="gdbParameters">Instance of <see cref="GenerateGeodatabaseParameters"/> that defines how geodatabase is created.</param>
        /// <param name="statusUpdateInterval">Interval when progress is checked from the server.</param>
        /// <param name="progress">Progress that is invoked every status update interval.</param>
        /// <param name="cancellationToken">Token for task cancellation.</param>
        /// <returns>Returns <see cref="GeodatabaseStatusInfo"/> when geonerating geodatabase is finished.</returns>
        /// <remarks>Use <see cref="GeodatabaseStatusInfo.ResultUri"/> for downloading the generated geodatabase.</remarks>
        public static async Task<GeodatabaseStatusInfo> ExGenerateGeodatabaseAsync(
            this GeodatabaseSyncTask task,
            GenerateGeodatabaseParameters gdbParameters,
            TimeSpan statusUpdateInterval,
            IProgress<GeodatabaseStatusInfo> progress,
            CancellationToken cancellationToken = new CancellationToken())
        {
            var tcs = new TaskCompletionSource<GeodatabaseStatusInfo>();

            await task.GenerateGeodatabaseAsync(gdbParameters, (statusInfo, exception) =>
            {
                if (exception != null)
                    tcs.SetException(exception);

                tcs.SetResult(statusInfo);

            }, statusUpdateInterval, progress, cancellationToken);

            GeodatabaseStatusInfo result = await tcs.Task;
            return result;
        }
        private async Task StartGeodatabaseGeneration()
        {
            // Update the geodatabase path.
            _gdbPath = $"{Path.GetTempFileName()}.geodatabase";

            // Create a task for generating a geodatabase (GeodatabaseSyncTask).
            _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri);

            // Get the current extent of the red preview box.
            Envelope extent = myMapView.GraphicsOverlays.First().Graphics.First().Geometry as Envelope;

            // Get the default parameters for the generate geodatabase task.
            GenerateGeodatabaseParameters generateParams = await _gdbSyncTask.CreateDefaultGenerateGeodatabaseParametersAsync(extent);

            // Create a generate geodatabase job.
            _generateGdbJob = _gdbSyncTask.GenerateGeodatabase(generateParams, _gdbPath);

            // Handle the progress changed event (to show progress bar).
            _generateGdbJob.ProgressChanged += (sender, e) =>
            {
                UpdateProgressBar();
            };

            // Show the progress bar.
            alertDialog.Show();

            // Start the job.
            _generateGdbJob.Start();

            // Wait for the geodatabase.
            Geodatabase resultGdb = await _generateGdbJob.GetResultAsync();

            // Hide the progress bar.
            alertDialog.Dismiss();

            // Do the rest of the work.
            await HandleGenerationCompleted(_generateGdbJob, resultGdb);
        }
        private void ExcludeLayerByName(string layerName)
        {
            // Get the feature layer with the specified name.
            FeatureLayer targetLayer = GetLayerByName(layerName);

            // Get the layer's ID.
            long targetLayerId = GetServiceLayerId(targetLayer);

            // Create a layer key for the selected layer.
            OfflineMapParametersKey layerKey = new OfflineMapParametersKey(targetLayer);

            // Get the parameters for the layer.
            GenerateGeodatabaseParameters generateParams = _overrides.GenerateGeodatabaseParameters[layerKey];

            // Get the layer options for the layer.
            IList <GenerateLayerOption> layerOptions = generateParams.LayerOptions;

            // Find the layer option matching the ID.
            GenerateLayerOption targetLayerOption = layerOptions.First(layer => layer.LayerId == targetLayerId);

            // Remove the layer option.
            layerOptions.Remove(targetLayerOption);
        }
예제 #5
0
        private async Task StartGeodatabaseGeneration()
        {
            _generateButton.Enabled = false;

            // Update geodatabase path.
            _gdbPath = $"{Path.GetTempFileName()}.geodatabase";

            // Create a task for generating a geodatabase (GeodatabaseSyncTask).
            _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri);

            // Get the (only) graphic in the map view.
            Graphic redPreviewBox = _myMapView.GraphicsOverlays.First().Graphics.First();

            // Get the current extent of the red preview box.
            Envelope extent = redPreviewBox.Geometry as Envelope;

            // Get the default parameters for the generate geodatabase task.
            GenerateGeodatabaseParameters generateParams = await _gdbSyncTask.CreateDefaultGenerateGeodatabaseParametersAsync(extent);

            // Create a generate geodatabase job.
            _gdbGenJob = _gdbSyncTask.GenerateGeodatabase(generateParams, _gdbPath);

            // Handle the progress changed event.
            _gdbGenJob.ProgressChanged += GenerateGdbJob_ProgressChanged;

            // Show the progress bar.
            _progressBar.Hidden = false;

            // Start the job.
            _gdbGenJob.Start();

            // Get the result.
            _resultGdb = await _gdbGenJob.GetResultAsync();

            // Do the rest of the work.
            HandleGenerationCompleted(_gdbGenJob);
        }
예제 #6
0
        private async void StartGeodatabaseGeneration()
        {
            // Update geodatabase path
            _gdbPath = GetGdbPath();

            // Create a task for generating a geodatabase (GeodatabaseSyncTask)
            _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri);

            // Get the (only) graphic in the map view
            Graphic redPreviewBox = myMapView.GraphicsOverlays.First().Graphics.First();

            // Get the current extent of the red preview box
            Envelope extent = redPreviewBox.Geometry as Envelope;

            // Get the default parameters for the generate geodatabase task
            GenerateGeodatabaseParameters generateParams = await _gdbSyncTask.CreateDefaultGenerateGeodatabaseParametersAsync(extent);

            // Create a generate geodatabase job
            GenerateGeodatabaseJob generateGdbJob = _gdbSyncTask.GenerateGeodatabase(generateParams, _gdbPath);

            // Handle the job changed event
            generateGdbJob.JobChanged += GenerateGdbJobChanged;

            // Handle the progress changed event with an inline (lambda) function to show the progress bar
            generateGdbJob.ProgressChanged += ((object sender, EventArgs e) =>
            {
                // Get the job
                GenerateGeodatabaseJob job = sender as GenerateGeodatabaseJob;

                // Update the progress bar
                UpdateProgressBar(job.Progress);
            });

            // Start the job
            generateGdbJob.Start();
        }
예제 #7
0
        private async Task GetLocalGeodatabase()
        {
            // Get the path to the local geodatabase for this platform (temp directory, for example)
            string localGeodatabasePath = GetGdbPath();

            try
            {
                // See if the geodatabase file is already present
                if (File.Exists(localGeodatabasePath))
                {
                    // If the geodatabase is already available, open it, hide the progress control, and update the message
                    _localGeodatabase = await Geodatabase.OpenAsync(localGeodatabasePath);

                    _progressBar.Visibility = Android.Views.ViewStates.Gone;
                    _messageTextBlock.Text  = "Using local geodatabase from '" + _localGeodatabase.Path + "'";
                }
                else
                {
                    // Create a new GeodatabaseSyncTask with the uri of the feature server to pull from
                    GeodatabaseSyncTask gdbTask = await GeodatabaseSyncTask.CreateAsync(new Uri(SyncServiceUrl));

                    // Create parameters for the task: layers and extent to include, out spatial reference, and sync model
                    GenerateGeodatabaseParameters gdbParams = await gdbTask.CreateDefaultGenerateGeodatabaseParametersAsync(_extent);

                    gdbParams.OutSpatialReference = _mapView.SpatialReference;
                    gdbParams.SyncModel           = SyncModel.Layer;
                    gdbParams.LayerOptions.Clear();
                    gdbParams.LayerOptions.Add(new GenerateLayerOption(0));
                    gdbParams.LayerOptions.Add(new GenerateLayerOption(1));

                    // Create a geodatabase job that generates the geodatabase
                    GenerateGeodatabaseJob generateGdbJob = gdbTask.GenerateGeodatabase(gdbParams, localGeodatabasePath);

                    // Handle the job changed event and check the status of the job; store the geodatabase when it's ready
                    generateGdbJob.JobChanged += (s, e) =>
                    {
                        // Call a function to update the progress bar
                        RunOnUiThread(() => UpdateProgressBar(generateGdbJob.Progress));

                        // See if the job succeeded
                        if (generateGdbJob.Status == JobStatus.Succeeded)
                        {
                            RunOnUiThread(() =>
                            {
                                // Hide the progress control and update the message
                                _progressBar.Visibility = Android.Views.ViewStates.Gone;
                                _messageTextBlock.Text  = "Created local geodatabase";
                            });
                        }
                        else if (generateGdbJob.Status == JobStatus.Failed)
                        {
                            RunOnUiThread(() =>
                            {
                                // Hide the progress control and report the exception
                                _progressBar.Visibility = Android.Views.ViewStates.Gone;
                                _messageTextBlock.Text  = "Unable to create local geodatabase: " + generateGdbJob.Error.Message;
                            });
                        }
                    };

                    // Start the generate geodatabase job
                    _localGeodatabase = await generateGdbJob.GetResultAsync();
                }
            }
            catch (Exception ex)
            {
                // Show a message for the exception encountered
                RunOnUiThread(() =>
                {
                    ShowStatusMessage("Generate Geodatabase", "Unable to create offline database: " + ex.Message);
                });
            }
        }
        // Generate / download and display layers from a generated geodatabase
        private async Task GenerateLocalGeodatabaseAsync(Envelope extent)
        {
            try
            {
                IsBusy = true;

                ReportStatus("Creating GeodatabaseSyncTask...");
                var syncTask = new GeodatabaseSyncTask(new Uri(BASE_URL));

                var options = new GenerateGeodatabaseParameters(new int[] { 1 }, extent)
                {
                    GeodatabasePrefixName = GDB_PREFIX,
                    ReturnAttachments = false,
                    OutSpatialReference = extent.SpatialReference,
                    SyncModel = SyncModel.PerLayer
                };

                var tcs = new TaskCompletionSource<GeodatabaseStatusInfo>();
                Action<GeodatabaseStatusInfo, Exception> completionAction = (info, ex) =>
                {
                    if (ex != null)
                        tcs.SetException(ex);
                    tcs.SetResult(info);
                };

                var generationProgress = new Progress<GeodatabaseStatusInfo>();
                generationProgress.ProgressChanged += (sndr, sts) => { SecondaryStatus = sts.Status.ToString(); };

                ReportStatus("Starting GenerateGeodatabase...");
                var result = await syncTask.GenerateGeodatabaseAsync(options, completionAction,
                    TimeSpan.FromSeconds(3), generationProgress, CancellationToken.None);

                ReportStatus("Waiting on geodatabase from server...");
                var statusResult = await tcs.Task;

                ReportStatus("Downloading Geodatabase...");
                await DownloadGeodatabaseAsync(statusResult);

                ReportStatus("Opening Geodatabase...");
                var gdb = await Geodatabase.OpenAsync(_gdbPath);

                ReportStatus("Create local feature layers...");
                await CreateFeatureLayers(gdb);

                _onlineBirdsLayer.IsVisible = false;
            }
            finally
            {
                IsBusy = false;
            }
        }
예제 #9
0
        public static async Task <Geodatabase> DownloadOrUpdateFeatureService(String serviceUrl, Extent extent, Action <double, double> ProgressUpdate)
        {
            var task     = new TaskCompletionSource <Geodatabase>();
            var syncTask = await GeodatabaseSyncTask.CreateAsync(new Uri(serviceUrl));

            var         serviceName         = PullArcgisServiceName(serviceUrl);
            var         geodatabaseFilePath = Path.Combine(CachePath, serviceName + ".gdb");
            Geodatabase ret;

            if (File.Exists(geodatabaseFilePath))
            {
                //add service to existing mobile geodatabase
                ret = await Geodatabase.OpenAsync(geodatabaseFilePath);

                // create sync parameters
                var taskParameters = new SyncGeodatabaseParameters()
                {
                    RollbackOnFailure        = true,
                    GeodatabaseSyncDirection = SyncDirection.Download
                };

                // create a synchronize geodatabase job, pass in the parameters and the geodatabase
                SyncGeodatabaseJob syncGdbJob = syncTask.SyncGeodatabase(taskParameters, ret);

                syncGdbJob.JobChanged += (async(object sender, EventArgs e) =>
                {
                    var job = sender as SyncGeodatabaseJob;
                    switch (job?.Status)
                    {
                    case JobStatus.Succeeded:
                        await syncTask.UnregisterGeodatabaseAsync(ret);

                        task.SetResult(ret);
                        break;

                    case JobStatus.Failed:
                        if (job.Error != null)
                        {
                            task.SetException(job.Error);
                        }
                        else
                        {
                            String message = string.Empty;

                            var m = from msg in job.Messages select msg.Message;
                            message += ": " + string.Join <string>("\n", m);
                            task.SetException(new Exception(message));
                        }
                        task.SetResult(null);
                        break;
                    }
                });

                syncGdbJob.ProgressChanged += ((object sender, EventArgs e) =>
                {
                    ProgressUpdate?.Invoke(syncGdbJob.Progress, 1.0);
                });

                // Start the job
                var result = await syncGdbJob.GetResultAsync();
            }
            else
            {
                var envelope = new Envelope(extent.MinX, extent.MinY, extent.MaxX, extent.MaxY, SpatialReference.Create(extent.WKID));
                // Get the default parameters for the generate geodatabase task
                GenerateGeodatabaseParameters generateParams = await syncTask.CreateDefaultGenerateGeodatabaseParametersAsync(envelope);

                // Create a generate geodatabase job
                var generateGdbJob = syncTask.GenerateGeodatabase(generateParams, geodatabaseFilePath);

                // Handle the job changed event
                generateGdbJob.JobChanged += (async(object sender, EventArgs e) =>
                {
                    var job = sender as GenerateGeodatabaseJob;
                    switch (job?.Status)
                    {
                    case JobStatus.Succeeded:
                        ret = await job.GetResultAsync();

                        await syncTask.UnregisterGeodatabaseAsync(ret);

                        task.SetResult(ret);
                        break;

                    case JobStatus.Failed:
                        if (job.Error != null)
                        {
                            task.SetException(job.Error);
                        }
                        else
                        {
                            String message = string.Empty;

                            var m = from msg in job.Messages select msg.Message;
                            message += ": " + string.Join <string>("\n", m);
                            task.SetException(new Exception(message));
                        }
                        task.SetResult(null);
                        break;
                    }
                });

                // Handle the progress changed event (to show progress bar)
                generateGdbJob.ProgressChanged += ((object sender, EventArgs e) =>
                {
                    ProgressUpdate?.Invoke(generateGdbJob.Progress, 1.0);
                });

                // Start the job
                generateGdbJob.Start();
            }
            return(await task.Task);
        }
예제 #10
0
        private async Task GetLocalGeodatabase()
        {
            string localGeodatabasePath = GetGdbPath();

            try
            {
                // See if the geodatabase file is already present.
                if (File.Exists(localGeodatabasePath))
                {
                    // If the geodatabase is already available, open it, hide the progress control, and update the message.
                    _localGeodatabase = await Geodatabase.OpenAsync(localGeodatabasePath);

                    _progressBar.Hidden = true;
                    _statusLabel.Text   = "Using local geodatabase.";
                }
                else
                {
                    // Create a new GeodatabaseSyncTask with the URI of the feature server to pull from.
                    Uri uri = new Uri(SyncServiceUrl);
                    GeodatabaseSyncTask gdbTask = await GeodatabaseSyncTask.CreateAsync(uri);

                    // Create parameters for the task: layers and extent to include, out spatial reference, and sync model.
                    GenerateGeodatabaseParameters gdbParams = await gdbTask.CreateDefaultGenerateGeodatabaseParametersAsync(_extent);

                    gdbParams.OutSpatialReference = _mapView.SpatialReference;
                    gdbParams.SyncModel           = SyncModel.Layer;
                    gdbParams.LayerOptions.Clear();
                    gdbParams.LayerOptions.Add(new GenerateLayerOption(0));
                    gdbParams.LayerOptions.Add(new GenerateLayerOption(1));

                    // Create a geodatabase job that generates the geodatabase.
                    GenerateGeodatabaseJob generateGdbJob = gdbTask.GenerateGeodatabase(gdbParams, localGeodatabasePath);

                    // Handle the job changed event and check the status of the job; store the geodatabase when it's ready.
                    generateGdbJob.JobChanged += (s, e) =>
                    {
                        // Call a function to update the progress bar.
                        InvokeOnMainThread(() => UpdateProgressBar(generateGdbJob.Progress));

                        switch (generateGdbJob.Status)
                        {
                        // See if the job succeeded.
                        case JobStatus.Succeeded:
                            InvokeOnMainThread(() =>
                            {
                                // Hide the progress control and update the message.
                                _progressBar.Hidden = true;
                                _statusLabel.Text   = "Created local geodatabase";
                            });
                            break;

                        case JobStatus.Failed:
                            InvokeOnMainThread(() =>
                            {
                                // Hide the progress control and report the exception.
                                _progressBar.Hidden = true;
                                _statusLabel.Text   = "Unable to create local geodatabase: " + generateGdbJob.Error.Message;
                            });
                            break;
                        }
                    };

                    // Start the generate geodatabase job.
                    _localGeodatabase = await generateGdbJob.GetResultAsync();
                }
            }
            catch (Exception ex)
            {
                // Show a message for the exception encountered.
                InvokeOnMainThread(() => { ShowMessage("Generate Geodatabase", "Unable to create offline database: " + ex.Message, "OK"); });
            }
        }
예제 #11
0
        private async void GetFeatures(object sender, RoutedEventArgs e)
        {
            try
            {
                StatusPanel.Visibility = Visibility.Visible;
                StatusMessagesList.Items.Add("Submitting generate geodatabase job ...");
                StatusProgressBar.IsIndeterminate = true;
                StatusProgressBar.IsEnabled = true;

                // cancel if an erliear call was made
                if (cancellationTokenSource != null)
                {
                    cancellationTokenSource.Cancel();
                }

                // get a cancellation token
                cancellationTokenSource = new CancellationTokenSource();
                var cancelToken = cancellationTokenSource.Token;

                // create a new GeodatabaseSncTask with the uri of the feature service to pull from
                var serverUrl = operationalUrl.Substring(0, operationalUrl.LastIndexOf('/'));
                var uri = new Uri(serverUrl);
                var getFeaturesTask = new GeodatabaseSyncTask(uri);

                // crate parameters for the task: layers and extent to include, out spation reference and sync model
                var layers = new List<int>(new int[1] { 0 }); //just get the first layer
                var extent = MyMapView.Extent;
                var getFeaturesParams = new GenerateGeodatabaseParameters(layers, extent)
                {
                    OutSpatialReference = MyMapView.SpatialReference,
                    SyncModel = SyncModel.PerLayer
                };

                // check progress every two seconds
                var checkInterval = TimeSpan.FromSeconds(2);
                var creationProgress = new Progress<GeodatabaseStatusInfo>(p =>
                {
                    this.StatusMessagesList.Items.Add(DateTime.Now.ToShortTimeString() + ": " + p.Status);
                });

                // call GenerateGeodatabaseAsync, the GenerateFeautresCompleteCallback callback will execute when it's complete
                var gdbResults = await getFeaturesTask.GenerateGeodatabaseAsync(getFeaturesParams,
                                                                                GenerateFeatuersCompleteCallback,
                                                                                checkInterval,
                                                                                creationProgress,
                                                                                cancelToken);

            }
            catch (Exception ex)
            {
                StatusMessagesList.Items.Add("Unable to create offline database: " + ex.Message);
                StatusProgressBar.IsIndeterminate = false;
            }
        }
예제 #12
0
        public static async void LoadCache(CacheSettings cache)
        {
            Logging.LogMethodCall(MethodBase.GetCurrentMethod().DeclaringType.Name, () => new Dictionary <String, Object> {
                { nameof(cache), cache }
            });
            if (cache == null)
            {
                throw new ArgumentNullException("cache");
            }
            try
            {
                if (File.Exists(CacheFilePath(cache.IsBaseMap, cache.Name, false, true)))
                {
                    if (File.Exists(CacheFilePath(cache.IsBaseMap, cache.Name, true, true)))
                    {
                        File.Delete(CacheFilePath(cache.IsBaseMap, cache.Name, true, true));
                    }
                    if (cache.IsBaseMap || true)//handle not purge on sync
                    {
                        File.Move(CacheFilePath(cache.IsBaseMap, cache.Name, false, true), CacheFilePath(cache.IsBaseMap, cache.Name, true, true));
                    }
                    else
                    {
                        File.Copy(CacheFilePath(cache.IsBaseMap, cache.Name, false, true), CacheFilePath(cache.IsBaseMap, cache.Name, true, true));
                    }
                }

                if (File.Exists(CacheFilePath(cache.IsBaseMap, cache.Name, true, true)))
                {
                    try
                    {
                        if (cache.IsBaseMap)
                        {
                            TileCacheLoaded.Invoke(null, new TileCacheLoadedEventArgs(cache.Name, new TileCache(CacheFilePath(cache.IsBaseMap, cache.Name, true, true)), null));
                        }
                        else
                        {
                            GeodatabaseLoaded.Invoke(null, new GeodatabaseLoadedEventArgs(cache.Name, await Geodatabase.OpenAsync(CacheFilePath(cache.IsBaseMap, cache.Name, true, true)), null));
                        }
                    }
                    catch (Exception ex)
                    {
                        if (cache.IsBaseMap)
                        {
                            TileCacheLoaded.Invoke(null, new TileCacheLoadedEventArgs(cache.Name, null, ex));
                        }
                        else
                        {
                            GeodatabaseLoaded.Invoke(null, new GeodatabaseLoadedEventArgs(cache.Name, null, ex));
                        }
                    }

                    if (cache.SyncType == CacheSyncTypes.AdminSync && File.GetLastWriteTime(CacheFilePath(cache.IsBaseMap, cache.Name, true, true)) >= cache.LastUpdate)
                    {
                        return;
                    }
                }

                if (cache.SyncType == CacheSyncTypes.NeverSync)
                {
                    return;
                }

                if (cache.IsBaseMap)
                {
                    // Create a task for generating a geodatabase (GeodatabaseSyncTask)
                    var etcTask = await ExportTileCacheTask.CreateAsync(new Uri(cache.URL));

                    // Get the default parameters for the generate geodatabase task
                    var etcParams = await etcTask.CreateDefaultExportTileCacheParametersAsync(etcTask.ServiceInfo.FullExtent, etcTask.ServiceInfo.MinScale, etcTask.ServiceInfo.MaxScale);

                    // Create a generate geodatabase job
                    var etcJob = etcTask.ExportTileCache(etcParams, CacheFilePath(cache.IsBaseMap, cache.Name, false, false));

                    // Handle the job changed event
                    etcJob.JobChanged += (object sender, EventArgs e) =>
                    {
                        JobStatus status = etcJob.Status;

                        // If the job completed successfully, add the geodatabase data to the map
                        if (status == JobStatus.Succeeded)
                        {
                            File.Move(CacheFilePath(cache.IsBaseMap, cache.Name, false, false), CacheFilePath(cache.IsBaseMap, cache.Name, false, true));

                            TileCacheLoaded.Invoke(null, new TileCacheLoadedEventArgs(cache.Name, new TileCache(CacheFilePath(cache.IsBaseMap, cache.Name, false, true)), null));
                        }

                        // See if the job failed
                        if (status == JobStatus.Failed)
                        {
                            // Create a message to show the user
                            string message = "Generate tile cache job failed";

                            // Show an error message (if there is one)
                            if (etcJob.Error != null)
                            {
                                message += ": " + etcJob.Error.Message;
                            }
                            else
                            {
                                // If no error, show messages from the job
                                var m = from msg in etcJob.Messages select msg.Message;
                                message += ": " + string.Join <string>("\n", m);
                            }

                            TileCacheLoaded.Invoke(null, new TileCacheLoadedEventArgs(cache.Name, null, new Exception(message)));
                        }
                    };

                    // Handle the progress changed event (to show progress bar)
                    etcJob.ProgressChanged += ((object sender, EventArgs e) =>
                    {
                        String message = String.Format("Loading {0}", cache.Name);
                        CacheUpdating.Invoke(null, new CacheUpdatingEventArgs(message, etcJob.Progress, 100));
                    });

                    // Start the job
                    etcJob.Start();
                }
                else
                {
                    // Create a task for generating a geodatabase (GeodatabaseSyncTask)
                    var gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(new Uri(cache.URL));

                    // Get the default parameters for the generate geodatabase task
                    GenerateGeodatabaseParameters generateParams = await gdbSyncTask.CreateDefaultGenerateGeodatabaseParametersAsync(gdbSyncTask.ServiceInfo.FullExtent);

                    // Create a generate geodatabase job
                    gdbJob = gdbSyncTask.GenerateGeodatabase(generateParams, CacheFilePath(cache.IsBaseMap, cache.Name, false, false));

                    // Handle the job changed event
                    gdbJob.JobChanged += (async(object sender, EventArgs e) =>
                    {
                        var job = sender as GenerateGeodatabaseJob;

                        // See if the job failed
                        if (job.Status == JobStatus.Failed)
                        {
                            // Create a message to show the user
                            string message = "Generate geodatabase job failed";

                            // Show an error message (if there is one)
                            if (job.Error != null)
                            {
                                message += ": " + job.Error.Message;
                            }
                            else
                            {
                                // If no error, show messages from the job
                                var m = from msg in job.Messages select msg.Message;
                                message += ": " + string.Join <string>("\n", m);
                            }

                            GeodatabaseLoaded.Invoke(null, new GeodatabaseLoadedEventArgs(cache.Name, null, new Exception(message)));
                        }

                        if (job.Status == JobStatus.Succeeded)
                        {
                            // Get the new geodatabase
                            var _currentGeodatabase = await job.GetResultAsync();

                            // Best practice is to unregister the geodatabase
                            await gdbSyncTask.UnregisterGeodatabaseAsync(_currentGeodatabase);
                            _currentGeodatabase.Close();

                            File.Move(CacheFilePath(cache.IsBaseMap, cache.Name, false, false), CacheFilePath(cache.IsBaseMap, cache.Name, false, true));
                            var old = await Geodatabase.OpenAsync(CacheFilePath(cache.IsBaseMap, cache.Name, false, true));

                            GeodatabaseLoaded.Invoke(null, new GeodatabaseLoadedEventArgs(cache.Name, old, null));
                        }
                    });

                    // Handle the progress changed event (to show progress bar)
                    gdbJob.ProgressChanged += ((object sender, EventArgs e) =>
                    {
                        String message = String.Format("Loading {0}", cache.Name);
                        CacheUpdating.Invoke(null, new CacheUpdatingEventArgs(message, gdbJob.Progress, 100));
                    });

                    // Start the job
                    gdbJob.Start();
                }
            }
            catch (Exception ex)
            {
                if (cache.IsBaseMap)
                {
                    TileCacheLoaded.Invoke(null, new TileCacheLoadedEventArgs(cache.Name, null, ex));
                }
                else
                {
                    GeodatabaseLoaded.Invoke(null, new GeodatabaseLoadedEventArgs(cache.Name, null, ex));
                }
            }
        }
		private async Task DoExportGeodataBase(List<FeatureLayer> featureLayerList)
		{
			try
			{
				Uri featureServerUri = null;
				var layerIdList = new List<int>();
				foreach (var featureLayer in featureLayerList)
				{
					var geodatabaseFeatureServiceTable = featureLayer.FeatureTable as ServiceFeatureTable;
					if (geodatabaseFeatureServiceTable == null)
						return;

					var featureServiceUri = new Uri(geodatabaseFeatureServiceTable.ServiceUri);

					if (featureServerUri == null)
					{
						var newSegments = featureServiceUri.Segments.Take(featureServiceUri.Segments.Length - 1).ToArray();
						newSegments[newSegments.Length - 1] = newSegments[newSegments.Length - 1].TrimEnd('/');

						var uriBuilder = new UriBuilder(featureServiceUri) {Path = string.Concat(newSegments)};
						featureServerUri = uriBuilder.Uri;
					}

					if (featureServiceUri.ToString().Contains(featureServerUri.ToString()))
					{
						var layerId = int.Parse(featureServiceUri.Segments.Last());
						layerIdList.Add(layerId);
					}
				}

				_model.SetMessageInfo("Creating GeodatabaseSyncTask...");
				var geodatabaseSyncTask = new GeodatabaseSyncTask(featureServerUri);

				var generateGeodatabaseParameters = new GenerateGeodatabaseParameters(layerIdList, _areaToExportGraphic.Geometry)
				{
					GeodatabasePrefixName = "EsriDE.Samples", //
					ReturnAttachments = true,
					OutSpatialReference = CurrentEsriMapView.SpatialReference,
					SyncModel = SyncModel.PerGeodatabase
				};


				var taskCompletionSource = new TaskCompletionSource<GeodatabaseStatusInfo>();
				Action<GeodatabaseStatusInfo, Exception> completionAction = (info, ex) =>
				{
					if (ex != null)
						taskCompletionSource.SetException(ex);
					taskCompletionSource.SetResult(info);
				};

				var generationProgress = new Progress<GeodatabaseStatusInfo>();
				generationProgress.ProgressChanged +=
					(sndr, sts) => { _model.SetMessageInfo(string.Format("{0}: {1}", sts.Status.ToString(), sts.LastUpdatedTime)); };

				_model.SetMessageInfo("Starting Generate Geodatabase...");
				var result = await geodatabaseSyncTask.GenerateGeodatabaseAsync(generateGeodatabaseParameters, completionAction,
					TimeSpan.FromSeconds(3), generationProgress, CancellationToken.None);

				_model.SetMessageInfo("Waiting on geodatabase from server...");
				var statusResult = await taskCompletionSource.Task;

				_model.SetMessageInfo("Downloading Geodatabase...");
				var gdbPath = await DownloadGeodatabase(statusResult, GetServiceNameByUrl(featureServerUri));
				_model.SetMessageInfo(string.Format("Download completed : {0}", gdbPath));
			}
			catch (Exception ex)
			{
				_model.SetMessageInfo(ex.Message);
			}
		}
예제 #14
0
        private async Task GetLocalGeodatabase()
        {
            // Get the path to the local geodatabase for this platform (temp directory, for example)
            string localGeodatabasePath = GetGdbPath();

            try
            {
                // See if the geodatabase file is already present
                if (File.Exists(localGeodatabasePath))
                {
                    // If the geodatabase is already available, open it, hide the progress control, and update the message
                    _localGeodatabase = await Geodatabase.OpenAsync(localGeodatabasePath);

                    LoadingProgressBar.IsVisible = false;
                    MessageTextBlock.Text        = "Using local geodatabase from '" + _localGeodatabase.Path + "'";
                }
                else
                {
                    // Create a new GeodatabaseSyncTask with the uri of the feature server to pull from
                    Uri uri = new Uri(SyncServiceUrl);
                    GeodatabaseSyncTask gdbTask = await GeodatabaseSyncTask.CreateAsync(uri);

                    // Create parameters for the task: layers and extent to include, out spatial reference, and sync model
                    GenerateGeodatabaseParameters gdbParams = await gdbTask.CreateDefaultGenerateGeodatabaseParametersAsync(_extent);

                    gdbParams.OutSpatialReference = MyMapView.SpatialReference;
                    gdbParams.SyncModel           = SyncModel.Layer;
                    gdbParams.LayerOptions.Clear();
                    gdbParams.LayerOptions.Add(new GenerateLayerOption(0));
                    gdbParams.LayerOptions.Add(new GenerateLayerOption(1));

                    // Create a geodatabase job that generates the geodatabase
                    GenerateGeodatabaseJob generateGdbJob = gdbTask.GenerateGeodatabase(gdbParams, localGeodatabasePath);

                    // Handle the job changed event and check the status of the job; store the geodatabase when it's ready
                    generateGdbJob.JobChanged += (s, e) =>
                    {
                        // See if the job succeeded
                        if (generateGdbJob.Status == JobStatus.Succeeded)
                        {
                            Device.BeginInvokeOnMainThread(() =>
                            {
                                // Hide the progress control and update the message
                                LoadingProgressBar.IsVisible = false;
                                MessageTextBlock.Text        = "Created local geodatabase";
                            });
                        }
                        else if (generateGdbJob.Status == JobStatus.Failed)
                        {
                            Device.BeginInvokeOnMainThread(() =>
                            {
                                // Hide the progress control and report the exception
                                LoadingProgressBar.IsVisible = false;
                                MessageTextBlock.Text        = "Unable to create local geodatabase: " + generateGdbJob.Error.Message;
                            });
                        }
                    };

                    // Start the generate geodatabase job
                    _localGeodatabase = await generateGdbJob.GetResultAsync();
                }
            }
            catch (Exception ex)
            {
                // Show a message for the exception encountered
                Device.BeginInvokeOnMainThread(() =>
                {
                    Application.Current.MainPage.DisplayAlert("Generate Geodatabase", "Unable to create offline database: " + ex.Message, "OK");
                });
            }
        }
예제 #15
0
파일: Helpers.cs 프로젝트: fjkish/DotNet
        //await CreateReplica(url, layerNumList, thisExtent, gdbName, geodatabasePath, gdbExt,prog);
        private static async Task CreateReplica(string featureServiceUrl, IEnumerable<int> layerNumList, Geometry geometry, string gdbNameNoExt, string geodatabasePath, string gdbExt, IProgress<string> prog)
        {


            try
            {
                DateTime begin = DateTime.UtcNow;

                var generationProgress = new Progress<GeodatabaseStatusInfo>();
                Int64 i = 0;
                generationProgress.ProgressChanged += (sender, s) =>
                {
                    
                    i++;
                };

                //setup parameters
                var geodatabaseSyncTask = new GeodatabaseSyncTask(new Uri(featureServiceUrl));
                FeatureServiceInfo serviceInfo = await geodatabaseSyncTask.GetServiceInfoAsync();

                var parameters = new GenerateGeodatabaseParameters(layerNumList, geometry)
                {
                    GeodatabasePrefixName = gdbNameNoExt,
                    OutSpatialReference = SpatialReferences.WebMercator,

                };

                if (serviceInfo.SyncEnabled)
                {
                    parameters.SyncModel = serviceInfo.SyncCapabilities.SupportsPerLayerSync ? SyncModel.PerLayer : SyncModel.PerGeodatabase;
                }


                //call extension method
                GeodatabaseStatusInfo resultInfo =
                    await geodatabaseSyncTask.ExGenerateGeodatabaseAsync(parameters, new TimeSpan(0, 0, 2), generationProgress);

                // Download geodatabase only if generation was completed without errors. Other statuses that might be checked and handled are
                // GeodatabaseSyncStatus.Failed and GeodatabaseSyncStatus.CompletedWithErrors.
                if (resultInfo.Status != GeodatabaseSyncStatus.Completed)
                {
                    Logger.Report(string.Format("Geodatabase: Generating geodatabase failed. Status = {0}.", resultInfo.Status), prog);
                    return;
                }

                //Download database ... with no buffer

                Logger.Report("Geodatabase: Replica created, starting download.", prog);
                var client = new ArcGISHttpClient();
                HttpResponseMessage gdbStream = await client.GetAsync(resultInfo.ResultUri, HttpCompletionOption.ResponseHeadersRead);


                using (FileStream stream = File.Create(geodatabasePath + "\\" + gdbNameNoExt + gdbExt))
                {
                    await gdbStream.Content.CopyToAsync(stream);
                    await stream.FlushAsync();
                }
                DateTime end = DateTime.UtcNow;
                Logger.Report("Measured time: " + (end - begin).TotalMilliseconds + " ms.", prog);
            }

            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.ToString());
                Console.WriteLine("CreateReplica Exception" + Environment.NewLine + ex.Message);
            }
        }
예제 #16
0
        private async Task GenerateGeodatabase()
        {
            var syncTask = new GeodatabaseSyncTask(new Uri(_url));
            var serviceInfo = await syncTask.GetServiceInfoAsync();

            var syncModel = serviceInfo.SyncCapabilities.SupportsPerLayerSync
                ? SyncModel.PerLayer
                : SyncModel.PerGeodatabase;


            var layerNumList = await Helpers.GetLayersIdList(_url);

            var options = new GenerateGeodatabaseParameters(layerNumList, serviceInfo.FullExtent) {
                ReturnAttachments = false,
                OutSpatialReference = serviceInfo.SpatialReference,
                SyncModel = syncModel
            };

            var tcs = new TaskCompletionSource<GeodatabaseStatusInfo>();
            Action<GeodatabaseStatusInfo, Exception> completionAction = (statusInfo, ex) =>
            {
                try {
                    if (ex != null) {
                        tcs.SetException(ex);
                        return;
                    }
                    tcs.SetResult(statusInfo);
                }
                catch (Exception) {
                }
            };

            var generationProgress = new Progress<GeodatabaseStatusInfo>();

            var result = await syncTask.GenerateGeodatabaseAsync(options, completionAction,
                TimeSpan.FromSeconds(3), generationProgress, CancellationToken.None);


            var statusResult = await tcs.Task;

            if (statusResult.Status == GeodatabaseSyncStatus.Failed)
                throw new ApplicationException("Map Download Failed, try again later.");


            await DownloadGeodatabase(statusResult, GDB_PATH);
        }