Add features with contingent values

View inMAUIWPFWinUIView on GitHub

Create and add features whose attribute values satisfy a predefined set of contingencies.

Add features with contingent values

Use case

Contingent values are a data design feature that allow you to make values in one field dependent on values in another field. Your choice for a value on one field further constrains the domain values that can be placed on another field. In this way, contingent values enforce data integrity by applying additional constraints to reduce the number of valid field inputs.

For example, a field crew working in a sensitive habitat area may be required to stay a certain distance away from occupied bird nests, but the size of that exclusion area differs depending on the bird's level of protection according to presiding laws. Surveyors can add points of bird nests in the work area and their selection of the size of the exclusion area will be contingent on the values in other attribute fields.

How to use the sample

Tap on the map to add a feature symbolizing a bird's nest. Then choose values describing the nest's status, protection, and buffer size. Notice how different values are available depending on the values of preceding fields. Once the contingent values are validated, tap "Done" to add the feature to the map.

How it works

  1. Create and load the Geodatabase from the mobile geodatabase location on file.
  2. Load the GeodatabaseFeatureTable.
  3. Load the ContingentValuesDefinition from the feature table with GeodatabaseFeatureTable.ContingentValuesDefinition.LoadAsync().
  4. Create a new FeatureLayer from the feature table and add it to the map.
  5. Create a new ArcGISFeature using GeodatabaseFeatureTable.CreateFeature().
  6. Add the new ArcGISFeature to the feature table using GeodatabaseFeatureTable.AddFeatureAsync(newFeature).
  7. After selecting a value from the initial coded values for the first field, retrieve the remaining valid contingent values for each field as you select the values for the attributes.
    i. Get the ContingentValueResults by using GeodatabaseFeatureTable.GetContingentValues(newFeature, fieldName) with the feature and the target field by name.
    ii. Get a list of valid ContingentValues from ContingentValuesResult.ContingentValuesByFieldGroup dictionary with the name of the relevant field group.
    iii. Iterate through the list of valid contingent values to create a list of ContingentCodedValue names or the minimum and maximum values of a ContingentRangeValue depending on the type of ContingentValue returned.
  8. Set the ArcGISFeature attribute values by name with ArcGISFeature.SetAttributeValue(fieldName, fieldValue).
  9. Validate the feature's contingent values by using GeodatabaseFeatureTable.ValidateContingencyConstraints(newFeature) with the created feature. If the resulting list is empty, the selected values are valid.

Relevant API

  • CodedValue
  • CodedValueDomain
  • ContingencyConstraintViolation
  • ContingentCodedValue
  • ContingentRangeValue
  • ContingentValuesDefinition
  • ContingentValuesResult
  • FeatureTable

Offline data

This sample uses the Contingent values birds nests mobile geodatabase and the Fillmore topographic map vector tile package for the basemap.

About the data

The mobile geodatabase contains birds nests in the Fillmore area, defined with contingent values. Each feature contains information about its status, protection, and buffer size.

Additional information

Learn more about contingent values and how to utilize them on the ArcGIS Pro documentation.

Tags

coded values, contingent values, feature table, geodatabase

Sample Code

AddFeaturesWithContingentValues.xaml.csAddFeaturesWithContingentValues.xaml.csAddFeaturesWithContingentValues.xaml
Use dark colors for code blocksCopy
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
// Copyright 2022 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 ArcGIS.Samples.Managers;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;

