Validate utility network topology

View inMAUIWPFWinUIView on GitHub

Demonstrates the workflow of getting the network state and validating the topology of a utility network.

Image of Validate utility network topology

Use case

Dirty areas are generated where edits to utility network features have not been evaluated against the network rules. Tracing across this area could result in an error or return inaccurate results. Validating the utility network updates the network topology with the edited feature data, maintaining consistency between the features and topology. Querying the network state allows you to determine if there are dirty areas or errors in a utility network, and if it supports network topology.

How to use the sample

Select features to make edits and then use 'Update and Apply Edit' to send edits to the server.

  • Tap 'Get state' to check if validate is required or if tracing is available.
  • Tap 'Validate' to validate network topology and clear dirty areas.
  • Tap 'Trace' to run a trace.

How it works

  1. Create and load a Map with a web map item URL.
  2. Load the UtilityNetwork from the web map and switch its ServiceGeodatabase to a new branch version.
  3. Add LabelDefinitions for the fields that will be updated on a feature edit.
  4. Add the UtilityNetwork.DirtyAreaTable to the map to visualize dirty areas or errors.
  5. Set a default starting location and trace parameters to stop traversability on an open device.
  6. Get the UtilityNetworkCapabilities from the UtilityNetworkDefinition and use these values to enable or disable the 'Get State', 'Validate', and 'Trace' buttons.
  7. When an ArcGISFeature is selected for editing, populate the choice list for the field value using the field's CodedValueDomain.CodedValues.
  8. When 'Update and Apply Edits' is clicked, update the value of the selected feature's attribute value with the selected CodedValue.Code and call ServiceGeodatabase.ApplyEditsAsync().
  9. When 'Get State' is clicked, call UtilityNetwork.GetStateAsync() and print the results.
  10. When 'Validate' is clicked, get the current map extent and call UtilityNetwork.ValidateNetworkTopology().
  11. When 'Trace' is clicked, call UtilityNetwork.TraceAsync() with the predefined parameters and select all features returned.
  12. When 'Clear Selection' or 'Cancel' are clicked, clear all selected features on each layer in the map and close the attribute picker.

Relevant API

  • UtilityElement
  • UtilityElementTraceResult
  • UtilityNetwork
  • UtilityNetworkCapabilities
  • UtilityNetworkState
  • UtilityNetworkValidationJob
  • UtilityTraceConfiguration
  • UtilityTraceParameters
  • UtilityTraceResult

About the data

The Naperville electric feature service contains a utility network that can be used to query the network state and validate network topology before tracing. The Naperville electric webmap uses the same feature service endpoint and is shown in this sample. Authentication is required and handled within the sample code.

Tags

dirty areas, edit, network topology, online, state, trace, utility network, validate

Sample Code

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

using System.Text;
using Esri.ArcGISRuntime;
using Esri.ArcGISRuntime.ArcGISServices;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Mapping.Labeling;
using Esri.ArcGISRuntime.Security;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using Color = System.Drawing.Color;
using Esri.ArcGISRuntime.Maui;
using Esri.ArcGISRuntime.UtilityNetworks;

namespace ArcGIS.Samples.ValidateUtilityNetworkTopology
{
    [ArcGIS.Samples.Shared.Attributes.Sample(
        name: "Validate utility network topology",
        category: "Utility network",
        description: "Demonstrates the workflow of getting the network state and validating the topology of a utility network.",
        instructions: "Select features to make edits and then use 'Update and Apply Edit' to send edits to the server.",
        tags: new[] { "dirty areas", "edit", "network topology", "online", "state", "trace", "utility network", "validate" })]
    [ArcGIS.Samples.Shared.Attributes.OfflineData()]
    public partial class ValidateUtilityNetworkTopology
    {
        private static readonly string WebmapItemUrl = "https://sampleserver7.arcgisonline.com/portal/home/item.html?id=6e3fc6db3d0b4e6589eb4097eb3e5b9b";

        private readonly Viewpoint InitialViewpoint = new Viewpoint(
            new Envelope(
                -9815489.0660101417,
                5128463.4221229386,
                -9814625.2768726498,
                5128968.4911854975,
                SpatialReferences.WebMercator
            )
        );

