public void SearchContactsTest()
        {
            //
            // digraph G {
            //   "7"  -> "11"
            //   "7"  -> "8"
            //   "5"  -> "11"
            //   "3"  -> "8"
            //   "3"  -> "10"
            //   "11" -> "2"
            //   "11" -> "9"
            //   "11" -> "10"
            //   "8"  -> "9"
            // }

            var ret = TopologicalSort.Sort(
                new HashSet <int>(new[] { 1, 7, 5, 3, 8, 11, 2, 9, 10, 2 }),
                new HashSet <Tuple <int, int> >(
                    new[] {
                Tuple.Create(7, 11),
                Tuple.Create(7, 8),
                Tuple.Create(5, 11),
                Tuple.Create(3, 8),
                Tuple.Create(3, 10),
                Tuple.Create(11, 2),
                Tuple.Create(11, 9),
                Tuple.Create(11, 10),
                Tuple.Create(8, 9)
            }
                    )
                ).ToList();

            System.Diagnostics.Debug.Assert(ret.SequenceEqual(new[] { 1, 7, 5, 11, 2, 3, 8, 9, 10 }));
        }
Ejemplo n.º 2
0
        public static Queue <MyInfo> PerformTopoSort(List <MyInfo> nodes)
        {
            var sorter = new TopologicalSort <MyInfo>();

            Queue <MyInfo> outQueue;

            foreach (var myInfo in nodes.Where(n => n.Checked))
            {
                if (myInfo.Dependencies.Any())
                {
                    foreach (var dependency in myInfo.Dependencies)
                    {
                        if (myInfo.Equals(dependency))
                        {
                            throw new Exception("Cyclic Dependency detected from '" + dependency + "' to '" + myInfo + "'");
                        }

                        sorter.Edge(myInfo, dependency);
                    }
                }
                else
                {
                    sorter.Edge(myInfo);
                }
            }

            sorter.Sort(out outQueue);

            return(outQueue);
        }
