Generate offline map (overrides)

View inWPFUWPFormsiOSAndroid
View on GitHub

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

Image of generate offline map overrides

Use case

When taking a web map offline, you may adjust the data (such as layers or tiles) that is downloaded by using custom parameter overrides. This can be used to reduce the extent of the map or the download size of the offline map. It can also be used to highlight specific data by removing irrelevant data. Additionally, this workflow allows you to take features offline that don't have a geometry - for example, features whose attributes have been populated in the office, but still need a site survey for their geometry.

How to use the sample

Modify the overrides parameters:

  • Use the min/max scale input fields to adjust the level IDs to be taken offline for the streets basemap.
  • Use the extent buffer distance input field to set the buffer radius for the streets basemap.
  • Check the checkboxes for the feature operational layers you want to include in the offline map.
  • Use the min hydrant flow rate input field to only download features with a flow rate higher than this value.
  • Select the "Water Pipes" checkbox if you want to crop the water pipe features to the extent of the map.

After you have set up the overrides to your liking, tap the "Generate offline map" button to start the download. A progress bar will display. Tap the "Cancel" button if you want to stop the download. When the download is complete, the view will display the offline map. Pan around to see that it is cropped to the download area's extent.

How it works

  1. Load a web map from a PortalItem. Authenticate with the portal if required.
  2. Create an OfflineMapTask with the map.
  3. Generate default task parameters using the extent area you want to download with offlineMapTask.CreateDefaultGenerateOfflineMapParametersAsync(extent).
  4. Generate additional "override" parameters using the default parameters with offlineMapTask.CreateGenerateOfflineMapParameterOverridesAsync(parameters).
  5. For the basemap:

    • Get the parameters OfflineMapParametersKey for the basemap layer.
    • Get the ExportTileCacheParameters for the basemap layer with overrides.ExportTileCacheParameters[basemapParamKey].
    • Set the level IDs you want to download with exportTileCacheParametersLevelIDs().Add(levelID).
    • To buffer the extent, set the exportTileCacheParameters.AreaOfInterest property. B uffered geometry can be calculated with the GeometryEngine.
  6. To remove operational layers from the download:

    • Create a OfflineParametersKey with the operational layer.
    • Get the generate geodatabase layer options using the key with List<GenerateLayerOption> layerOptions = overrides.GenerateGeodatabaseParameters[key].LayerOptions;
    • Loop through each GenerateLayerOption in the the list, and remove it if the layer option's ID matches the layer's ID.
  7. To filter the features downloaded in an operational layer:

    • Get the layer options for the operational layer using the directions in step 6.
    • Loop through the layer options. If the option LayerID matches the layer's ID, set the filter clause with layerOption.WhereClause property and set the query option with layerOption.QueryOption property.
  8. To not crop a layer's features to the extent of the offline map (default is true):

    • Set the layerOption.UseGeometry property to false.
  9. Create a GenerateOfflineMapJob with offlineMapTask.GenerateOfflineMap(parameters, downloadPath, overrides).
  10. Get a reference to the offline map with job.GetResultAsync()

Relevant API

  • ExportTileCacheParameters
  • GenerateGeodatabaseParameters
  • GenerateLayerOption
  • GenerateOfflineMapJob
  • GenerateOfflineMapParameterOverrides
  • GenerateOfflineMapParameters
  • GenerateOfflineMapResult
  • OfflineMapParametersKey
  • OfflineMapTask

Additional information

For applications where you just need to take all layers offline, use the standard workflow (using only GenerateOfflineMapParameters). For a simple example of how you take a map offline, please consult the "Generate offline map" sample.

Tags

adjust, download, extent, filter, LOD, offline, override, parameters, reduce, scale range, setting

Sample Code

GenerateOfflineMapWithOverrides.cs
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
// 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 ArcGISRuntime;
using CoreGraphics;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.Security;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks;
using Esri.ArcGISRuntime.Tasks.Offline;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using UIKit;
using Xamarin.Auth;