        // For editing
        private const string LineTableName = "Electric Distribution Line";
        private const string DeviceTableName = "Electric Distribution Device";
        private ArcGISFeature _featureToEdit;

        // To impact trace
        private const string DeviceStatusField = "devicestatus";

        private readonly LabelDefinition DeviceLabelDefinition = new LabelDefinition(
            new SimpleLabelExpression($"[{DeviceStatusField}]"),
            new TextSymbol
            {
                Color = Color.Blue,
                HaloColor = Color.White,
                HaloWidth = 2,
                Size = 12
            }
        )
        {
            UseCodedValues = true
        };

        // To better visualize dirty area
        private const string NominalVoltageField = "nominalvoltage";

        private readonly LabelDefinition LineLabelDefinition = new LabelDefinition(
            new SimpleLabelExpression($"[{NominalVoltageField}]"),
            new TextSymbol
            {
                Color = Color.Red,
                HaloColor = Color.White,
                HaloWidth = 2,
                Size = 12
            }
        )
        {
            UseCodedValues = true
        };

        // For tracing
        private const string AssetGroupName = "Circuit Breaker";
        private const string AssetTypeName = "Three Phase";
        private const string GlobalId = "{1CAF7740-0BF4-4113-8DB2-654E18800028}";
        private const string DomainNetworkName = "ElectricDistribution";
        private const string TierName = "Medium Voltage Radial";
        private UtilityTraceParameters _traceParameters;

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

