Example #1
0
 public static async Task<List<int>> GetLayersIdList(string url)
 {
     var geodatabaseTask = new GeodatabaseSyncTask(new Uri(url));
     FeatureServiceInfo fsInfo = await geodatabaseTask.GetServiceInfoAsync();
     IReadOnlyList<LayerServiceInfo> layerServiceInfos = fsInfo.Layers;
     return layerServiceInfos.Select(lsi => lsi.ID).ToList();
 }
Example #2
0
        private async Task UnregisterAndRemoveMobileMapPackage(MobileMapPackage mobileMapPackage)
        {
            // Unregister all geodatabases from all maps that are part of the mobile map package.
            // Offline areas that are downloaded by using OfflineMapTask will contain a single
            // map in them but it is a good practice to handle the case of multiple maps.
            foreach (Map map in mobileMapPackage.Maps)
            {
                // Find all geodatabases from the used map.
                List <Geodatabase> geodatabasesToUnregister = new List <Geodatabase>();

                // Add all geodatabases used in the feature layers.
                foreach (FeatureLayer featureLayer in map.OperationalLayers.OfType <FeatureLayer>())
                {
                    GeodatabaseFeatureTable geodatabaseFeatureTable = featureLayer.FeatureTable as GeodatabaseFeatureTable;
                    if (geodatabaseFeatureTable == null)
                    {
                        continue;
                    }
                    // Add the geodatabase feature table if it isn't already in the list.
                    if (geodatabasesToUnregister.All(x => x.Path != geodatabaseFeatureTable.Geodatabase.Path))
                    {
                        geodatabasesToUnregister.Add(geodatabaseFeatureTable.Geodatabase);
                    }
                }

                // Add all geodatabases used in a table.
                foreach (FeatureTable featureTable in map.Tables)
                {
                    GeodatabaseFeatureTable geodatabaseFeatureTable = featureTable as GeodatabaseFeatureTable;
                    if (geodatabaseFeatureTable == null)
                    {
                        continue;
                    }
                    // Add the geodatabase feature table if it isn't already in the list.
                    if (geodatabasesToUnregister.All(x => x.Path != geodatabaseFeatureTable.Geodatabase.Path))
                    {
                        geodatabasesToUnregister.Add(geodatabaseFeatureTable.Geodatabase);
                    }
                }

                // Unregister geodatabases that were used.
                foreach (Geodatabase geodatabaseToUnregister in geodatabasesToUnregister)
                {
                    GeodatabaseSyncTask geodatabaSyncTask = await GeodatabaseSyncTask.CreateAsync(geodatabaseToUnregister.Source);

                    await geodatabaSyncTask.UnregisterGeodatabaseAsync(geodatabaseToUnregister);
                }

                // Make sure that all geodatabases are closed and locks released.
                foreach (Geodatabase geodatabase in geodatabasesToUnregister)
                {
                    geodatabase.Close();
                }
            }

            // Remove package.
            Directory.Delete(mobileMapPackage.Path, true);
        }
Example #3
0
        // Generate / download and display layers from a generated geodatabase
        private async void GenerateGeodatabaseButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                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 gdbFile = await DownloadGeodatabase(statusResult);

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

                MyMapView.Map.Layers["onlineService"].IsVisible = false;
            }
            catch (Exception ex)
            {
                var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
            }
            finally
            {
                panelStatus.Visibility = Visibility.Collapsed;
            }
        }
        // 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;
            }
        }
        private async void Initialize()
        {
            // Create a tile cache and load it with the SanFrancisco streets tpk
            TileCache tileCache = new TileCache(await GetTpkPath());

            // Create the corresponding layer based on the tile cache
            ArcGISTiledLayer tileLayer = new ArcGISTiledLayer(tileCache);

            // Create the basemap based on the tile cache
            Basemap sfBasemap = new Basemap(tileLayer);

            // Create the map with the tile-based basemap
            Map myMap = new Map(sfBasemap);

            // Assign the map to the MapView
            MyMapView.Map = myMap;

            // Create a new symbol for the extent graphic
            SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Colors.Red, 2);

            // Create graphics overlay for the extent graphic and apply a renderer
            GraphicsOverlay extentOverlay = new GraphicsOverlay();

            extentOverlay.Renderer = new SimpleRenderer(lineSymbol);

            // Add graphics overlay to the map view
            MyMapView.GraphicsOverlays.Add(extentOverlay);

            // Set up an event handler for when the viewpoint (extent) changes
            MyMapView.ViewpointChanged += MapViewExtentChanged;

            // Update the local data path for the geodatabase file
            string uwpFolder = Windows.Storage.ApplicationData.Current.LocalFolder.Path.ToString();

            _gdbPath = Path.Combine(uwpFolder, "wildfire.geodatabase");

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

            // Add all graphics from the service to the map
            foreach (IdInfo layer in _gdbSyncTask.ServiceInfo.LayerInfos)
            {
                // Get the Uri for this particular layer
                Uri onlineTableUri = new Uri(_featureServiceUri + "/" + layer.Id);

                // Create the ServiceFeatureTable
                ServiceFeatureTable onlineTable = new ServiceFeatureTable(onlineTableUri);

                // Wait for the table to load
                await onlineTable.LoadAsync();

                // Add the layer to the map's operational layers if load succeeds
                if (onlineTable.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded)
                {
                    myMap.OperationalLayers.Add(new FeatureLayer(onlineTable));
                }
            }
        }
        private async void Initialize()
        {
            // Create a tile cache and load it with the SanFrancisco streets tpk
            TileCache _tileCache = new TileCache(GetTpkPath());

            // Create the corresponding layer based on the tile cache
            ArcGISTiledLayer _tileLayer = new ArcGISTiledLayer(_tileCache);

            // Create the basemap based on the tile cache
            Basemap _sfBasemap = new Basemap(_tileLayer);

            // Create the map with the tile-based basemap
            Map myMap = new Map(_sfBasemap);

            // Assign the map to the MapView
            MyMapView.Map = myMap;

            // Create a new symbol for the extent graphic
            SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Colors.Red, 2);

            // Create graphics overlay for the extent graphic and apply a renderer
            GraphicsOverlay extentOverlay = new GraphicsOverlay();

            extentOverlay.Renderer = new SimpleRenderer(lineSymbol);

            // Add graphics overlay to the map view
            MyMapView.GraphicsOverlays.Add(extentOverlay);

            // Set up an event handler for when the viewpoint (extent) changes
            MyMapView.ViewpointChanged += MapViewExtentChanged;

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

            // Add all graphics from the service to the map
            foreach (var layer in _gdbSyncTask.ServiceInfo.LayerInfos)
            {
                // Create the ServiceFeatureTable for this particular layer
                ServiceFeatureTable onlineTable = new ServiceFeatureTable(new Uri(_featureServiceUri + "/" + layer.Id));

                // Wait for the table to load
                await onlineTable.LoadAsync();

                // Add the layer to the map's operational layers if load succeeds
                if (onlineTable.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded)
                {
                    myMap.OperationalLayers.Add(new FeatureLayer(onlineTable));
                }
            }

            // Update the extent graphic so that it is valid before user interaction
            UpdateMapExtent();

            // Enable the generate button now that the sample is ready
            MyGenerateButton.IsEnabled = true;
        }
