Click or drag to resize

GenerateLayerOption Class

This can be used in conjunction with GenerateGeodatabaseParameters object to refine per layer what features are replicated.
Inheritance Hierarchy
SystemObject
  Esri.ArcGISRuntime.Tasks.OfflineGenerateLayerOption

Namespace:  Esri.ArcGISRuntime.Tasks.Offline
Assembly:  Esri.ArcGISRuntime (in Esri.ArcGISRuntime.dll) Version: 100.9.0.0
Syntax
C#
public sealed class GenerateLayerOption

The GenerateLayerOption type exposes the following members.

Constructors
  NameDescription
Public methodCode exampleGenerateLayerOption
Initializes a new instance of the GenerateLayerOption class.
Public methodGenerateLayerOption(Int64)
Initializes a new instance of the GenerateLayerOption class.
Public methodGenerateLayerOption(Int64, Boolean)
Initializes a new instance of the GenerateLayerOption class.
Public methodGenerateLayerOption(Int64, String)
Initializes a new instance of the GenerateLayerOption class.
Top
Properties
  NameDescription
Public propertyIncludeRelated
Gets or sets a value indicating whether only related rows are added to the specific LayerId in the generated geodatabase.
Public propertyCode exampleLayerId
Gets or sets the layer or table ID to further filter in the generated geodatabase.
Public propertyCode exampleQueryOption
Gets or sets a value indicating whether all, filtered or no features will be copied from the server when creating a geodatabase.
Public propertyCode exampleUseGeometry
Gets or sets a value indicating whether Extent is used to filter the features for downloading.
Public propertyCode exampleWhereClause
Gets or sets the where clause of the layer option.
Top
Methods
  NameDescription
Public methodClone
Clones this instance of the GenerateLayerOption and its members.
Top
Remarks
This parameter allows you to set properties on a per-layer or per-table basis. Only the properties for the layers and tables that you want changed from the default are required.
Examples

Android

Example Name: GeodatabaseTransactions

Use transactions to manage how changes are committed to a geodatabase.

Code example screen shot.

C#
// Copyright 2017 Esri.
// 
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// Language governing permissions and limitations under the License.

using Android.App;
using Android.OS;
using Android.Widget;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Tasks;
using Esri.ArcGISRuntime.Tasks.Offline;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.IO;
using System.Threading.Tasks;
using Android.Views;

