Пример #1
0
        public async void CreateDiagramLayerFromNetworkDiagram(NetworkDiagram myDiagram)
        {
            #region Open a diagram window from a Network Diagram

            // Create a diagram layer from a NetworkDiagram (myDiagram)
            DiagramLayer diagramLayer = await QueuedTask.Run <DiagramLayer>(() =>
            {
                // Create the diagram map
                var newMap = MapFactory.Instance.CreateMap(myDiagram.Name, ArcGIS.Core.CIM.MapType.NetworkDiagram, MapViewingMode.Map);
                if (newMap == null)
                {
                    return(null);
                }

                // Open the diagram map
                var mapPane = ArcGIS.Desktop.Core.ProApp.Panes.CreateMapPaneAsync(newMap, MapViewingMode.Map);
                if (mapPane == null)
                {
                    return(null);
                }

                //Add the diagram to the map
                return(newMap.AddDiagramLayer(myDiagram));
            });

            #endregion
        }
        /// <summary>
        /// Get the UtilityNetwork from active Map
        /// </summary>
        /// <returns>UtilityNetwork</returns>
        internal static UtilityNetwork GetUtilityNetworkFromActiveMap()
        {
            var unLayers = MapView.Active?.Map?.GetLayersAsFlattenedList().OfType <UtilityNetworkLayer>();

            if (unLayers == null || !unLayers.Any())
            {
                var dlLayers = MapView.Active?.Map?.GetLayersAsFlattenedList().OfType <DiagramLayer>();
                if (dlLayers == null)
                {
                    return(null);
                }

                foreach (var dlLayer in dlLayers)
                {
                    NetworkDiagram diagram = dlLayer.GetNetworkDiagram();
                    DiagramManager dm      = diagram.DiagramManager;
                    UtilityNetwork un      = dm.GetNetwork <UtilityNetwork>();
                    if (un != null)
                    {
                        return(un);
                    }
                }
            }

            foreach (var unLayer in unLayers)
            {
                UtilityNetwork un = unLayer.GetUtilityNetwork();
                if (un != null)
                {
                    return(un);
                }
            }

            return(null);
        }
Пример #3
0
        /// <summary>
        /// Get Utility Network from a map
        /// </summary>
        /// <param name="map">Map, use the active map if missing</param>
        /// <returns>Utility Network</returns>
        internal static UtilityNetwork GetUtilityNetworkFromActiveMap(Map map = null)
        {
            if (map == null)
            {
                map = MapView.Active.Map;
            }
            if (map == null)
            {
                return(null);
            }

            IReadOnlyList <Layer> myLayers = map.GetLayersAsFlattenedList();

            foreach (Layer l in myLayers)
            {
                if (l.GetType() == typeof(UtilityNetworkLayer))
                {
                    return(((UtilityNetworkLayer)l).GetUtilityNetwork());
                }
                else if (l.GetType() == typeof(DiagramLayer))
                {
                    DiagramLayer   dl = l as DiagramLayer;
                    NetworkDiagram nd = dl.GetNetworkDiagram();
                    return(nd.DiagramManager.GetNetwork <UtilityNetwork>());
                }
            }

            return(null);
        }