Example #7
0
        /**
         * GeoDatabaseを新規に作成する
         * ① 同期させたいArcGIS Online の Feature Layer でタスクを作成する
         ****/
        private async void createGeodatabaseSyncTask()
        {
            // TODO 同期させたいレイヤーで geodatabase 作成 タスクオブジェクトを作成する
            var featureServiceUri = new Uri(FEATURELAYER_SERVICE_URL);

            geodatabaseSyncTask = await GeodatabaseSyncTask.CreateAsync(featureServiceUri);

            // ② 同期させたいArcGIS Online の Feature Layer のパラメータを取得する
            generateGeodatabaseParameters();
        }
Example #8
0
        public static async void CreateReplicaDataBufferExtent(string url, string gdbName, string geodatabasePath, string gdbExt, IProgress<string> prog)
        {
            var serviceUrl = new Uri(url);
            var geodatabaseTask = new GeodatabaseSyncTask(serviceUrl);
            FeatureServiceInfo serviceInfo = await geodatabaseTask.GetServiceInfoAsync();
            List<int> layerNumList = await GetLayersIdList(url);
            Geometry smallEnvelope = GeometryEngine.Buffer(serviceInfo.FullExtent.GetCenter(), 1000);
            await CreateReplica(url, layerNumList, smallEnvelope, gdbName, geodatabasePath, gdbExt, prog);
            Console.WriteLine("Done CreateReplicaExtent");

        }
Example #9
0
        // Synchronize edits in the local geodatabase with the service.
        private async void SynchronizeEdits(object sender, EventArgs e)
        {
            // Show the progress bar while the sync is working.
            _progressBar.Hidden = false;

            try
            {
                // Create a sync task with the URL of the feature service to sync.
                GeodatabaseSyncTask syncTask = await GeodatabaseSyncTask.CreateAsync(new Uri(SyncServiceUrl));

                // Create sync parameters.
                SyncGeodatabaseParameters taskParameters = await syncTask.CreateDefaultSyncGeodatabaseParametersAsync(_localGeodatabase);

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

                // Handle the JobChanged event for the job.
                job.JobChanged += (s, arg) =>
                {
                    InvokeOnMainThread(() =>
                    {
                        // Update the progress bar.
                        UpdateProgressBar(job.Progress);

                        switch (job.Status)
                        {
                        // Report changes in the job status.
                        case JobStatus.Succeeded:
                            _statusLabel.Text   = "Synchronization is complete!";
                            _progressBar.Hidden = true;
                            break;

                        case JobStatus.Failed:
                            // Report failure.
                            _statusLabel.Text   = job.Error.Message;
                            _progressBar.Hidden = true;
                            break;

                        default:
                            _statusLabel.Text = "Sync in progress ...";
                            break;
                        }
                    });
                };

                // Await the completion of the job.
                await job.GetResultAsync();
            }
            catch (Exception ex)
            {
                // Show the message if an exception occurred.
                _statusLabel.Text = "Error when synchronizing: " + ex.Message;
            }
        }
Example #10
0
        /// <summary>Construct Generate Geodatabase sample control</summary>
        public SyncGeodatabase()
        {
            InitializeComponent();

            _syncTask         = new GeodatabaseSyncTask(new Uri(BASE_URL));
            _onlineBirdsLayer = MyMapView.Map.Layers.OfType <ArcGISDynamicMapServiceLayer>().First();
            _graphicsOverlay  = MyMapView.GraphicsOverlays["graphicsOverlay"];
            _localBirdsLayer  = null;
            CanGenerate       = true;

            this.DataContext = this;
        }