namespace ArcGISRuntime.Samples.GeodatabaseTransactions
{
    [Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Geodatabase transactions",
        category: "Data",
        description: "Use transactions to manage how changes are committed to a geodatabase.",
        instructions: "When the sample loads, a feature service is taken offline as a geodatabase. When the geodatabase is ready, you can add multiple types of features. To apply edits directly, uncheck the 'Require a transaction for edits' checkbox. When using transactions, use the buttons to start editing and stop editing. When you stop editing, you can choose to commit the changes or roll them back. At any point, you can synchronize the local geodatabase with the feature service.",
        tags: new[] { "commit", "database", "geodatabase", "transact", "transactions" })]
    public class GeodatabaseTransactions : Activity
    {
        // URL for the editable feature service
        private const string SyncServiceUrl = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/SaveTheBaySync/FeatureServer/";

        // Map view
        private MapView _mapView;

        // Work in a small extent south of Galveston, TX
        private Envelope _extent = new Envelope(-95.3035, 29.0100, -95.1053, 29.1298, SpatialReferences.Wgs84);

        // Store the local geodatabase to edit
        private Geodatabase _localGeodatabase;

        // Store references to two tables to edit: Birds and Marine points
        private GeodatabaseFeatureTable _birdTable;
        private GeodatabaseFeatureTable _marineTable;

        // Switch to control whether or not transactions are required for edits
        private Switch _requireTransactionSwitch;

        // Buttons to start/stop an edit transaction
        private Button _startEditingButton;
        private Button _stopEditingButton;

        // Buttons to add bird or marine features
        private Button _addBirdButton;
        private Button _addMarineButton;

        // Button to synchronize local edits with the service
        private Button _syncEditsButton;

        // Text view to show status messages
        private TextView _messageTextBlock;

        // Progress bar
        private ProgressBar _progressBar;

        // Dialog for choosing how to end the transaction (commit, rollback, cancel)
        private AlertDialog _stopEditDialog;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            Title = "Geodatabase transactions";

            // Create the UI
            CreateLayout();

            // Initialize the map and load local data (generate a local geodatabase if necessary)
            Initialize();
        }

        private void CreateLayout()
        {
            // Layout params for making buttons fill page width
            LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MatchParent,
                ViewGroup.LayoutParams.MatchParent,
                1.0f
            );

            // Button to start an edit transaction
            _startEditingButton = new Button(this)
            {
                Text = "Start",
                LayoutParameters = param
            };
            _startEditingButton.Click += BeginTransaction;

            // Button to stop a transaction
            _stopEditingButton = new Button(this)
            {
                Text = "Stop",
                Enabled = false,
                LayoutParameters = param
            };
            _stopEditingButton.Click += StopEditTransaction;

            // Button to synchronize local edits with the service
            _syncEditsButton = new Button(this)
            {
                Text = "Sync",
                Enabled = false,
                LayoutParameters = param
            };
            _syncEditsButton.Click += SynchronizeEdits;

            // Button to add bird features
            _addBirdButton = new Button(this)
            {
                Text = "Add Bird",
                Enabled = false,
                LayoutParameters = param
            };
            _addBirdButton.Click += AddNewFeature;

            // Button to add marine features
            _addMarineButton = new Button(this)
            {
                Text = "Add Marine",
                Enabled = false,
                LayoutParameters = param
            };
            _addMarineButton.Click += AddNewFeature;

            // Layout to hold the first row of buttons (start, stop, sync)
            LinearLayout editButtonsRow1 = new LinearLayout(this)
            {
                Orientation = Orientation.Horizontal
            };
            editButtonsRow1.AddView(_startEditingButton);
            editButtonsRow1.AddView(_stopEditingButton);
            editButtonsRow1.AddView(_syncEditsButton);

            // Layout to hold the second row of buttons (add bird, add marine)
            LinearLayout editButtonsRow2 = new LinearLayout(this)
            {
                Orientation = Orientation.Horizontal
            };
            editButtonsRow2.AddView(_addBirdButton);
            editButtonsRow2.AddView(_addMarineButton);

            // Layout for the 'require transaction' switch
            LinearLayout editSwitchRow = new LinearLayout(this)
            {
                Orientation = Orientation.Horizontal
            };
            _requireTransactionSwitch = new Switch(this)
            {
                Checked = true,
                Text = "Require transaction"
            };
            _requireTransactionSwitch.CheckedChange += RequireTransactionChanged;
            editSwitchRow.AddView(_requireTransactionSwitch);

            // Progress bar
            _progressBar = new ProgressBar(this)
            {
                Visibility = Android.Views.ViewStates.Gone
            };

            // Use the rest of the view to show status messages
            _messageTextBlock = new TextView(this);

            // Create the main layout
            LinearLayout layout = new LinearLayout(this)
            {
                Orientation = Orientation.Vertical
            };

            // Add the first row of buttons
            layout.AddView(editButtonsRow1);

            // Add the second row of buttons
            layout.AddView(editButtonsRow2);

            // Add the 'require transaction' switch and label
            layout.AddView(editSwitchRow);

            // Add the messages text view
            layout.AddView(_messageTextBlock);

            // Add the progress bar
            layout.AddView(_progressBar);            

            // Add the map view
            _mapView = new MapView(this);
            layout.AddView(_mapView);

            // Add the layout to the view
            SetContentView(layout);
        }

        private void Initialize()
        {
            // When the spatial reference changes (the map loads) add the local geodatabase tables as feature layers
            _mapView.SpatialReferenceChanged += async (s, e) =>
            {
                // Call a function (and await it) to get the local geodatabase (or generate it from the feature service)
                await GetLocalGeodatabase();

                // Once the local geodatabase is available, load the tables as layers to the map
                LoadLocalGeodatabaseTables();
            };

            // Create a new map with the oceans basemap and add it to the map view
            _mapView.Map = new Map(Basemap.CreateOceans());
        }

        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);
                });
            }
        }

        // Function that loads the two point tables from the local geodatabase and displays them as feature layers
        private async void LoadLocalGeodatabaseTables()
        {
            if (_localGeodatabase == null) { return; }

            // Read the geodatabase tables and add them as layers
            foreach (GeodatabaseFeatureTable table in _localGeodatabase.GeodatabaseFeatureTables)
            {
                try
                {
                    // Load the table so the TableName can be read
                    await table.LoadAsync();

                    // Store a reference to the Birds table
                    if (table.TableName.ToLower().Contains("birds"))
                    {
                        _birdTable = table;
                    }

                    // Store a reference to the Marine table
                    if (table.TableName.ToLower().Contains("marine"))
                    {
                        _marineTable = table;
                    }

                    // Create a new feature layer to show the table in the map
                    FeatureLayer layer = new FeatureLayer(table);
                    RunOnUiThread(() => _mapView.Map.OperationalLayers.Add(layer));
                }
                catch (Exception e)
                {
                    new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show();
                }
            }

            // Handle the transaction status changed event
            _localGeodatabase.TransactionStatusChanged += GdbTransactionStatusChanged;

            // Zoom the map view to the extent of the generated local datasets
            RunOnUiThread(() =>
            {
                _mapView.SetViewpoint(new Viewpoint(_marineTable.Extent));
                _startEditingButton.Enabled = true;
            });
        }

        private void GdbTransactionStatusChanged(object sender, TransactionStatusChangedEventArgs e)
        {
            // Update UI controls based on whether the geodatabase has a current transaction
            RunOnUiThread(() =>
            {
                // These buttons should be enabled when there IS a transaction
                _addBirdButton.Enabled = e.IsInTransaction;
                _addMarineButton.Enabled = e.IsInTransaction;
                _stopEditingButton.Enabled = e.IsInTransaction;

                // These buttons should be enabled when there is NOT a transaction
                _startEditingButton.Enabled = !e.IsInTransaction;
                _syncEditsButton.Enabled = !e.IsInTransaction;
            });
        }

        private void BeginTransaction(object sender, EventArgs e)
        {
            // See if there is a transaction active for the geodatabase
            if (_localGeodatabase!= null && !_localGeodatabase.IsInTransaction)
            {
                // If not, begin a transaction
                _localGeodatabase.BeginTransaction();
                _messageTextBlock.Text = "Transaction started";
            }
            else
            {
                _messageTextBlock.Text = "Not yet ready for new transaction.";
            }
        }

        private async void AddNewFeature(object sender, EventArgs args)
        {
            // See if it was the "Birds" or "Marine" button that was clicked
            Button addFeatureButton = (Button)sender;

            try
            {
                // Cancel execution of the sketch task if it is already active
                if (_mapView.SketchEditor.CancelCommand.CanExecute(null))
                {
                    _mapView.SketchEditor.CancelCommand.Execute(null);
                }

                // Store the correct table to edit (for the button clicked)
                GeodatabaseFeatureTable editTable = null;
                if (addFeatureButton == _addBirdButton)
                {
                    editTable = _birdTable;
                }
                else
                {
                    editTable = _marineTable;
                }

                // Inform the user which table is being edited
                _messageTextBlock.Text = "Click the map to add a new feature to the geodatabase table '" + editTable.TableName + "'";

                // Create a random value for the 'type' attribute (integer between 1 and 7)
                Random random = new Random(DateTime.Now.Millisecond);
                int featureType = random.Next(1, 7);

                // Use the sketch editor to allow the user to draw a point on the map
                MapPoint clickPoint = await _mapView.SketchEditor.StartAsync(SketchCreationMode.Point, false) as MapPoint;

                // Create a new feature (row) in the selected table
                Feature newFeature = editTable.CreateFeature();

                // Set the geometry with the point the user clicked and the 'type' with the random integer
                newFeature.Geometry = clickPoint;
                newFeature.SetAttributeValue("type", featureType);

                // Add the new feature to the table
                await editTable.AddFeatureAsync(newFeature);

                // Clear the message
                _messageTextBlock.Text = "New feature added to the '" + editTable.TableName + "' table";
            }
            catch (TaskCanceledException)
            {
                // Ignore if the edit was canceled
            }
            catch (Exception ex)
            {
                // Report other exception messages
                _messageTextBlock.Text = ex.Message;
            }
        }

        private void StopEditTransaction(object sender, EventArgs e)
        {
            // Create a dialog to prompt the user to commit or rollback
            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

            // Create the layout
            LinearLayout dialogLayout = new LinearLayout(this)
            {
                Orientation = Orientation.Vertical
            };

            // Create a button to commit edits
            Button commitButton = new Button(this)
            {
                Text = "Commit"
            };

            // Handle the click event for the Commit button
            commitButton.Click += (s, args) =>
            {
                // See if there is a transaction active for the geodatabase
                if (_localGeodatabase.IsInTransaction)
                {
                    // If there is, commit the transaction to store the edits (this will also end the transaction)
                    _localGeodatabase.CommitTransaction();
                    _messageTextBlock.Text = "Edits were committed to the local geodatabase.";
                }

                _stopEditDialog.Dismiss();
            };

            // Create a button to rollback edits
            Button rollbackButton = new Button(this)
            {
                Text = "Rollback"
            };

            // Handle the click event for the Rollback button
            rollbackButton.Click += (s, args) => 
            {
                // See if there is a transaction active for the geodatabase
                if (_localGeodatabase.IsInTransaction)
                {
                    // If there is, rollback the transaction to discard the edits (this will also end the transaction)
                    _localGeodatabase.RollbackTransaction();
                    _messageTextBlock.Text = "Edits were rolled back and not stored to the local geodatabase.";
                }

                _stopEditDialog.Dismiss();
            };

            // Create a button to cancel and return to the transaction
            Button cancelButton = new Button(this)
            {
                Text = "Cancel"
            };

            // Handle the click event for the Cancel button
            rollbackButton.Click += (s, args) => _stopEditDialog.Dismiss();

            // Add the controls to the dialog
            dialogLayout.AddView(cancelButton);
            dialogLayout.AddView(rollbackButton);
            dialogLayout.AddView(commitButton);
            dialogBuilder.SetView(dialogLayout);
            dialogBuilder.SetTitle("Stop Editing");

            // Show the dialog
            _stopEditDialog = dialogBuilder.Show();
        }

        // Change which controls are enabled if the user chooses to require/not require transactions for edits
        private void RequireTransactionChanged(object sender, EventArgs e)
        {
            // If the local geodatabase isn't created yet, return
            if (_localGeodatabase == null) { return; }

            // Get the value of the "require transactions" switch
            bool mustHaveTransaction = _requireTransactionSwitch.Checked;

            // Warn the user if disabling transactions while a transaction is active
            if (!mustHaveTransaction && _localGeodatabase.IsInTransaction)
            {
                ShowStatusMessage("Stop editing to end the current transaction.", "Current Transaction");
                _requireTransactionSwitch.Checked = true;
                return;
            }

            // Enable or disable controls according to the switch value
            _startEditingButton.Enabled = mustHaveTransaction;
            _stopEditingButton.Enabled = mustHaveTransaction && _localGeodatabase.IsInTransaction;
            _addBirdButton.Enabled = !mustHaveTransaction;
            _addMarineButton.Enabled = !mustHaveTransaction;
        }

        // 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;
            }
        }

        private string GetGdbPath()
        {
            return GetFileStreamPath("wildfire.geodatabase").AbsolutePath;
        }

        private void ShowStatusMessage(string title, string message)
        {
            // Display the message to the user
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.SetMessage(message).SetTitle(title).Show();
        }

        private void UpdateProgressBar(int progress)
        {
            // Due to the nature of the threading implementation,
            //     the dispatcher needs to be used to interact with the UI
            RunOnUiThread(() =>
            {
                // Update the progress bar value
                _progressBar.Progress = progress;
            });
        }
    }
}
Examples