Ejemplo n.º 3
0
        public void DoImport(Stream backupStream, Action <ExportImportProgressInfo> progressCallback)
        {
            var progressInfo      = new ExportImportProgressInfo();
            var membersTotalCount = 0;

            using (var streamReader = new StreamReader(backupStream))
                using (var reader = new JsonTextReader(streamReader))
                {
                    while (reader.Read())
                    {
                        if (reader.TokenType == JsonToken.PropertyName)
                        {
                            if (reader.Value.ToString() == "MembersTotalCount")
                            {
                                membersTotalCount = reader.ReadAsInt32() ?? 0;
                            }
                            else if (reader.Value.ToString() == "Members")
                            {
                                reader.Read();
                                if (reader.TokenType == JsonToken.StartArray)
                                {
                                    reader.Read();

                                    var members      = new List <Member>();
                                    var membersCount = 0;
                                    //TODO: implement to iterative import without whole members loading
                                    while (reader.TokenType != JsonToken.EndArray)
                                    {
                                        var member = _serializer.Deserialize <Member>(reader);
                                        members.Add(member);
                                        membersCount++;

                                        reader.Read();
                                    }
                                    //Need to import by topological sort order, because Organizations have a graph structure and here references integrity must be preserved
                                    var organizations             = members.OfType <Organization>();
                                    var nodes                     = new HashSet <string>(organizations.Select(x => x.Id));
                                    var edges                     = new HashSet <Tuple <string, string> >(organizations.Where(x => !string.IsNullOrEmpty(x.ParentId)).Select(x => new Tuple <string, string>(x.Id, x.ParentId)));
                                    var orgsTopologicalSortedList = TopologicalSort.Sort(nodes, edges);
                                    members = members.OrderByDescending(x => orgsTopologicalSortedList.IndexOf(x.Id)).ToList();
                                    for (int i = 0; i < membersCount; i += _batchSize)
                                    {
                                        _memberService.SaveChanges(members.Skip(i).Take(_batchSize).ToArray());

                                        if (membersTotalCount > 0)
                                        {
                                            progressInfo.Description = $"{ i } of { membersTotalCount } members imported";
                                        }
                                        else
                                        {
                                            progressInfo.Description = $"{ i } members imported";
                                        }
                                        progressCallback(progressInfo);
                                    }
                                }
                            }
                        }
                    }
                }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Calculate all cells in spreadsheet.
        /// </summary>
        /// <exception cref="SpreadsheetInternalException">Cyclic dependency found.</exception>
        public void Calculate()
        {
            IList <string> sortedKeys;

            try
            {
                sortedKeys = TopologicalSort.Sort(
                    GetAllKeys(),
                    key => GetCellByKey(key).CellDependencies.Where(d => CellInSpreadsheet(d))
                    );
            }
            catch (CyclicDependencyException exception)
            {
                throw new SpreadsheetInternalException($"Cannot calculate spreadsheet, there is cyclic dependencies between cells. {exception.Message}", exception);
            }

            foreach (var key in sortedKeys)
            {
                CalculateCell(GetCellByKey(key));
            }

            // Validate that all cells were calculated.
            foreach (var key in GetAllKeys())
            {
                if (GetCellByKey(key).CellState == CellState.Pending)
                {
                    throw new SpreadsheetInternalException($"The cell {key} was lost during the calculation.");
                }
            }
        }
Ejemplo n.º 5
0
        public void Process(Configurator configurator, bool runAsCoroutine = true)
        {
            if (configurator != null)
            {
                m_configurator = configurator;
            }
            Logger.LogDebug(this, "Starting to run init actions", Logger.TagFlags.INIT);
            ValidateDependencies();
            List <ITopologicalNode> list = new List <ITopologicalNode>();

            list          = m_initActions.ConvertAll((Converter <InitAction, ITopologicalNode>)((InitAction obj) => obj));
            list          = TopologicalSort.Sort(list);
            m_initActions = list.ConvertAll((ITopologicalNode obj) => obj as InitAction);
            EventDispatcher.AddListener <ActionCompleteEvent>(OnInitActionComplete);
            EventDispatcher.DispatchEvent(new InitStartEvent(InitActions.Count));
            if (CheckAllComplete())
            {
                OnAllInitComplete();
                return;
            }
            m_runAsCoroutine = runAsCoroutine;
            if (m_runAsCoroutine)
            {
                BaseGameController.Instance.StartCoroutine(ExecuteReadyActionsCoroutine());
            }
            else
            {
                CoroutineHelper.RunCoroutineToCompletion(ExecuteReadyActionsCoroutine());
            }
        }
        public void Test()
        {
            var graph1 = new DirectedWeightedGraph(false);

            for (int i = 'a'; i <= 'h'; i++)
            {
                graph1.AddVertex(Convert.ToString(Convert.ToChar(i)));
            }

            graph1.AddEdge("a", "b", 1);
            graph1.AddEdge("b", "c", 2);
            graph1.AddEdge("c", "d", 3);
            graph1.AddEdge("a", "g", 600);
            graph1.AddEdge("b", "f", 0);
            graph1.AddEdge("e", "b", 7);


            Stack <Vertex> stack = new Stack <Vertex>();

            stack.Push(graph1.GetVertex("d"));
            stack.Push(graph1.GetVertex("c"));
            stack.Push(graph1.GetVertex("f"));
            stack.Push(graph1.GetVertex("b"));
            stack.Push(graph1.GetVertex("g"));
            stack.Push(graph1.GetVertex("a"));
            stack.Push(graph1.GetVertex("e"));
            stack.Push(graph1.GetVertex("h"));

            var testStack = TopologicalSort <DirectedWeightedGraph> .Sort(graph1);

            for (int i = 'a'; i <= 'h'; i++)
            {
                Assert.AreEqual(stack.Pop(), testStack.Pop());
            }
        }
Ejemplo n.º 7
0
        public void Process(bool runAsCoroutine = true, MonoBehaviour coroutineOwner = null)
        {
            m_coroutineOwner = coroutineOwner;
            ValidateDependencies();
            List <ITopologicalNode> list = new List <ITopologicalNode>();

            list = m_initActions.ConvertAll((Converter <InitAction, ITopologicalNode>)((InitAction obj) => obj));
            list.AddRange(m_completedActions.ConvertAll((Converter <CompletedInitAction, ITopologicalNode>)((CompletedInitAction obj) => obj)));
            list = TopologicalSort.Sort(list);
            list.RemoveAll((ITopologicalNode obj) => obj is CompletedInitAction);
            m_initActions = list.ConvertAll((ITopologicalNode obj) => obj as InitAction);
            EventDispatcher.AddListener <ActionCompleteEvent>(OnInitActionComplete);
            EventDispatcher.DispatchEvent(new InitStartEvent(InitActions.Count));
            if (CheckAllComplete())
            {
                OnAllInitComplete();
                return;
            }
            m_runAsCoroutine = runAsCoroutine;
            if (m_runAsCoroutine)
            {
                m_coroutineOwner.StartCoroutine(ExecuteReadyActionsCoroutine());
            }
            else
            {
                CoroutineHelper.RunCoroutineToCompletion(ExecuteReadyActionsCoroutine());
            }
        }
Ejemplo n.º 8
0
        public List <string> GetTableOrderByDependencies()
        {
            //Chứa cặp các table và các dependency của chúng
            Dictionary <string, Item> existedAdj = new Dictionary <string, Item>();
            List <Item> graphTableDependency     = new List <Item>();

            List <string> tables = _dbUtilities.GetAllTable();

            foreach (var table in tables)
            {
                List <Item> adjTableDenpendencies = new List <Item>();
                //List các table dependency của table
                var dependencies = _dbUtilities.GetAllTableDependOn(table).ToArray();

                foreach (var dependency in dependencies)
                {
                    if (!table.Equals(dependency))               //Kiểm tra có phải là chính nó
                    {
                        if (!existedAdj.ContainsKey(dependency)) //Kiểm tra là đã tạo Item này chưa
                        {
                            var item = new Item(dependency);
                            existedAdj.Add(item.Name, item);
                        }
                        adjTableDenpendencies.Add(existedAdj[dependency]); //Tạo mới cạnh
                    }
                }
                //Tạo mới đỉnh là table các cạch là adjTableDenpendencies
                graphTableDependency.Add(new Item(table, adjTableDenpendencies.ToArray()));
            }

            return(TopologicalSort.Sort(graphTableDependency.ToArray(), x => x.Dependencies));
        }
Ejemplo n.º 9
0
        private void SortDependencyGraph()
        {
            OnProgress("Sorting dependency graph");
            var sort = new TopologicalSort <CodeUnit>(_rootUnit, parent => parent.Dependencies);

            _orderedUnitList = sort.Sort();
        }
Ejemplo n.º 10
0
        public static IEnumerable <Step <TCtx> > OrderRequiredFirst(DependencyGraphBuilder <Step <TCtx> > _graphBuilder, IEnumerable <Step <TCtx> > steps)
        {
            var sort     = new TopologicalSort <Step <TCtx> >();
            var unsorted = steps.ToList();
            var edges    = _graphBuilder.BuildDependencyGraph(unsorted).ToArray();

            return(sort.Sort(unsorted.ToList(), edges));
        }
Ejemplo n.º 11
0
 private void CalculateReachableBlocks()
 {
     _reachableBlocks = new Dictionary <BasicBlock, HashSet <BasicBlock> >();
     foreach (var block in TopologicalSort.Sort(_basicBlocks, p => p.ExitBlocks, ignoreCycles: true))
     {
         _reachableBlocks[block] = CalculateReachableBlocks(block, new HashSet <BasicBlock>());
     }
 }
Ejemplo n.º 12
0
        public void TopoTest_One()
        {
            TopologicalSort.Node        node  = new TopologicalSort.Node();
            List <TopologicalSort.Node> nodes = new List <TopologicalSort.Node> {
                node
            };

            List <TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes);

            Assert.AreEqual(sortedNodes[0], nodes[0]);
        }