Example #11
0
        // 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;
            }
        }
        // call GenerateGeodatabaseAsync from a button click
        private async void GetDataButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // cancel if an earlier call was made
                if (_syncCancellationTokenSource != null)
                {
                    _syncCancellationTokenSource.Cancel();
                }

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

                // create a new GeodatabaseSyncTask with the uri of the feature server to pull from
                var serverUrl = this.featureLayerServiceUrl.Substring(0, this.featureLayerServiceUrl.LastIndexOf('/'));
                var uri       = new Uri(serverUrl);
                var gdbTask   = new GeodatabaseSyncTask(uri);

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

                // Create a System.Progress<T> object to report status as the task executes
                var progress = new Progress <GeodatabaseStatusInfo>();
                progress.ProgressChanged += (s, info) =>
                {
                    this.SyncStatusTextBlock.Text   = "Generate GDB: " + info.Status;
                    this.SyncProgressBar.Visibility = System.Windows.Visibility.Visible;
                };

                // call GenerateGeodatabaseAsync, pass in the parameters and the callback to execute when it's complete
                this.SyncProgressBar.Visibility = System.Windows.Visibility.Visible;
                this.SyncStatusTextBlock.Text   = "Generate GDB: Job submitted ...";

                // show progress bar and label
                this.SyncStatusPanel.Visibility = System.Windows.Visibility.Visible;

                // generate the database
                var gdbResult = await gdbTask.GenerateGeodatabaseAsync(gdbParams, GdbCompleteCallback, new TimeSpan(0, 0, 3), progress, cancelToken);
            }
            catch (Exception ex)
            {
                this.Dispatcher.Invoke(() => this.SyncStatusTextBlock.Text = "Unable to create offline database: " + ex.Message);
            }
        }
Example #13
0
        // Synchronize edits in the local geodatabase with the service
        public async void SynchronizeEdits(object sender, EventArgs e)
        {
            // Show the progress bar while the sync is working
            _progressBar.Visibility = Android.Views.ViewStates.Visible;

            try
            {
                // Create a sync task with the URL of the feature service to sync
                GeodatabaseSyncTask syncTask = await GeodatabaseSyncTask.CreateAsync(new Uri(SyncServiceUrl));

                // Create sync parameters
                SyncGeodatabaseParameters taskParameters = await syncTask.CreateDefaultSyncGeodatabaseParametersAsync(_localGeodatabase);

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

                // Handle the JobChanged event for the job
                job.JobChanged += (s, arg) =>
                {
                    RunOnUiThread(() =>
                    {
                        // Update the progress bar
                        UpdateProgressBar(job.Progress);

                        // Report changes in the job status
                        if (job.Status == JobStatus.Succeeded)
                        {
                            _messageTextBlock.Text  = "Synchronization is complete!";
                            _progressBar.Visibility = Android.Views.ViewStates.Gone;
                        }
                        else if (job.Status == JobStatus.Failed)
                        {
                            // Report failure ...
                            _messageTextBlock.Text  = job.Error.Message;
                            _progressBar.Visibility = Android.Views.ViewStates.Gone;
                        }
                        else
                        {
                            // Report that the job is in progress ...
                            _messageTextBlock.Text = "Sync in progress ...";
                        }
                    });
                };

                // Await the completion of the job
                await job.GetResultAsync();
            }
            catch (Exception ex)
            {
                // Show the message if an exception occurred
                _messageTextBlock.Text = "Error when synchronizing: " + ex.Message;
            }
        }
Example #14
0
        ////////////////////////////////////////////////////////////////
        // 同期
        ////////////////////////////////////////////////////////////////

        /**
         * サーバー(AGOL)と同期する
         * ① 同期タスクを作成する
         * ② 同期パラメータを取得する
         **/
        private async void OnSyncClick(object sender, RoutedEventArgs e)
        {
            // 同期したいレイヤーでタスクオブジェクトを作成する
            geodatabaseSyncTask = await GeodatabaseSyncTask.CreateAsync(new Uri(FEATURELAYER_SERVICE_URL));

            readGeoDatabase();

            // タスクオブジェクトから同期するためのパラメータを作成する
            syncParams = await geodatabaseSyncTask.CreateDefaultSyncGeodatabaseParametersAsync(geodatabase);

            // パラーメータを使用してgeodatabaseを同期する
            syncGeodatabase();
        }
        // Synchronize edits in the local geodatabase with the service
        public async void SynchronizeEdits(object sender, RoutedEventArgs e)
        {
            // Show the progress bar while the sync is working
            LoadingProgressBar.Visibility = Visibility.Visible;

            try
            {
                // Create a sync task with the URL of the feature service to sync
                var syncTask = await GeodatabaseSyncTask.CreateAsync(new Uri(SyncServiceUrl));

                // Create sync parameters
                var taskParameters = await syncTask.CreateDefaultSyncGeodatabaseParametersAsync(_localGeodatabase);

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

                // Handle the JobChanged event for the job
                job.JobChanged += async(s, arg) =>
                {
                    // Report changes in the job status
                    if (job.Status == JobStatus.Succeeded)
                    {
                        // Report success ...
                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => MessageTextBlock.Text = "Synchronization is complete!");
                    }
                    else if (job.Status == JobStatus.Failed)
                    {
                        // Report failure ...
                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => MessageTextBlock.Text = job.Error.Message);
                    }
                    else
                    {
                        // Report that the job is in progress ...
                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => MessageTextBlock.Text = "Sync in progress ...");
                    }
                };

                // Await the completion of the job
                var result = await job.GetResultAsync();
            }
            catch (Exception ex)
            {
                // Show the message if an exception occurred
                MessageTextBlock.Text = "Error when synchronizing: " + ex.Message;
            }
            finally
            {
                // Hide the progress bar when the sync job is complete
                LoadingProgressBar.Visibility = Visibility.Collapsed;
            }
        }
        // Synchronize edits in the local geodatabase with the service
        public async void SynchronizeEdits(object sender, EventArgs e)
        {
            // Show the progress bar while the sync is working
            LoadingProgressBar.IsVisible = true;

            try
            {
                // Create a sync task with the URL of the feature service to sync
                GeodatabaseSyncTask syncTask = await GeodatabaseSyncTask.CreateAsync(new Uri(SyncServiceUrl));

                // Create sync parameters
                SyncGeodatabaseParameters taskParameters = await syncTask.CreateDefaultSyncGeodatabaseParametersAsync(_localGeodatabase);

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

                // Handle the JobChanged event for the job
                job.JobChanged += (s, arg) =>
                {
                    // Report changes in the job status
                    if (job.Status == JobStatus.Succeeded)
                    {
                        // Report success ...
                        Device.BeginInvokeOnMainThread(() => MessageTextBlock.Text = "Synchronization is complete!");
                    }
                    else if (job.Status == JobStatus.Failed)
                    {
                        // Report failure ...
                        Device.BeginInvokeOnMainThread(() => MessageTextBlock.Text = job.Error.Message);
                    }
                    else
                    {
                        // Report that the job is in progress ...
                        Device.BeginInvokeOnMainThread(() => MessageTextBlock.Text = "Sync in progress ...");
                    }
                };

                // Await the completion of the job
                await job.GetResultAsync();
            }
            catch (Exception ex)
            {
                // Show the message if an exception occurred
                MessageTextBlock.Text = "Error when synchronizing: " + ex.Message;
            }
            finally
            {
                // Hide the progress bar when the sync job is complete
                LoadingProgressBar.IsVisible = false;
            }
        }
        /// <summary>Construct Generate Geodatabase sample control</summary>
        public SyncGeodatabase()
        {
            InitializeComponent();

            mapView.Map.InitialExtent = new Envelope(-13446093.133, 4183761.731, -13432118.570, 4190880.0245, SpatialReferences.WebMercator);

            _syncTask         = new GeodatabaseSyncTask(new Uri(BASE_URL));
            _onlineBirdsLayer = mapView.Map.Layers.OfType <ArcGISDynamicMapServiceLayer>().First();
            _graphicsLayer    = mapView.Map.Layers.OfType <GraphicsLayer>().First();
            _localBirdsLayer  = null;
            CanGenerate       = true;

            this.DataContext = this;
        }