Xamarin Forms Android

Example Name: GenerateOfflineMapWithOverrides

Take a web map offline with additional options for each layer.

Code example screen shot.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Tasks.Offline;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace ArcGISRuntimeXamarin.Samples.GenerateOfflineMapWithOverrides
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ConfigureOverridesPage : ContentPage
    {
        private Esri.ArcGISRuntime.Mapping.Map _map;
        private Envelope _areaOfInterest = new Envelope(-88.1541, 41.7690, -88.1471, 41.7720, SpatialReferences.Wgs84);
        private GenerateOfflineMapParameterOverrides _overrides;

        public ConfigureOverridesPage ()
        {
            InitializeComponent ();
        }

        public ConfigureOverridesPage(GenerateOfflineMapParameterOverrides overrides, Esri.ArcGISRuntime.Mapping.Map map)
        {
            InitializeComponent();

            // Hold a reference to the map & overrides.
            _map = map;
            _overrides = overrides;
        }

        #region overrides

        private void ConfigureTileLayerOverrides(GenerateOfflineMapParameterOverrides overrides)
        {
            // Create a parameter key for the first basemap layer.
            OfflineMapParametersKey basemapKey = new OfflineMapParametersKey(_map.Basemap.BaseLayers.First());

            // Get the export tile cache parameters for the layer key.
            ExportTileCacheParameters basemapParams = overrides.ExportTileCacheParameters[basemapKey];

            // Clear the existing level IDs.
            basemapParams.LevelIds.Clear();

            // Get the min and max scale from the UI.
            int minScale = (int)MinScaleEntry.Value;
            int maxScale = (int) MaxScaleEntry.Value;

            // Re-add selected scales.
            for (int i = minScale; i < maxScale; i++)
            {
                basemapParams.LevelIds.Add(i);
            }

            // Expand the area of interest based on the specified buffer distance.
            int bufferDistance = (int)ExtentBufferEntry.Value;
            basemapParams.AreaOfInterest = GeometryEngine.BufferGeodetic(_areaOfInterest, bufferDistance, LinearUnits.Meters);
        }

        private void ConfigureLayerExclusion(GenerateOfflineMapParameterOverrides overrides)
        {
            // Apply layer exclusions as specified in the UI.
            if (ServiceConnCheckbox.IsToggled == false)
            {
                ExcludeLayerByName("Service Connection", overrides);
            }

            if (SysValvesLayerCheckbox.IsToggled == false)
            {
                ExcludeLayerByName("System Valve", overrides);
            }
        }

        private void CropWaterPipes(GenerateOfflineMapParameterOverrides overrides)
        {
            if (CropLayerCheckbox.IsToggled)
            {
                // Get the ID of the water pipes layer.
                long targetLayerId = GetServiceLayerId(GetLayerByName("Main"));

                // For each layer option.
                foreach (GenerateLayerOption layerOption in GetAllLayerOptions(overrides))
                {
                    // If the option's LayerId matches the selected layer's ID.
                    if (layerOption.LayerId == targetLayerId)
                    {
                        layerOption.UseGeometry = true;
                    }
                }
            }
        }

        private void ApplyFeatureFilter(GenerateOfflineMapParameterOverrides overrides)
        {
            // For each layer option.
            foreach (GenerateLayerOption option in GetAllLayerOptions(overrides))
            {
                // If the option's LayerId matches the selected layer's ID.
                if (option.LayerId == GetServiceLayerId(GetLayerByName("Hydrant")))
                {
                    // Apply the where clause.
                    option.WhereClause = "FLOW >= " + (int)FlowRateFilterEntry.Value;
                    // Configure the option to use the where clause.
                    option.QueryOption = GenerateLayerQueryOption.UseFilter;
                }
            }
        }

        private IList<GenerateLayerOption> GetAllLayerOptions(GenerateOfflineMapParameterOverrides overrides)
        {
            // Find the first feature layer.
            FeatureLayer targetLayer = _map.OperationalLayers.OfType<FeatureLayer>().First();

            // Get the key for the layer.
            OfflineMapParametersKey layerKey = new OfflineMapParametersKey(targetLayer);

            // Use that key to get the generate options for the layer.
            GenerateGeodatabaseParameters generateParams = overrides.GenerateGeodatabaseParameters[layerKey];

            // Return the layer options.
            return generateParams.LayerOptions;
        }

        private void ExcludeLayerByName(string layerName, GenerateOfflineMapParameterOverrides overrides)
        {
            // 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);
        }

        private FeatureLayer GetLayerByName(string layerName)
        {
            // Get the first map in the operational layers collection that is a feature layer with name matching layerName
            return _map.OperationalLayers.OfType<FeatureLayer>().First(layer => layer.Name == layerName);
        }

        private long GetServiceLayerId(FeatureLayer layer)
        {
            // Find the service feature table for the layer; this assumes the layer is backed by a service feature table.
            ServiceFeatureTable serviceTable = (ServiceFeatureTable) layer.FeatureTable;

            // Return the layer ID.
            return serviceTable.LayerInfo.ServiceLayerId;
        }

        #endregion overrides

        private void TakeMapOffline_Clicked(object sender, EventArgs e)
        {
            // Configure the overrides using helper methods.
            ConfigureTileLayerOverrides(_overrides);
            ConfigureLayerExclusion(_overrides);
            CropWaterPipes(_overrides);
            ApplyFeatureFilter(_overrides);

            // The main sample page continues when OnDisappearing is called.
            // OnDisappearing is called by Xamarin.Forms when navigation away from this page happens.
            Navigation.PopModalAsync(true);
        }
    }
}
C#
// Copyright 2019 Esri.
// 
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an 
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific 
// language governing permissions and limitations under the License.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks;
using Esri.ArcGISRuntime.Tasks.Offline;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.Security;
using Xamarin.Forms;
#if __IOS__
using Xamarin.Auth;
using UIKit;
#endif

