Skip To Content ArcGIS for Developers Sign In Dashboard

ArcGIS Runtime SDK for .NET

Configure subnetwork trace

This code sample is available for these platforms:
View Sample on GitHub

Get a server-defined trace configuration for a given tier and modify its traversability scope, add new condition barriers and control what is included in the subnetwork trace result.

Image of configure subnetwork trace

Use case

While some traces are built from an ad-hoc group of parameters, many are based on a variation of the trace configuration taken from the subnetwork definition. For example, an electrical trace will be based on the trace configuration of the subnetwork, but may add additional clauses to constrain the trace along a single phase. Similarly, a trace in a gas or electric design application may include features with a status of "In Design" that are normally excluded from trace results.

How to use the sample

The sample loads with a server-defined trace configuration from a tier. Check or uncheck which options to include in the trace - such as containers or barriers. Use the selection boxes to define a new condition network attribute comparison, and then use 'Add' to add the it to the trace configuration. Click 'Trace' to run a subnetwork trace with this modified configuration from a default starting location.

Example barrier conditions for the default dataset:

  • 'Transformer Load' Equal '15'
  • 'Phases Current' DoesNotIncludeTheValues 'A'
  • 'Generation KW' LessThan '50'

How it works

  1. Create and load a UtilityNetwork with a feature service URL, then get an asset type and a tier by their names.
  2. Populate the choice list for the comparison source with the non-system defined Definition.NetworkAttributes. Populate the choice list for the comparison operator with the enum values from UtilityAttributeComparisonOperator.
  3. Create a UtilityElement from this asset type to use as the starting location for the trace.
  4. Update the selected barrier expression and the checked options in the UI using this tier's TraceConfiguration.
  5. When 'Network Attribute' is selected, if its Domain is a CodedValueDomain, populate the choice list for the comparison value with its CodedValues. Otherwise, display a free-form textbox for entering an attribute value.
  6. When 'Add' is clicked, create a new UtilityNetworkAttributeComparison using the selected comparison source, operator, and selected or typed value. Use the selected source's NetworkAttribute.DataType to convert the comparison value to the correct data type.
  7. If the Traversability's list of Barriers is not empty, create a UtilityTraceOrCondition with the existing Barriers and the new comparison from Step 6.
  8. When 'Trace' is clicked, create UtilityTraceParameters passing in UtilityTraceType.Subnetwork and the default starting location. Set its TraceConfiguration with the modified options, selections, and expression; then run a UtilityNetwork.TraceAsync.
  9. When Reset is clicked, set the trace configurations expression back to its original value.
  10. Display the count of returned UtilityElementTraceResult.Elements.

Relevant API

  • CodedValueDomain
  • UtilityAssetType
  • UtilityAttributeComparisonOperator
  • UtilityCategory
  • UtilityCategoryComparison
  • UtilityCategoryComparisonOperator
  • UtilityDomainNetwork
  • UtilityElement
  • UtilityElementTraceResult
  • UtilityNetwork
  • UtilityNetworkAttribute
  • UtilityNetworkAttributeComparison
  • UtilityNetworkDefinition
  • UtilityTerminal
  • UtilityTier
  • UtilityTraceAndCondition
  • UtilityTraceConfiguration
  • UtilityTraceOrCondition
  • UtilityTraceParameters
  • UtilityTraceResult
  • UtilityTraceType
  • UtilityTraversability

About the data

The Naperville electrical network feature service, hosted on ArcGIS Online, contains a utility network used to run the subnetwork-based trace shown in this sample.

Tags

category comparison, condition barriers, network analysis, network attribute comparison, subnetwork trace, trace configuration, traversability, utility network, validate consistency

Sample Code