Example #18
0
        // Sychronizes local data with the online service
        private async void SyncButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (LocalBirdsLayer == null)
                {
                    throw new ApplicationException("Could not find local geodatabase.");
                }

                IsBusy = true;
                ReportStatus("Synchronizing Local and Online data...");

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

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

                var syncTask = new GeodatabaseSyncTask(new Uri(BASE_URL));
                var gdbTable = _localBirdsLayer.FeatureTable as GeodatabaseFeatureTable;
                await syncTask.SyncGeodatabaseAsync(gdbTable.Geodatabase,
                                                    completionAction,
                                                    null,
                                                    TimeSpan.FromSeconds(3),
                                                    syncProgress,
                                                    CancellationToken.None);

                await tcs.Task;

                ReportStatus("Refreshing map view...");
                await RefreshDataView();
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
Example #19
0
        private async Task DeltasSyncAsync()
        {
            Log.Debug("Starting download sync");
            Log.Debug("Start delta download");

            await DownloadDeltasAsync();

            Log.Debug("Delta download complete");
            Log.Debug("Start merge deltas");

            foreach (var fileName in Directory.EnumerateFiles(TempFolder()))
            {
                var gdbpath = GetGeodatabasePath(fileName);
                if (gdbpath == null)
                {
                    continue;
                }

                Log.Debug($"Start delta sync {gdbpath} with {fileName}");

                IReadOnlyList <SyncLayerResult> syncLayerResults = null;
                try
                {
                    syncLayerResults = await GeodatabaseSyncTask.ImportGeodatabaseDeltaAsync(gdbpath, fileName);
                }
                catch (Exception e)
                {
                    Log.Error(e.Message, e);
                }

                Log.Debug($"Complete delta sync {gdbpath} with {fileName}");

                LogResults(syncLayerResults);

                try
                {
                    File.Delete(fileName);
                }
                catch (Exception e)
                {
                    Log.Error(e.Message, e);
                }
            }

            Log.Debug("End merge deltas");
            Log.Debug("Completed download sync");
        }
Example #20
0
        private async void Download_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // cancel if an earlier call was made
                if (_syncCancellationTokenSource != null)
                {
                    _syncCancellationTokenSource.Cancel();
                }

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

                // create a new GeodatabaseSyncTask with the uri of the feature server to pull from
                var uri     = new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/SaveTheBaySync/FeatureServer");
                var gdbTask = new GeodatabaseSyncTask(uri);

                // create parameters for the task: layers and extent to include, out spatial reference, and sync model
                var layers = new List <int>(new int[3] {
                    0, 1, 2
                });
                var extent    = MyMapView.Extent;
                var gdbParams = new GenerateGeodatabaseParameters(layers, extent)
                {
                    OutSpatialReference = MyMapView.SpatialReference,
                    SyncModel           = SyncModel.PerLayer,
                    ReturnAttachments   = true
                };

                // Create a System.Progress<T> object to report status as the task executes
                var progress = new Progress <GeodatabaseStatusInfo>();
                progress.ProgressChanged += (s, info) =>
                {
                    //ShowStatus(info.Status);
                    Console.WriteLine(info.Status);
                };

                // call GenerateGeodatabaseAsync, pass in the parameters and the callback to execute when it's complete
                var gdbResult = await gdbTask.GenerateGeodatabaseAsync(gdbParams, GdbCompleteCallback, new TimeSpan(0, 1, 0), progress, cancelToken);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to create offline database: " + ex.Message);
            }
        }