#if __ANDROID__
using Android.App;
using Application = Xamarin.Forms.Application;
using Xamarin.Auth;
#endif

namespace ArcGISRuntimeXamarin.Samples.GenerateOfflineMapWithOverrides
{
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Generate offline map (overrides)",
        category: "Map",
        description: "Take a web map offline with additional options for each layer.",
        instructions: "Modify the overrides parameters:",
        tags: new[] { "LOD", "adjust", "download", "extent", "filter", "offline", "override", "parameters", "reduce", "scale range", "setting" })]
    public partial class GenerateOfflineMapWithOverrides : ContentPage, IOAuthAuthorizeHandler
    {
        // The job to generate an offline map.
        private GenerateOfflineMapJob _generateOfflineMapJob;

        // The extent of the data to take offline.
        private Envelope _areaOfInterest = new Envelope(-88.1541, 41.7690, -88.1471, 41.7720, SpatialReferences.Wgs84);

        // The ID for a web map item hosted on the server (water network map of Naperville IL).
        private const string WebMapId = "acc027394bc84c2fb04d1ed317aac674";

        public GenerateOfflineMapWithOverrides()
        {
            InitializeComponent();

            // Load the web map, show area of interest, restrict map interaction, and set up authorization. 
            Initialize();
        }

        private async void Initialize()
        {
            try
            {
                // Call a function to set up the AuthenticationManager for OAuth.
                SetOAuthInfo();

                // Create the ArcGIS Online portal.
                ArcGISPortal portal = await ArcGISPortal.CreateAsync();

                // Get the Naperville water web map item using its ID.
                PortalItem webmapItem = await PortalItem.CreateAsync(portal, WebMapId);

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

                // Display the map in the MapView.
                MyMapView.Map = onlineMap;

                // Disable user interactions on the map (no panning or zooming from the initial extent).
                MyMapView.InteractionOptions = new MapViewInteractionOptions
                {
                    IsEnabled = false
                };

                // Create a graphics overlay for the extent graphic and apply a renderer.
                SimpleLineSymbol aoiOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Red, 3);
                GraphicsOverlay extentOverlay = new GraphicsOverlay
                {
                    Renderer = new SimpleRenderer(aoiOutlineSymbol)
                };
                MyMapView.GraphicsOverlays.Add(extentOverlay);

                // Add a graphic to show the area of interest (extent) that will be taken offline.
                Graphic aoiGraphic = new Graphic(_areaOfInterest);
                extentOverlay.Graphics.Add(aoiGraphic);

                // Hide the map loading progress indicator.
                loadingIndicator.IsVisible = false;
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Alert", ex.ToString(), "OK");
            }
        }

        private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
        {
            // Clean up any previous outputs in the temp directory.
            string tempPath = $"{Path.GetTempPath()}";
            string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");

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

            // Create a new folder for the output mobile map.
            string packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork");
            int num = 1;
            while (Directory.Exists(packagePath))
            {
                packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num.ToString());
                num++;
            }

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

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

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

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

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

                // Create the UI for configuring the overrides.
                ConfigureOverridesPage configurationPage = new ConfigureOverridesPage(overrides, MyMapView.Map);

                // Wait for the user to finish with the configuration, then continue.
                configurationPage.Disappearing += async (o, args) =>
                {
                    // Re-show the busy indicator.
                    busyIndicator.IsVisible = true;

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

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

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

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

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

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

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

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

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

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

                    // Show a message that the map is offline.
                    messageArea.IsVisible = true;

                    // Hide the busy indicator.
                    busyIndicator.IsVisible = false;
                };

                // Show the configuration UI.
                await Navigation.PushModalAsync(configurationPage, true);

            }
            catch (TaskCanceledException)
            {
                // Generate offline map task was canceled.
                await Application.Current.MainPage.DisplayAlert("Alert", "Taking map offline was canceled", "OK");
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                await Application.Current.MainPage.DisplayAlert("Alert", ex.Message, "OK");
            }
            finally
            {
                // Hide the activity indicator when the job is done.
                busyIndicator.IsVisible = false;
            }
        }

        // Show changes in job progress.
        private void OfflineMapJob_ProgressChanged(object sender, EventArgs e)
        {
            // Get the job.
            GenerateOfflineMapJob job = sender as GenerateOfflineMapJob;

            // Dispatch to the UI thread.
            Device.BeginInvokeOnMainThread(() =>
            {
                // Show the percent complete and update the progress bar.
                Percentage.Text = job.Progress > 0 ? job.Progress.ToString() + " %" : string.Empty;
                progressBar.Progress = job.Progress / 100.0;
            });
        }

        private void CancelJobButton_Click(object sender, EventArgs e)
        {
            // The user canceled the job.
            _generateOfflineMapJob.Cancel();
        }

        #region Authentication

        // Constants for OAuth-related values.
        // - The URL of the portal to authenticate with (ArcGIS Online).
        private const string ServerUrl = "https://www.arcgis.com/sharing/rest";

        // - The Client ID for an app registered with the server (the ID below is for a public app created by the ArcGIS Runtime team).
        private const string AppClientId = @"6wMAmbUEX1rvsOb4";

        // - A URL for redirecting after a successful authorization (this must be a URL configured with the app).
        private const string OAuthRedirectUrl = @"forms-samples-app://auth";

        private void SetOAuthInfo()
        {
            // Register the server information with the AuthenticationManager.
            ServerInfo serverInfo = new ServerInfo
            {
                ServerUri = new Uri(ServerUrl),
                TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit,
                OAuthClientInfo = new OAuthClientInfo
                {
                    ClientId = AppClientId,
                    RedirectUri = new Uri(OAuthRedirectUrl)
                }
            };

            // Register this server with AuthenticationManager.
            AuthenticationManager.Current.RegisterServer(serverInfo);

            // Use a function in this class to challenge for credentials.
            AuthenticationManager.Current.ChallengeHandler = new ChallengeHandler(CreateCredentialAsync);

            // Set the OAuthAuthorizeHandler component (this class) for Android or iOS platforms.
#if __ANDROID__ || __IOS__
            AuthenticationManager.Current.OAuthAuthorizeHandler = this;
#endif
        }

        // ChallengeHandler function that will be called whenever access to a secured resource is attempted.
        public async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info)
        {
            Credential credential = null;

            try
            {
                // IOAuthAuthorizeHandler will challenge the user for OAuth credentials.
                credential = await AuthenticationManager.Current.GenerateCredentialAsync(info.ServiceUri);
            }
            catch (TaskCanceledException)
            {
                return credential;
            }
            catch (Exception)
            {
                // Exception will be reported in calling function.
                throw;
            }

            return credential;
        }

        #region IOAuthAuthorizationHandler implementation

        // Use a TaskCompletionSource to track the completion of the authorization.
        private TaskCompletionSource<IDictionary<string, string>> _taskCompletionSource;

        // IOAuthAuthorizeHandler.AuthorizeAsync implementation.
        public Task<IDictionary<string, string>> AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization may already be in progress and should be canceled.
            if (_taskCompletionSource != null)
            {
                // Try to cancel any existing authentication task.
                _taskCompletionSource.TrySetCanceled();
            }

            // Create a task completion source.
            _taskCompletionSource = new TaskCompletionSource<IDictionary<string, string>>();