Пример #4
0
        public async Task <IActionResult> PutNetworkDiagram(int id, NetworkDiagram networkDiagram)
        {
            if (id != networkDiagram.DiagramId)
            {
                return(BadRequest());
            }

            _context.Entry(networkDiagram).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!NetworkDiagramExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Пример #5
0
        public void DiagramElementQueryResultAndNetworkDiagramSubsetClasses(Geodatabase geodatabase, DiagramManager diagramManager, string diagramName)
        {
            // Retrieve a diagram
            using (NetworkDiagram diagramTest = diagramManager.GetNetworkDiagram(diagramName))
            {
                // Create a DiagramElementQueryByElementTypes query object to get the diagram elements we want to work with
                DiagramElementQueryByElementTypes query = new DiagramElementQueryByElementTypes();
                query.QueryDiagramJunctionElement  = true;
                query.QueryDiagramEdgeElement      = true;
                query.QueryDiagramContainerElement = true;

                // Retrieve those diagram elements
                DiagramElementQueryResult elements = diagramTest.QueryDiagramElements(query);

                // Create a NetworkDiagramSubset object to edit this set of diagram elements
                NetworkDiagramSubset subset = new NetworkDiagramSubset();
                subset.DiagramJunctionElements  = elements.DiagramJunctionElements;
                subset.DiagramEdgeElements      = elements.DiagramEdgeElements;
                subset.DiagramContainerElements = elements.DiagramContainerElements;

                // Edit the shapes of the diagram elements - left as an exercise for the student
                TranslateDiagramElements(subset);

                // Save the new layout of the diagram elements
                diagramTest.SaveLayout(subset, true);
            }
        }
Пример #6
0
        static void Main(string[] args)
        {
            NetworkDiagram networkDiagram = new NetworkDiagram();

            do
            {
                NetworkDiagramEntity Entity = new NetworkDiagramEntity();
                Console.Write("Entity Title = ");
                Entity.Title = Console.ReadLine();
                Console.Write("Entity Duration = ");
                Entity.Duration = int.Parse(Console.ReadLine());
                networkDiagram.AddEntity(Entity);
                Console.WriteLine("Do you want to input another entity? (Y/N)");
            } while (char.ToLower(Console.ReadKey(true).KeyChar) == 'y');
            Console.Clear();
            NetworkDiagramEntity[] Entities = networkDiagram.GetAllEntites();
            for (int i = 0; i < Entities.Length; i++)
            {
                Console.WriteLine($"{i} - {Entities[i].Title}");
            }
            Console.WriteLine("Please define relations between entites by\n" +
                              "typing the number of the parent entity followed by" +
                              "the number of the child entity in a single line" +
                              "type \"-1\" (without the quotes) to finish");
            while (true)
            {
                string line = Console.ReadLine();
                if (line.Trim() == "-1")
                {
                    break;
                }
                int[] arr = Array.ConvertAll(line.Split(' '), int.Parse);
                networkDiagram.SetRelation(arr[0], arr[1]);
            }
            networkDiagram.Solve();
            Console.Clear();
            foreach (var Entity in networkDiagram.GetAllEntites())
            {
                Console.WriteLine($"{Entity.Title}:\n\tDuration = {Entity.Duration}\n\tEarliest Start = {Entity.EarliestStart}\n\t" +
                                  $"Earliest Finish = {Entity.EarliestFinish}\n\tLatest Start = {Entity.LatestStart}\n\t" +
                                  $"Latest Finish = {Entity.LatestFinish}\n\tFloat = {Entity.TotalFloat}\n");
            }
            var CriticalPaths = networkDiagram.GetCriticalPaths();

            Console.WriteLine($"There are {CriticalPaths.Length} critical paths:");
            for (int i = 0; i < CriticalPaths.Length; i++)
            {
                Console.Write($"{i + 1}: ");
                for (int j = 0; j < CriticalPaths[i].Length; j++)
                {
                    if (j != 0)
                    {
                        Console.Write(", ");
                    }
                    Console.Write(CriticalPaths[i][j].Title);
                }
                Console.WriteLine(".");
            }
        }
Пример #7
0
        /// <summary>
        /// Get the Un Schema version
        /// </summary>
        /// <param name="diagram">NetworkDiagram</param>
        /// <returns>string</returns>
        /// <remarks>UN Version 3 and earlier use only Subnetwork name
        /// UN Version 4 and later use Supported subnetwork name for container
        /// UN Version 5 and later use Supporting subnetwork name for structure</remarks>
        internal static int GetSchemaVersion(NetworkDiagram diagram)
        {
            DiagramManager diagramManager = diagram.DiagramManager;
            UtilityNetwork utilityNetwork = diagramManager.GetNetwork <UtilityNetwork>();

            UtilityNetworkDefinition unDefinition = utilityNetwork.GetDefinition();

            return(Convert.ToInt32(unDefinition.GetSchemaVersion()));
        }
        /// <summary>
        /// Get the UtilityNetwork from the layer
        /// </summary>
        /// <param name="layer">Layer</param>
        /// <returns>UtilityNetwork</returns>
        private static UtilityNetwork GetUtilityNetworkFromLayer(Layer layer)
        {
            if (layer == null)
            {
                return(null);
            }

            if (layer is UtilityNetworkLayer)
            {
                UtilityNetworkLayer utilityNetworkLayer = layer as UtilityNetworkLayer;
                return(utilityNetworkLayer.GetUtilityNetwork());
            }

            else if (layer is SubtypeGroupLayer)
            {
                CompositeLayer compositeLayer = layer as CompositeLayer;
                UtilityNetwork un;

                foreach (var v in compositeLayer.Layers)
                {
                    un = GetUtilityNetworkFromLayer(v);
                    if (un != null)
                    {
                        return(un);
                    }
                }
            }

            else if (layer is FeatureLayer)
            {
                FeatureLayer featureLayer = layer as FeatureLayer;
                using FeatureClass featureClass = featureLayer.GetFeatureClass();
                if (featureClass.IsControllerDatasetSupported())
                {
                    IReadOnlyList <Dataset> controllerDatasets = featureClass.GetControllerDatasets();
                    foreach (Dataset controllerDataset in controllerDatasets)
                    {
                        if (controllerDataset is UtilityNetwork)
                        {
                            return(controllerDataset as UtilityNetwork);
                        }
                    }
                }
            }

            else if (layer is DiagramLayer dl)
            {
                NetworkDiagram diagram        = dl.GetNetworkDiagram();
                DiagramManager diagramManager = diagram.DiagramManager;

                return(diagramManager.GetNetwork <UtilityNetwork>());
            }
            return(null);
        }
        /// <summary>
        /// Get all diagram Elements
        /// </summary>
        internal static void LoadDiagramFeatures(NetworkDiagram Diagram, out SelectionSet selection)
        {
            DiagramElementQueryResult deqr;

            selection = MapView.Active.Map.GetSelection();
            if (selection == null || selection.Count == 0)
            {
                DiagramElementQueryByElementTypes query = new DiagramElementQueryByElementTypes
                {
                    QueryDiagramContainerElement = true,
                    QueryDiagramEdgeElement      = true,
                    QueryDiagramJunctionElement  = true
                };
                deqr = Diagram.QueryDiagramElements(query);
            }
            else
            {
                List <long> junctionIDs  = new List <long>();
                List <long> edgeIDs      = new List <long>();
                List <long> containerIDs = new List <long>();

                foreach (var v in selection.ToDictionary())
                {
                    if (v.Key is FeatureLayer layer)
                    {
                        if (layer.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPoint)
                        {
                            junctionIDs.AddRange(v.Value);
                        }
                        else if (layer.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolygon)
                        {
                            containerIDs.AddRange(v.Value);
                        }
                        else if (layer.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolyline)
                        {
                            edgeIDs.AddRange(v.Value);
                        }
                    }
                }

                DiagramElementQueryByObjectIDs query1 = new DiagramElementQueryByObjectIDs
                {
                    JunctionObjectIDs  = junctionIDs,
                    ContainerObjectIDs = containerIDs,
                    EdgeObjectIDs      = edgeIDs
                };
                deqr = Diagram.QueryDiagramElements(query1);
            }


            g_DiagramJunctionElements  = deqr.DiagramJunctionElements.ToList();
            g_DiagramEdgeElements      = deqr.DiagramEdgeElements.ToList();
            g_DiagramContainerElements = deqr.DiagramContainerElements.ToList();
        }
Пример #10
0
        /// <summary>
        /// Initialize class
        /// </summary>
        /// <param name="Diagram">NetworkDiagram</param>
        public void Initialize(NetworkDiagram Diagram)
        {
            _junctions.Clear();
            _edges.Clear();
            _containers.Clear();
            _adjacentEdges.Clear();
            _containment.Clear();

            DiagramElementQueryByElementTypes query = new DiagramElementQueryByElementTypes
            {
                QueryDiagramContainerElement = true,
                QueryDiagramEdgeElement      = true,
                QueryDiagramJunctionElement  = true
            };

            DiagramElementQueryResult deqr = Diagram.QueryDiagramElements(query);

            foreach (var container in deqr.DiagramContainerElements)
            {
                _containers[container.ID] = new CustomContainer(container);

                if (container.ContainerID > 0)
                {
                    AddContainment(container.ContainerID, container.ID);
                }
            }

            foreach (var junction in deqr.DiagramJunctionElements)
            {
                _junctions[junction.ID] = new CustomJunction(junction);

                if (junction.ContainerID > 0)
                {
                    AddContainment(junction.ContainerID, junction.ID);
                }
            }

            foreach (var edge in deqr.DiagramEdgeElements)
            {
                _edges[edge.ID] = new CustomEdge(edge);

                AddAdjacentEdge(edge.FromID, edge.ID);
                AddAdjacentEdge(edge.ToID, edge.ID);

                if (edge.ContainerID > 0)
                {
                    AddContainment(edge.ContainerID, edge.ID);
                }
            }
        }
        /// <summary>
        /// Save diagram in geodatabase
        /// </summary>
        /// <param name="Diagram">Diagram to save</param>
        internal static void SaveDiagram(NetworkDiagram Diagram)
        {
            if (g_JunctionsToSave.Count + g_EdgesToSave.Count > 0)
            {
                NetworkDiagramSubset nds = new NetworkDiagramSubset
                {
                    DiagramContainerElements = null,
                    DiagramEdgeElements      = g_EdgesToSave,
                    DiagramJunctionElements  = g_JunctionsToSave
                };

                Diagram.SaveLayout(nds, true);

                MapView.Active.Redraw(true);
            }
        }
Пример #12
0
        public void RetrieveDiagramElements(MapView mapView, NetworkDiagram networkDiagram)
        {
            // Create a DiagramElementQueryByExtent to retrieve diagram element junctions whose extent
            // intersects the active map extent

            DiagramElementQueryByExtent elementQuery = new DiagramElementQueryByExtent();

            elementQuery.ExtentOfInterest             = MapView.Active.Extent;
            elementQuery.AddContents                  = false;
            elementQuery.QueryDiagramJunctionElement  = true;
            elementQuery.QueryDiagramEdgeElement      = false;
            elementQuery.QueryDiagramContainerElement = false;

            // Use this DiagramElementQueryByExtent as an argument to the QueryDiagramElements method

            DiagramElementQueryResult result = networkDiagram.QueryDiagramElements(elementQuery);
        }
Пример #13
0
        public async Task <ActionResult <NetworkDiagram> > PostNetworkDiagram(NetworkDiagram networkDiagram)
        {
            _context.NetworkDiagram.Add(networkDiagram);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (NetworkDiagramExists(networkDiagram.DiagramId))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction("GetNetworkDiagram", new { id = networkDiagram.DiagramId }, networkDiagram));
        }
        /// <summary>
        /// Apply the layout to the layer
        /// </summary>
        /// <param name="diagramLayer">Diagram Layer</param>
        public void Apply(DiagramLayer diagramLayer)
        {
            if (diagramLayer == null)
            {
                return;
            }
            QueuedTask.Run(() =>
            {
                try
                {
                    NetworkDiagram Diagram = diagramLayer.GetNetworkDiagram();
                    Execute(Diagram);

                    MapView.Active.Redraw(true);
                    MapView.Active.ZoomTo(Diagram.GetDiagramInfo().DiagramExtent.Expand(1.08, 1.08, true));
                }
                catch (Exception ex)
                {
                    CreateDiagramWithACustomLayoutModule.ShowException(ex);
                }
            });
        }
        /// <summary>
        /// Execute the layout on the Diagram
        /// </summary>
        /// <param name="diagram"></param>
        internal void Execute(NetworkDiagram diagram)
        {
            _graphModel.Initialize(diagram);

            var junctions = _graphModel.Junctions;

            if (!junctions.Any())
            {
                return;
            }

            int maxColorCount = 12;

            var containerIDs = new HashSet <int>();

            UtilityNetwork un = diagram.DiagramManager?.GetNetwork <UtilityNetwork>();

            IReadOnlyList <NetworkSource> theSources = un.GetDefinition().GetNetworkSources();

            if (!_graphModel.Containers.Any() || !_graphModel.Edges.Any())
            {
                return;
            }

            Dictionary <int, Dictionary <int, Dictionary <string, string> > > attributesBySourceID = new Dictionary <int, Dictionary <int, Dictionary <string, string> > >();

            foreach (var jsonContainer in _graphModel.Containers)
            {
                int sourceID = jsonContainer.Element.AssociatedSourceID;
                if (sourceID != 9) // Communications Device source ID
                {
                    continue;
                }

                if (!attributesBySourceID.TryGetValue(sourceID, out Dictionary <int, Dictionary <string, string> > AttributesByEID))
                {
                    AttributesByEID = FillSources(Diagram: diagram, theSources: theSources, SourceID: sourceID);
                    attributesBySourceID.Add(sourceID, AttributesByEID);
                }

                if (AttributesByEID.TryGetValue(jsonContainer.ID, out Dictionary <string, string> IdProperties))
                {
                    jsonContainer.AssetGroup = IdProperties["Asset group"];
                    jsonContainer.AssetType  = IdProperties["Asset type"];
                }
            }

            foreach (var jsonEdge in _graphModel.Edges)
            {
                int sourceID = jsonEdge.Element.AssociatedSourceID;
                if (sourceID != 15) // Communications Edge Object source ID
                {
                    continue;
                }

                if (!attributesBySourceID.TryGetValue(sourceID, out Dictionary <int, Dictionary <string, string> > AttributesByEID))
                {
                    AttributesByEID = FillSources(Diagram: diagram, theSources: theSources, SourceID: sourceID, IsEdge: true);
                    attributesBySourceID.Add(sourceID, AttributesByEID);
                }

                if (AttributesByEID.TryGetValue(jsonEdge.ID, out Dictionary <string, string> IdProperties))
                {
                    string assetGroup = IdProperties["Asset group"];
                    string assetType  = IdProperties["Asset type"];

                    if (assetGroup != "Strand" || assetType != "Fiber")
                    {
                        continue;
                    }

                    string groupColor = IdProperties["Strand Group Color"].ToString();
                    string color      = IdProperties["Strand Color"].ToString();

                    int groupColorRank = GetColorRank(groupColor);
                    int colorRank      = GetColorRank(color);

                    if (groupColorRank < 0 || colorRank < 0)
                    {
                        continue;
                    }

                    int rank = maxColorCount * groupColorRank + colorRank;

                    int fromID = jsonEdge.Element.FromID;
                    int toID   = jsonEdge.Element.ToID;

                    int fromContainerID = 0;
                    int toContainerID   = 0;

                    var fromJunction = _graphModel.GetJunction(fromID);
                    fromJunction.Rank = rank;
                    fromContainerID   = fromJunction.Element.ContainerID;
                    if (fromContainerID > 0)
                    {
                        containerIDs.Add(fromContainerID);
                    }

                    var toJunction = _graphModel.GetJunction(toID);
                    toJunction.Rank = rank;
                    toContainerID   = toJunction.Element.ContainerID;
                    if (toContainerID > 0)
                    {
                        containerIDs.Add(toContainerID);
                    }

                    if (fromContainerID > 0 && toContainerID > 0)
                    {
                        var fromContainer = _graphModel.GetContainer(fromContainerID);
                        fromContainer.ToContainers.Add(toContainerID);
                        fromContainer.HasOutputFibers = true;

                        var toContainer = _graphModel.GetContainer(toContainerID);
                        toContainer.FromContainers.Add(fromContainerID);
                        toContainer.HasInputFibers = true;
                        if (fromJunction.Rank < toContainer.FromJunctionRankMin)
                        {
                            toContainer.FromJunctionRankMin = fromJunction.Rank;
                        }
                    }
                }
            }

            attributesBySourceID = null;

            foreach (var junction in junctions)
            {
                if (junction.Element.ContainerID < 1)
                {
                    continue;
                }

                if (junction.Rank >= 0)
                {
                    continue;
                }

                _graphModel.GetConnectedJunctions(junction.Element.ID, out IList <int> connectedJunctions);

                int             fromRank      = -1;
                int             toRank        = -1;
                CustomContainer fromContainer = null;
                CustomContainer toContainer   = null;

                int count = Math.Min(connectedJunctions.Count, 2);
                for (int i = 0; i < count; i++)
                {
                    var connectedJunction = _graphModel.GetJunction(connectedJunctions[i]);
                    var container         = _graphModel.GetContainer(connectedJunction.Element.ContainerID);
                    if (container.HasInputFibers)
                    {
                        fromRank      = connectedJunction.Rank;
                        fromContainer = container;
                    }
                    else if (container.HasOutputFibers)
                    {
                        toRank      = connectedJunction.Rank;
                        toContainer = container;
                    }
                }

                if (fromRank >= 0 || toRank >= 0)
                {
                    junction.Rank = fromRank >= 0 ? fromRank : toRank;

                    var container = _graphModel.GetContainer(junction.Element.ContainerID);
                    containerIDs.Add(container.Element.ID);

                    if (fromContainer != null)
                    {
                        container.FromContainers.Add(fromContainer.Element.ID);
                        fromContainer.ToContainers.Add(container.Element.ID);
                    }

                    if (toContainer != null)
                    {
                        container.ToContainers.Add(toContainer.Element.ID);
                        toContainer.FromContainers.Add(container.Element.ID);
                        if (junction.Rank < toContainer.FromJunctionRankMin)
                        {
                            toContainer.FromJunctionRankMin = junction.Rank;
                        }
                    }
                }
            }

            var    diagramInfo   = diagram.GetDiagramInfo();
            var    diagramExtent = diagramInfo.DiagramExtent;
            double ySpacing      = diagramInfo.ContainerMargin;
            double xSpacingMin   = diagramInfo.ContainerMargin * 15;

            var startContainers = new List <CustomContainer>();

            foreach (var containerID in containerIDs)
            {
                var container = _graphModel.GetContainer(containerID);
                if (!(container is null) && (container.FromContainers.Count > 0 || container.ToContainers.Count < 1))
                {
                    continue;
                }

                if (container.Element is null)
                {
                    continue;
                }

                var parent = _graphModel.GetContainer(container.Element.ContainerID);
                if (parent == null)
                {
                    continue;
                }

                if (parent.AssetType != "Hub Terminator" && parent.AssetType != "Mid Cable Splice Enclosure")
                {
                    continue;
                }

                startContainers.Add(container);
            }

            double startY = diagramExtent.YMax;

            foreach (var startContainer in startContainers)
            {
                if (startContainer.FromContainerOrder != Int32.MaxValue)
                {
                    continue;
                }

                var toContainerIDs = new HashSet <int>();
                foreach (var toContainerID in startContainer.ToContainers)
                {
                    toContainerIDs.Add(toContainerID);
                }

                double startX = diagramExtent.XMin;

                startContainer.X = startX;
                startContainer.Y = startY;

                while (toContainerIDs.Count > 0)
                {
                    double y     = startY;
                    bool   first = true;

                    var toContainers = new List <CustomContainer>();
                    foreach (var containerID in toContainerIDs)
                    {
                        var toContainer = _graphModel.GetContainer(containerID);
                        if (startContainer.FromContainerOrder == Int32.MaxValue)
                        {
                            toContainers.Add(toContainer);
                        }
                    }

                    var sortedContainers = toContainers.OrderBy(cntr => cntr.FromContainerOrder + 0.001 * cntr.FromJunctionRankMin);

                    int vertivalOrder = 0;
                    foreach (var container in sortedContainers)
                    {
                        int containerID = container.Element.ID;

                        container.Y = y;

                        y -= (_graphModel.GetContainedElements(containerID).Count() * ySpacing + 7 * diagramInfo.ContainerMargin);

                        if (first)
                        {
                            first       = false;
                            container.X = startX + xSpacingMin;
                            startX      = container.X;
                        }
                        else
                        {
                            container.X = startX;
                        }

                        foreach (var toContainerID in container.ToContainers)
                        {
                            var toContainer = _graphModel.GetContainer(toContainerID);
                            if (toContainer.FromContainerOrder == Int32.MaxValue)
                            {
                                toContainer.FromContainerOrder = vertivalOrder;
                                toContainerIDs.Add(toContainerID);
                            }
                        }

                        vertivalOrder++;

                        toContainerIDs.Remove(containerID);
                    }
                }

                startY -= (_graphModel.GetContainedElements(startContainer.Element.ID).Count() * ySpacing + 4 * diagramInfo.ContainerMargin);
            }

            IList <DiagramJunctionElement> junctionsToSave = new List <DiagramJunctionElement>();

            SpatialReference spatialRef      = diagramInfo.DiagramExtent.SpatialReference;
            MapPointBuilder  mapPointBuilder = new MapPointBuilder(spatialRef)
            {
                Z = 0
            };

            foreach (var containerID in containerIDs)
            {
                var container = _graphModel.GetContainer(containerID);
                if (container == null)
                {
                    continue;
                }

                int rankCount = maxColorCount * maxColorCount;

                BitArray isEmpty = new BitArray(rankCount, true);

                double yTop = container.Y;

                var containedJunctions   = _graphModel.GetContainedElements(containerID);
                var unconnectedJunctions = new Stack <int>();

                foreach (var junctionID in containedJunctions)
                {
                    var junction = _graphModel.GetJunction(junctionID);
                    if (junction == null)
                    {
                        continue;
                    }

                    if (junction.Rank < 0)
                    {
                        unconnectedJunctions.Push(junction.Element.ID);
                        continue;
                    }

                    isEmpty[junction.Rank] = false;

                    mapPointBuilder.X      = container.X;
                    mapPointBuilder.Y      = yTop - junction.Rank * ySpacing;
                    junction.Element.Shape = mapPointBuilder.ToGeometry();

                    junctionsToSave.Add(junction.Element);
                }

                int rank = 0;
                while (unconnectedJunctions.Count > 0 && rank < rankCount)
                {
                    if (isEmpty[rank])
                    {
                        var junction = _graphModel.GetJunction(unconnectedJunctions.Pop());
                        if (junction != null)
                        {
                            mapPointBuilder.X      = container.X;
                            mapPointBuilder.Y      = yTop - rank * ySpacing;
                            junction.Element.Shape = mapPointBuilder.ToGeometry();
                            junctionsToSave.Add(junction.Element);
                        }
                    }
                    rank++;
                }
            }

            if (junctionsToSave.Count > 0)
            {
                NetworkDiagramSubset nds = new NetworkDiagramSubset
                {
                    DiagramJunctionElements = junctionsToSave
                };

                diagram.SaveLayout(nds, true);
            }
        }