Example #21
0
        private async void Initialize()
        {
            // タイル キャッシュをを読み込む
            TileCache tileCache = new TileCache(GetTpkPath());

            // タイル キャッシュレイヤーの作成
            ArcGISTiledLayer tileLayer = new ArcGISTiledLayer(tileCache);

            // ベースマップクラスにタイル キャッシュ レイヤーを設定
            Basemap sfBasemap = new Basemap(tileLayer);

            // マップにタイル キャッシュ レイヤーのベースマップを設定
            Map myMap = new Map(sfBasemap);

            Envelope initialLocation = new Envelope(
                15539982.3500528, 4255968.158699, 15545870.466201, 4262306.70411199,
                SpatialReferences.WebMercator);

            myMap.InitialViewpoint = new Viewpoint(initialLocation);

            // MapView に作成したマップを設定
            myMapView.Map = myMap;

            // ジオデータベース ファイルのローカルデータパスを取得
            _gdbPath = GetGdbPath();

            // ジオデータベースを生成するためのタスクを作成する
            _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(FEATURELAYER_SERVICE_URL);

            // サービスから地図にフィーチャ レイヤーを追加する
            foreach (IdInfo layer in _gdbSyncTask.ServiceInfo.LayerInfos)
            {
                Uri onlineTableUri = new Uri(FEATURELAYER_SERVICE_URL + "/" + layer.Id);

                // ServiceFeatureTableを作成する
                ServiceFeatureTable onlineTable = new ServiceFeatureTable(onlineTableUri);

                await onlineTable.LoadAsync();

                // ロードが成功した場合は、マップの操作レイヤーにレイヤーを追加
                if (onlineTable.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded)
                {
                    myMap.OperationalLayers.Add(new FeatureLayer(onlineTable));
                }
            }
        }
        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 (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);

            // Show the progress bar.
            myProgressBar.IsVisible = true;

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

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

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

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

            // Hide the progress bar.
            myProgressBar.IsVisible = false;

            // Handle the job completion.
            HandleGenerationStatusChange(generateGdbJob);
        }
Example #23
0
        private async Task SyncDataAsync(IEnumerable <Geodatabase> syncGeodatabases, SyncDirection syncDirection)
        {
            foreach (var geodatabase in syncGeodatabases)
            {
                IReadOnlyList <SyncLayerResult> results = null;
                try
                {
                    Log.Debug($"{geodatabase.Path} about to start {syncDirection} sync");

                    if (!geodatabase.HasLocalEdits() && syncDirection == SyncDirection.Upload)
                    {
                        Log.Debug("No edits skipping sync");
                        continue;
                    }

                    Log.Debug($"ServiceUrl: {geodatabase.Source}");
                    GeodatabaseSyncTask syncTask = await GeodatabaseSyncTask.CreateAsync(geodatabase.Source);

                    SyncGeodatabaseParameters syncParameters = await syncTask.CreateDefaultSyncGeodatabaseParametersAsync(geodatabase);

                    syncParameters.GeodatabaseSyncDirection = syncDirection;

                    SyncGeodatabaseJob job = syncTask.SyncGeodatabase(syncParameters, geodatabase);

                    results = await job.GetResultAsync();

                    LogResults(results);
                }
                catch (Exception e)
                {
                    Log.Error(e.Message);
                    Log.Error($"{geodatabase.Path} did not sync");
                    if (results != null)
                    {
                        LogResults(results);
                    }
                }
            }

            if (syncDirection == SyncDirection.Bidirectional || syncDirection == SyncDirection.Download)
            {
                EventAggregator.GetEvent <SyncCompleteEvent>().Publish(SyncCompleteEventArgs.Empty);
            }
        }
Example #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="map"></param>
        /// <returns></returns>
        public async Task <string> DeleteReplicaAsync(Map map)
        {
            var sb           = new StringBuilder();
            var geodatabases = GetGeodatabases(map);

            if (geodatabases.Any())
            {
                foreach (var gdb in geodatabases)
                {
                    var syncId = Guid.Empty;
                    try
                    {
                        syncId = gdb.SyncId;

                        var task = await GeodatabaseSyncTask.CreateAsync(gdb.Source);

                        await task.UnregisterGeodatabaseAsync(gdb);

                        gdb.Close();
                        sb.Append($"{AppResources.DeleteReplicaMessageDeleted} {syncId}.");
                    }
                    catch (ArcGISWebException ex)
                    {
                        Debug.WriteLine(ex.Message);
                        sb.Append($"{AppResources.DeleteReplicaMessageCantDelete} {syncId}.");
                    }
                    catch
                    {
                        throw;
                    }
                    finally
                    {
                        gdb.Close();
                        sb.Append($"{AppResources.DeleteReplicaMessageDone}.");
                    }
                }
            }

            await DeleteReplicaFolderAsync();

            return(sb.ToString());
        }
        private async Task SyncGeodatabaes(SyncDirection syncDirection)
        {
            foreach (var gdbPath in BidirectionalGdbs)
            {
                Geodatabase geodatabase = null;
                IReadOnlyList <SyncLayerResult> results = null;

                try
                {
                    geodatabase = await Geodatabase.OpenAsync(gdbPath);

                    Log.Debug($"{geodatabase.Path} about to start {syncDirection} sync");

                    if (!geodatabase.HasLocalEdits() && syncDirection == SyncDirection.Upload)
                    {
                        Log.Debug("No edits skipping sync");
                        continue;
                    }

                    Log.Debug($"ServiceUrl: {geodatabase.Source}");
                    GeodatabaseSyncTask syncTask = await GeodatabaseSyncTask.CreateAsync(geodatabase.Source);

                    SyncGeodatabaseParameters syncParameters = await syncTask.CreateDefaultSyncGeodatabaseParametersAsync(geodatabase);

                    syncParameters.GeodatabaseSyncDirection = syncDirection;

                    SyncGeodatabaseJob job = syncTask.SyncGeodatabase(syncParameters, geodatabase);

                    results = await job.GetResultAsync();

                    LogResults(results);
                }
                catch (Exception e)
                {
                    Log.Error(e.Message);
                    Log.Error($"{geodatabase?.Path} did not sync");
                    LogResults(results);
                }
            }
        }
