public void DependencyTreeWithHoles() { var tree = new DependencyTree <Int32>(); tree.Include(1, 0); tree.Include(2, 1); tree.Include(-1, 0); tree.Include(20, 10); tree.Include(30, 20); tree.Include(300, 200); tree.Include(200, 100); tree.Include(100, 0); var controllers = tree.Controllers().ToArray(); Assert.AreEqual(2, controllers.Length); Assert.AreEqual(0, controllers[0]); Assert.AreEqual(10, controllers[1]); var zeros = tree.Dependencies(0).ToArray(); var tens = tree.Dependencies(10).ToArray(); Assert.AreEqual(6, zeros.Length); Assert.AreEqual(2, tens.Length); CollectionAssert.AreEqual(new[] { 1, 2, -1, 100, 200, 300 }, zeros); CollectionAssert.AreEqual(new[] { 20, 30 }, tens); }
/// <summary> /// Event handler for where used menu item. /// Adds a "USED BY" node and performs a dependency discovery after which /// all dependents are added to the "USED BY" node. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void WhereUsedToolStripMenuItem_Click(object sender, EventArgs e) { TreeNode node, newNode; node = DependenciesTreeView.SelectedNode; if (node.Nodes.ContainsKey(Properties.Resources.UsedBy) || node.Name == Properties.Resources.UsedBy) { return; } newNode = new TreeNode(Properties.Resources.UsedBy); newNode.Name = Properties.Resources.UsedBy; node.Nodes.Add(newNode); // Advanced Scripting Scripter scripter = new Scripter(this.sqlServerSelection); Urn[] urns = new Urn[1]; urns[0] = (Urn)node.Tag; // Discover dependents DependencyTree tree = scripter.DiscoverDependencies(urns, DependencyType.Children); // Add to tree (recursive) AddChildren(newNode, tree.FirstChild); node.Expand(); newNode.Expand(); }
public DependenciesForm(Server srvr, DependencyTree dependTree) { InitializeComponent(); if (dependTree != null) { this.sqlServerSelection = srvr; DependencyTreeNode root; TreeNode node; root = dependTree.FirstChild; while (root != null) { node = new TreeNode(root.Urn.GetAttribute("Name") + " (" + root.Urn.Type + ")"); node.Tag = root.Urn; DependenciesTreeView.Nodes.Add(node); AddChildren(node, root); root = root.NextSibling; } if (DependenciesTreeView.Nodes.Count > 0) { DependenciesTreeView.Nodes[0].Expand(); } } }
public IEnumerable<ContributorCall> GenerateCallGraph(PipelineRunner pipelineRunner) { var bootstrapper = pipelineRunner.Contributors.OfType<KnownStages.IBegin>().Single(); var tree = new DependencyTree<ContributorNotification>( new ContributorNotification(bootstrapper, new Notification(pipelineRunner, null))); foreach (var contrib in pipelineRunner.Contributors.Where(x => x != bootstrapper)) { pipelineRunner.NotificationRegistrations.Clear(); using (pipelineRunner.PipelineLog.Operation(pipelineRunner, "Initializing contributor {0}.".With(contrib.GetType().Name))) contrib.Initialize(pipelineRunner); foreach (var reg in pipelineRunner.NotificationRegistrations.DefaultIfEmpty(new Notification(pipelineRunner, null))) { tree.CreateNode(new ContributorNotification(contrib, reg)); } } foreach (var notificationNode in tree.Nodes) { foreach (var parentNode in GetCompatibleTypes(tree, notificationNode, notificationNode.Value.Notification.AfterTypes)) parentNode.ChildNodes.Add(notificationNode); foreach (var childNode in GetCompatibleTypes(tree, notificationNode, notificationNode.Value.Notification.BeforeTypes)) childNode.ParentNodes.Add(notificationNode); } return tree.GetCallGraph().Select(x => new ContributorCall(x.Value.Contributor, x.Value.Notification.Target, x.Value.Notification.Description)); }
public DataStructure( Schema schema, DependencyTree dependencyTree) { Schema = schema; DependencyTree = dependencyTree; }
public void GetNodes_ShouldReturnInTheExpectedOrder() { // we should have 4 nodes since we register // A to D, even thought we register C twice // Arrange var tree = new DependencyTree(ModuleFactory.Default, typeof(A)); var expected = new List <Type>() { typeof(D), typeof(C), typeof(B), typeof(A) }; // Act var subject = tree.GetNodes() .Select(x => (x as Nandel.Modules.DependencyNode)?.ModuleType) .Where(x => x is not null) .ToList() ; // Assert Assert.True(subject.SequenceEqual(expected), "Not returned in the expected order"); }
public string ScriptObjects(ScriptingArgs args) { if (args == null || args.Objects == null || args.Objects.Count == 0) { return(String.Empty); } FireTaskProgressInfo("Preparing for scripting..."); scrp.Options = args.Options; scrp.Options.ToFileOnly = false; scrp.Options.AppendToFile = false; scrp.Options.FileName = String.Empty; scrp.Server.ConnectionContext.BatchSeparator = "GO"; StringCollection scr = null; _recentErrors = null; if (scrp.Options.ContinueScriptingOnError) { _recentErrors = new StringBuilder(); scrp.ScriptingError += new ScriptingErrorEventHandler(scrp_ScriptingError); } try { if (scrp.Options.WithDependencies) { scrp.DiscoveryProgress += new ProgressReportEventHandler(dWalk_DiscoveryProgress); FireTaskProgressInfo("Discovering dependencies. (Task 1 of 3)"); DependencyTree dTree = scrp.DiscoverDependencies(PrepareObjectUrns(args.Objects), DependencyType.Parents); FireTaskProgressInfo("Walking dependencies. (Task 2 of 3)"); DependencyCollection dCol = scrp.WalkDependencies(dTree); FireTaskProgressInfo("Scripting objects. (Task 3 of 3)"); scr = scrp.ScriptWithList(dCol); } else { FireTaskProgressInfo("Scripting objects. (Task 1 of 1)"); scr = scrp.ScriptWithList(PrepareObjectUrns(args.Objects)); } } catch (Exception ex) { if (_cancelRequested) { return(String.Empty); } throw ex; } string myComment = "/***** Script generated with PragmaSQL Scripter on " + DateTime.Now.ToString() + " ******/"; string[] result = new string[scr.Count]; scr.CopyTo(result, 0); return(myComment + "\r\n" + String.Join((String.IsNullOrEmpty(args.BatchSeparator) ? "\r\n" : "\r\n" + args.BatchSeparator + "\r\n"), result)); }
public DependencyNode(ModuleFactory factory, Type moduleType, IDependencyNode root) { _factory = factory; ModuleType = moduleType; Root = root; Dependencies = new DependencyTree(factory, Root); }
static IEnumerable<DependencyNode<ContributorNotification>> GetCompatibleTypes(DependencyTree<ContributorNotification> tree, DependencyNode<ContributorNotification> notificationNode, IEnumerable<Type> beforeTypes) { return from childType in beforeTypes from compatibleNode in tree.Nodes where compatibleNode != notificationNode && childType.IsAssignableFrom(compatibleNode.Value.Contributor.GetType()) select compatibleNode; }
private void PrepareTreeViewNodes(TreeNodeCollection appendTo, DependencyTree dTree) { _parentNames.Clear(); if (dTree == null || dTree.Count == 0) { return; } TraverseTreeNodes(appendTo, dTree.FirstChild); return; }
static IEnumerable <DependencyNode <ContributorNotification> > GetCompatibleTypes( DependencyTree <ContributorNotification> tree, DependencyNode <ContributorNotification> notificationNode, IEnumerable <Type> beforeTypes) { return(from childType in beforeTypes from compatibleNode in tree.Nodes where compatibleNode != notificationNode && childType.IsInstanceOfType(compatibleNode.Value.Contributor) select compatibleNode); }
public static IEnumerable <DependencyBranch> GetRelatedBranches(this DependencyTree tree, Table table) { var constrainedTableGuids = table .ConstrainedTo; var relatedBranches = tree .Branches .Where(b => constrainedTableGuids .Any(c => c.Equals(b.TableGuid))); return(relatedBranches); }
public IDependencyTree <T> Convert <T>(string json, Func <string, T> mapFromString) { var dependencyTree = new DependencyTree <T>(); var dependencyTreeFromJson = JsonConvert.DeserializeObject <dependencyTree>(json); foreach (var branch in dependencyTreeFromJson.branches) { dependencyTree.Add(mapFromString(branch.module), branch.dependencies.Select(mapFromString).ToArray()); } return(dependencyTree); }
private void PrintTree(DependencyTree tree, int indentationLevel, IDictionary <string, bool> alreadyPrinted) { Console.WriteLine(new string(' ', indentationLevel) + tree.AssemblyName); if (alreadyPrinted.ContainsKey(tree.AssemblyName)) { return; } alreadyPrinted[tree.AssemblyName] = true; foreach (DependencyTree a in tree.ReferencedAssemblies.Values) { PrintTree(a, indentationLevel + 3, alreadyPrinted); } }
public Result <IEnumerable <string> > Handle(DecrementProjectsCommand message) { var projects = ProjectsScanner.GetAllProjectsInSln(message.SlnPath) .Choose(x => x).ToList(); return(Prelude.Optional(DependencyTree.FindReferences(projects, message.ProjectNames) .Select(x => VersionModifier.DecrementVersion(x, message.Version)) .Select(ProjectSaver.Save) .Select(ProjectConverter.ToViewString) .DefaultIfEmpty()) .Match(x => new Result <IEnumerable <string> >(x), new Result <IEnumerable <string> >(new NothingFoundException("no projects were found")))); }
public Result <IEnumerable <string> > Handle(ListDependentProjectsCommand message) { var projects = ProjectsScanner.GetAllProjectsInSln(message.SlnPath) .Choose(x => x) .ToList(); var dependentProjects = DependencyTree.FindReferences(projects, message.ProjectNames) .Select(ProjectConverter.ToViewString).ToList(); return(dependentProjects.Any() ? new Result <IEnumerable <string> >(dependentProjects) : new Result <IEnumerable <string> >(new NothingFoundException("no projects were found"))); }
public void DiscoverDependencies(TreeNodeCollection appendTo, IList <DbObjectList.DbObjectInfo> objects) { if (objects == null || objects.Count == 0) { return; } DependencyWalker dWalk = new DependencyWalker(srvr); dWalk.DiscoveryProgress += new ProgressReportEventHandler(dWalk_DiscoveryProgress); DependencyTree dTree = dWalk.DiscoverDependencies(PrepareObjectUrns(objects), DependencyType.Parents); PrepareTreeViewNodes(appendTo, dTree); }
public void GetNodes_ShouldReturn4Nodes() { // we should have 4 nodes since we register // A to D, even thought we register C twice // Arrange var tree = new DependencyTree(ModuleFactory.Default, typeof(A)); // Act var subject = tree.GetNodes(); // Assert Assert.Equal(4, subject.Count()); }
public IEnumerable <ContributorCall> GenerateCallGraph(IEnumerable <IPipelineContributor> contributors) { var contribList = contributors.ToList(); var bootstrapper = contribList.OfType <KnownStages.IBegin>().SingleOrDefault(); bool isSyntheticBootstrap = false; if (bootstrapper == null) { bootstrapper = new BootstrapperContributor(); contribList.Add(bootstrapper); isSyntheticBootstrap = true; } contributors = contribList; var tree = new DependencyTree <ContributorInvocation>(); foreach (var node in new ContributorBuilder().Build(contributors)) { tree.CreateNode(node); } var rootNode = tree.Nodes.First(n => n.Value.Owner is KnownStages.IBegin); foreach (var notificationNode in tree.Nodes) { foreach (var parentNode in GetCompatibleTypes(tree, notificationNode, notificationNode.Value.AfterTypes)) { parentNode.ChildNodes.Add(notificationNode); } foreach (var childNode in GetCompatibleTypes(tree, notificationNode, notificationNode.Value.BeforeTypes)) { childNode.ParentNodes.Add(notificationNode); } } return(tree .GetCallGraph(rootNode) .Where(n => !isSyntheticBootstrap || n.Value.Owner != bootstrapper) .Select(x => new ContributorCall( x.Value.Owner, x.Value.Target, x.Value.Description))); }
public void Invoke_WithCustomContract_ShouldBeInvokedOnlyOnce() { var collection = new ServiceCollection(); var tree = new DependencyTree(ModuleFactory.Default, typeof(CustomA)); tree.ConfigureServices(collection);; var services = collection.BuildServiceProvider(); var counter = services.GetRequiredService <Counter>(); tree.Invoke <ICount>(counter); Assert.Equal(2, counter.Count); }
public Result <IEnumerable <string> > Handle(PushProjectsCommand message) { var projects = ProjectsScanner.GetAllProjectsInSln(message.SlnPath) .Choose(x => x).ToList(); return(Prelude.Optional(DependencyTree.FindReferences(projects, message.ProjectNames) .SelectMany(x => { var buildLog = Pusher.Build(x, message.BuildProfile); var pushLog = Pusher.PushToSource(x, message.Source, message.BuildProfile); return new[] { buildLog, pushLog }; }).DefaultIfEmpty()) .Match(x => new Result <IEnumerable <string> >(x), new Result <IEnumerable <string> >(new NothingFoundException("no projects were found")))); }
public static IEnumerable <Guid> GetChildrenOf(this DependencyTree tree, Table table) { var tableBranch = tree .Branches .Where(b => b.TableGuid.Equals(table.CorrelationId)) .FirstOrDefault(); var connectingBranches = tree .Branches .Where(b => table.ConstrainedTo.Any(c => c.Equals(b.TableGuid))); var childrenTables = connectingBranches .Where(c => c.Depth.Equals(tableBranch.Depth + 1)) .Select(c => c.TableGuid); return(childrenTables); }
public IEnumerable <ContributorCall> GenerateCallGraph(IEnumerable <IPipelineContributor> contributors) { contributors = contributors.ToList(); var bootstrapper = contributors.OfType <KnownStages.IBegin>().Single(); var tree = new DependencyTree <ContributorNotification>( new ContributorNotification(bootstrapper, new Notification(Middleware.IdentitySingleTap, contributors))); foreach (var contrib in contributors.Where(x => x != bootstrapper)) { var builder = new PipelineBuilder(contributors); builder.ContributorRegistrations.Clear(); contrib.Initialize(builder); var contributorRegistrations = builder.ContributorRegistrations.DefaultIfEmpty(new Notification(Middleware.IdentitySingleTap, contributors)).ToList(); foreach (var registration in contributorRegistrations) { tree.CreateNode(new ContributorNotification(contrib, registration)); } } foreach (var notificationNode in tree.Nodes) { foreach (var parentNode in GetCompatibleTypes(tree, notificationNode, notificationNode.Value.Notification.AfterTypes)) { parentNode.ChildNodes.Add(notificationNode); } foreach (var childNode in GetCompatibleTypes(tree, notificationNode, notificationNode.Value.Notification.BeforeTypes)) { childNode.ParentNodes.Add(notificationNode); } } return (tree.GetCallGraph() .Select( x => new ContributorCall(x.Value.Contributor, x.Value.Notification.Target, x.Value.Notification.Description))); }
/// <summary> /// Add modules to current ServiceCollection /// </summary> /// <param name="services">Collection of services</param> /// <param name="factory">Factory used to create the instance of modules</param> /// <param name="moduleTypes">Collection of classes that implements IModule</param> /// <returns></returns> private static IServiceCollection AddModules(this IServiceCollection services, ModuleFactory factory, params Type[] moduleTypes) { var dependencies = (DependencyTree)services .FirstOrDefault(x => x.ServiceType == typeof(IDependencyNode)) ?.ImplementationInstance ; if (dependencies is null) { dependencies = new DependencyTree(factory); services.AddSingleton <IDependencyNode>(dependencies); // add first to re-use the same ModuleFactory instance } dependencies.AddRange(moduleTypes); dependencies.ConfigureServices(services); return(services); }
public static Guid GetParentOf(this DependencyTree tree, Table table) { var tableBranch = tree .Branches .Where(b => b.TableGuid.Equals(table.CorrelationId)) .FirstOrDefault(); var connectingBranches = tree .Branches .Where(b => table.ConstrainedTo.Any(c => c.Equals(b.TableGuid))); var parentTable = connectingBranches .Where(c => c.Depth.Equals(tableBranch.Depth - 1)) .Select(c => c.TableGuid) .FirstOrDefault(); return(parentTable); }
public DependencyTree GetDependencyTree(Assembly assembly) { // Avoid procesing twice same assembly. if (_alreadyProcessed.ContainsKey(assembly.FullName)) { return(_alreadyProcessed[assembly.FullName]); } var item = new DependencyTree(); item.AssemblyName = assembly.FullName; item.ReferencedAssemblies = new Dictionary <string, DependencyTree>(); _alreadyProcessed.Add(item.AssemblyName, item); foreach (AssemblyName assemblyName in assembly.GetReferencedAssemblies()) { item.ReferencedAssemblies.Add(assemblyName.FullName, GetDependencyTree(Assembly.Load(assemblyName))); } return(item); }
private static int CountTableDependancies(Scripter scripter, SqlSmoObject[] objectArray) { int retVal = 0; DependencyWalker dependencyWalker = new DependencyWalker(scripter.Server); DependencyTree dependencyTree = dependencyWalker.DiscoverDependencies(objectArray, true); DependencyCollection dependencyCollection = dependencyWalker.WalkDependencies(dependencyTree); foreach (DependencyCollectionNode oneDep in dependencyCollection) { if (oneDep.Urn.Type.Equals("Table")) { retVal++; } } return(retVal); }
public ScriptingForm(Server srvr, SqlSmoObject smoObject) { InitializeComponent(); this.sqlServerSelection = srvr; this.smoScripter = new Scripter(srvr); // Generate the dependency tree this.dependTree = this.smoScripter.DiscoverDependencies(new SqlSmoObject[] { smoObject }, true); UpdateTree(); UpdateListAndScript(); if (Phase1TreeView.Nodes.Count > 0) { Phase1TreeView.Nodes[0].ExpandAll(); } }
private IEnumerable <DependencyCollectionNode> GetDependencies(SqlSmoObject smoObject, Location location) { Logger.WriteLine("Gathering dependencies for {0}", smoObject.Urn); try { var dependencyWalker = new DependencyWalker(location == Location.Source ? _sourceServer : _targetServer); DependencyTree parents = dependencyWalker.DiscoverDependencies(new[] { smoObject }, DependencyType.Parents); DependencyCollection dependencies = dependencyWalker.WalkDependencies(parents); return(dependencies); } catch { Logger.WriteLine("Failed to get dependencies for {0}", smoObject.Urn); throw; } }
public void Setup() { var instances = new IMappingProviderVisitor[] { new YetAnotherDependentyResponseModelTransformer(), new SomeAnotherDependentyResponseModelTransformer(), new SomeDependentyResponseModelTransformer(), new SomeResponseModelTransformer() }; _dependencyTree = new DependencyTree <IMappingProviderVisitor>(instances); _expected = new[] { instances[3], instances[2], instances[0], instances[1] }; }
public async Task StartAsync_ShouldBeInvokedOnlyOnceByModule() { // Module `C` is registred twice in the tree // and has a ServiceC singleton with a counter // so we can check how many times it was invoked // Arrange var tree = new DependencyTree(ModuleFactory.Default, typeof(A)); var collection = new ServiceCollection(); tree.ConfigureServices(collection); var services = collection.BuildServiceProvider(); // Act await tree.StartAsync(services, CancellationToken.None); // Assert Assert.Equal(1, services.GetRequiredService <ServiceC>().Count); }
private SqlSmoObject[] Sort(Database sourceDatabase, SqlSmoObject[] smoObjects) { if (smoObjects.Count() < 2) { return(smoObjects); } DependencyTree dt = null; DependencyWalker dw = new DependencyWalker(sourceDatabase.Parent); try { dt = dw.DiscoverDependencies(smoObjects, true); } catch (Exception ex) { AsyncNotificationEventArgs eventArgs = new AsyncNotificationEventArgs(NotificationEventFunctionCode.ExecuteSqlOnAzure, 100, "", DateTime.Now.ToString(CultureInfo.CurrentCulture) + Environment.NewLine + ex.Message, Color.Red); _updateStatus(eventArgs); return(smoObjects); } SqlSmoObject[] sorted = new SqlSmoObject[smoObjects.Count()]; int index = 0; foreach (DependencyCollectionNode d in dw.WalkDependencies(dt)) { if (d.Urn.Type.Equals("UnresolvedEntity")) { continue; } foreach (SqlSmoObject sso in smoObjects) { if (sso.Urn.ToString().Equals(d.Urn, StringComparison.CurrentCultureIgnoreCase)) { sorted[index++] = sso; break; } } } return(sorted); }
public IEnumerable<ContributorCall> GenerateCallGraph(IEnumerable<IPipelineContributor> contributors) { contributors = contributors.ToList(); var bootstrapper = contributors.OfType<KnownStages.IBegin>().Single(); var tree = new DependencyTree<ContributorNotification>( new ContributorNotification(bootstrapper, new Notification(Middleware.IdentitySingleTap, contributors))); foreach (var contrib in contributors.Where(x => x != bootstrapper)) { var builder = new PipelineBuilder(contributors); builder.ContributorRegistrations.Clear(); contrib.Initialize(builder); var contributorRegistrations = builder.ContributorRegistrations.DefaultIfEmpty(new Notification(Middleware.IdentitySingleTap, contributors)).ToList(); foreach (var registration in contributorRegistrations) { tree.CreateNode(new ContributorNotification(contrib, registration)); } } foreach (var notificationNode in tree.Nodes) { foreach (var parentNode in GetCompatibleTypes(tree, notificationNode, notificationNode.Value.Notification.AfterTypes)) parentNode.ChildNodes.Add(notificationNode); foreach (var childNode in GetCompatibleTypes(tree, notificationNode, notificationNode.Value.Notification.BeforeTypes)) childNode.ParentNodes.Add(notificationNode); } return tree.GetCallGraph() .Select( x => new ContributorCall(x.Value.Contributor, x.Value.Notification.Target, x.Value.Notification.Description)); }
private IEnumerable<IAnalyzedSourceFile> GetSourceFiles() { Log.LogMessage("Collecting source files from the following roots:"); foreach (var taskItem in Roots) { Log.LogMessage("- {0}", taskItem.ItemSpec); } var sources = CollectSources(); Log.LogMessage("Collected '{0}' sources", sources.Count); Log.LogMessage("Buildling dependency tree"); var dependencyTree = new DependencyTree(sources); Log.LogMessage("Determining dependencies for the following namespaces:"); var namespaces = Namespaces.Select(x => x.ItemSpec).ToList(); foreach (var ns in namespaces) { Log.LogMessage("- {0}", ns); } var dependencies = dependencyTree.GetDependencies(namespaces); // base.js goes first dependencies.Insert(0, Helpers.GetClosureBaseFile(sources)); Log.LogMessage("Found '{0}' required source files", dependencies.Count); foreach (var dependency in dependencies) { Log.LogMessage("- {0}", dependency.Path); } return dependencies; }
public void DependencyTreeWithHoles() { var tree = new DependencyTree<Int32>(); tree.Include(1, 0); tree.Include(2, 1); tree.Include(-1, 0); tree.Include(20, 10); tree.Include(30, 20); tree.Include(300, 200); tree.Include(200, 100); tree.Include(100, 0); var controllers = tree.Controllers().ToArray(); Assert.AreEqual(2, controllers.Length); Assert.AreEqual(0, controllers[0]); Assert.AreEqual(10, controllers[1]); var zeros = tree.Dependencies(0).ToArray(); var tens = tree.Dependencies(10).ToArray(); Assert.AreEqual(6, zeros.Length); Assert.AreEqual(2, tens.Length); CollectionAssert.AreEqual(new[] { 1, 2, -1, 100, 200, 300 }, zeros); CollectionAssert.AreEqual(new[] { 20, 30 }, tens); }
public GeneratorVisitor(Options options) { _files = new List<GeneratedFile>(); _names = new DependencyTree<String>(); _options = options; }
private static List<View> SortViews(Database db, List<SqlSmoObject> sso) { var dw = new DependencyWalker(db.Parent); var dt = new DependencyTree(dw.DiscoverDependencies(sso.ToArray(), true)); var views = new List<View>(); foreach (var d in dw.WalkDependencies(dt)) { if (d.Urn.Type != "View") continue; var o = db.Views[d.Urn.GetNameForType(d.Urn.Type)]; if (o != null) views.Add(db.Views[d.Urn.GetNameForType(d.Urn.Type)]); } return views; }