namespace ArcGIS.Samples.AddFeaturesWithContingentValues
{
    [ArcGIS.Samples.Shared.Attributes.Sample(
        name: "Add features with contingent values",
        category: "Data",
        description: "Create and add features whose attribute values satisfy a predefined set of contingencies.",
        instructions: "Tap on the map to add a feature symbolizing a bird's nest. Then choose values describing the nest's status, protection, and buffer size. Notice how different values are available depending on the values of preceding fields. Once the contingent values are validated, tap \"Done\" to add the feature to the map.",
        tags: new[] { "coded values", "contingent values", "feature table", "geodatabase" })]
    [ArcGIS.Samples.Shared.Attributes.OfflineData("e12b54ea799f4606a2712157cf9f6e41", "b5106355f1634b8996e634c04b6a930a")]
    public partial class AddFeaturesWithContingentValues : ContentPage
    {
        // The coded value domains in this sample are hardcoded for simplicity, but can be retrieved from the GeodatabaseFeatureTable's Field's Domains.
        private readonly Dictionary<string, string> _statusValues = new Dictionary<string, string>() { { "Occupied", "OCCUPIED" }, { "Unoccupied", "UNOCCUPIED" } };
        private readonly Dictionary<string, string> _protectionValues = new Dictionary<string, string>() { { "Endangered", "ENDANGERED" }, { "Not endangered", "NOT_ENDANGERED" }, { "N/A", "NA" } };

        // Hold references for use in event handlers.
        private GeodatabaseFeatureTable _geodatabaseFeatureTable;
        private GraphicsOverlay _graphicsOverlay;
        private ArcGISFeature _newFeature;

        public AddFeaturesWithContingentValues()
        {
            InitializeComponent();
            _ = Initialize();
        }

        private async Task Initialize()
        {
            #region Basemap

            // Get the full path for the vector tile package.
            string vectorTilePackagePath = DataManager.GetDataFolder("b5106355f1634b8996e634c04b6a930a", "FillmoreTopographicMap.vtpk");

            // Open the vector tile package.
            ArcGISVectorTiledLayer fillmoreVectorTiledLayer = new ArcGISVectorTiledLayer(new Uri(vectorTilePackagePath));

            // Load the basemap from the ArcGISVectorTiledLayer.
            Basemap fillmoreBasemap = new Basemap(fillmoreVectorTiledLayer);

            // Add the base map to the map view.
            MyMapView.Map = new Map(fillmoreBasemap);

            #endregion Basemap

            #region FeatureLayer

            // Get the full path for the mobile geodatabase.
            string geodatabasePath = DataManager.GetDataFolder("e12b54ea799f4606a2712157cf9f6e41", "ContingentValuesBirdNests.geodatabase");

            // Load the geodatabase.
            Geodatabase geodatabase = await Geodatabase.OpenAsync(geodatabasePath);

            // Load the Geodatabase, GeodatabaseFeatureTable and the ContingentValuesDefinition.
            // Get the 'BirdNests' geodatabase feature table from the mobile geodatabase.
            _geodatabaseFeatureTable = geodatabase.GetGeodatabaseFeatureTable("BirdNests");

            // Asynchronously load the 'BirdNests' geodatabase feature table.
            await _geodatabaseFeatureTable.LoadAsync();

            // Asynchronously load the contingent values definition.
            await _geodatabaseFeatureTable.ContingentValuesDefinition.LoadAsync();

            // Create a FeatureLayer based on the GeoDatabaseFeatureTable.
            FeatureLayer nestLayer = new FeatureLayer(_geodatabaseFeatureTable);

            // Add the FeatureLayer to the OperationalLayers.
            MyMapView.Map.OperationalLayers.Add(nestLayer);

            #endregion FeatureLayer

            #region GraphicsOverlay

            // Create the GraphicsOverlay with which to display the nest buffer exclusion areas.
            _graphicsOverlay = new GraphicsOverlay();
            Symbol bufferSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.ForwardDiagonal, System.Drawing.Color.Red, new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Black, 2));
            _graphicsOverlay.Renderer = new SimpleRenderer(bufferSymbol);
            MyMapView.GraphicsOverlays.Add(_graphicsOverlay);

            // Query all the features that have a buffer size greater than zero and render a graphic that depicts the buffer.
            await QueryAndBufferFeatures();

            #endregion GraphicsOverlay

            #region Initialize UI components

            // Zoom the map to the extent of the FeatureLayer.
            await MyMapView.SetViewpointGeometryAsync(nestLayer.FullExtent, 50);