Example #26
0
        private async Task StartGeodatabaseGeneration()
        {
            // 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 progress changed event with an inline (lambda) function to show the progress bar.
            generateGdbJob.ProgressChanged += (sender, e) =>
            {
                // Update the progress bar.
                UpdateProgressBar(generateGdbJob.Progress);
            };

            // Show the progress bar.
            MyProgressBar.Visibility = Visibility.Visible;

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

            // Get the result of the job.
            _resultGdb = await generateGdbJob.GetResultAsync();

            // Hide the progress bar.
            MyProgressBar.Visibility = Visibility.Collapsed;

            // Do the rest of the work.
            HandleGenerationCompleted(generateGdbJob);
        }
        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[0].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.
            myProgressBar.IsVisible = true;

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

            // Get the result.
            Geodatabase resultGdb = await _generateGdbJob.GetResultAsync();

            // Hide the progress bar.
            myProgressBar.IsVisible = false;

            // Do the rest of the work.
            await HandleGenerationStatusChange(_generateGdbJob, resultGdb);
        }
Example #28
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);
        }
Example #29
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();
        }
Example #30
0
        private async void CreateOfflineData()
        {
            // create a new GeodatabaseSyncTask to create a local version of feature service data
            var featureServiceUri = new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/SaveTheBaySync/FeatureServer");
            var gdbSyncTask       = await GeodatabaseSyncTask.CreateAsync(featureServiceUri);

            // define an extent for the features to include
            Envelope extent = mv.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry as Envelope;
            // get the default parameters for generating a geodatabase
            var generateGdbParams = await gdbSyncTask.CreateDefaultGenerateGeodatabaseParametersAsync(extent);

            // set the sync model to per layer
            generateGdbParams.SyncModel = SyncModel.Layer;
            // define the layers and features to include
            var marineLayerId           = 0;
            var birdsLayerId            = 1;
            var dolphinsOnlyWhereClause = "type = 11";


            // Clear and re-create the layer options
            generateGdbParams.LayerOptions.Clear();
            generateGdbParams.LayerOptions.Add(new GenerateLayerOption(marineLayerId, dolphinsOnlyWhereClause));
            generateGdbParams.LayerOptions.Add(new GenerateLayerOption(birdsLayerId));


            // do not return attachments
            generateGdbParams.ReturnAttachments = false;
            // create the generate geodatabase job, pass in the parameters and an output path for the local geodatabase
            var generateGdbJob = gdbSyncTask.GenerateGeodatabase(generateGdbParams, outGeodatabasePath);

            // handle the JobChanged event to check the status of the job
            generateGdbJob.JobChanged += OnGenerateGdbJobChanged;
            // start the job and report the job ID
            generateGdbJob.Start();
            Console.WriteLine("Submitted job #" + generateGdbJob.ServerJobId + " to create local geodatabase");
        }
Example #31
0
        private async void Initialize()
        {
            // Create a tile cache and load it with the SanFrancisco streets tpk.
            TileCache tileCache = new TileCache(DataManager.GetDataFolder("e4a398afe9a945f3b0f4dca1e4faccb5", "SanFrancisco.tpkx"));

            // Create the corresponding layer based on the tile cache.
            ArcGISTiledLayer tileLayer = new ArcGISTiledLayer(tileCache);

            // Create the basemap based on the tile cache.
            Basemap sfBasemap = new Basemap(tileLayer);

            // Create the map with the tile-based basemap.
            Map myMap = new Map(sfBasemap);

            // Assign the map to the MapView.
            MyMapView.Map = myMap;

            // Create a new symbol for the extent graphic.
            SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Red, 2);

            // Create graphics overlay for the extent graphic and apply a renderer.
            GraphicsOverlay extentOverlay = new GraphicsOverlay
            {
                Renderer = new SimpleRenderer(lineSymbol)
            };

            // Add graphics overlay to the map view.
            MyMapView.GraphicsOverlays.Add(extentOverlay);

            // Set up an event handler for when the viewpoint (extent) changes.
            MyMapView.ViewpointChanged += MapViewExtentChanged;

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

                // Add all layers from the service to the map.
                foreach (IdInfo layer in _gdbSyncTask.ServiceInfo.LayerInfos)
                {
                    // Get the URL for this particular layer.
                    Uri onlineTableUri = new Uri(_featureServiceUri + "/" + layer.Id);

                    // Create the ServiceFeatureTable.
                    ServiceFeatureTable onlineTable = new ServiceFeatureTable(onlineTableUri);

                    // Wait for the table to load.
                    await onlineTable.LoadAsync();

                    // Skip tables that aren't for point features.{
                    if (onlineTable.GeometryType != GeometryType.Point)
                    {
                        continue;
                    }

                    // Add the layer to the map's operational layers if load succeeds.
                    if (onlineTable.LoadStatus == LoadStatus.Loaded)
                    {
                        myMap.OperationalLayers.Add(new FeatureLayer(onlineTable));
                    }
                }

                // Update the extent graphic so that it is valid before user interaction.
                UpdateMapExtent();

                // Enable the generate button now that the sample is ready.
                GenerateButton.IsEnabled = true;
            }
            catch (Exception e)
            {
                ShowStatusMessage(e.ToString());
            }
        }
		// function to submit a sync task 
		// -the url for the feature service and the path to the local geodatabase are passed in
		public async Task SyncronizeEditsAsync(FeatureLayerInfo featureLayerInfo, Uri uri)
		{
			// create sync parameters
			var taskParameters = new SyncGeodatabaseParameters
			{
				RollbackOnFailure = true,
				SyncDirection = SyncDirection.Bidirectional
			};

			// cancel if an earlier call was made and hasn't completed
			if (_syncCancellationTokenSource != null)
			{
				_syncCancellationTokenSource.Cancel();
			}

			// create a new cancellation token
			_syncCancellationTokenSource = new CancellationTokenSource();
			var cancelToken = _syncCancellationTokenSource.Token;


			// create a sync task with the url of the feature service to sync
			var syncTask = new GeodatabaseSyncTask(uri);

			// create a new Progress object to report updates to the sync status
			var progress = new Progress<GeodatabaseStatusInfo>();
			progress.ProgressChanged += (sender, s) => { _model.SetMessageInfo("Progress: " + s.Status.ToString()); };

			// call SyncGeodatabaseAsync and pass in: sync params, local geodatabase, completion callback, update interval, progress, and cancellation token

			var geodatabaseFeatureTable = featureLayerInfo.FeatureLayer.FeatureTable as GeodatabaseFeatureTable;

			var gdbResult = await syncTask.SyncGeodatabaseAsync(
				taskParameters,
				geodatabaseFeatureTable.Geodatabase,
				(p, q) =>
				{
					// reset the cancellation token source
					_syncCancellationTokenSource = null;

					// if unsuccessful, report the exception and return
					if (q != null)
					{
						_model.SetMessageInfo("An exception occured: " + q.Message);
						return;
					}

					// if successful, notify the user
					_model.SetMessageInfo("--- Sync completed ---");

					//// optionally, do something with the result
					//var resultUri = p.ResultUri;
					// ...

					UpdateToc(featureLayerInfo);
					_model.SetSyncState(CheckSyncState(false));
				},
				null,
				new TimeSpan(0, 0, 10),
				progress,
				cancelToken);
		}
        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;
            }
        }