#if __ANDROID__ || __IOS__

#if __ANDROID__
            // Get the current Android Activity.
            Activity activity = (Activity)ArcGISRuntime.Droid.MainActivity.Instance;
#endif
#if __IOS__
            // Get the current iOS ViewController.
            UIViewController viewController = null;
            Device.BeginInvokeOnMainThread(() => { viewController = UIApplication.SharedApplication.KeyWindow.RootViewController; });
#endif
            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in.
            OAuth2Authenticator authenticator = new OAuth2Authenticator(
                clientId: AppClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: callbackUri)
            {
                ShowErrors = false,
                // Allow the user to cancel the OAuth attempt.
                AllowCancel = true
            };

            // Define a handler for the OAuth2Authenticator.Completed event.
            authenticator.Completed += (sender, authArgs) =>
            {
                try
                {
#if __IOS__
                    // Dismiss the OAuth UI when complete.
                    viewController.DismissViewController(true, null);
#endif

                    // Check if the user is authenticated.
                    if (authArgs.IsAuthenticated)
                    {
                        // If authorization was successful, get the user's account.
                        Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                        // Set the result (Credential) for the TaskCompletionSource.
                        _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                    }
                    else
                    {
                        throw new Exception("Unable to authenticate user.");
                    }
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource.
                    _taskCompletionSource.TrySetException(ex);

                    // Cancel authentication.
                    authenticator.OnCancelled();
                }
                finally
                {
                    // Dismiss the OAuth login.
#if __ANDROID__
                    activity.FinishActivity(99);
#endif
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource.
            authenticator.Error += (sndr, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first.
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    // Login canceled: dismiss the OAuth login.
                    if (_taskCompletionSource != null)
                    {
                        _taskCompletionSource.TrySetCanceled();
#if __ANDROID__
                        activity.FinishActivity(99);
#endif
                    }
                }

                // Cancel authentication.
                authenticator.OnCancelled();
            };

            // Present the OAuth UI so the user can enter user name and password.
#if __ANDROID__
            Android.Content.Intent intent = authenticator.GetUI(activity);
            activity.StartActivityForResult(intent, 99);
#endif
#if __IOS__
            // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password.
            Device.BeginInvokeOnMainThread(() => { viewController.PresentViewController(authenticator.GetUI(), true, null); });
#endif

#endif // (If Android or iOS)
            // Return completion source task so the caller can await completion.
            return _taskCompletionSource.Task;
        }

        #endregion IOAuthAuthorizationHandler implementation

        #endregion Authentication
    }
}
XAML
<?xml version="1.0" encoding="utf-8" ?>