Ejemplo n.º 13
0
        public void Sort_DirectedGraphWithoutEdges_NothingToSort()
        {
            Dictionary <string, string[]> mock = new Dictionary <string, string[]>();

            mock.Add("A", new string[0]);
            mock.Add("B", new string[0]);
            mock.Add("C", new string[0]);

            var graphWithoutEdges = new[] { "A", "B", "C" };

            Assert.Equal(graphWithoutEdges, TopologicalSort.Sort(graphWithoutEdges, item => mock[item]));
        }
Ejemplo n.º 14
0
        public void Test_Topological_Sorting()
        {
            var edgeList = new int[3][];

            edgeList[0] = new int[] { 1, 2 };
            edgeList[1] = new int[] { 2, 3 };
            edgeList[2] = new int[] { 3, 4 };
            var graph           = Graph.BuildDirectedGraph(edgeList);
            var topologicalSort = new TopologicalSort(4, graph);

            Assert.Equal(new int[] { 4, 3, 2, 1 }, topologicalSort.Sort());
        }
Ejemplo n.º 15
0
 public void TopoTest_Circular()
 {
     TopologicalSort.Node a = new TopologicalSort.Node();
     TopologicalSort.Node b = new TopologicalSort.Node();
     a.Dependencies.Add(b);
     b.Dependencies.Add(a);
     List <TopologicalSort.Node> nodes = new List <TopologicalSort.Node> {
         a, b
     };
     // ReSharper disable once UnusedVariable
     List <TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes);
 }