<UserControl
    x:Class="ArcGISRuntime.UWP.Samples.ConfigureSubnetworkTrace.ConfigureSubnetworkTrace"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid x:Name="Configuration" Background="LightGray">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="auto" />
            <ColumnDefinition Width="auto" />
            <ColumnDefinition Width="auto" />
            <ColumnDefinition Width="auto" />
            <ColumnDefinition Width="auto" />
            <ColumnDefinition Width="auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
        </Grid.RowDefinitions>

        <!--  Row 1  -->

        <TextBlock
            Grid.Row="0"
            Grid.Column="0"
            Margin="5"
            HorizontalAlignment="Right"
            FontSize="15"
            FontWeight="SemiBold"
            Text="Trace options:" />

        <!--  NOTE that There are also: IncludeContent, IncludeStructures, IgnoreBarriersAtStartingPoints, ValidateConsistency  -->

        <CheckBox
            Grid.Column="1"
            Margin="5"
            Content="Include Barriers"
            FontSize="15"
            IsChecked="{Binding IncludeBarriers}" />
        <CheckBox
            Grid.Column="2"
            Margin="5"
            Content="Include Containers"
            FontSize="15"
            IsChecked="{Binding IncludeContainers}" />

        <!--  Row 2  -->
        <TextBlock
            Grid.Row="1"
            Grid.ColumnSpan="4"
            HorizontalAlignment="Center"
            FontSize="15"
            Text="Example barrier condition for this data: 'Transformer Load' Equal '15'" />

        <!--  Row 3  -->
        <TextBlock
            Grid.Row="2"
            Grid.Column="0"
            Margin="5"
            HorizontalAlignment="Right"
            FontSize="15"
            FontWeight="SemiBold"
            Text="Define new condition:" />
        <ComboBox
            x:Name="Attributes"
            Grid.Row="2"
            Grid.Column="1"
            Width="175"
            Margin="5"
            SelectionChanged="OnAttributeChanged">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}" />
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
        <ComboBox
            x:Name="Operators"
            Grid.Row="2"
            Grid.Column="2"
            Width="150"
            Margin="5" />
        <ComboBox
            x:Name="ValueSelection"
            Grid.Row="2"
            Grid.Column="3"
            Width="125"
            Margin="5"
            Visibility="Collapsed">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}" />
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
        <TextBox
            x:Name="ValueEntry"
            Grid.Row="2"
            Grid.Column="3"
            Width="125"
            Margin="5"
            Visibility="Visible" />
        <Button
            Grid.Row="2"
            Grid.Column="4"
            Margin="5"
            HorizontalAlignment="Stretch"
            Click="OnAddCondition"
            Content="Add"
            FontSize="15" />


        <!--  Row 4  -->
        <TextBlock
            Grid.Row="3"
            Grid.Column="0"
            Margin="5"
            HorizontalAlignment="Right"
            FontSize="15"
            FontWeight="SemiBold"
            Text="Barrier conditions:" />
        <Grid
            Grid.Row="3"
            Grid.Column="1"
            Grid.ColumnSpan="4"
            Margin="5"
            Background="White">
            <TextBlock
                x:Name="ConditionBarrierExpression"
                Margin="5"
                FontSize="15"
                TextTrimming="WordEllipsis"
                TextWrapping="WrapWholeWords" />
        </Grid>

        <!--  Row 5  -->
        <Button
            Grid.Row="4"
            Grid.ColumnSpan="3"
            Margin="5"
            HorizontalAlignment="Stretch"
            Click="OnTrace"
            Content="Trace"
            FontSize="15" />
        <Button
            Grid.Row="4"
            Grid.Column="3"
            Grid.ColumnSpan="2"
            Margin="5"
            HorizontalAlignment="Stretch"
            Click="OnReset"
            Content="Reset"
            FontSize="15" />
    </Grid>