<ContentPage x:Class="ArcGISRuntimeXamarin.Samples.GenerateOfflineMapWithOverrides.ConfigureOverridesPage" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" Title="Configure offline map job">
    <Grid Margin="10" VerticalOptions="Center">
        <Grid.Resources>
            <Style TargetType="Label">
                <Setter Property="Margin" Value="0,0,0,5" />
                <Setter Property="VerticalOptions" Value="Center" />
            </Style>
            <Style TargetType="Entry">
                <Setter Property="Margin" Value="0,0,0,5" />
            </Style>
            <Style TargetType="Switch">
                <Setter Property="Margin" Value="0,0,0,5" />
            </Style>
        </Grid.Resources>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Label Grid.Row="0" Grid.Column="0" FontAttributes="Bold" Text="Adjust the basemap" />
        <Label Grid.Row="1" Grid.Column="0" Text="Min scale:" />
        <Slider
            x:Name="MinScaleEntry"
            Grid.Row="1"
            Grid.Column="1"
            Maximum="23"
            MaximumTrackColor="CadetBlue"
            Minimum="0"
            MinimumTrackColor="CadetBlue"
            Value="0" />
        <Label Grid.Row="1" Grid.Column="2" Text="{Binding Source={x:Reference MinScaleEntry}, Path=Value, StringFormat='{0:N0}'}" />
        <Label Grid.Row="2" Grid.Column="0" Text="Max scale:" />
        <Slider
            x:Name="MaxScaleEntry"
            Grid.Row="2"
            Grid.Column="1"
            Maximum="23"
            MaximumTrackColor="CadetBlue"
            Minimum="0"
            MinimumTrackColor="CadetBlue"
            Value="23" />
        <Label Grid.Row="2" Grid.Column="2" Text="{Binding Source={x:Reference MaxScaleEntry}, Path=Value, StringFormat='{0:N0}'}" />
        <Label Grid.Row="3" Grid.Column="0" Text="Buffer distance:" />
        <Slider
            x:Name="ExtentBufferEntry"
            Grid.Row="3"
            Grid.Column="1"
            Maximum="500"
            MaximumTrackColor="CadetBlue"
            Minimum="0"
            MinimumTrackColor="CadetBlue"
            Value="250" />
        <Label Grid.Row="3" Grid.Column="2" Text="{Binding Source={x:Reference ExtentBufferEntry}, Path=Value, StringFormat='{0:N0}m'}" />
        <Label Grid.Row="4" Grid.Column="0" FontAttributes="Bold" Text="Choose layers" />
        <Label Grid.Row="5" Grid.Column="0" Text="System valves:" />
        <Switch x:Name="SysValvesLayerCheckbox" Grid.Row="5" Grid.Column="2" IsToggled="True" />
        <Label Grid.Row="6" Grid.Column="0" Text="Service connections:" />
        <Switch x:Name="ServiceConnCheckbox" Grid.Row="6" Grid.Column="2" />
        <Label
            Grid.Row="7"
            Grid.Column="0"
            Margin="0,0,0,5"
            FontAttributes="Bold"
            Text="Apply a feature layer filer" />
        <Label Grid.Row="8" Grid.Column="0" Margin="0,0,5,5" Text="Min Flow Rate:" />
        <Slider
            x:Name="FlowRateFilterEntry"
            Grid.Row="8"
            Grid.Column="1"
            Maximum="999"
            MaximumTrackColor="CadetBlue"
            Minimum="0"
            MinimumTrackColor="CadetBlue"
            Value="500" />
        <Label Grid.Row="8" Grid.Column="2" MinimumWidthRequest="40" Text="{Binding Source={x:Reference FlowRateFilterEntry}, Path=Value, StringFormat='{0:N0} GPM'}" />
        <Label Grid.Row="9" Grid.Column="0" FontAttributes="Bold" Text="Crop layers to extent" />
        <Label Grid.Row="10" Grid.Column="0" Text="Water pipes:" />
        <Switch x:Name="CropLayerCheckbox" Grid.Row="10" Grid.Column="2" IsToggled="True" />
        <Button
            Grid.Row="11"
            Grid.Column="0"
            Grid.ColumnSpan="3"
            Clicked="TakeMapOffline_Clicked"
            IsEnabled="True"
            Text="Take map offline" />
    </Grid>