            StatusPicker.ItemsSource = _statusValues.Keys.ToList();
            FeatureAttributesPopup.IsVisible = false;
            FeatureAttributesPopup.PropertyChanged += FeatureAttributesPopup_PropertyChanged;

            #endregion Initialize UI components
        }

        #region AddFeature

        private async Task QueryAndBufferFeatures()
        {
            if (_geodatabaseFeatureTable == null || _geodatabaseFeatureTable.LoadStatus != Esri.ArcGISRuntime.LoadStatus.Loaded) return;

            try
            {
                // Clear the existing buffer graphics.
                _graphicsOverlay.Graphics.Clear();

                // Get all the features that have buffer size greater than zero.
                QueryParameters parameters = new QueryParameters();
                parameters.WhereClause = "BufferSize > 0";
                FeatureQueryResult results = await _geodatabaseFeatureTable.QueryFeaturesAsync(parameters);

                // Add a buffer graphic for each feature based on the above query.
                foreach (Feature feature in results.ToList())
                {
                    double bufferDistance = Convert.ToDouble(feature.GetAttributeValue("BufferSize"));
                    Geometry buffer = feature.Geometry.Buffer(bufferDistance);
                    MyMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(buffer));
                }
            }
            catch (Exception e)
            {
                await Application.Current.MainPage.DisplayAlert("Error", e.Message, "OK");
            }
        }

        private async Task CreateNewEmptyFeature(Esri.ArcGISRuntime.Maui.GeoViewInputEventArgs e)
        {
            try
            {
                // Create a new empty feature to define attributes for.
                _newFeature = (ArcGISFeature)_geodatabaseFeatureTable.CreateFeature();

                // Get the normalized geometry for the tapped location and use it as the feature's geometry.
                MapPoint tappedPoint = (MapPoint)e.Location.NormalizeCentralMeridian();
                _newFeature.Geometry = tappedPoint;

                // Add the feature to the table.
                await _geodatabaseFeatureTable.AddFeatureAsync(_newFeature);

                // Update the feature to get the updated objectid - a temporary ID is used before the feature is added.
                _newFeature.Refresh();

                if (!FeatureAttributesPopup.IsVisible)
                {
                    FeatureAttributesPopup.IsVisible = true;
                }
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK");
            }
        }

        private async Task<List<string>> GetContingentValues(string field, string fieldGroupName)
        {
            // Create an empty list with which to return the valid contingent values.
            List<string> contingentValuesNamesList = new List<string>();

            if (_geodatabaseFeatureTable.ContingentValuesDefinition.LoadStatus != Esri.ArcGISRuntime.LoadStatus.Loaded) return contingentValuesNamesList;

            try
            {
                // Instantiate a dictionary containing all possible values for a field in the context of the contingent field groups it participates in.
                ContingentValuesResult contingentValuesResult = _geodatabaseFeatureTable.GetContingentValues(_newFeature, field);

                // Loop through the contingent values.
                foreach (ContingentValue contingentValue in contingentValuesResult.ContingentValuesByFieldGroup[fieldGroupName])
                {
                    // Contingent coded values are contingent values defined from a coded value domain.
                    // There are often multiple results returned by the ContingentValuesResult.
                    if (contingentValue is ContingentCodedValue contingentCodedValue)
                    {
                        contingentValuesNamesList.Add(contingentCodedValue.CodedValue.Name);
                    }
                    else if (contingentValue is ContingentRangeValue contingentRangeValue)
                    {
                        contingentValuesNamesList.Add(contingentRangeValue.MinValue.ToString());
                        contingentValuesNamesList.Add(contingentRangeValue.MaxValue.ToString());
                    }
                }
            }
            catch (Exception e)
            {
                await Application.Current.MainPage.DisplayAlert("Error", e.Message, "OK");
            }

            return contingentValuesNamesList;
        }

        private bool ValidateContingentValues(out List<string> fieldGroupNames, out int numberOfViolations)
        {
            fieldGroupNames = new List<string>();
            numberOfViolations = 0;

            if (_geodatabaseFeatureTable.ContingentValuesDefinition.LoadStatus != Esri.ArcGISRuntime.LoadStatus.Loaded || _newFeature == null) return false;

            IReadOnlyList<ContingencyConstraintViolation> contingencyConstraintViolations = _geodatabaseFeatureTable.ValidateContingencyConstraints(_newFeature);
            numberOfViolations = contingencyConstraintViolations.Count;

            // If the number of contingency constraint violations is zero the attribute map satisfies all contingencies.
            if (numberOfViolations.Equals(0))
            {
                return true;
            }
            else
            {
                foreach (ContingencyConstraintViolation violation in contingencyConstraintViolations)
                {
                    fieldGroupNames.Add(violation.FieldGroup.Name);
                }
            }

            return false;
        }

        private async Task CreateNewNest()
        {
            // Once the attribute map is filled and validated, save the feature to the geodatabase feature table.
            await _geodatabaseFeatureTable.UpdateFeatureAsync(_newFeature);

            _ = QueryAndBufferFeatures();

            _newFeature = null;
        }

        private async Task DiscardFeature()
        {
            try
            {
                // Delete the newly created feature from the geodatabase feature table.
                await _geodatabaseFeatureTable.DeleteFeatureAsync(_newFeature);

                _newFeature = null;
            }
            catch (Exception e)
            {
                await Application.Current.MainPage.DisplayAlert("Error", e.Message, "OK");
            }
        }

        private async Task UpdateField(string field, object value)
        {
            try
            {
                // Update the feature's appropriate attribute based on a given field name and a value.
                switch (field)
                {
                    case "Status":
                        _newFeature.SetAttributeValue(field, _statusValues[value.ToString()]);
                        break;

                    case "Protection":
                        _newFeature.SetAttributeValue(field, _protectionValues[value.ToString()]);
                        break;

                    case "BufferSize":
                        _newFeature.SetAttributeValue(field, Convert.ToInt32(value));
                        break;

                    default:
                        await Application.Current.MainPage.DisplayAlert("Error", $"{field} not found in any of the data dictionaries.", "OK");
                        break;
                }
            }
            catch (Exception e)
            {
                await Application.Current.MainPage.DisplayAlert("Error", e.Message, "OK");
            }
        }

        private async Task SetProtectionComboItems()
        {
            List<string> protectionItems = await GetContingentValues("Protection", "ProtectionFieldGroup");

            // Get the appropriate contingent values for populating the protection combo component.
            if (protectionItems.Any())
            {
                ProtectionPicker.SelectedIndexChanged -= ProtectionCombo_SelectedIndexChanged;
                ProtectionPicker.ItemsSource = protectionItems;
                ProtectionPicker.SelectedIndexChanged += ProtectionCombo_SelectedIndexChanged;
            }
        }

        private async Task SetBufferSizeSliderRange()
        {
            // Get the valid contingent range values for the subsequent buffer size slider.
            List<string> minMax = await GetContingentValues("BufferSize", "BufferSizeFieldGroup");

            if (minMax[0] != "")
            {
                // Set the minimum and maximum slider values based on the valid contingent value buffer size range.
                if (minMax[1] == "0")
                {
                    // If the max value in the range is 0, set the buffer size to 0.
                    BufferSizeSlider.Minimum = 0;
                    BufferSizeSlider.Maximum = 1;
                    BufferSizeSlider.IsEnabled = false;

                    // Update the feature's buffer size with the selected value.
                    await UpdateField("BufferSize", 0);
                }
                else if (BufferSizeSlider.Maximum <= double.Parse(minMax[0]))
                {
                    BufferSizeSlider.Maximum = double.Parse(minMax[1]);
                    BufferSizeSlider.Minimum = double.Parse(minMax[0]);
                }
                else
                {
                    BufferSizeSlider.Minimum = double.Parse(minMax[0]);
                    BufferSizeSlider.Maximum = double.Parse(minMax[1]);
                }

                BufferSizeSlider.Value = BufferSizeSlider.Minimum;
            }
        }

        private async Task SaveFeature()
        {
            List<string> fieldGroupNames = new List<string>();
            int numberOfViolations = 0;

            // If the contingent values are valid, save the data and hide the attribute panel.
            if (ValidateContingentValues(out fieldGroupNames, out numberOfViolations))
            {
                _ = CreateNewNest();

                FeatureAttributesPopup.IsVisible = false;
            }
            else
            {
                await Application.Current.MainPage.DisplayAlert("Error", $"Error saving feature. {numberOfViolations} violation(s) in field group(s) {string.Join(", ", fieldGroupNames)}.", "OK");
            }
        }

        private void ClearAndDisableBufferSizeSlider()
        {
            BufferSizeSlider.Minimum = 0;
            BufferSizeSlider.Maximum = 1;
            BufferSizeSlider.Value = BufferSizeSlider.Minimum;
            BufferSizeLabel.Text = BufferSizeSlider.Minimum.ToString();
            BufferSizeSlider.IsEnabled = false;
        }

        #endregion AddFeature

        #region EventHandlers

        private void MyMapView_GeoViewTapped(object sender, Esri.ArcGISRuntime.Maui.GeoViewInputEventArgs e)
        {
            // If a new feature is currently being created do not create another one.
            if (_newFeature == null)
            {
                _ = CreateNewEmptyFeature(e);
            }
        }

        private void StatusCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Update the feature's attribute map with the selection.
            _ = UpdateField("Status", StatusPicker.SelectedItem);
            _ = SetProtectionComboItems();

            if (BufferSizeSlider.IsEnabled)
            {
                ClearAndDisableBufferSizeSlider();
            }
        }

        private void ProtectionCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Update the feature's attribute map with the selection.
            _ = UpdateField("Protection", ProtectionPicker.SelectedItem);

            BufferSizeSlider.IsEnabled = ProtectionPicker.SelectedIndex != -1;

            if (ProtectionPicker.SelectedIndex == -1)
            {
                BufferSizeSlider.Minimum = 0;
                BufferSizeSlider.Maximum = 1;
                BufferSizeSlider.Value = BufferSizeSlider.Minimum;
            }
            else
            {
                _ = SetBufferSizeSliderRange();
            }
        }

        private void BufferSizeSlider_ValueChanged(object sender, ValueChangedEventArgs e)
        {
            BufferSizeSlider.Value = (double)Convert.ToInt32(BufferSizeSlider.Value);

            // Update the feature's buffer size with the selected value.
            _ = UpdateField("BufferSize", BufferSizeSlider.Value);

            BufferSizeLabel.Text = BufferSizeSlider.Value.ToString();
        }

        private void DiscardButton_Clicked(object sender, EventArgs e)
        {
            _ = DiscardFeature();

            FeatureAttributesPopup.IsVisible = false;
        }

        private void SaveButton_Clicked(object sender, EventArgs e)
        {
            _ = SaveFeature();
        }

        private void FeatureAttributesPopup_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (FeatureAttributesPopup == null || e.PropertyName != "IsVisible")
            {
                return;
            }

            // Disable event handlers when the attribute panel is hidden.
            if (!FeatureAttributesPopup.IsVisible)
            {
                StatusPicker.SelectedIndexChanged -= StatusCombo_SelectedIndexChanged;
                ProtectionPicker.SelectedIndexChanged -= ProtectionCombo_SelectedIndexChanged;
                BufferSizeSlider.ValueChanged -= BufferSizeSlider_ValueChanged;

                return;
            }

            // Reset attribute panel values when the panel opens.
            StatusPicker.SelectedIndex = -1;
            ProtectionPicker.SelectedIndex = -1;
            ClearAndDisableBufferSizeSlider();

            // Add the event handlers to the attribute panel.
            StatusPicker.SelectedIndexChanged += StatusCombo_SelectedIndexChanged;
            ProtectionPicker.SelectedIndexChanged += ProtectionCombo_SelectedIndexChanged;
            BufferSizeSlider.ValueChanged += BufferSizeSlider_ValueChanged;
        }

        #endregion EventHandlers
    }
}

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