        private async Task Initialize()
        {
            try
            {
                IsBusy.IsVisible = true;
                Status.Text = "Loading a webmap...";

                // Add credential for this webmap.
                // WARNING: Never hardcode login information in a production application. This is done solely for the sake of the sample.
                string sampleServerPortalUrl =
                    "https://sampleserver7.arcgisonline.com/portal/sharing/rest";
                string sampleServer7User = "editor01";
                string sampleServer7Pass = "S7#i2LWmYH75";
                var credential = await AuthenticationManager
                    .Current
                    .GenerateCredentialAsync(
                        new Uri(sampleServerPortalUrl),
                        sampleServer7User,
                        sampleServer7Pass
                    );
                AuthenticationManager.Current.AddCredential(credential);

                // Load map to access utility network.
                var map = new Map(new Uri(WebmapItemUrl)) { InitialViewpoint = InitialViewpoint };

                // Load in persistent session mode (workaround for server caching issue).
                // https://support.esri.com/en-us/bug/asynchronous-validate-request-for-utility-network-servi-bug-000160443
                map.LoadSettings = new LoadSettings() { FeatureServiceSessionType = FeatureServiceSessionType.Persistent };

                MyMapView.Map = map;
                await map.LoadAsync();

                // Load and switch utility network version.
                Status.Text = "Loading the utility network...";
                var utilityNetwork =
                    map.UtilityNetworks.FirstOrDefault()
                    ?? throw new InvalidOperationException("Expected a utility network");
                await utilityNetwork.LoadAsync();

                var sgdb =
                    utilityNetwork.ServiceGeodatabase
                    ?? throw new InvalidOperationException("Expected a service geodatabase");
                IsBusy.IsVisible = true;

                // Restrict editing and tracing on a random branch.
                var parameters = new ServiceVersionParameters();
                parameters.Name = $"ValidateNetworkTopology_{Guid.NewGuid()}";
                parameters.Access = VersionAccess.Private;
                parameters.Description = "Validate network topology with ArcGIS Runtime";

                var info = await sgdb.CreateVersionAsync(parameters);
                await sgdb.SwitchVersionAsync(info.Name);

                // Visualize attribute editing using labels.
                foreach (var layer in map.OperationalLayers.OfType<FeatureLayer>())
                {
                    if (layer.Name == DeviceTableName)
                    {
                        layer.LabelDefinitions.Add(DeviceLabelDefinition);
                        layer.LabelsEnabled = true;
                    }
                    else if (layer.Name == LineTableName)
                    {
                        layer.LabelDefinitions.Add(LineLabelDefinition);
                        layer.LabelsEnabled = true;
                    }
                }

                // Visualize dirty area by adding to the map.
                var dirtyAreaTable =
                    utilityNetwork.DirtyAreaTable
                    ?? throw new InvalidOperationException("Expected a dirty area table");
                MyMapView.Map.OperationalLayers.Insert(0, new FeatureLayer(utilityNetwork.DirtyAreaTable));

                // Trace with a subnetwork controller as default starting location.
                var networkSource = utilityNetwork.Definition.GetNetworkSource(DeviceTableName);
                var assetGroup = networkSource.GetAssetGroup(AssetGroupName);
                var assetType = assetGroup.GetAssetType(AssetTypeName);
                var globalId = Guid.Parse(GlobalId);
                var startingLocation = utilityNetwork.CreateElement(assetType, globalId);
                startingLocation.Terminal = startingLocation
                    .AssetType
                    .TerminalConfiguration
                    ?.Terminals
                    .FirstOrDefault(term => term.Name == "Load");

                // Display starting location as graphic.
                var features = await utilityNetwork.GetFeaturesForElementsAsync(
                    new[] { startingLocation }
                );
                var feature = features.FirstOrDefault();
                if (feature != null)
                {
                    await feature.LoadAsync();
                    var graphic = new Graphic(feature.Geometry)
                    {
                        Symbol = new SimpleMarkerSymbol(
                            SimpleMarkerSymbolStyle.Cross,
                            Color.Green,
                            25d
                        )
                    };
                    var overlay = new GraphicsOverlay();
                    overlay.Graphics.Add(graphic);
                    MyMapView.GraphicsOverlays.Add(overlay);
                }

                // Trace with a configuration that stops traversability on an open device.
                var domainNetwork = utilityNetwork.Definition.GetDomainNetwork(DomainNetworkName);
                var sourceTier = domainNetwork.GetTier(TierName);

                _traceParameters = new UtilityTraceParameters(
                    UtilityTraceType.Downstream,
                    new[] { startingLocation }
                )
                {
                    TraceConfiguration = sourceTier.GetDefaultTraceConfiguration()
                };

                // Enable buttons with UtilityNetworkCapabilities.
                ValidateBtn.IsEnabled = utilityNetwork
                    .Definition
                    .Capabilities
                    .SupportsValidateNetworkTopology;
                TraceBtn.IsEnabled = utilityNetwork.Definition.Capabilities.SupportsTrace;
                StateBtn.IsEnabled = utilityNetwork.Definition.Capabilities.SupportsNetworkState;
                ClearBtn.IsEnabled = false;

                // Set the instruction text.
                Status.Text = "Utility Network Loaded\n" +
                    "Tap on a feature to edit.\n" +
                    "Click 'Get State' to check if validating is necessary " +
                    "or if tracing is available.\n" +
                    "Click 'Trace' to run a trace.";
            }
            catch (Exception ex)
            {
                Status.Text = "Initialization failed.";
                await DisplayAlert(ex.Message, ex.GetType().Name, "OK");
            }
            finally
            {
                IsBusy.IsVisible = false;
            }
        }