</ContentPage>
XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"             
             xmlns:esriUI="clr-namespace:Esri.ArcGISRuntime.Xamarin.Forms;assembly=Esri.ArcGISRuntime.Xamarin.Forms"
             xmlns:mapping="clr-namespace:Esri.ArcGISRuntime.Mapping;assembly=Esri.ArcGISRuntime" 
             x:Class="ArcGISRuntimeXamarin.Samples.GenerateOfflineMapWithOverrides.GenerateOfflineMapWithOverrides">
  <Grid>
        <esriUI:MapView x:Name="MyMapView"/>

        <Frame x:Name="takeOfflineArea" 
               BackgroundColor="White" BorderColor="Black"
               HorizontalOptions="End" VerticalOptions="Start"
               Margin="30" Padding="20" WidthRequest="375">
            <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
                <Button x:Name="TakeMapOfflineButton" 
                        WidthRequest="250"
                        Clicked="TakeMapOfflineButton_Click" 
                        IsEnabled="True" 
                        Text="Take map offline"/>
            </StackLayout>
        </Frame>

        <Frame x:Name="messageArea" 
               IsVisible="False"
               BackgroundColor="White" BorderColor="Black"
               HorizontalOptions="End" VerticalOptions="Start"
               Margin="30" Padding="5" WidthRequest="450">
            <StackLayout>
                <Label HorizontalOptions="Center" VerticalOptions="Center" Margin="10"
                       Text="Map is offline!"/>
            </StackLayout>
        </Frame>

        <Grid x:Name="busyIndicator" BackgroundColor="#807f7f7f" IsVisible="False">
            <Grid HorizontalOptions="Center" VerticalOptions="Center">
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto"/>
                    <RowDefinition Height="auto"/>
                    <RowDefinition Height="auto"/>
                </Grid.RowDefinitions>
                <Label HorizontalOptions="Center" VerticalOptions="Center" Margin="10"
                       TextColor="White" FontSize="18">
                    <Label.FormattedText>
                        <FormattedString>
                            <Span Text="Generating offline map... "/>
                            <Span x:Name="Percentage" Text=""/>
                        </FormattedString>
                    </Label.FormattedText>
                </Label>
                <ProgressBar x:Name="progressBar"
                             Grid.Row="1"
                             IsEnabled="True"
                             HorizontalOptions="Center" VerticalOptions="Center" 
                             WidthRequest="100" HeightRequest="10" Margin="0,0,0,10"/>
                <Button x:Name="CancelJobButton" 
                        Grid.Row="3"
                        Text="Cancel" 
                        Clicked="CancelJobButton_Click" 
                        HorizontalOptions="Center" 
                        WidthRequest="100"/>
            </Grid>
        </Grid>
        <Grid x:Name="loadingIndicator" 
              BackgroundColor="#807f7f7f" 
              IsVisible="True">
            <Grid HorizontalOptions="Center" VerticalOptions="Center">
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto"/>
                    <RowDefinition Height="auto"/>
                </Grid.RowDefinitions>
                <Label Text="Loading online map..." 
                           TextColor="White" FontSize="18"
                           Margin="10"/>
                <ProgressBar Grid.Row="1"
                             IsEnabled="True"
                             WidthRequest="100" HeightRequest="10" 
                             HorizontalOptions="Center" VerticalOptions="Center"/>
            </Grid>
        </Grid>
    </Grid>
</ContentPage>
See Also
Additional Examples
Hyperlink to ExampleDescription
GenerateOfflineMapWithOverridesTake a web map offline with additional options for each layer.
GeodatabaseTransactionsUse transactions to manage how changes are committed to a geodatabase.