Example #34
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);
        }
Example #35
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);
                });
            }
        }
        /// <summary>Construct Generate Geodatabase sample control</summary>
        public SyncGeodatabase()
        {
            InitializeComponent();

            mapView.Map.InitialExtent = new Envelope(-13446093.133, 4183761.731, -13432118.570, 4190880.0245, SpatialReferences.WebMercator);

            _syncTask = new GeodatabaseSyncTask(new Uri(BASE_URL));
            _onlineBirdsLayer = mapView.Map.Layers.OfType<ArcGISDynamicMapServiceLayer>().First();
            _graphicsLayer = mapView.Map.Layers.OfType<GraphicsLayer>().First();
            _localBirdsLayer = null;
            CanGenerate = true;

            this.DataContext = this;
        }
Example #37
0
        //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);
            }
        }
		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);
			}
		}
		private async Task DeleteOfflineMap(OfflineMapItem offlineMapItem)
		{
			// TODO Ensure, map isn't loaded
			// TODO Ensure, user is logged on

			_model.SetMessageInfo(string.Format("Unregister Geodatabases..."));
			var gdbFiles = Directory.GetFiles(offlineMapItem.OfflineMapPath,
				string.Format("*{0}", OfflineMapItem.GeodatabaseFilenameExtension));
			foreach (var gdbFile in gdbFiles)
			{
				_model.SetMessageInfo(string.Format("\tUnregister Geodatabase '{0}'...", gdbFile));
				var gdbPath = gdbFile.Replace("/", @"\");
				var geodatabase = await Geodatabase.OpenAsync(gdbPath);

				var serviceUri = geodatabase.GetServiceUri();
				var geodatabaseSyncTask = new GeodatabaseSyncTask(serviceUri);
				var result = await geodatabaseSyncTask.UnregisterGeodatabaseAsync(geodatabase);
				_model.SetMessageInfo(string.Format("\t...Geodatabase {0} {1}successfully unregistered", gdbFile,
					result.Success ? "" : "NOT "));

				// Workaround to release file handle, as Geodatabase does not implement IDisposable
				geodatabase = null;
				GC.Collect();
				GC.WaitForPendingFinalizers();
				GC.Collect();

				File.Delete(gdbFile);
			}

			// delete directory, including basemap
			Directory.Delete(offlineMapItem.OfflineMapPath, true);
		}
        /// <summary>Construct Generate Geodatabase sample control</summary>
        public SyncGeodatabase()
        {
            InitializeComponent();

            _syncTask = new GeodatabaseSyncTask(new Uri(BASE_URL));
            _onlineBirdsLayer = MyMapView.Map.Layers.OfType<ArcGISDynamicMapServiceLayer>().First();
			_graphicsOverlay = MyMapView.GraphicsOverlays["graphicsOverlay"];
            _localBirdsLayer = null;
            CanGenerate = true;

            this.DataContext = this;
        }
        // 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;
            }
        }
		private async Task SyncOfflineMap(OfflineMapItem offlineMapItem)
		{
			var gdbFiles = Directory.GetFiles(offlineMapItem.OfflineMapPath,
				string.Format("*{0}", OfflineMapItem.GeodatabaseFilenameExtension));
			foreach (var gdbFile in gdbFiles)
			{
				var gdbPath = gdbFile.Replace("/", @"\");
				var geodatabase = await Geodatabase.OpenAsync(gdbPath);
				if (!geodatabase.FeatureTables.Any(table => table.HasEdits))
				{
					// nothing to sync..
					continue;
				}

				_model.SetMessageInfo("Sync geodatabase...");
				var serviceUri = geodatabase.GetServiceUri();
				var geodatabaseSyncTask = new GeodatabaseSyncTask(serviceUri);
				var statusCallback =
					new Progress<GeodatabaseStatusInfo>(
						statusInfo => _model.SetMessageInfo(string.Format("Current Status: {0}", statusInfo.Status)));

				var tcs = new TaskCompletionSource<GeodatabaseStatusInfo>();

				try
				{
					// At this point, we are submitting a job. Therefore, the await returns pretty fast.
					await geodatabaseSyncTask.SyncGeodatabaseAsync(
						new SyncGeodatabaseParameters
						{
							RollbackOnFailure = true,
							SyncDirection = SyncDirection.Upload,
							UnregisterGeodatabase = false
						},
						geodatabase,
						(geodatabaseStatusInfo, exc) =>
						{
							if (geodatabaseStatusInfo != null)
							{
								tcs.SetResult(geodatabaseStatusInfo);
							}
							if (exc != null)
							{
								tcs.SetException(exc);
							}
						},
						uploadResult => { _model.SetMessageInfo(string.Format("UploadResult: {0}", uploadResult.Success)); },
						TimeSpan.FromSeconds(5),
						statusCallback,
						CancellationToken.None);

					// This is the call we are really waiting for..
					await tcs.Task;
					_model.SetMessageInfo(string.Format("Finished Status: {0}", tcs.Task.Result.Status));
				}
				catch (Exception exc)
				{
					_model.SetMessageInfo(string.Format("Executing SyncGeodatabaseAsync failed: {0}", exc.Message));
				}
				_model.SetMessageInfo("...done syncing geodatabase");
			}
		}
        // Sychronizes local data with the online service
        private async void SyncButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (LocalBirdsLayer == null)
                    throw new ApplicationException("Could not find local geodatabase.");

                IsBusy = true;
                ReportStatus("Synchronizing Local and Online data...");

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

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

                var syncTask = new GeodatabaseSyncTask(new Uri(BASE_URL));
                var gdbTable = _localBirdsLayer.FeatureTable as GeodatabaseFeatureTable;
                await syncTask.SyncGeodatabaseAsync(gdbTable.Geodatabase,
                    completionAction,
                    null,
                    TimeSpan.FromSeconds(3),
                    syncProgress,
                    CancellationToken.None);

                await tcs.Task;

                ReportStatus("Refreshing map view...");
                await RefreshDataView();
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
        private async void Initialize()
        {
            // Create a tile cache and load it with the SanFrancisco streets tpk.
            try
            {
                TileCache tileCache = new TileCache(DataManager.GetDataFolder("3f1bbf0ec70b409a975f5c91f363fe7d", "SanFrancisco.tpk"));

                // Create the corresponding layer based on the tile cache.
                ArcGISTiledLayer tileLayer = new ArcGISTiledLayer(tileCache);

                // Create the basemap based on the tile cache.
                Basemap sfBasemap = new Basemap(tileLayer);

                // Create the map with the tile-based basemap.
                Map myMap = new Map(sfBasemap);

                // Assign the map to the MapView.
                myMapView.Map = myMap;

                // Create a new symbol for the extent graphic.
                SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Colors.Red, 2);

                // Create a graphics overlay for the extent graphic and apply a renderer.
                GraphicsOverlay extentOverlay = new GraphicsOverlay
                {
                    Renderer = new SimpleRenderer(lineSymbol)
                };

                // Add the graphics overlay to the map view.
                myMapView.GraphicsOverlays.Add(extentOverlay);

                // Set up an event handler for when the viewpoint (extent) changes.
                myMapView.ViewpointChanged += MapViewExtentChanged;

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

                // Add all layers from the service to the map.
                foreach (IdInfo layer in _gdbSyncTask.ServiceInfo.LayerInfos)
                {
                    // Get the URL for this layer.
                    Uri onlineTableUri = new Uri(_featureServiceUri + "/" + layer.Id);

                    // Create the ServiceFeatureTable.
                    ServiceFeatureTable onlineTable = new ServiceFeatureTable(onlineTableUri);

                    // Wait for the table to load.
                    await onlineTable.LoadAsync();

                    // Add the layer to the map's operational layers if load succeeds.
                    if (onlineTable.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded)
                    {
                        myMap.OperationalLayers.Add(new FeatureLayer(onlineTable));
                    }
                }

                // Update the graphic - needed in case the user decides not to interact before pressing the button.
                UpdateMapExtent();

                // Enable the generate button now that sample is ready.
                myGenerateButton.IsEnabled = true;
            }
            catch (Exception ex)
            {
                await((Page)Parent).DisplayAlert("Error", ex.ToString(), "OK");
            }
        }