Ejemplo n.º 16
0
        public void TopoTest_NoDependencies()
        {
            TopologicalSort.Node        a     = new TopologicalSort.Node();
            TopologicalSort.Node        b     = new TopologicalSort.Node();
            List <TopologicalSort.Node> nodes = new List <TopologicalSort.Node> {
                a, b
            };
            List <TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes);

            Assert.IsTrue(sortedNodes.Contains(a));
            Assert.IsTrue(sortedNodes.Contains(b));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Reorders Any WixSearch items.
        /// </summary>
        /// <param name="output">Output containing the tables to process.</param>
        private void ReorderWixSearch(Output output)
        {
            Table wixSearchTable = output.Tables["WixSearch"];

            if (null == wixSearchTable || wixSearchTable.Rows.Count == 0)
            {
                // nothing to do!
                return;
            }

            RowDictionary rowDictionary = new RowDictionary();

            foreach (Row row in wixSearchTable.Rows)
            {
                rowDictionary.AddRow(row);
            }

            Constraints constraints            = new Constraints();
            Table       wixSearchRelationTable = output.Tables["WixSearchRelation"];

            if (null != wixSearchRelationTable && wixSearchRelationTable.Rows.Count > 0)
            {
                // add relational info to our data...
                foreach (Row row in wixSearchRelationTable.Rows)
                {
                    constraints.AddConstraint((string)row[0], (string)row[1]);
                }
            }

            this.FindCircularReference(constraints);

            if (this.Core.EncounteredError)
            {
                return;
            }

            this.FlattenDependentReferences(constraints);

            // Reorder by topographical sort (http://en.wikipedia.org/wiki/Topological_sorting)
            // We use a variation of Kahn (1962) algorithm as described in
            // Wikipedia, with the additional criteria that start nodes are sorted
            // lexicographically at each step to ensure a deterministic ordering
            // based on 'after' dependencies and ID.
            TopologicalSort sorter    = new TopologicalSort();
            List <string>   sortedIds = sorter.Sort(rowDictionary.Keys, constraints);

            // Now, re-write the table with the searches in order...
            wixSearchTable.Rows.Clear();
            foreach (string id in sortedIds)
            {
                wixSearchTable.Rows.Add(rowDictionary[id]);
            }
        }