namespace ArcGISRuntimeXamarin.Samples.GenerateOfflineMapWithOverrides
{
    [Register("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 class GenerateOfflineMapWithOverrides : UIViewController, IOAuthAuthorizeHandler
    {
        // Hold references to UI controls.
        private MapView _myMapView;
        private UIActivityIndicatorView _loadingIndicator;
        private UIBarButtonItem _takeMapOfflineButton;
        private UILabel _statusLabel;
        private ConfigureOverridesViewController _overridesVC;
        private OAuth2Authenticator _auth;

        // Class-scope variables needed because job continues after configuration by separate class.
        private OfflineMapTask _takeMapOfflineTask;
        private GenerateOfflineMapParameters _parameters;
        private GenerateOfflineMapParameterOverrides _overrides;
        private string _packagePath;

        // The job to generate an offline map.
        private GenerateOfflineMapJob _generateOfflineMapJob;

        // The extent of the data to take offline.
        private readonly 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()
        {
            Title = "Generate offline map (overrides)";
        }

        private async void Initialize()
        {
            try
            {
                // Start the loading indicator.
                _loadingIndicator.StartAnimating();

                // 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.StopAnimating();
            }
            catch (Exception ex)
            {
                // Show the exception message to the user.
                UIAlertController messageAlert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }
        }

        private void ShowConfigurationWindow(GenerateOfflineMapParameterOverrides overrides)
        {
            if (_overridesVC == null)
            {
                _overridesVC = new ConfigureOverridesViewController(overrides, _myMapView.Map);
            }

            // Show the layer list popover. Note: most behavior is managed by the table view & its source. See MapViewModel.
            var controller = new UINavigationController(_overridesVC);
            controller.Title = "Override parameters";
            // Show a close button in the top right.
            var closeButton = new UIBarButtonItem("Close", UIBarButtonItemStyle.Plain, (o, ea) => controller.DismissViewController(true, null));
            controller.NavigationBar.Items[0].SetRightBarButtonItem(closeButton, false);
            // Show the table view in a popover.
            controller.ModalPresentationStyle = UIModalPresentationStyle.Popover;
            controller.PreferredContentSize = new CGSize(300, 250);
            UIPopoverPresentationController pc = controller.PopoverPresentationController;
            if (pc != null)
            {
                pc.BarButtonItem = (UIBarButtonItem)_takeMapOfflineButton;
                pc.PermittedArrowDirections = UIPopoverArrowDirection.Down;
                pc.Delegate = new ppDelegate();
            }

            PresentViewController(controller, true, null);
        }

        private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
        {
            // Make sure the user is logged in.
            /*
            bool loggedIn = await EnsureLoggedInAsync();
            if (!loggedIn)
            {
                return;
            }
            */

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

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

            // Create a path for the output mobile map.
            string tempPath = $"{Path.GetTempPath()}";
            string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");

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

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

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

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

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

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

                // Generate parameter overrides for more in-depth control of the job.
                _overrides = await _takeMapOfflineTask.CreateGenerateOfflineMapParameterOverridesAsync(_parameters);

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

                // Finish work once the user has configured the override.
                _overridesVC.FinishedConfiguring += ConfigurationContinuation;
            }
            catch (TaskCanceledException)
            {
                // Generate offline map task was canceled.
                UIAlertController messageAlert = UIAlertController.Create("Canceled", "Taking map offline was canceled", UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                UIAlertController messageAlert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }
            finally
            {
                // Hide the loading overlay when the job is done.
                _loadingIndicator.StopAnimating();
            }
        }

        private async void ConfigurationContinuation()
        {
            // Hide the configuration UI.
            _overridesVC.DismissViewController(true, null);

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

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

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

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

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

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

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

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

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

            // Change the title and disable the "Take map offline" button.
            _statusLabel.Text = "Map is offline";
            _takeMapOfflineButton.Enabled = false;
        }

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

            // Dispatch to the UI thread.
            InvokeOnMainThread(() =>
            {
                // Show the percent complete and update the progress bar.
                _statusLabel.Text = $"Taking map offline ({job.Progress}%) ...";
            });
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            Initialize();
        }

        public override void LoadView()
        {
            // Create the views.
            View = new UIView { BackgroundColor = ApplicationTheme.BackgroundColor };

            _myMapView = new MapView();
            _myMapView.TranslatesAutoresizingMaskIntoConstraints = false;

            _takeMapOfflineButton = new UIBarButtonItem();
            _takeMapOfflineButton.Title = "Generate offline map";

            UIToolbar toolbar = new UIToolbar();
            toolbar.TranslatesAutoresizingMaskIntoConstraints = false;
            toolbar.Items = new[]
            {
                new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
                _takeMapOfflineButton
            };

            _statusLabel = new UILabel
            {
                Text = "Use the button to take the map offline.",
                AdjustsFontSizeToFitWidth = true,
                TextAlignment = UITextAlignment.Center,
                BackgroundColor = UIColor.FromWhiteAlpha(0, .6f),
                TextColor = UIColor.White,
                Lines = 1,
                TranslatesAutoresizingMaskIntoConstraints = false
            };

            _loadingIndicator = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.WhiteLarge);
            _loadingIndicator.TranslatesAutoresizingMaskIntoConstraints = false;
            _loadingIndicator.BackgroundColor = UIColor.FromWhiteAlpha(0, .6f);

            // Add the views.
            View.AddSubviews(_myMapView, toolbar, _loadingIndicator, _statusLabel);

            // Lay out the views.
            NSLayoutConstraint.ActivateConstraints(new[]
            {
                _myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
                _myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
                _myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
                _myMapView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor),

                toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
                toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
                toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor),

                _statusLabel.TopAnchor.ConstraintEqualTo(_myMapView.TopAnchor),
                _statusLabel.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
                _statusLabel.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
                _statusLabel.HeightAnchor.ConstraintEqualTo(40),

                _loadingIndicator.TopAnchor.ConstraintEqualTo(_statusLabel.BottomAnchor),
                _loadingIndicator.BottomAnchor.ConstraintEqualTo(View.BottomAnchor),
                _loadingIndicator.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
                _loadingIndicator.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor)
            });
        }

        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            // Subscribe to events.
            _takeMapOfflineButton.Clicked += TakeMapOfflineButton_Click;

            if (_overridesVC != null) _overridesVC.FinishedConfiguring += ConfigurationContinuation;
            if (_generateOfflineMapJob != null) _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;
        }

        public override void ViewDidDisappear(bool animated)
        {
            base.ViewDidDisappear(animated);

            // Unsubscribe from events, per best practice.
            if (_generateOfflineMapJob != null) _generateOfflineMapJob.ProgressChanged -= OfflineMapJob_ProgressChanged;
            if (_overridesVC != null) _overridesVC.FinishedConfiguring -= ConfigurationContinuation;
            _takeMapOfflineButton.Clicked -= TakeMapOfflineButton_Click;
        }

        #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 = @"2Gh53JRzkPtOENQq";

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

        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.
            AuthenticationManager.Current.OAuthAuthorizeHandler = this;
        }

        // ChallengeHandler function that will be called whenever access to a secured resource is attempted.
        private 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.
            // Try to cancel any existing authentication process.
            _taskCompletionSource?.TrySetCanceled();

            // Create a task completion source.
            _taskCompletionSource = new TaskCompletionSource<IDictionary<string, string>>();

            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in.
            _auth = new OAuth2Authenticator(
                clientId: AppClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: new Uri(OAuthRedirectUrl))
            {
                ShowErrors = false,
                // Allow the user to cancel the OAuth attempt.
                AllowCancel = true
            };

            // Define a handler for the OAuth2Authenticator.Completed event.
            _auth.Completed += (o, authArgs) =>
            {
                try
                {
                    // Dismiss the OAuth UI when complete.
                    InvokeOnMainThread(() => { UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null); });

                    // 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.
                    _auth.OnCancelled();
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource.
            _auth.Error += (o, 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.
                    _taskCompletionSource?.TrySetCanceled();
                }

                // Cancel authentication.
                _auth.OnCancelled();
                _auth = null;
            };

            // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password.
            InvokeOnMainThread(() => { UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(_auth.GetUI(), true, null); });

            // Return completion source task so the caller can await completion.
            return _taskCompletionSource.Task;
        }

        #endregion IOAuthAuthorizationHandler implementation

        #endregion Authentication

        // Force popover to display on iPhone.
        private class ppDelegate : UIPopoverPresentationControllerDelegate
        {
            public override UIModalPresentationStyle GetAdaptivePresentationStyle(
                UIPresentationController forPresentationController) => UIModalPresentationStyle.None;

            public override UIModalPresentationStyle GetAdaptivePresentationStyle(UIPresentationController controller,
                UITraitCollection traitCollection) => UIModalPresentationStyle.None;
        }
    }

    public class ConfigureOverridesViewController : UIViewController
    {
        // Hold references to the overrides and the map.
        private GenerateOfflineMapParameterOverrides _overrides;
        private Map _map;
        private UIButton _takeOfflineButton;
        private readonly Envelope _areaOfInterest = new Envelope(-88.1541, 41.7690, -88.1471, 41.7720, SpatialReferences.Wgs84);

        // Hold state from UI selections.
        private int _minScale = 0;
        private int _maxScale = 23;
        private int _bufferExtent = 0;
        private int _flowRate = 500;
        private bool _includeServiceConn;
        private bool _includeSystemValues;
        private bool _cropWaterPipes;

        public ConfigureOverridesViewController(GenerateOfflineMapParameterOverrides overrides, Map map)
        {
            _overrides = overrides;
            _map = map;
            Title = "Parameter overrides";
        }

        private void ConfigureOverrides()
        {
            ConfigureTileLayerOverrides();
            ConfigureLayerExclusion();
            CropWaterPipes();
            ApplyFeatureFilter();
        }

        #region overrides

        private void ConfigureTileLayerOverrides()
        {
            // 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();

            // 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.
            basemapParams.AreaOfInterest = GeometryEngine.BufferGeodetic(_areaOfInterest, _bufferExtent, LinearUnits.Meters);
        }

        private void ConfigureLayerExclusion()
        {
            // Apply layer exclusions as specified in the UI.
            if (!_includeServiceConn)
            {
                ExcludeLayerByName("Service Connection");
            }

            if (!_includeSystemValues)
            {
                ExcludeLayerByName("System Valve");
            }
        }

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

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

        private void ApplyFeatureFilter()
        {
            // For each layer option.
            foreach (GenerateLayerOption option in GetAllLayerOptions())
            {
                // If the option's LayerId matches the selected layer's ID.
                if (option.LayerId == GetServiceLayerId(GetLayerByName("Hydrant")))
                {
                    // Apply the where clause.
                    option.WhereClause = $"FLOW >= {_flowRate}";

                    // Configure the option to use the where clause.
                    option.QueryOption = GenerateLayerQueryOption.UseFilter;
                }
            }
        }

        private IList<GenerateLayerOption> GetAllLayerOptions()
        {
            // 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)
        {
            // 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

        public override void ViewWillDisappear(bool animated)
        {
            // This is called when the popover closes for any reason.
            ConfigureOverrides();
            FinishedConfiguring?.Invoke();
            base.ViewWillDisappear(animated);
        }

        public override void LoadView()
        {
            // Create the views.
            View = new UIView { BackgroundColor = ApplicationTheme.BackgroundColor };

            UIScrollView outerScroller = new UIScrollView();
            outerScroller.TranslatesAutoresizingMaskIntoConstraints = false;

            UIStackView outerStackView = new UIStackView();
            outerStackView.TranslatesAutoresizingMaskIntoConstraints = false;
            outerStackView.Axis = UILayoutConstraintAxis.Horizontal;
            outerStackView.Alignment = UIStackViewAlignment.Center;
            outerStackView.Distribution = UIStackViewDistribution.Fill;

            UIStackView innerStackView = new UIStackView();
            innerStackView.TranslatesAutoresizingMaskIntoConstraints = false;
            innerStackView.Axis = UILayoutConstraintAxis.Vertical;
            innerStackView.Alignment = UIStackViewAlignment.Fill;
            innerStackView.Spacing = 5;

            outerStackView.AddArrangedSubview(innerStackView);

            innerStackView.AddArrangedSubview(getLabel("Configure basemap"));

            innerStackView.AddArrangedSubview(getSliderRow("Min scale: ", 0, 23, _minScale, "", (sender, args) => { _minScale = (int)((UISlider)sender).Value; }));

            innerStackView.AddArrangedSubview(getSliderRow("Max scale: ", 0, 23, _maxScale, "", (sender, args) => { _maxScale = (int)((UISlider)sender).Value; }));

            innerStackView.AddArrangedSubview(getSliderRow("Buffer dist.: ", 0, 500, _bufferExtent, "m", (sender, args) => { _bufferExtent = (int)((UISlider)sender).Value; }));

            innerStackView.AddArrangedSubview(getLabel("Include layers"));

            innerStackView.AddArrangedSubview(getCheckRow("System valves: ", (sender, args) => { _includeSystemValues = !_includeSystemValues; }));

            innerStackView.AddArrangedSubview(getCheckRow("Service connections: ", (sender, args) => { _includeServiceConn = !_includeServiceConn; }));

            innerStackView.AddArrangedSubview(getLabel("Filter feature layer"));

            innerStackView.AddArrangedSubview(getSliderRow("Min. flow: ", 0, 1000, _flowRate, "", (sender, args) => { _flowRate = (int)((UISlider)sender).Value; }));

            innerStackView.AddArrangedSubview(getLabel("Crop layer to extent"));

            innerStackView.AddArrangedSubview(getCheckRow("Water pipes: ", (sender, args) => _cropWaterPipes = !_cropWaterPipes));

            _takeOfflineButton = new UIButton();
            _takeOfflineButton.TranslatesAutoresizingMaskIntoConstraints = false;
            _takeOfflineButton.SetTitle("Take map offline", UIControlState.Normal);
            _takeOfflineButton.SetTitleColor(View.TintColor, UIControlState.Normal);
            innerStackView.AddArrangedSubview(_takeOfflineButton);

            // Add the views.
            View.AddSubview(outerScroller);
            outerScroller.AddSubview(outerStackView);

            // Lay out the views.
            NSLayoutConstraint.ActivateConstraints(new[]
            {
                outerScroller.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
                outerScroller.LeadingAnchor.ConstraintEqualTo(View.LayoutMarginsGuide.LeadingAnchor),
                outerScroller.TrailingAnchor.ConstraintEqualTo(View.LayoutMarginsGuide.TrailingAnchor),
                outerScroller.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor),
                outerStackView.LeadingAnchor.ConstraintEqualTo(outerScroller.LeadingAnchor),
                outerStackView.TrailingAnchor.ConstraintEqualTo(outerScroller.TrailingAnchor),
                outerStackView.TopAnchor.ConstraintEqualTo(outerScroller.TopAnchor),
                outerStackView.BottomAnchor.ConstraintEqualTo(outerScroller.BottomAnchor),
                outerStackView.WidthAnchor.ConstraintEqualTo(outerScroller.WidthAnchor)
            });
        }

        private void TakeOffline_Click(Object sender, EventArgs e) => DismissViewController(true, null);

        private UILabel getLabel(string text)
        {
            UILabel label = new UILabel();
            label.TranslatesAutoresizingMaskIntoConstraints = false;
            label.Text = text;
            label.Font = UIFont.BoldSystemFontOfSize(16);

            return label;
        }

        private UIStackView getSliderRow(string label, int min, int max, int startingValue, string units, EventHandler sliderChangeAction)
        {
            UIStackView rowView = new UIStackView();
            rowView.TranslatesAutoresizingMaskIntoConstraints = false;
            rowView.Axis = UILayoutConstraintAxis.Horizontal;
            rowView.Alignment = UIStackViewAlignment.Center;
            rowView.Distribution = UIStackViewDistribution.Fill;
            rowView.Spacing = 5;

            UILabel descriptionLabel = new UILabel();
            descriptionLabel.TranslatesAutoresizingMaskIntoConstraints = false;
            descriptionLabel.Text = label;
            descriptionLabel.WidthAnchor.ConstraintGreaterThanOrEqualTo(140).Active = true;
            descriptionLabel.SetContentCompressionResistancePriority((float)UILayoutPriority.Required, UILayoutConstraintAxis.Horizontal);
            rowView.AddArrangedSubview(descriptionLabel);

            UILabel valueLabel = new UILabel();
            valueLabel.TranslatesAutoresizingMaskIntoConstraints = false;
            valueLabel.Text = $"{startingValue}{units}";
            valueLabel.WidthAnchor.ConstraintEqualTo(60).Active = true;

            UISlider sliderView = new UISlider();
            sliderView.TranslatesAutoresizingMaskIntoConstraints = false;
            sliderView.MinValue = min;
            sliderView.MaxValue = max;
            sliderView.Value = startingValue;
            sliderView.WidthAnchor.ConstraintGreaterThanOrEqualTo(100).Active = true;
            sliderView.SetContentCompressionResistancePriority((float)UILayoutPriority.DefaultLow, UILayoutConstraintAxis.Horizontal);
            sliderView.ValueChanged += sliderChangeAction;
            sliderView.ValueChanged += (sender, args) => { valueLabel.Text = $"{(int)sliderView.Value}{units}"; };
            rowView.AddArrangedSubview(sliderView);

            rowView.AddArrangedSubview(valueLabel);

            return rowView;
        }

        private UIStackView getCheckRow(string label, EventHandler checkboxChecked)
        {
            UIStackView rowView = new UIStackView();
            rowView.TranslatesAutoresizingMaskIntoConstraints = false;
            rowView.Axis = UILayoutConstraintAxis.Horizontal;
            rowView.Alignment = UIStackViewAlignment.Center;
            rowView.Distribution = UIStackViewDistribution.Fill;
            rowView.Spacing = 5;
            rowView.LayoutMarginsRelativeArrangement = true;
            rowView.LayoutMargins = new UIEdgeInsets(0, 0, 0, 5);

            UILabel descriptionLabel = new UILabel();
            descriptionLabel.TranslatesAutoresizingMaskIntoConstraints = false;
            descriptionLabel.Text = label;
            rowView.AddArrangedSubview(descriptionLabel);

            UISwitch valueSwitch = new UISwitch();
            valueSwitch.TranslatesAutoresizingMaskIntoConstraints = false;
            valueSwitch.ValueChanged += checkboxChecked;
            rowView.AddArrangedSubview(valueSwitch);

            return rowView;
        }

        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            // Subscribe to events.
            _takeOfflineButton.TouchUpInside += TakeOffline_Click;
        }

        public override void ViewDidDisappear(bool animated)
        {
            base.ViewDidDisappear(animated);

            // Unsubscribe from events, per best practice.
            _takeOfflineButton.TouchUpInside -= TakeOffline_Click;
        }

        public delegate void CompletionEventHandler();

        public event CompletionEventHandler FinishedConfiguring;
    }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.