Example #45
0
        public async Task<GeodatabaseStatusInfo> SyncGeodatabase(string url, Geodatabase gdb, bool unregister, bool syncing)
        {
            Console.WriteLine("Starting Sync " + DateTime.Now + " --> " + syncing);
            var syncTask = new GeodatabaseSyncTask(new Uri(url));


            var layerIdsAndName = new Dictionary<int, string>();

            FeatureServiceInfo serviceInfo = await syncTask.GetServiceInfoAsync();
            foreach (LayerServiceInfo layerServiceInfo in serviceInfo.Layers)
            {
                if (!layerIdsAndName.ContainsKey(layerServiceInfo.ID))
                {
                    layerIdsAndName.Add(layerServiceInfo.ID, layerServiceInfo.Name);
                }
            }


            


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

            var syncProgress = new Progress<GeodatabaseStatusInfo>();
            syncProgress.ProgressChanged += (sndr, sts) => Console.WriteLine("Status:" + sts.Status.ToString() + "," +" --> " + syncing + "," + sts.SubmissionTime + "," + sts.ResultUri);


            IDictionary<int, LayerSyncInfo> layerSync = null;

            layerSync = new Dictionary<int, LayerSyncInfo>();
            foreach (var id_name in layerIdsAndName)
            {
                    var layerQuery = new LayerSyncInfo { SyncDirection = SyncDirection.Bidirectional };
                    layerSync.Add(id_name.Key, layerQuery);
                
            }
            Action<UploadResult> uploadAction = result => { Console.Write(""); };

            //should we remove sync direction since it should be defined in layers?
            var syncParams = new SyncGeodatabaseParameters(gdb) { RollbackOnFailure = false, UnregisterGeodatabase = unregister, LayerSyncInfos = layerSync, SyncDirection = SyncDirection.Bidirectional };
            Console.WriteLine("Calling sync " + DateTime.Now);
            await syncTask.SyncGeodatabaseAsync(syncParams, gdb,
                completionAction,
                uploadAction,
                TimeSpan.FromSeconds(3),
                syncProgress,
                CancellationToken.None);
            
            

            return await tcs.Task;

            

        }