Ejemplo n.º 18
0
    public List <IStrategyResult> ExecuteQueuedActions()
    {
        var results       = new List <IStrategyResult>();
        var actions       = this.queuedActions.AsQueryable();
        var sortedActions = TopologicalSort.Sort(actions, action => action.Dependencies, action => action.Name);

        foreach (var strategyAction in sortedActions)
        {
            this.queuedActions.Remove(strategyAction);
            results.Add(Execute(strategyAction.Name));
        }
        return(results);
    }
Ejemplo n.º 19
0
    public static void UpdateSorting()
    {
        FilterListByVisibility(staticSpriteList, currentlyVisibleStaticSpriteList);
        FilterListByVisibility(moveableSpriteList, currentlyVisibleMoveableSpriteList);

        ClearMovingDependencies(currentlyVisibleStaticSpriteList);
        ClearMovingDependencies(currentlyVisibleMoveableSpriteList);

        AddMovingDependencies(currentlyVisibleMoveableSpriteList, currentlyVisibleStaticSpriteList);

        sortedSprites.Clear();
        TopologicalSort.Sort(currentlyVisibleStaticSpriteList, currentlyVisibleMoveableSpriteList, sortedSprites);
        SetSortOrderBasedOnListOrder(sortedSprites);
    }
Ejemplo n.º 20
0
        public void Test_Topological_Sorting_multiple_prerequisites()
        {
            var edgeList = new int[5][];

            edgeList[0] = new[] { 1, 2 };
            edgeList[1] = new[] { 2, 3 };
            edgeList[2] = new[] { 2, 5 };
            edgeList[3] = new[] { 3, 4 };
            edgeList[4] = new[] { 5, 6 };
            var graph           = Graph.BuildDirectedGraph(edgeList);
            var topologicalSort = new TopologicalSort(6, graph);

            Assert.Equal(new int[] { 4, 3, 6, 5, 2, 1 }, topologicalSort.Sort());
        }
Ejemplo n.º 21
0
        public void Sort_TrivialDirectedGraph_GraphSorted()
        {
            Dictionary <string, string[]> mock = new Dictionary <string, string[]>();

            mock.Add("A", new string[0]);
            mock.Add("B", new[] { "A" });
            mock.Add("C", new[] { "B" });
            mock.Add("D", new[] { "C" });

            var unsorted = new[] { "D", "C", "B", "A" };
            var expected = new[] { "A", "B", "C", "D" };

            Assert.Equal(expected, TopologicalSort.Sort(unsorted, item => mock[item]));
        }