        private async void OnGetState(object sender, EventArgs e)
        {
            try
            {
                var utilityNetwork =
                    MyMapView?.Map?.UtilityNetworks.FirstOrDefault()
                    ?? throw new InvalidOperationException("Expected a utility network");

                if (utilityNetwork.Definition.Capabilities.SupportsNetworkState)
                {
                    IsBusy.IsVisible = true;
                    Status.Text = "Getting utility network state...";

                    var state = await utilityNetwork.GetStateAsync();

                    // Validate if dirty areas or errors exist.
                    ValidateBtn.IsEnabled = state.HasDirtyAreas;

                    // Trace if network topology is enabled.
                    TraceBtn.IsEnabled = state.IsNetworkTopologyEnabled;

                    var sb = new StringBuilder(
                        "Utility Network State:\n"
                            + $"- Has Dirty Areas: {state.HasDirtyAreas}\n"
                            + $"- Has Errors: {state.HasErrors}\n"
                            + $"- Is Network Topology Enabled: {state.IsNetworkTopologyEnabled}\n"
                    );

                    if (state.HasDirtyAreas || state.HasErrors)
                    {
                        sb.AppendLine("Click 'Validate' before trace or expect a trace error.");
                    }
                    else
                    {
                        sb.AppendLine("Tap on a feature to edit or click 'Trace' to run a trace.");
                    }

                    Status.Text = sb.ToString();
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert(ex.GetType().Name, ex.Message, "OK");
            }
            finally
            {
                IsBusy.IsVisible = false;
            }
        }

        private async void OnValidate(object sender, EventArgs e)
        {
            try
            {
                var utilityNetwork =
                    MyMapView?.Map?.UtilityNetworks.FirstOrDefault()
                    ?? throw new InvalidOperationException("Expected a utility network");

                // Validate using the current extent.
                var extent = MyMapView
                    ?.GetCurrentViewpoint(ViewpointType.BoundingGeometry)
                    ?.TargetGeometry
                    ?.Extent
                    ?? throw new InvalidOperationException("Expected current extent");

                IsBusy.IsVisible = true;
                Status.Text = "Validating utility network topology...";

                // Get the validation result.
                var job = utilityNetwork.ValidateNetworkTopology(extent);
                var result = await job.GetResultAsync();

                Status.Text =
                    "Utility Validation Result:\n"
                    + $"- Has Dirty Areas: {result.HasDirtyAreas}\n"
                    + $"- Has Errors: {result.HasErrors}\n" +
                    "Click 'Get State' to check the updated network state.";

                ValidateBtn.IsEnabled = result.HasDirtyAreas;
            }
            catch (Exception ex)
            {
                Status.Text = "Validate network topology failed.";
                await DisplayAlert(ex.GetType().Name, ex.Message, "OK");
            }
            finally
            {
                IsBusy.IsVisible = false;
            }
        }

        private async void OnGeoViewTapped(object sender, GeoViewInputEventArgs e)
        {
            try
            {
                IsBusy.IsVisible = true;
                Status.Text = "Identifying feature to edit...";

                // Perform an identify to determine if a user tapped on a feature.
                var layerResults = await MyMapView.IdentifyLayersAsync(e.Position, 5, false);
                var feature =
                    layerResults
                        .FirstOrDefault(
                            l =>
                                (
                                    l.LayerContent.Name == DeviceTableName
                                    || l.LayerContent.Name == LineTableName
                                )
                        )
                        ?.GeoElements
                        .FirstOrDefault() as ArcGISFeature;
                if (feature is null)
                {
                    Status.Text = "No feature identified. Tap on a feature to edit.";
                    return;
                }

                var updateFieldName =
                    feature.FeatureTable.TableName == DeviceTableName
                        ? DeviceStatusField
                        : NominalVoltageField;
                var field = feature.FeatureTable.GetField(updateFieldName);
                var codedValues = (field?.Domain as CodedValueDomain)?.CodedValues;
                if (field is null || codedValues is null || codedValues.Count == 0)
                {
                    return;
                }

                if (feature.LoadStatus != LoadStatus.Loaded)
                {
                    await feature.LoadAsync();
                }

                _featureToEdit = feature;

                // Clear previous selection.
                MyMapView
                    .Map
                    .OperationalLayers
                    .OfType<FeatureLayer>()
                    .ToList()
                    .ForEach(layer => layer.ClearSelection());

                // Select the feature.
                if (_featureToEdit.FeatureTable.Layer is FeatureLayer featureLayer)
                    featureLayer.SelectFeature(_featureToEdit);

                Choices.ItemsSource = (System.Collections.IList)codedValues;
                var actualValue = Convert.ToInt32(_featureToEdit.Attributes[field.Name]);
                Choices.SelectedItem = codedValues.Single(
                    c => Convert.ToInt32(c.Code).Equals(actualValue)
                );

                FieldName.Text = field.Name;
                Status.Text = $"Select a new '{field.Alias ?? field.Name}'";

                // Update the UI for the selection.
                AttributePicker.IsVisible = true;
                ClearBtn.IsEnabled = true;
            }
            catch (Exception ex)
            {
                Status.Text = "Identifying feature to edit failed.";
                await DisplayAlert(ex.GetType().Name, ex.Message, "OK");
            }
            finally
            {
                IsBusy.IsVisible = false;
            }
        }

        private async void OnApplyEdits(object sender, EventArgs e)
        {
            try
            {
                var serviceGeodatabase = (
                    _featureToEdit?.FeatureTable as ServiceFeatureTable
                )?.ServiceGeodatabase;

                var fieldName = FieldName?.Text?.Trim();
                if (
                    _featureToEdit is null
                    || serviceGeodatabase is null
                    || string.IsNullOrWhiteSpace(fieldName)
                    || !_featureToEdit.Attributes.ContainsKey(fieldName)
                    || !(Choices.SelectedItem is CodedValue codedValue)
                )
                {
                    return;
                }

                IsBusy.IsVisible = true;

                Status.Text = "Updating feature...";
                _featureToEdit.Attributes[fieldName] = codedValue.Code;
                await _featureToEdit.FeatureTable.UpdateFeatureAsync(_featureToEdit);

                Status.Text = "Applying edits...";
                var applyEditsResult = await serviceGeodatabase.ApplyEditsAsync();

                if (
                    applyEditsResult.Any(
                        r => r.EditResults.Any(er => er.CompletedWithErrors || er.Error != null)
                    )
                )
                {
                    Status.Text = "Apply edits completed with error.";
                }
                else
                {
                    Status.Text = "Apply edits completed successfully.\n" +
                        "Click 'Get State' to check the updated network state.";
                }
            }
            catch (Exception ex)
            {
                Status.Text = "Apply edits failed.";
                await DisplayAlert(ex.GetType().Name, ex.Message, "OK");
            }
            finally
            {
                // Clear selection.
                MyMapView
                   .Map
                   .OperationalLayers
                   .OfType<FeatureLayer>()
                   .ToList()
                   .ForEach(layer => layer.ClearSelection());

                AttributePicker.IsVisible = false;
                ClearBtn.IsEnabled = false;
                ValidateBtn.IsEnabled = true;
                IsBusy.IsVisible = false;
            }
        }

        private async void OnTrace(object sender, EventArgs e)
        {
            var utilityNetwork =
                MyMapView?.Map?.UtilityNetworks.FirstOrDefault()
                ?? throw new InvalidOperationException("Expected a utility network");

            try
            {
                // Update the UI.
                IsBusy.IsVisible = true;
                Status.Text = $"Running a downstream trace...";

                // Clear previous selection from the layers.
                MyMapView
                   .Map
                   .OperationalLayers
                   .OfType<FeatureLayer>()
                   .ToList()
                   .ForEach(layer => layer.ClearSelection());

                //  Get the trace result from the utility network.
                var traceResult = await utilityNetwork.TraceAsync(_traceParameters);
                var elementTraceResult =
                    traceResult.FirstOrDefault(r => r is UtilityElementTraceResult)
                    as UtilityElementTraceResult;

                // Check if there are any elements in the result.
                var elementsFound = elementTraceResult?.Elements.Count ?? 0;
                Status.Text = $"Trace completed: {elementsFound} elements found";
                foreach (var layer in MyMapView.Map.OperationalLayers.OfType<FeatureLayer>())
                {
                    var elements = elementTraceResult
                        .Elements
                        .Where(element => element.NetworkSource.FeatureTable == layer.FeatureTable);
                    if (elements.Any())
                    {
                        var features = await utilityNetwork.GetFeaturesForElementsAsync(elements);
                        layer.SelectFeatures(features);
                    }
                }

                ClearBtn.IsEnabled = true;
            }
            catch (Exception ex)
            {
                Status.Text = "Trace failed.\n" +
                    "Click 'Get State' to check the updated network state.";
                await DisplayAlert(ex.GetType().Name, ex.Message, "OK");
            }
            finally
            {
                IsBusy.IsVisible = false;
            }
        }

        private void OnClear(object sender, EventArgs e)
        {
            AttributePicker.IsVisible = false;

            // Clear the selection.
            MyMapView
               .Map
               .OperationalLayers
               .OfType<FeatureLayer>()
               .ToList()
               .ForEach(layer => layer.ClearSelection());

            _featureToEdit = null;

            Status.Text = "Selection cleared.";

            ClearBtn.IsEnabled = false;
        }
    }
}

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