Add features with contingent values

View inMAUIWPFWinUIView on GitHubSample viewer app

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
// 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;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace ArcGIS.WPF.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
    {
        // 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);

            StatusCombo.ItemsSource = _statusValues.Keys;
            FeatureAttributesPanel.Visibility = Visibility.Hidden;

            #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)
            {
                MessageBox.Show(e.Message, "Error");
            }
        }

        private async Task CreateNewEmptyFeature(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 (!FeatureAttributesPanel.IsVisible)
                {
                    FeatureAttributesPanel.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }

        private 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)
            {
                MessageBox.Show(e.Message, "Error");
            }

            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)
            {
                MessageBox.Show(e.Message, "Error");
            }
        }

        private void 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:
                        MessageBox.Show($"{field} not found in any of the data dictionaries.");
                        break;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Error");
            }
        }

        #endregion AddFeature

        #region EventHandlers

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

        private void StatusCombo_Selected(object sender, RoutedEventArgs e)
        {
            // Update the feature's attribute map with the selection.
            UpdateField("Status", StatusCombo.SelectedItem);

            List<string> protectionItems = GetContingentValues("Protection", "ProtectionFieldGroup");

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

        private void ProtectionCombo_Selected(object sender, RoutedEventArgs e)
        {
            // Update the feature's attribute map with the selection.
            UpdateField("Protection", ProtectionCombo.SelectedItem);

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

            if (minMax[0] != "")
            {
                // Set the minimum and maximum slider values based on the valid contingent value buffer size range.
                BufferSizeSlider.Minimum = int.Parse(minMax[0]);
                BufferSizeSlider.Maximum = int.Parse(minMax[1]);

                BufferSizeSlider.Value = BufferSizeSlider.Minimum;

                // If the max value in the range is 0, set the buffer size to 0.
                if (minMax[1] == "0")
                {
                    // Update the feature's buffer size with the selected value.
                    UpdateField("BufferSize", 0);
                }
            }
        }

        private void BufferSizeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            // Update the feature's buffer size with the selected value.
            UpdateField("BufferSize", BufferSizeSlider.Value);
        }

        private void DiscardButton_Click(object sender, RoutedEventArgs e)
        {
            _ = DiscardFeature();

            FeatureAttributesPanel.Visibility = Visibility.Hidden;
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            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();

                FeatureAttributesPanel.Visibility = Visibility.Hidden;
            }
            else
            {
                MessageBox.Show($"Error saving feature. {numberOfViolations} violation(s) in field group(s) {string.Join(", ", fieldGroupNames)}.", "Error");
            }
        }

        private void FeatureAttributesPanel_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            // Disable event handlers when the attribute panel is hidden.
            if (!FeatureAttributesPanel.IsVisible)
            {
                StatusCombo.SelectionChanged -= StatusCombo_Selected;
                ProtectionCombo.SelectionChanged -= ProtectionCombo_Selected;
                BufferSizeSlider.ValueChanged -= BufferSizeSlider_ValueChanged;

                return;
            }

            // Reset attribute panel values when the panel opens.
            StatusCombo.SelectedIndex = -1;
            ProtectionCombo.SelectedIndex = -1;
            BufferSizeSlider.Value = BufferSizeSlider.Minimum;

            // Add the event handlers to the attribute panel.
            StatusCombo.SelectionChanged += StatusCombo_Selected;
            ProtectionCombo.SelectionChanged += ProtectionCombo_Selected;
            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.