Ejemplo n.º 22
0
        public void TopoTest_Two()
        {
            TopologicalSort.Node a = new TopologicalSort.Node();
            TopologicalSort.Node b = new TopologicalSort.Node();
            a.Dependencies.Add(b);
            List <TopologicalSort.Node> nodes = new List <TopologicalSort.Node> {
                a, b
            };

            List <TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes);

            Assert.AreEqual(sortedNodes[0], b);
            Assert.AreEqual(sortedNodes[1], a);
        }
        public void SortTest()
        {
            var graph = TestHelper.CreateSampleGraph();

            var sut = new TopologicalSort <int>();

            var iterator = new DepthFirstSearchIterator <int>(graph, 0);

            var actual = sut.Sort(iterator);

            var sortedVertices = actual.Select(x => x.Vertice).ToList();

            var expected = new int[] { 0, 1, 3, 2, 4 };

            CollectionAssert.AreEqual(expected, sortedVertices);
        }
        public void Execute()
        {
            this.ExtensionSearchSymbolsByExtensionId = new Dictionary <string, IList <IntermediateSymbol> >();
            this.OrderedSearchFacades = new List <ISearchFacade>();

            var searchRelationSymbols = this.Section.Symbols.OfType <WixSearchRelationSymbol>().ToList();
            var searchSymbols         = this.Section.Symbols.OfType <WixSearchSymbol>().ToList();

            if (searchSymbols.Count == 0)
            {
                // nothing to do!
                return;
            }

            var symbolDictionary = searchSymbols.ToDictionary(t => t.Id.Id);

            var constraints = new Constraints();

            if (searchRelationSymbols.Count > 0)
            {
                // add relational info to our data...
                foreach (var searchRelationSymbol in searchRelationSymbols)
                {
                    constraints.AddConstraint(searchRelationSymbol.Id.Id, searchRelationSymbol.ParentSearchRef);
                }
            }

            this.FindCircularReference(constraints);

            if (this.Messaging.EncounteredError)
            {
                return;
            }

            this.FlattenDependentReferences(constraints);

            // Reorder by topographical sort (http://en.wikipedia.org/wiki/Topological_sorting)
            // We use a variation of Kahn (1962) algorithm as described in
            // Wikipedia, with the additional criteria that start nodes are sorted
            // lexicographically at each step to ensure a deterministic ordering
            // based on 'after' dependencies and ID.
            var sorter    = new TopologicalSort();
            var sortedIds = sorter.Sort(symbolDictionary.Keys, constraints);

            // Now, create the search facades with the searches in order...
            this.OrderSearches(sortedIds, symbolDictionary);
        }
Ejemplo n.º 25
0
        public void Sort_DirectedGraphWithCyclicDependency_ThrowCyclicDependencyException()
        {
            Dictionary <string, string[]> mock = new Dictionary <string, string[]>();

            mock.Add("A", new string[0]);
            mock.Add("B", new[] { "C", "E" });
            mock.Add("C", new string[0]);
            mock.Add("D", new[] { "A" });
            mock.Add("E", new[] { "D", "G" }); //Cyclic Dependency: E -> G -> F -> E
            mock.Add("F", new[] { "E" });
            mock.Add("G", new[] { "F", "H" });
            mock.Add("H", new string[0]);

            var unsorted = new[] { "A", "B", "C", "D", "E", "F", "G", "H" };

            Assert.Throws <CyclicDependencyException>(() => TopologicalSort.Sort(unsorted, item => mock[item]));
        }
        public StronglyConnectedComponents(DirectedGraph g)
        {
            this.G  = g;
            id      = new int[G.GetVertices()];
            visited = new bool[G.GetVertices()];
            count   = 1;

            TopologicalSort tpsort = new TopologicalSort(G);

            foreach (var vertex in tpsort.Sort())
            {
                if (!visited[vertex])
                {
                    Dfs(G, vertex);
                    ++count;
                }
            }
        }
Ejemplo n.º 27
0
        public void TopoTest_Multiple()
        {
            TopologicalSort.Node a = new TopologicalSort.Node();
            TopologicalSort.Node b = new TopologicalSort.Node();
            TopologicalSort.Node c = new TopologicalSort.Node();
            TopologicalSort.Node d = new TopologicalSort.Node();
            a.Dependencies.Add(b);
            a.Dependencies.Add(c);
            b.Dependencies.Add(d);
            List <TopologicalSort.Node> nodes = new List <TopologicalSort.Node> {
                a, b, c, d
            };
            List <TopologicalSort.Node> sortedNodes = TopologicalSort.Sort(nodes);

            Assert.IsTrue(sortedNodes.IndexOf(d) < sortedNodes.IndexOf(b));
            Assert.IsTrue(sortedNodes.IndexOf(b) < sortedNodes.IndexOf(a));
            Assert.IsTrue(sortedNodes.IndexOf(c) < sortedNodes.IndexOf(a));
        }