Пример #16
0
        /// <summary>
        /// Apply the layout to the diagram layer
        /// </summary>
        /// <param name="diagramLayer">Diagram Layer</param>
        public void Apply(DiagramLayer diagramLayer)
        {
            if (diagramLayer == null)
            {
                return;
            }
            try
            {
                QueuedTask.Run(() =>
                {
                    NetworkDiagram Diagram = diagramLayer.GetNetworkDiagram();

                    var selection = MapView.Active.Map.GetSelection();
                    if (selection != null && selection.Count > 0)
                    {
                        List <long> JunctionObjectIDs  = new List <long>();
                        List <long> ContainerObjectIDs = new List <long>();
                        List <long> EdgeObjectIDs      = new List <long>();

                        foreach (var v in selection.ToDictionary())
                        {
                            if (v.Key is FeatureLayer layer)
                            {
                                if (layer.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPoint)
                                {
                                    JunctionObjectIDs.AddRange(v.Value);
                                }
                                else if (layer.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolygon)
                                {
                                    ContainerObjectIDs.AddRange(v.Value);
                                }
                                else if (layer.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolyline)
                                {
                                    EdgeObjectIDs.AddRange(v.Value);
                                }
                            }
                        }

                        Diagram.ApplyLayout(layoutParameters, new DiagramElementObjectIDs
                        {
                            ContainerObjectIDs = ContainerObjectIDs,
                            JunctionObjectIDs  = JunctionObjectIDs,
                            EdgeObjectIDs      = EdgeObjectIDs
                        }, ArcGIS.Core.Data.ServiceSynchronizationType.Synchronous);
                    }
                    else
                    {
                        Diagram.ApplyLayout(layoutParameters, ArcGIS.Core.Data.ServiceSynchronizationType.Synchronous);
                    }

                    MapView.Active.Redraw(true);
                    MapView.Active.ZoomTo(Diagram.GetDiagramInfo().DiagramExtent.Expand(1.05, 1.05, true));

                    if (FrameworkApplication.CurrentTool.Contains("_networkdiagrams_"))
                    {
                        FrameworkApplication.SetCurrentToolAsync("esri_mapping_exploreTool");
                    }
                });
            }
            catch (Exception ex)
            {
                ShowException(ex);
            }
        }
        /// <summary>
        /// Get a GlogalID list per subnework name
        /// </summary>
        /// <param name="diagram">Network Diagram</param>
        /// <returns>Dictionary(Subnetwork name, GlobalID list)</returns>
        internal static Dictionary <string, List <string> > GetSubnetworkNameToGlobalIDs(NetworkDiagram diagram)
        {
            string       subnetworkNameLabel;
            const string subnetworkNameLabelFeature  = "Subnetwork name";
            const string subnetworkNameLabelAssembly = "Supported subnetwork name";
            const string unknwonLabel = "Unknown";

            string useSubnetworkNameLabelAssembly = GetSchemaVersion(diagram) <= 3 ? subnetworkNameLabelFeature : subnetworkNameLabelAssembly;

            Dictionary <int, string>            jctIDToSubnetworkName     = new Dictionary <int, string>();
            Dictionary <string, List <string> > subnetworkNameToGlobalIDs = new Dictionary <string, List <string> >();
            List <string> assemblySources = new List <string>();
            JObject       content         = JObject.Parse(diagram.GetContent(false, false, true, false));

            JObject mapping = content["sourceMapping"] as JObject;

            foreach (var item in mapping)
            {
                if (item.Key.Contains("Assembly"))
                {
                    assemblySources.Add((string)item.Value);
                }
            }

            JToken junctions = content["junctions"];

            foreach (var item in junctions)
            {
                string source = item["assocSourceID"].ToString();
                if (assemblySources.Contains(source))
                {
                    subnetworkNameLabel = useSubnetworkNameLabelAssembly;
                }
                else
                {
                    subnetworkNameLabel = subnetworkNameLabelFeature;
                }

                if (item["attributes"] is JObject attributes && attributes.ContainsKey(subnetworkNameLabel))
                {
                    jctIDToSubnetworkName.Add((int)item["id"], attributes[subnetworkNameLabel].ToString());
                }
Пример #18
0
 public NetworkDiagramModel(NetworkDiagram diagram)
 {
     Layers      = diagram.Layers.Select(l => new LayerModel(l)).ToList();
     Connections = diagram.Connections.Select(c => new ConnectionModel(c)).ToList();
 }
        /// <summary>
        /// Fill the dictionary with Element Id, Properties
        /// </summary>
        /// <param name="Diagram">Network Diagram</param>
        /// <param name="theSources">List of network sources</param>
        /// <param name="SourceID">Source Id</param>
        /// <param name="IsEdge">Flag for edges treatement</param>
        /// <returns>Dictionary</returns>
        private static Dictionary <int, Dictionary <string, string> > FillSources(NetworkDiagram Diagram, IReadOnlyList <NetworkSource> theSources, int SourceID, bool IsEdge = false)
        {
            Dictionary <int, Dictionary <string, string> > AttributesByEID = new Dictionary <int, Dictionary <string, string> >();

            NetworkSource source = theSources.FirstOrDefault(a => a.ID == SourceID);

            if (source != null)
            {
                string[] attributeNames;
                if (IsEdge)
                {
                    attributeNames = new string[4] {
                        "Asset group", "Asset type", "Strand Group Color", "Strand Color"
                    }
                }
                ;
                else
                {
                    attributeNames = new string[2] {
                        "Asset group", "Asset type"
                    }
                };

                string  content        = Diagram.GetSourceAttributeValues(attributeNames: attributeNames, sourceName: source.Name, useCodedValueNames: true);
                JObject attributesList = JObject.Parse(content);
                JToken  elements;

                if (IsEdge)
                {
                    elements = attributesList["edges"];
                    if (!(elements == null || !elements.Any()))
                    {
                        foreach (var element in elements)
                        {
                            int id = (int)element["id"];
                            if (!AttributesByEID.TryGetValue(id, out Dictionary <string, string> IdProperties))
                            {
                                IdProperties = new Dictionary <string, string>();
                                AttributesByEID.Add(id, IdProperties);
                            }

                            if (element["attributes"] is JObject attributes)
                            {
                                IdProperties.Add("Asset group", attributes["Asset group"].ToString());
                                IdProperties.Add("Asset type", attributes["Asset type"].ToString());
                                IdProperties.Add("Strand Group Color", attributes["Strand Group Color"].ToString());
                                IdProperties.Add("Strand Color", attributes["Strand Color"].ToString());
                            }
                        }
                    }
                }
                else
                {
                    elements = attributesList["containers"];
                    if (!(elements == null || !elements.Any()))
                    {
                        foreach (var element in elements)
                        {
                            int id = (int)element["id"];
                            if (!AttributesByEID.TryGetValue(id, out Dictionary <string, string> IdProperties))
                            {
                                IdProperties = new Dictionary <string, string>();
                                AttributesByEID.Add(id, IdProperties);
                            }
                            if (element["attributes"] is JObject attributes)
                            {
                                IdProperties.Add("Asset group", attributes["Asset group"].ToString());
                                IdProperties.Add("Asset type", attributes["Asset type"].ToString());
                            }
                        }
                    }

                    elements = attributesList["junctions"];
                    if (!(elements == null || !elements.Any()))
                    {
                        foreach (var element in elements)
                        {
                            int id = (int)element["id"];
                            if (!AttributesByEID.TryGetValue(id, out Dictionary <string, string> IdProperties))
                            {
                                IdProperties = new Dictionary <string, string>();
                                AttributesByEID.Add(id, IdProperties);
                            }
                            if (element["attributes"] is JObject attributes)
                            {
                                IdProperties.Add("Asset group", attributes["Asset group"].ToString());
                                IdProperties.Add("Asset type", attributes["Asset type"].ToString());
                            }
                        }
                    }
                }
            }

            return(AttributesByEID);
        }
        /// <summary>
        /// Generate a diagram and apply the EnclosureLayout custom telco layout on its content
        /// </summary>
        /// <param name="cps">Cancelable Progressor Source to show the progression</param>
        /// <returns>An error comment if needed, empty of no error</returns>
        private async Task <string> RunCancelableEnclosure(CancelableProgressorSource cps)
        {
            string         status    = "";
            List <Guid>    listIds   = null;
            NetworkDiagram myDiagram = null;

            await QueuedTask.Run(() =>
            {
                cps.Progressor.Max = 3;

                cps.Progressor.Value  += 0;
                cps.Progressor.Status  = (cps.Progressor.Value * 100 / cps.Progressor.Max) + @" % Completed";
                cps.Progressor.Message = "Step 1 – Get Selected Guids";

                try
                {
                    if (m_DiagramManager == null)
                    {
                        UtilityNetwork un = GetUtilityNetworkFromActiveMap();
                        if (un == null)
                        {
                            return;
                        }

                        m_DiagramManager = un.GetDiagramManager();

                        if (m_DiagramManager == null)
                        {
                            return;
                        }
                    }

                    if (m_Template == null)
                    {
                        m_Template = m_DiagramManager.GetDiagramTemplate(csTemplateName);
                        if (m_Template == null)
                        {
                            return;
                        }
                    }

                    listIds = GetSelectedGuidFromActiveMap();
                    if (listIds.Count == 0)
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                    status = string.Format("Selected guids\n{0}", ExceptionFormat(ex));
                }
            }, cps.Progressor);

            await QueuedTask.Run(() =>
            {
                cps.Progressor.Value  += 1;
                cps.Progressor.Status  = (cps.Progressor.Value * 100 / cps.Progressor.Max) + @" % Completed";
                cps.Progressor.Message = string.Format("Step 2 – Generate a diagram based on the '{0}' template", csTemplateName);

                try
                {
                    // generate a diagram
                    myDiagram = m_DiagramManager.CreateNetworkDiagram(diagramTemplate: m_Template, globalIDs: listIds);
                }
                catch (Exception ex)
                {
                    if (string.IsNullOrEmpty(status))
                    {
                        status = string.Format("Generate diagram\n{0}", ExceptionFormat(ex));
                    }
                    else
                    {
                        status = string.Format("Generate diagram\n{0}", ExceptionFormat(ex));
                    }
                }
            }, cps.Progressor);

            await QueuedTask.Run(() =>
            {
                cps.Progressor.Value  += 1;
                cps.Progressor.Status  = (cps.Progressor.Value * 100 / cps.Progressor.Max) + @" % Completed";
                cps.Progressor.Message = "Step 3 – Apply the EnclosureLayout custom telco layout";

                try
                {
                    // apply the telco custom layout
                    EnclosureLayout myLayout = new EnclosureLayout();
                    myLayout.Execute(myDiagram);

                    ShowDiagram(myDiagram);
                }
                catch (Exception ex)
                {
                    if (string.IsNullOrEmpty(status))
                    {
                        status = string.Format("Apply layout\n{0}", ExceptionFormat(ex));
                    }
                    else
                    {
                        status = string.Format("Apply layout\n{0}", ExceptionFormat(ex));
                    }
                }
            });

            return(status);
        }
Пример #21
0
        /// <summary>
        /// Run the rotate selected junctions
        /// </summary>
        /// <param name="rotation">Rotation Angle</param>
        private void RotateSelectedJunctions(double rotation)
        {
            if (MapView.Active != null)
            {
                // Get the Network Diagram Layer
                DiagramLayer diagramLayer = GetDiagramLayerFromMap(MapView.Active.Map);
                if (diagramLayer != null)
                {
                    QueuedTask.Run(() =>
                    {
                        // Get the Network Diagram
                        NetworkDiagram diagram = diagramLayer.GetNetworkDiagram();
                        if (diagram != null)
                        {
                            try
                            {
                                List <long> junctionObjectIDs = new List <long>();

                                // get the selection by Layer
                                SelectionSet selection = MapView.Active.Map.GetSelection();

                                // Get the selection only for junctions
                                foreach (var v in selection.ToDictionary())
                                {
                                    FeatureLayer featureLayer = v.Key as FeatureLayer;
                                    if (featureLayer != null)
                                    {
                                        if (featureLayer.ShapeType != esriGeometryType.esriGeometryPoint)
                                        {
                                            continue;
                                        }

                                        junctionObjectIDs.AddRange(v.Value);
                                    }
                                }

                                // if no junction selected, work on all diagram junctions
                                DiagramElementQueryResult result;
                                if (junctionObjectIDs.Count == 0)
                                {
                                    DiagramElementQueryByElementTypes query = new DiagramElementQueryByElementTypes
                                    {
                                        QueryDiagramContainerElement = false,
                                        QueryDiagramEdgeElement      = false,
                                        QueryDiagramJunctionElement  = true
                                    };

                                    result = diagram.QueryDiagramElements(query);
                                }
                                else
                                {
                                    DiagramElementQueryByObjectIDs query = new DiagramElementQueryByObjectIDs
                                    {
                                        AddConnected      = false,
                                        AddContents       = false,
                                        JunctionObjectIDs = junctionObjectIDs
                                    };

                                    result = diagram.QueryDiagramElements(query);
                                }

                                List <DiagramJunctionElement> junctionsToSave = new List <DiagramJunctionElement>();

                                // Set the new Rotation Value
                                foreach (var junction in result.DiagramJunctionElements)
                                {
                                    if (_isRelative)
                                    {
                                        junction.Rotation += rotation;
                                    }
                                    else
                                    {
                                        junction.Rotation = rotation;
                                    }

                                    junctionsToSave.Add(junction);
                                }

                                // Save junctions if needed
                                if (junctionsToSave.Count() > 0)
                                {
                                    NetworkDiagramSubset nds = new NetworkDiagramSubset
                                    {
                                        DiagramEdgeElements      = null,
                                        DiagramContainerElements = null,
                                        DiagramJunctionElements  = junctionsToSave
                                    };

                                    diagram.SaveLayout(nds, true);

                                    MapView.Active.Redraw(true);

                                    // re set the selection
                                    if (selection.Count > 0)
                                    {
                                        MapView.Active.Map.SetSelection(selection, SelectionCombinationMethod.New);
                                    }
                                }
                            }
                            catch (GeodatabaseException e)
                            {
                                MessageBox.Show(e.Message, "Failed to Rotate Junctions ");
                            }
                        }
                    });
                }
            }
        }