</UserControl>
// Copyright 2020 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 Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.UtilityNetworks;
using System;
using System.Collections.Generic;
using System.Linq;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace ArcGISRuntime.UWP.Samples.ConfigureSubnetworkTrace
{
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Configure subnetwork trace",
        category: "Utility network",
        description: "Get a server-defined trace configuration for a given tier and modify its traversability scope, add new condition barriers and control what is included in the subnetwork trace result.",
        instructions: "The sample loads with a server-defined trace configuration from a tier. Check or uncheck which options to include in the trace - such as containers or barriers. Use the selection boxes to define a new condition network attribute comparison, and then use 'Add' to add the it to the trace configuration. Click 'Trace' to run a subnetwork trace with this modified configuration from a default starting location.",
        tags: new[] { "category comparison", "condition barriers", "network analysis", "network attribute comparison", "subnetwork trace", "trace configuration", "traversability", "utility network", "validate consistency" })]
    public partial class ConfigureSubnetworkTrace
    {
        // Feature service for an electric utility network in Naperville, Illinois.
        private const string FeatureServiceUrl = "https://sampleserver7.arcgisonline.com/arcgis/rest/services/UtilityNetwork/NapervilleElectric/FeatureServer";
        private UtilityNetwork _utilityNetwork;

        // For creating the default starting location.
        private const string DeviceTableName = "Electric Distribution Device";
        private const string AssetGroupName = "Circuit Breaker";
        private const string AssetTypeName = "Three Phase";
        private const string GlobalId = "{1CAF7740-0BF4-4113-8DB2-654E18800028}";

        // For creating the default trace configuration.
        private const string DomainNetworkName = "ElectricDistribution";
        private const string TierName = "Medium Voltage Radial";

        // Utility element to start the trace from.
        private UtilityElement _startingLocation;

        // Holding the initial conditional expression.
        private UtilityTraceConditionalExpression _initialExpression;

        // The trace configuration.
        private UtilityTraceConfiguration _configuration;

        public ConfigureSubnetworkTrace()
        {
            InitializeComponent();
            Initialize();
        }

        private async void Initialize()
        {
            try
            {
                // Create and load the utility network.
                _utilityNetwork = await UtilityNetwork.CreateAsync(new Uri(FeatureServiceUrl));

                // Build the choice lists for network attribute comparison.
                Attributes.ItemsSource = _utilityNetwork.Definition.NetworkAttributes.Where(netattr => !netattr.IsSystemDefined);
                Operators.ItemsSource = Enum.GetValues(typeof(UtilityAttributeComparisonOperator));

                // Create a default starting location.
                UtilityNetworkSource networkSource = _utilityNetwork.Definition.GetNetworkSource(DeviceTableName);
                UtilityAssetGroup assetGroup = networkSource.GetAssetGroup(AssetGroupName);
                UtilityAssetType assetType = assetGroup.GetAssetType(AssetTypeName);
                Guid globalId = Guid.Parse(GlobalId);
                _startingLocation = _utilityNetwork.CreateElement(assetType, globalId);

                // Set the terminal for this location. (For our case, we use the 'Load' terminal.)
                _startingLocation.Terminal = _startingLocation.AssetType.TerminalConfiguration?.Terminals.FirstOrDefault(term => term.Name == "Load");

                // Get a default trace configuration from a tier to update the UI.
                UtilityDomainNetwork domainNetwork = _utilityNetwork.Definition.GetDomainNetwork(DomainNetworkName);
                UtilityTier sourceTier = domainNetwork.GetTier(TierName);

                // Set the trace configuration.
                _configuration = sourceTier.TraceConfiguration;

                // Set the default expression (if provided).
                if (sourceTier.TraceConfiguration.Traversability.Barriers is UtilityTraceConditionalExpression expression)
                {
                    ConditionBarrierExpression.Text = ExpressionToString(expression);
                    _initialExpression = expression;
                }

                // Setting DataContext will resolve the data-binding in XAML.
                Configuration.DataContext = _configuration;

                // Set the traversability scope.
                sourceTier.TraceConfiguration.Traversability.Scope = UtilityTraversabilityScope.Junctions;
            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.Message, ex.Message.GetType().Name).ShowAsync();
            }
        }

        private async void OnAddCondition(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_configuration == null)
                {
                    _configuration = new UtilityTraceConfiguration();
                }
                if (_configuration.Traversability == null)
                {
                    _configuration.Traversability = new UtilityTraversability();
                }

                // NOTE: You may also create a UtilityCategoryComparison with UtilityNetworkDefinition.Categories and UtilityCategoryComparisonOperator.
                if (Attributes.SelectedItem is UtilityNetworkAttribute attribute
                    && Operators.SelectedItem is UtilityAttributeComparisonOperator attributeOperator)
                {
                    object selectedValue;

                    // If the value is a coded value.
                    if (attribute.Domain is CodedValueDomain && ValueSelection.SelectedItem is CodedValue codedValue)
                    {
                        selectedValue = ConvertToDataType(codedValue.Code, attribute.DataType);
                    }
                    // If the value is free entry.
                    else
                    {
                        selectedValue = ConvertToDataType(ValueEntry.Text.Trim(), attribute.DataType);
                    }
                    // NOTE: You may also create a UtilityNetworkAttributeComparison with another NetworkAttribute.
                    UtilityTraceConditionalExpression expression = new UtilityNetworkAttributeComparison(attribute, attributeOperator, selectedValue);
                    if (_configuration.Traversability.Barriers is UtilityTraceConditionalExpression otherExpression)
                    {
                        // NOTE: You may also combine expressions with UtilityTraceAndCondition
                        expression = new UtilityTraceOrCondition(otherExpression, expression);
                    }
                    _configuration.Traversability.Barriers = expression;
                    ConditionBarrierExpression.Text = ExpressionToString(expression);
                }
            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.Message, ex.Message.GetType().Name).ShowAsync();
            }
        }

        private string ExpressionToString(UtilityTraceConditionalExpression expression)
        {
            if (expression is UtilityCategoryComparison categoryComparison)
            {
                return $"`{categoryComparison.Category.Name}` {categoryComparison.ComparisonOperator}";
            }
            else if (expression is UtilityNetworkAttributeComparison attributeComparison)
            {
                // Check if attribute domain is a coded value domain.
                if (attributeComparison.NetworkAttribute.Domain is CodedValueDomain domain)
                {
                    // Get the coded value using the the attribute comparison value and attribute data type.
                    UtilityNetworkAttributeDataType dataType = attributeComparison.NetworkAttribute.DataType;
                    object attributeValue = ConvertToDataType(attributeComparison.Value, attributeComparison.NetworkAttribute.DataType);
                    CodedValue codedValue = domain.CodedValues.FirstOrDefault(value => ConvertToDataType(value.Code, dataType).Equals(attributeValue));
                    return $"`{attributeComparison.NetworkAttribute.Name}` {attributeComparison.ComparisonOperator} `{codedValue?.Name}`";
                }
                else
                {
                    return $"`{attributeComparison.NetworkAttribute.Name}` {attributeComparison.ComparisonOperator} `{attributeComparison.OtherNetworkAttribute?.Name ?? attributeComparison.Value}`";
                }
            }
            else if (expression is UtilityTraceAndCondition andCondition)
            {
                return $"({ExpressionToString(andCondition.LeftExpression)}) AND\n ({ExpressionToString(andCondition.RightExpression)})";
            }
            else if (expression is UtilityTraceOrCondition orCondition)
            {
                return $"({ExpressionToString(orCondition.LeftExpression)}) OR\n ({ExpressionToString(orCondition.RightExpression)})";
            }
            else
            {
                return null;
            }
        }

        private object ConvertToDataType(object otherValue, UtilityNetworkAttributeDataType dataType)
        {
            switch (dataType)
            {
                case UtilityNetworkAttributeDataType.Boolean:
                    return Convert.ToBoolean(otherValue);

                case UtilityNetworkAttributeDataType.Double:
                    return Convert.ToDouble(otherValue);

                case UtilityNetworkAttributeDataType.Float:
                    return Convert.ToSingle(otherValue);

                case UtilityNetworkAttributeDataType.Integer:
                    return Convert.ToInt32(otherValue);
            }
            throw new NotSupportedException();
        }

        private async void OnTrace(object sender, RoutedEventArgs e)
        {
            if (_utilityNetwork == null || _startingLocation == null)
            {
                return;
            }
            try
            {
                // Create utility trace parameters for the starting location.
                UtilityTraceParameters parameters = new UtilityTraceParameters(UtilityTraceType.Subnetwork, new[] { _startingLocation });
                parameters.TraceConfiguration = _configuration;

                // Trace the utility network.
                IEnumerable<UtilityTraceResult> results = await _utilityNetwork.TraceAsync(parameters);

                // Get the first result.
                UtilityElementTraceResult elementResult = results?.FirstOrDefault() as UtilityElementTraceResult;

                // Display the number of elements found by the trace.
                await new MessageDialog($"`{elementResult?.Elements?.Count ?? 0}` elements found.", "Trace Result").ShowAsync();
            }
            catch (Exception ex)
            {
                await new MessageDialog($"{ex.Message}\nFor a working barrier condition, try \"Transformer Load\" Equal \"15\".", ex.GetType().Name).ShowAsync();
            }
        }

        private void OnAttributeChanged(object sender, SelectionChangedEventArgs e)
        {
            ValueEntry.Text = string.Empty;

            // Update the UI to show the correct value entry for the attribute.
            if (Attributes.SelectedItem is UtilityNetworkAttribute attribute)
            {
                if (attribute.Domain is CodedValueDomain domain)
                {
                    ValueSelection.ItemsSource = domain.CodedValues;
                    ValueSelection.Visibility = Visibility.Visible;
                    ValueEntry.Visibility = Visibility.Collapsed;
                }
                else
                {
                    ValueEntry.Visibility = Visibility.Visible;
                    ValueSelection.Visibility = Visibility.Collapsed;
                }
            }
        }

        private void OnReset(object sender, RoutedEventArgs e)
        {
            // Reset the barrier condition to the initial value.
            UtilityTraceConfiguration traceConfiguration = _configuration;
            traceConfiguration.Traversability.Barriers = _initialExpression;
            ConditionBarrierExpression.Text = ExpressionToString(_initialExpression);
        }
    }
}