Ejemplo n.º 28
0
        public void TopSort_SortItems_ReturnResult()
        {
            var a        = new Item("A");
            var b        = new Item("B", "C", "E");
            var c        = new Item("C");
            var d        = new Item("D", "A");
            var e        = new Item("E", "D", "G");
            var f        = new Item("F");
            var g        = new Item("G", "F", "H");
            var h        = new Item("H");
            var unsorted = new[] { a, b, c, d, e, f, g, h };
            var expected = "ACDFHGEB";

            var sortedItems = TopologicalSort.Sort(unsorted, x => x.Dependencies, x => x.Name);
            var data        = sortedItems.Aggregate("", (current, group) => current + group.Name);

            data.Should().Be(expected);
        }
        public static void Main()
        {
            var ts = new TopologicalSort<char>();
            Queue<char> outQueue;
            PriorityQueue<char> res= new PriorityQueue<char>();

            bool returnValue;

            int n = int.Parse(Console.ReadLine());

            for (int i = 0; i < n; i++)
            {
                char[] l = Console.ReadLine().ToCharArray();
                foreach (var p in l)
                {
                    res.Enqueue(p);
                }

                for (int j = 0; j < l.Length-1; j++)
                {
                    ts.Edge(l[j+1], l[j]);
                }

            }

            returnValue = ts.Sort(out outQueue);
            StringBuilder result = new StringBuilder();

            if (outQueue.Count == 0)
            {
               StringBuilder m = new StringBuilder();
                while (res.Count != 0)
                {
                    m.Append(res.Dequeue());
                }

                Console.WriteLine(m);
                return;
            }

            while (outQueue.Count != 0)
                result.Append(outQueue.Dequeue());
            Console.WriteLine(result);
        }
Ejemplo n.º 30
0
        private List <Library> GetSortedLibraries(Library rootLibrary)
        {
            var traversed       = new List <Library>();
            var topologicalSort = new TopologicalSort <Library>();

            var toTraverse = new Queue <Library>();

            toTraverse.Enqueue(rootLibrary);
            while (toTraverse.Count > 0)
            {
                Library predecessor = toTraverse.Dequeue();
                if (traversed.Any(l => l.Equals(predecessor)) == false)
                {
                    traversed.Add(predecessor);
                }
                topologicalSort.Node(predecessor);
                foreach (Library successor in predecessor.Dependencies)
                {
                    Library realSuccessor = traversed.Find(t => t.Equals(successor));

                    if (realSuccessor == null)
                    {
                        if (toTraverse.Any(l => l.Equals(successor)) == false)
                        {
                            toTraverse.Enqueue(successor);
                        }

                        realSuccessor = successor;

                        if (traversed.Any(l => l.Equals(realSuccessor)) == false)
                        {
                            traversed.Add(realSuccessor);
                        }
                    }

                    topologicalSort.Edge(predecessor, realSuccessor);
                }
            }

            Queue <Library> sorted       = topologicalSort.Sort();
            List <Library>  allLibraries = sorted.ToList();

            return(allLibraries);
        }
Ejemplo n.º 31
0
        /// <inheritdoc />
        public void Initialize()
        {
            void SortAspects()
            {
                const string sameKeyPrefix = "An item with the same key has already been added. Key: ";

                try
                {
                    var sortedAspects = TopologicalSort.Sort(_aspects, x => x.Dependencies, x => x.Id, ignoreCycles: false);
                    _aspects.Clear();
                    _aspects.AddRange(sortedAspects);
                }
                catch (ArgumentException e)
                {
                    if (e.Message.StartsWith(sameKeyPrefix))
                    {
                        throw new Exception($"Aspect Id must be unique - {e.Message.Substring(sameKeyPrefix.Length)}");
                    }

                    throw;
                }
                catch (KeyNotFoundException e)
                {
                    var parts = e.Message.Split('\'');
                    //TODO: USe RegEx
                    if (parts.Length == 3)
                    {
                        throw new Exception($"Missing dependency {parts[1]}");
                    }
                    throw;
                }
            }

            _aspects.AddRange(_coreAspects);
            SortAspects();
            foreach (var aspect in _aspects)
            {
                aspect.Initialize();
            }
        }