public void Run(string solutionPathName, string projectFilterRegex = null)
        {
            if (String.IsNullOrWhiteSpace(solutionPathName))
            {
                throw new ArgumentNullException("solutionPathName");
            }

            var solutionPath = Path.GetDirectoryName(solutionPathName);
            var solutionName = Path.GetFileName(solutionPathName);

            Console.WriteLine("Running");
            var reader = new ProjectReader(solutionPath, solutionName);

            Console.WriteLine(String.Format("Reading files for the solution {0} (path {1})", solutionName, solutionPath));

            var regexProjectFilter = !String.IsNullOrWhiteSpace(projectFilterRegex) ? new Regex(projectFilterRegex, RegexOptions.IgnoreCase) : null;
            var model = regexProjectFilter == null?reader.Read() : reader.Read(p => regexProjectFilter.IsMatch(p.Name));

            Console.WriteLine(String.Format("Loaded '{0}' project(s); '{1}' symbol(s)", model.SolutionNamespaces.Count(), model.Symbols.Count()));

            Console.WriteLine("Building dependency tree");
            new ReferenceBuilder().Build(model);

            Console.WriteLine("Collecting indirect references");
            var final = new DependencyAnalyzer().SelectIndirectReferences(model);

            Console.WriteLine("Writing a report file");
            var report = new Reporter().PrintFromToEndpoints(final);

            Console.WriteLine();
            Console.WriteLine(report);
        }
Beispiel #2
0
        public void DependencyAnalyzerBuildAnalyzerContextTest()
        {
            log.Info("-----------------------------DependencyAnalyzer BuildAnalyzerContext-----------------------------");

            // Test setup.
            var tapPackage = new PackageDef()
            {
                Name = "Tap", Version = PluginManager.GetOpenTapAssembly().SemanticVersion
            };
            var packages = new List <PackageDef>();

            packages.Add(tapPackage);

            // Correct packages.
            using (var xmlText = File.OpenRead(Path.Combine(Directory.GetCurrentDirectory(), "TapPackages/MyPlugin1.xml")))
            {
                packages.AddRange(PackageDef.ManyFromXml(xmlText));

                // Multiple identical packages.
                xmlText.Seek(0, 0);
                packages.AddRange(PackageDef.ManyFromXml(xmlText));
            }

            // Reset test.
            packages.Clear();

            // No packages.
            var dependencyAnalyzer = DependencyAnalyzer.BuildAnalyzerContext(packages);

            Assert.IsTrue(dependencyAnalyzer.BrokenPackages.Count == 0, "No packages");
            log.Info("Multiple identical items - SUCCESS");
        }
Beispiel #3
0
        public void FetchAssemblyList(string directoryPath)
        {
            ConsoleLogger consoleLogger = new ConsoleLogger(true);

            DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);

            if (!Directory.Exists(directoryPath))
            {
                consoleLogger.LogMessage(string.Format("Directory: '{0}' does not exist.", directoryPath));
                throw new ArgumentException("Cannot process files in directory: " + directoryPath);
            }

            // For each directory inside the directoryPath, analyze its dependencies
            IEnumerable <string> extensionDirs = Directory.EnumerateDirectories(directoryPath);

            foreach (string extensionDir in extensionDirs)
            {
                IDependencyAnalyzer analyzer = new DependencyAnalyzer()
                {
                    DirectoryInfo = new DirectoryInfo(extensionDir)
                };
                DependencyAnalyzerResult result = analyzer.Analyze(consoleLogger);

                // Output results to Console
                IDependencyVisualizer visualizer = new ConsoleVisualizer(result);
                visualizer.Visualize();

                // Export results to file
                IDependencyVisualizer export = new DgmlExport(result, Path.Combine(directoryPath, extensionDir + ".references.dgml"), consoleLogger);
                export.Visualize();
            }

            Console.Out.WriteLine("Finished fetching assemblies");
        }
        private void RewriteComponentFile(string inputFile, string outputFile, string ownerExecutableName)
        {
            EcmaModule inputModule = NodeFactory.TypeSystemContext.GetModuleFromPath(inputFile);

            CopiedCorHeaderNode copiedCorHeader  = new CopiedCorHeaderNode(inputModule);
            DebugDirectoryNode  debugDirectory   = new DebugDirectoryNode(inputModule, outputFile);
            NodeFactory         componentFactory = new NodeFactory(
                _nodeFactory.TypeSystemContext,
                _nodeFactory.CompilationModuleGroup,
                _nodeFactory.NameMangler,
                copiedCorHeader,
                debugDirectory,
                win32Resources: new Win32Resources.ResourceData(inputModule),
                Internal.ReadyToRunConstants.ReadyToRunFlags.READYTORUN_FLAG_Component |
                Internal.ReadyToRunConstants.ReadyToRunFlags.READYTORUN_FLAG_NonSharedPInvokeStubs);

            IComparer <DependencyNodeCore <NodeFactory> > comparer       = new SortableDependencyNode.ObjectNodeComparer(new CompilerComparer());
            DependencyAnalyzerBase <NodeFactory>          componentGraph = new DependencyAnalyzer <NoLogStrategy <NodeFactory>, NodeFactory>(componentFactory, comparer);

            componentGraph.AddRoot(componentFactory.Header, "Component module R2R header");
            OwnerCompositeExecutableNode ownerExecutableNode = new OwnerCompositeExecutableNode(_nodeFactory.Target, ownerExecutableName);

            componentGraph.AddRoot(ownerExecutableNode, "Owner composite executable name");
            componentGraph.AddRoot(copiedCorHeader, "Copied COR header");
            componentGraph.AddRoot(debugDirectory, "Debug directory");
            if (componentFactory.Win32ResourcesNode != null)
            {
                componentGraph.AddRoot(componentFactory.Win32ResourcesNode, "Win32 resources");
            }
            componentGraph.ComputeMarkedNodes();
            componentFactory.Header.Add(Internal.Runtime.ReadyToRunSectionType.OwnerCompositeExecutable, ownerExecutableNode, ownerExecutableNode);
            ReadyToRunObjectWriter.EmitObject(outputFile, componentModule: inputModule, componentGraph.MarkedNodeList, componentFactory, generateMapFile: false, customPESectionAlignment: null);
        }
Beispiel #5
0
        public void FindSqlServerObjectNamesTest()
        {
            var correct = new string[] {
                "innovator.USER", "innovator.PERSON", "innovator.IDENTITY", "innovator.Person_Search", "innovator.IDENTITY",
                "innovator.Person_Search", "innovator.DEPARTMENT", "innovator.INVENTORY_ORG", "innovator.COMPANY", "innovator.COMPANY",
                "innovator.FEATURE", "innovator.DEFECT", "innovator.htmltotext", "innovator.COMPANY", "innovator.INVENTORY_ORG", "innovator.PART",
                "innovator.PART", "innovator.FUNCTIONAL_GROUP", "innovator.CONCERN", "innovator.ISSUE", "innovator.IDENTITY", "innovator.ALIAS",
                "innovator.PERSON", "innovator.FEATURE_DEFECT", "innovator.MANUFACTURING_ENTITY", "innovator.PART", "innovator.PART",
                "innovator.MANUFACTURING_ENTITY", "innovator.DEPARTMENT", "innovator.Last_Comments", "innovator.ANALYSIS", "innovator.PROGRAM",
                "innovator.LAB_TEST_ROUND", "innovator.ConvertToLocalTbl", "innovator.ConvertToLocalTbl", "innovator.ConvertToLocalTbl",
                "innovator.ConvertToLocalTbl", "innovator.ConvertToLocalTbl"
            };
            var names = DependencyAnalyzer.GetInnovatorNames(prop.Resources.SampleSql)
                        .Select(n => n.FullName).ToArray();

            CollectionAssert.AreEqual(correct, names);

            correct = new string[] {
                "PE_RollupAllPartsInDB", "PART", "PART", "PART", "PART_GOAL", "PART", "PART", "PART", "PART_GOAL", "PART", "PART_BOM",
                "PART_GOAL", "PART_GOAL", "PART", "PART", "PART_GOAL", "PART", "PART", "PART_GOAL", "PART", "PART_BOM",
                "ind_tmp_BOMS_TO_USE_source_id", "ind_tmp_BOMS_TO_USE_related_id", "PART", "PART", "PART_GOAL", "PART_GOAL", "PART_GOAL",
                "PART_BOM", "PART", "PART", "PART", "PART_GOAL", "PART_GOAL", "PART_GOAL", "PART_GOAL", "PART_BOM", "PART", "PART", "PART", "PART_GOAL"
            };

            names = DependencyAnalyzer.GetInnovatorNames(prop.Resources.SampleSql_PartRollup)
                    .Select(n => n.FullName).ToArray();
            CollectionAssert.AreEqual(correct, names);
        }
 public static bool ShouldAnalyze(Compilation compilation, DurianModule module)
 {
     return
         (IsCSharpCompilationAnalyzer.Analyze(compilation) &&
          DisabledModuleAnalyzer.IsEnabled(module, compilation) &&
          DependencyAnalyzer.Analyze(compilation));
 }
Beispiel #7
0
        private void RewriteComponentFile(string inputFile, string outputFile, string ownerExecutableName)
        {
            EcmaModule inputModule = NodeFactory.TypeSystemContext.GetModuleFromPath(inputFile);

            Directory.CreateDirectory(Path.GetDirectoryName(outputFile));

            ReadyToRunFlags flags =
                ReadyToRunFlags.READYTORUN_FLAG_Component |
                ReadyToRunFlags.READYTORUN_FLAG_NonSharedPInvokeStubs;

            if (inputModule.IsPlatformNeutral)
            {
                flags |= ReadyToRunFlags.READYTORUN_FLAG_PlatformNeutralSource;
            }

            CopiedCorHeaderNode copiedCorHeader  = new CopiedCorHeaderNode(inputModule);
            DebugDirectoryNode  debugDirectory   = new DebugDirectoryNode(inputModule, outputFile);
            NodeFactory         componentFactory = new NodeFactory(
                _nodeFactory.TypeSystemContext,
                _nodeFactory.CompilationModuleGroup,
                null,
                _nodeFactory.NameMangler,
                copiedCorHeader,
                debugDirectory,
                win32Resources: new Win32Resources.ResourceData(inputModule),
                flags);

            IComparer <DependencyNodeCore <NodeFactory> > comparer       = new SortableDependencyNode.ObjectNodeComparer(new CompilerComparer());
            DependencyAnalyzerBase <NodeFactory>          componentGraph = new DependencyAnalyzer <NoLogStrategy <NodeFactory>, NodeFactory>(componentFactory, comparer);

            componentGraph.AddRoot(componentFactory.Header, "Component module R2R header");
            OwnerCompositeExecutableNode ownerExecutableNode = new OwnerCompositeExecutableNode(_nodeFactory.Target, ownerExecutableName);

            componentGraph.AddRoot(ownerExecutableNode, "Owner composite executable name");
            componentGraph.AddRoot(copiedCorHeader, "Copied COR header");
            componentGraph.AddRoot(debugDirectory, "Debug directory");
            if (componentFactory.Win32ResourcesNode != null)
            {
                componentGraph.AddRoot(componentFactory.Win32ResourcesNode, "Win32 resources");
            }
            componentGraph.ComputeMarkedNodes();
            componentFactory.Header.Add(Internal.Runtime.ReadyToRunSectionType.OwnerCompositeExecutable, ownerExecutableNode, ownerExecutableNode);
            ReadyToRunObjectWriter.EmitObject(
                outputFile,
                componentModule: inputModule,
                inputFiles: new string[] { inputFile },
                componentGraph.MarkedNodeList,
                componentFactory,
                generateMapFile: false,
                generateMapCsvFile: false,
                generatePdbFile: false,
                pdbPath: null,
                generatePerfMapFile: false,
                perfMapPath: null,
                perfMapFormatVersion: _perfMapFormatVersion,
                generateProfileFile: false,
                _profileData.CallChainProfile,
                customPESectionAlignment: 0);
        }
Beispiel #8
0
        private IEnumerable <ItemReference> GetDependencies(InstallItem installItem)
        {
            var analyzer = new DependencyAnalyzer(new MockMetadata());

            analyzer.AddReferenceAndDependencies(installItem);
            analyzer.FinishAdding();
            return(analyzer.GetDependencies(installItem.Reference));
        }
        public void AnalyzeShouldReturnSystemAssemblies()
        {
            var result = DependencyAnalyzer.Analyze(filesToAnalyse, null, logger, options);

            Assert.Contains(result.Assemblies.Values, x => x.AssemblyName.Name == "mscorlib");
            Assert.Contains(result.Assemblies.Values, x => x.AssemblyName.Name == "netstandard");
            Assert.Contains(result.Assemblies.Values, x => x.AssemblyName.Name == "System");
        }
        public void AnalyzeShouldReturnTestAssemblies()
        {
            var result = DependencyAnalyzer.Analyze(filesToAnalyse, null, logger, options);

            Assert.Contains(result.Assemblies.Values, x => x.AssemblyName.Name == "AsmSpy.Core");
            Assert.Contains(result.Assemblies.Values, x => x.AssemblyName.Name == "AsmSpy.Core.Tests");
            Assert.Contains(result.Assemblies.Values, x => x.AssemblyName.Name == "AsmSpy.Core.TestLibrary");
            Assert.Contains(result.Assemblies.Values, x => x.AssemblyName.Name == "xunit.core");
        }
        public void AnalyzeShouldNotReturnSystemAssembliesWhenFlagIsSet()
        {
            var altOptions = new VisualizerOptions(true, false, "");
            var result     = DependencyAnalyzer.Analyze(filesToAnalyse, null, logger, altOptions);

            Assert.DoesNotContain(result.Assemblies.Values, x => x.AssemblyName.Name == "mscorlib");
            Assert.DoesNotContain(result.Assemblies.Values, x => x.AssemblyName.Name == "netstandard");
            Assert.DoesNotContain(result.Assemblies.Values, x => x.AssemblyName.Name == "System");
        }
        public void AnalyzeShouldReturnCorrectAssemblySource()
        {
            var result = DependencyAnalyzer.Analyze(filesToAnalyse, null, logger, options);

            var tests = result.Assemblies.Values.Single(x => x.AssemblyName.Name == "AsmSpy.Core.Tests");

            var mscorlib = tests.References.Single(x => x.AssemblyName.Name == "mscorlib");

            Assert.Equal(AssemblySource.GlobalAssemblyCache, mscorlib.AssemblySource);
        }
Beispiel #13
0
        public void DependencyAnalyzerGetIssuesTest()
        {
            log.Info("-----------------------------DependencyAnalyzer GetIssues-----------------------------");

            // Test setup.
            var tapPackage = new PackageDef()
            {
                Name = "Tap", Version = SemanticVersion.Parse("7.0.700")
            };
            var packages = new List <PackageDef>();

            packages.Add(tapPackage);

            // Dependencies without any issues.
            using (var xmlText = File.OpenRead(Path.Combine(Directory.GetCurrentDirectory(), "TapPackages/MyPlugin1.xml")))
                packages.AddRange(PackageDef.ManyFromXml(xmlText));
            var dependencyAnalyzer = DependencyAnalyzer.BuildAnalyzerContext(packages);
            var issues             = dependencyAnalyzer.GetIssues(packages.Last());

            if (issues.Any())
            {
                Assert.Fail("Unexpected Dependency Issue: {1} {0} ", issues.First().IssueType, issues.First().PackageName);
            }
            log.Info("Dependencies without any issues - SUCCESS");

            // Reset test.
            packages = packages.Take(1).ToList();

            // Dependencies with issues (Tap newer than plugin).
            using (var xmlText = File.OpenRead(Path.Combine(Directory.GetCurrentDirectory(), "TapPackages/MyPlugin2.xml")))
            {
                var pkgs = PackageDef.ManyFromXml(xmlText);
                packages.AddRange(pkgs);
                Assert.IsTrue(pkgs.First().Version.Major == 1);
                Assert.IsTrue(pkgs.First().Version.Minor == 2);
                Assert.IsTrue(pkgs.First().Version.Patch == 3);
            }
            dependencyAnalyzer = DependencyAnalyzer.BuildAnalyzerContext(packages);
            issues             = dependencyAnalyzer.GetIssues(packages.Last());
            Assert.IsTrue(issues.Count == 1, "Dependencies with issues (Tap newer than plugin)");
            log.Info("Dependencies with issues (Tap newer than plugin) - SUCCESS");

            // Reset test.
            packages = packages.Take(1).ToList();

            // No dependencies.
            dependencyAnalyzer = DependencyAnalyzer.BuildAnalyzerContext(packages);
            issues             = dependencyAnalyzer.GetIssues(new PackageDef());
            Assert.IsTrue(issues.Count == 0, "No dependencies");
            log.Info("No dependencies - SUCCESS");
        }
Beispiel #14
0
        public async Task BasicSolutionAnalysis()
        {
            var currentDir  = AppContext.BaseDirectory;
            var goUp        = string.Format("..{0}..{0}..{0}..{0}", Path.DirectorySeparatorChar);
            var solutionDir = Path.GetFullPath(Path.Combine(currentDir, goUp));
            var solution    = Path.Combine(solutionDir, "SolutionDependencyAnalyzer.sln");
            var analyzer    = new DependencyAnalyzer(solution);
            await analyzer.AnalyzeAsync();

            Assert.AreEqual(6, analyzer.PackageResults.Count);
            Assert.AreEqual(2, analyzer.PackagesByProject.Count);
            Assert.AreEqual(2, analyzer.ProjectResults.Count);
            Assert.AreEqual(6, analyzer.ProjectsByPackage.Count);
        }
        public void AnalyzeShouldReturnDependencies()
        {
            var exampleClass = new ExampleClass();
            var result       = DependencyAnalyzer.Analyze(filesToAnalyse, null, logger, options);

            var tests = result.Assemblies.Values.Single(x => x.AssemblyName.Name == "AsmSpy.Core.Tests");

            Assert.Contains(tests.References, x => x.AssemblyName.Name == "AsmSpy.Core");
            Assert.Contains(tests.References, x => x.AssemblyName.Name == "AsmSpy.Core.TestLibrary");
            Assert.Contains(tests.References, x => x.AssemblyName.Name == "xunit.core");
            foreach (var reference in tests.References)
            {
                output.WriteLine(reference.AssemblyName.Name);
            }
        }
Beispiel #16
0
        public void CheckDependencies_MissingDep()
        {
            string inputFilename = "Packages/CheckDependencies_MissingDep/package.xml";

            //PackageDependencyExt.CheckDependencies(inputFilename);
            var xseries = PackageDef.FromXml(PackageDef.GetDefaultPackageMetadataPath("XSeries"));

            PackageDef.ValidateXml(inputFilename);
            var missing = PackageDef.FromXml(inputFilename);
            var tree    = DependencyAnalyzer.BuildAnalyzerContext(new List <PackageDef> {
                xseries, missing
            });

            Assert.IsTrue(tree.GetIssues(missing).Any(issue => issue.IssueType == DependencyIssueType.Missing));
            //Assert.Fail("CheckDependencies should have thrown an exception");
        }
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            Title =
                $"{Package.Name} {(PackageVersion == null ? "" : PackageVersion.Version+" ")}- All Package References";

            if (PackageVersion != null)
            {
                ListView.ItemsSource = DependencyAnalyzer.GetDependentPackages(PackageVersion);
            }
            else
            {
                ListView.ItemsSource = DependencyAnalyzer.GetDependentPackages(Package);
            }

            var x = ImpactAnalyzer.Analyze(PackageVersion);
        }
Beispiel #18
0
        public AnalyzerMessageBase[] AnalyzeProject(IAnalyzerConfig config, string[] sourcePaths, string[] referencedAssemblyPaths)
        {
            var resultBuilder = new AnalyzeProjectResultBuilder();

            var typeDependencyEnumerator = GetTypeDependencyEnumerator(resultBuilder.AddTrace);
            var dependencyAnalyzer       = new DependencyAnalyzer(config, typeDependencyEnumerator, resultBuilder.AddTrace);
            var illegalDependencies      = dependencyAnalyzer.AnalyzeProject(sourcePaths, referencedAssemblyPaths);

            foreach (var illegalDependency in illegalDependencies)
            {
                resultBuilder.AddIllegalDependency(illegalDependency);
            }

            resultBuilder.AddCacheStatistics(dependencyAnalyzer.HitCount, dependencyAnalyzer.MissCount, dependencyAnalyzer.EfficiencyPercent);

            return(resultBuilder.ToArray());
        }
        /// <summary>
        /// Test on every graph type. Used to ensure that the behavior of the various markers is consistent
        /// </summary>
        /// <param name="testGraph"></param>
        private void TestOnGraphTypes(Action<TestGraph, DependencyAnalyzerBase<TestGraph>> testGraph)
        {
            // Test using the full logging strategy
            TestGraph testGraphFull = new TestGraph();
            DependencyAnalyzerBase<TestGraph> analyzerFull = new DependencyAnalyzer<FullGraphLogStrategy<TestGraph>, TestGraph>(testGraphFull, null);
            testGraphFull.AttachToDependencyAnalyzer(analyzerFull);
            testGraph(testGraphFull, analyzerFull);

            TestGraph testGraphFirstMark = new TestGraph();
            DependencyAnalyzerBase<TestGraph> analyzerFirstMark = new DependencyAnalyzer<FirstMarkLogStrategy<TestGraph>, TestGraph>(testGraphFirstMark, null);
            testGraphFirstMark.AttachToDependencyAnalyzer(analyzerFirstMark);
            testGraph(testGraphFirstMark, analyzerFirstMark);

            TestGraph testGraphNoLog = new TestGraph();
            DependencyAnalyzerBase<TestGraph> analyzerNoLog = new DependencyAnalyzer<NoLogStrategy<TestGraph>, TestGraph>(testGraphNoLog, null);
            testGraphNoLog.AttachToDependencyAnalyzer(analyzerNoLog);
            testGraph(testGraphNoLog, analyzerNoLog);
        }
Beispiel #20
0
        private DependencyGraph GetDependencyGraph(ILoggerFactory loggerFactory)
        {
            var             analyzer = new DependencyAnalyzer(loggerFactory);
            DependencyGraph graph;

            if (!string.IsNullOrEmpty(Package))
            {
                graph = analyzer.Analyze(Package, Version, Framework);
            }
            else if (Path.GetExtension(Project).Equals(".sln", StringComparison.OrdinalIgnoreCase))
            {
                graph = analyzer.AnalyzeSolution(Project, Framework);
            }
            else
            {
                graph = analyzer.Analyze(Project, Framework);
            }
            return(graph);
        }
Beispiel #21
0
        public override bool Execute()
        {
            logger = new MsBuildLogger(Log);

            var directoryInfo = new DirectoryInfo(Directory);

            logger.LogMessage(string.Format(CultureInfo.InvariantCulture, "Checking assemblies in: {0}", directoryInfo));

            var fileList = GetFilesToAnalyze(directoryInfo);

            IDependencyAnalyzerResult analyzerResult = new DependencyAnalyzer(fileList).Analyze(logger);
            var filteredAnalyzerResult = ApplyFilters(analyzerResult);

            if (HasNotFoundAssembly(filteredAnalyzerResult))
            {
                logger.LogError($"Some dll references could not be found. Run \"AsmSpy {Directory} -s -i -n\", and check the red entries for more info.");
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Test on every graph type. Used to ensure that the behavior of the various markers is consistent
        /// </summary>
        /// <param name="testGraph"></param>
        private void TestOnGraphTypes(Action <TestGraph, DependencyAnalyzerBase <TestGraph> > testGraph)
        {
            // Test using the full logging strategy
            TestGraph testGraphFull = new TestGraph();
            DependencyAnalyzerBase <TestGraph> analyzerFull = new DependencyAnalyzer <FullGraphLogStrategy <TestGraph>, TestGraph>(testGraphFull, null);

            testGraphFull.AttachToDependencyAnalyzer(analyzerFull);
            testGraph(testGraphFull, analyzerFull);

            TestGraph testGraphFirstMark = new TestGraph();
            DependencyAnalyzerBase <TestGraph> analyzerFirstMark = new DependencyAnalyzer <FirstMarkLogStrategy <TestGraph>, TestGraph>(testGraphFirstMark, null);

            testGraphFirstMark.AttachToDependencyAnalyzer(analyzerFirstMark);
            testGraph(testGraphFirstMark, analyzerFirstMark);

            TestGraph testGraphNoLog = new TestGraph();
            DependencyAnalyzerBase <TestGraph> analyzerNoLog = new DependencyAnalyzer <NoLogStrategy <TestGraph>, TestGraph>(testGraphNoLog, null);

            testGraphNoLog.AttachToDependencyAnalyzer(analyzerNoLog);
            testGraph(testGraphNoLog, analyzerNoLog);
        }
Beispiel #23
0
        public void DependencyAnalyzerFilterRelatedTest()
        {
            log.Info("-----------------------------DependencyAnalyzer FilterRelated-----------------------------");

            // Test setup.
            var tapPackage = new PackageDef()
            {
                Name = "Tap", Version = SemanticVersion.Parse("9.0")
            };                                                                                         // TapVersion.GetTapEngineVersion().ToString() };
            var packages = new List <PackageDef>();

            packages.Add(tapPackage);
            using (var xmlText = File.OpenRead(Path.Combine(Directory.GetCurrentDirectory(), "TapPackages/MyPlugin3.xml")))
                packages.AddRange(PackageDef.ManyFromXml(xmlText));
            using (var xmlText = File.OpenRead(Path.Combine(Directory.GetCurrentDirectory(), "TapPackages/MyPlugin2.xml")))
                packages.AddRange(PackageDef.ManyFromXml(xmlText));
            using (var xmlText = File.OpenRead(Path.Combine(Directory.GetCurrentDirectory(), "TapPackages/MyPlugin1.xml")))
                packages.AddRange(PackageDef.ManyFromXml(xmlText));

            // No dependencies
            var dependencyAnalyzer = DependencyAnalyzer.BuildAnalyzerContext(packages.Take(2).ToList());
            var issues             = dependencyAnalyzer.FilterRelated(packages.Take(2).ToList());

            Assert.IsTrue(issues.BrokenPackages.Count == 0, "No dependencies");
            log.Info("No dependencies - SUCCESS");

            // Tap dependency
            dependencyAnalyzer = DependencyAnalyzer.BuildAnalyzerContext(packages.Take(3).ToList());
            issues             = dependencyAnalyzer.FilterRelated(packages.Take(3).ToList());
            Assert.IsTrue(issues.BrokenPackages.Count == 1, "Tap dependency");
            log.Info("Tap dependency - SUCCESS");

            // Several Tap dependencies
            dependencyAnalyzer = DependencyAnalyzer.BuildAnalyzerContext(packages.ToList());
            issues             = dependencyAnalyzer.FilterRelated(packages.ToList());
            Assert.IsTrue(issues.BrokenPackages.Count == 2, "Several Tap dependencies");
            log.Info("Several Tap dependencies - SUCCESS");
        }
Beispiel #24
0
        public void TriggerSqlTest()
        {
            var sql   = @"CREATE TRIGGER [Project_Task_Step04_Create_Trigger] ON [PROJECT_TASK]
INSTEAD OF UPDATE
AS
BEGIN
  UPDATE Activity2
  SET locked_by_id = inserted.locked_by_id
  FROM inserted
  WHERE Activity2.id = inserted.id

  UPDATE Activity2_Assignment
  SET locked_by_id = inserted.locked_by_id
  FROM inserted
  WHERE Activity2_Assignment.id = inserted.id

END";
            var names = DependencyAnalyzer.GetInnovatorNames(sql)
                        .Select(n => n.FullName).ToArray();
            var correct = new string[] { "Project_Task_Step04_Create_Trigger", "Activity2", "inserted", "Activity2_Assignment", "inserted" };

            CollectionAssert.AreEqual(correct, names);
        }
Beispiel #25
0
        public static int Main(string[] args)
        {
            var commandLineApplication = new CommandLineApplication(throwOnUnexpectedArg: true);
            var directoryOrFile        = commandLineApplication.Argument("directoryOrFile", "The directory to search for assemblies or file path to a single assembly");
            var dgmlExport             = commandLineApplication.Option("-dg|--dgml <filename>", "Export to a dgml file", CommandOptionType.SingleValue);
            var nonsystem             = commandLineApplication.Option("-n|--nonsystem", "Ignore 'System' assemblies", CommandOptionType.NoValue);
            var all                   = commandLineApplication.Option("-a|--all", "List all assemblies and references.", CommandOptionType.NoValue);
            var noconsole             = commandLineApplication.Option("-nc|--noconsole", "Do not show references on console.", CommandOptionType.NoValue);
            var silent                = commandLineApplication.Option("-s|--silent", "Do not show any message, only warnings and errors will be shown.", CommandOptionType.NoValue);
            var bindingRedirect       = commandLineApplication.Option("-b|--bindingredirect", "Create binding-redirects", CommandOptionType.NoValue);
            var referencedStartsWith  = commandLineApplication.Option("-rsw|--referencedstartswith", "Referenced Assembly should start with <string>. Will only analyze assemblies if their referenced assemblies starts with the given value.", CommandOptionType.SingleValue);
            var includeSubDirectories = commandLineApplication.Option("-i|--includesub", "Include subdirectories in search", CommandOptionType.NoValue);
            var configurationFile     = commandLineApplication.Option("-c|--configurationFile", "Use the binding redirects of the given configuration file (Web.config or App.config)", CommandOptionType.SingleValue);
            var failOnMissing         = commandLineApplication.Option("-f|--failOnMissing", "Whether to exit with an error code when AsmSpy detected Assemblies which could not be found", CommandOptionType.NoValue);

            commandLineApplication.HelpOption("-? | -h | --help");
            commandLineApplication.OnExecute(() =>
            {
                var consoleLogger = new ConsoleLogger(!silent.HasValue());

                var directoryOrFilePath = directoryOrFile.Value;
                var directoryPath       = directoryOrFile.Value;

                if (!File.Exists(directoryOrFilePath) && !Directory.Exists(directoryOrFilePath))
                {
                    consoleLogger.LogMessage(string.Format(CultureInfo.InvariantCulture, "Directory or file: '{0}' does not exist.", directoryOrFilePath));
                    return(-1);
                }

                var configurationFilePath = configurationFile.Value();
                if (!string.IsNullOrEmpty(configurationFilePath) && !File.Exists(configurationFilePath))
                {
                    consoleLogger.LogMessage(string.Format(CultureInfo.InvariantCulture, "Directory or file: '{0}' does not exist.", configurationFilePath));
                    return(-1);
                }

                var isFilePathProvided = false;
                var fileName           = "";
                if (File.Exists(directoryOrFilePath))
                {
                    isFilePathProvided = true;
                    fileName           = Path.GetFileName(directoryOrFilePath);
                    directoryPath      = Path.GetDirectoryName(directoryOrFilePath);
                }

                var onlyConflicts = !all.HasValue();
                var skipSystem    = nonsystem.HasValue();
                var searchPattern = includeSubDirectories.HasValue() ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;

                var directoryInfo = new DirectoryInfo(directoryPath);

                List <FileInfo> fileList;
                if (isFilePathProvided)
                {
                    fileList = directoryInfo.GetFiles(fileName, SearchOption.TopDirectoryOnly).ToList();
                    consoleLogger.LogMessage(string.Format(CultureInfo.InvariantCulture, "Check assemblies referenced in: {0}", directoryOrFilePath));
                }
                else
                {
                    fileList = directoryInfo.GetFiles("*.dll", searchPattern).Concat(directoryInfo.GetFiles("*.exe", searchPattern)).ToList();
                    consoleLogger.LogMessage(string.Format(CultureInfo.InvariantCulture, "Check assemblies in: {0}", directoryInfo));
                }

                AppDomain appDomainWithBindingRedirects = null;
                try
                {
                    var domaininfo = new AppDomainSetup
                    {
                        ConfigurationFile = configurationFilePath
                    };
                    appDomainWithBindingRedirects = AppDomain.CreateDomain("AppDomainWithBindingRedirects", null, domaininfo);
                }
                catch (Exception ex)
                {
                    consoleLogger.LogError($"Failed creating AppDomain from configuration file with message {ex.Message}");
                    return(-1);
                }

                IDependencyAnalyzer analyzer = new DependencyAnalyzer(fileList, appDomainWithBindingRedirects);

                var result = analyzer.Analyze(consoleLogger);

                if (!noconsole.HasValue())
                {
                    IDependencyVisualizer visualizer = new ConsoleVisualizer(result)
                    {
                        SkipSystem = skipSystem, OnlyConflicts = onlyConflicts, ReferencedStartsWith = referencedStartsWith.HasValue() ? referencedStartsWith.Value() : string.Empty
                    };
                    visualizer.Visualize();
                }

                if (dgmlExport.HasValue())
                {
                    IDependencyVisualizer export = new DgmlExport(result, string.IsNullOrWhiteSpace(dgmlExport.Value()) ? Path.Combine(directoryInfo.FullName, "references.dgml") : dgmlExport.Value(), consoleLogger)
                    {
                        SkipSystem = skipSystem
                    };
                    export.Visualize();
                }

                if (bindingRedirect.HasValue())
                {
                    // binding redirect export explicitly doesn't respect SkipSystem
                    IDependencyVisualizer bindingRedirects = new BindingRedirectExport(result, string.IsNullOrWhiteSpace(dgmlExport.Value()) ? Path.Combine(directoryInfo.FullName, "bindingRedirects.xml") : dgmlExport.Value(), consoleLogger);
                    bindingRedirects.Visualize();
                }

                if (failOnMissing.HasValue() && result.MissingAssemblies.Any(x => !skipSystem || !x.IsSystem))
                {
                    return(-1);
                }
                return(0);
            });
            try
            {
                if (args == null || args.Length == 0)
                {
                    commandLineApplication.ShowHelp();
                    return(0);
                }

                return(commandLineApplication.Execute(args));
            }
            catch (CommandParsingException cpe)
            {
                Console.WriteLine(cpe.Message);
                commandLineApplication.ShowHelp();
                return(0);
            }
        }
Beispiel #26
0
        // ReSharper disable once UnusedMember.Local
        private void OnExecute()
        {
            var loggerFactory = LoggerFactory.Create(builder => builder
                                                     .SetMinimumLevel(Verbosity)
                                                     .AddConsole());

            var             analyzer = new DependencyAnalyzer(loggerFactory);
            DependencyGraph graph;

            if (!string.IsNullOrEmpty(Package))
            {
                graph = analyzer.Analyze(Package, Version, Framework);
            }
            else if (Path.GetExtension(Project).Equals(".sln", StringComparison.OrdinalIgnoreCase))
            {
                graph = analyzer.AnalyzeSolution(Project, Framework);
            }
            else
            {
                graph = analyzer.Analyze(Project, Framework);
            }

            Application.Init();

            var top = new CustomWindow();

            var left = new FrameView("Dependencies")
            {
                Width  = Dim.Percent(50),
                Height = Dim.Fill(1)
            };
            var right = new View()
            {
                X      = Pos.Right(left),
                Width  = Dim.Fill(),
                Height = Dim.Fill(1)
            };
            var helpText = new Label("Use arrow keys and Tab to move around. Ctrl+D to toggle assembly visibility. Esc to quit.")
            {
                Y = Pos.AnchorEnd(1)
            };

            var runtimeDepends = new FrameView("Runtime depends")
            {
                Width  = Dim.Fill(),
                Height = Dim.Percent(33f)
            };
            var packageDepends = new FrameView("Package depends")
            {
                Y      = Pos.Bottom(runtimeDepends),
                Width  = Dim.Fill(),
                Height = Dim.Percent(50f)
            };
            var reverseDepends = new FrameView("Reverse depends")
            {
                Y      = Pos.Bottom(packageDepends),
                Width  = Dim.Fill(),
                Height = Dim.Fill()
            };

            var orderedDependencyList = graph.Nodes.OrderBy(x => x.Id).ToImmutableList();
            var dependenciesView      = new ListView(orderedDependencyList)
            {
                CanFocus      = true,
                AllowsMarking = false
            };

            left.Add(dependenciesView);
            var runtimeDependsView = new ListView(Array.Empty <Node>())
            {
                CanFocus      = true,
                AllowsMarking = false
            };

            runtimeDepends.Add(runtimeDependsView);
            var packageDependsView = new ListView(Array.Empty <Node>())
            {
                CanFocus      = true,
                AllowsMarking = false
            };

            packageDepends.Add(packageDependsView);
            var reverseDependsView = new ListView(Array.Empty <Node>())
            {
                CanFocus      = true,
                AllowsMarking = false
            };

            reverseDepends.Add(reverseDependsView);

            right.Add(runtimeDepends, packageDepends, reverseDepends);
            top.Add(left, right, helpText);
            Application.Top.Add(top);

            top.Dependencies        = orderedDependencyList;
            top.VisibleDependencies = orderedDependencyList;
            top.DependenciesView    = dependenciesView;

            dependenciesView.SelectedItem = 0;
            UpdateLists();

            dependenciesView.SelectedChanged += UpdateLists;

            Application.Run();

            void UpdateLists()
            {
                var selectedNode = top.VisibleDependencies[dependenciesView.SelectedItem];

                runtimeDependsView.SetSource(graph.Edges.Where(x => x.Start.Equals(selectedNode) && x.End is AssemblyReferenceNode)
                                             .Select(x => x.End).ToImmutableList());
                packageDependsView.SetSource(graph.Edges.Where(x => x.Start.Equals(selectedNode) && x.End is PackageReferenceNode)
                                             .Select(x => $"{x.End}{(string.IsNullOrEmpty(x.Label) ? string.Empty : " (Wanted: " + x.Label + ")")}").ToImmutableList());
                reverseDependsView.SetSource(graph.Edges.Where(x => x.End.Equals(selectedNode))
                                             .Select(x => $"{x.Start}{(string.IsNullOrEmpty(x.Label) ? string.Empty : " (Wanted: " + x.Label + ")")}").ToImmutableList());
            }
        }
Beispiel #27
0
        public void FindSqlServerObjectNamesTest()
        {
            var correct = new string[] {
                "innovator.USER", "innovator.PERSON", "innovator.IDENTITY", "innovator.Person_Search", "innovator.IDENTITY",
                "innovator.Person_Search", "innovator.DEPARTMENT", "innovator.INVENTORY_ORG", "innovator.COMPANY", "innovator.COMPANY",
                "innovator.FEATURE", "innovator.DEFECT", "innovator.htmltotext", "innovator.COMPANY", "innovator.INVENTORY_ORG", "innovator.PART",
                "innovator.PART", "innovator.FUNCTIONAL_GROUP", "innovator.CONCERN", "innovator.ISSUE", "innovator.IDENTITY", "innovator.ALIAS",
                "innovator.PERSON", "innovator.FEATURE_DEFECT", "innovator.MANUFACTURING_ENTITY", "innovator.PART", "innovator.PART",
                "innovator.MANUFACTURING_ENTITY", "innovator.DEPARTMENT", "innovator.Last_Comments", "innovator.ANALYSIS", "innovator.PROGRAM",
                "innovator.LAB_TEST_ROUND", "innovator.ConvertToLocalTbl", "innovator.ConvertToLocalTbl", "innovator.ConvertToLocalTbl",
                "innovator.ConvertToLocalTbl", "innovator.ConvertToLocalTbl"
            };
            var names = DependencyAnalyzer.GetInnovatorNames(@"SELECT
    c.[id]
  , case when charindex('/', c.[CLASSIFICATION]) = 0 then c.[CLASSIFICATION] else left(c.CLASSIFICATION, charindex('/', c.[CLASSIFICATION])-1) end classification_01
  , case when charindex('/', c.[CLASSIFICATION]) = 0 then c.[CLASSIFICATION]
     when charindex('/', c.[CLASSIFICATION], charindex('/', c.[CLASSIFICATION])+1) = 0 then c.[CLASSIFICATION]
     else left(c.CLASSIFICATION, charindex('/', c.[CLASSIFICATION],charindex('/', c.[CLASSIFICATION])+1)-1) end classification_02
  , c.[CLASSIFICATION]
  , d_cr.LocalDate CREATED_ON
  , (select KEYED_NAME from innovator.[USER] where id = c.CREATED_BY_ID) CREATED_BY
  , (select Employee_ID from innovator.PERSON where ARAS_USER = c.CREATED_BY_ID) CREATED_BY_EMP_ID
  , (select KEYED_NAME from innovator.[IDENTITY] where id = c.OWNED_BY_ID) OWNED_BY
  , (select employee_id from innovator.Person_Search where ident_id = c.OWNED_BY_ID) OWNED_BY_emp_id
  , (select KEYED_NAME from innovator.[IDENTITY] where id = c.MANAGED_BY_ID) ISSUE_OWNER_REVIEWER
  , (select employee_id from innovator.Person_Search where ident_id = c.MANAGED_BY_ID) ISSUE_OWNER_REVIEWER_emp_id
  , resp.KEYED_NAME problem_assigned_to
  , presp.employee_id problem_assigned_to_emp_id
  , presp.department_text problem_assigned_to_dept
  , c.[CONCERN_ID]
  , cpmfg.ITEM_NUMBER current_part_mfg_line
  , isnull((select MFG_GROUP from innovator.DEPARTMENT where id = cpmfg.DEPARTMENT), pa.primary_mfg_group) current_part_mfg_group
  , (select CODE from innovator.INVENTORY_ORG where id = c.CURRENT_PART_ORGANIZATION) current_part_mfg_org
  , (select keyed_name from innovator.COMPANY where id = c.[CUSTOMER]) customer_direct
  , (select keyed_name from innovator.COMPANY where id = isnull(c.[CUSTOMER_OEM], c.[CUSTOMER])) customer_oem
  , d_cl.LocalDate date_closed
  , d_vb.LocalDate DATE_VEHICLE_BUILD
  , c.[DEALER_NUMBER]
  , c.[DEALER_STATE]
  , (select KEYED_NAME from innovator.FEATURE where id = fd.source_id) defective_feature
  , (select KEYED_NAME from innovator.DEFECT where id = fd.RELATED_ID) defect_type
  , innovator.htmltotext(c.[DESCRIPTION]) DESCRIPTION
  , c.[ISSUE]
  , pa.ITEM_NUMBER current_part_number
  , pa.MAJOR_REV current_part_rev
  , pb.ITEM_NUMBER problem_part_number
  , pb.MAJOR_REV problem_part_rev
  , c.TEST_PHASE
  , c.[TEST_PROBLEM_TYPE]
  , c.LAB
  , c.LAB_TEST_ROUND lab_round_ct_id
  , rnd.LAB_ROUND_ID LAB_ROUND_ID
  , (select keyed_name from innovator.COMPANY where id = c.[MANUFACTURER]) manufacturer
  , ppmfg.ITEM_NUMBER problem_part_mfg_line
  , isnull(ppdep.MFG_GROUP, pb.primary_mfg_group) problem_part_mfg_group
  , (select CODE from innovator.INVENTORY_ORG where id = isnull(c.[MANUFACTURING_ORG], ppdep.inventory_org)) problem_part_mfg_org
  , c.[NAME]
  , d_oc.LocalDate OCCURRENCE_DATE
  , c.[PROBLEM_STATE]
  , c.[PRODUCT_LINE]
  , prgm.TEAMLINK_ID program
  , prgm.NAME program_name
  , c.[QTY_FOUND]
  , c.[QTY_TO_REPORT]
  , c.[QUANTITY_INSPECTED]
  , c.[RESPONSIBILITY]
  , (select item_number from innovator.PART where id = c.[RESPONSIBLE_PART_NUMBER]) RESPONSIBLE_PART_NUMBER
  , (select PRIMARY_MFG_GROUP from innovator.PART where id = c.[RESPONSIBLE_PART_NUMBER]) RESPONSIBLE_PART_MFG_GROUP
  , (select keyed_name from innovator.FUNCTIONAL_GROUP where id = c.[RESPONSIBLE_PARTY]) RESPONSIBLE_PARTY
  , c.[SEVERITY]
  , c.[VEHICLE_MAKE]
  , c.[VEHICLE_MODEL]
  , c.[VEHICLE_MODEL_YEAR]
  , c.[MANUFACTURING_LOCATION_TYPE]
  , d_ev.LocalDate comment_date
  , com.comments
  , c.CURRENT_PART_SHIFT
  , c.OCCURRENCE_SHIFT
  , case when a.DATE_CLOSED is null then null else cast(round(DATEDIFF(ss, c.CREATED_ON, a.DATE_CLOSED) / 86400.0,0) as int) end CUSTOMER_ANALYSIS_DAYS_TO_COMPLETE
FROM innovator.[CONCERN] c
left join innovator.ISSUE i
  on i.id = c.ISSUE
left join innovator.[IDENTITY] resp
  on resp.id = case when c.issue is not null then 
                case when i.STATE = 'Verification' then i.MANAGED_BY_ID
                else i.OWNED_BY_ID end
               when c.state in ('Canceled', 'Closed', 'Closed : Conversion') then isnull(c.MANAGED_BY_ID, c.OWNED_BY_ID)
               when c.state = 'In Work' then c.OWNED_BY_ID
               else c.MANAGED_BY_ID end
left join innovator.ALIAS aresp
  on aresp.RELATED_ID = resp.id
left join innovator.PERSON presp
  on presp.ARAS_USER = aresp.SOURCE_ID
left join innovator.FEATURE_DEFECT fd
  on fd.id = c.DEFECT
left join innovator.MANUFACTURING_ENTITY cpmfg
  on cpmfg.id = c.CURRENT_PART_MFG_LINE
left join innovator.PART pa
  on pa.id = c.ITEM_NBR_ASSY
left join innovator.PART pb
  on pb.id = c.ITEM_NBR_BASE
left join innovator.MANUFACTURING_ENTITY ppmfg
on ppmfg.id = c.MANUFACTURING_LINE
left join innovator.DEPARTMENT ppdep
on ppdep.id = ppmfg.DEPARTMENT
left join innovator.Last_Comments com
on com.item_id = c.id
and com.itemtype_id = 'F1D2DE3EAFAB4B2B with innovator.[another] 935D7061C49DF35B'
left join (
  select a.concern, min(a.DATE_CLOSED) DATE_CLOSED
  from innovator.ANALYSIS a
  where a.CLASSIFICATION in ('Customer Return/Initial IEC Functional (Stage 1)', 'Customer Return/Initial Visual (Stage 1)') 
  and a.DATE_CLOSED is not null
  group by a.CONCERN
) a
on a.CONCERN = c.id
left join innovator.PROGRAM prgm
on prgm.id = c.PROGRAM
left join innovator.LAB_TEST_ROUND rnd
on rnd.id = c.LAB_TEST_ROUND
/* a test for innovator.[thingy] */
CROSS APPLY innovator.ConvertToLocalTbl(c.[CREATED_ON], 'Eastern Standard Time') d_cr
CROSS APPLY innovator.ConvertToLocalTbl(c.[DATE_CLOSED], 'Eastern Standard Time') d_cl
CROSS APPLY innovator.ConvertToLocalTbl(c.[DATE_VEHICLE_BUILD], 'Eastern Standard Time') d_vb
CROSS APPLY innovator.ConvertToLocalTbl(c.[OCCURRENCE_DATE], 'Eastern Standard Time') d_oc
CROSS APPLY innovator.ConvertToLocalTbl(com.event_date, 'Eastern Standard Time') d_ev")
                        .Select(n => n.FullName).ToArray();

            CollectionAssert.AreEqual(correct, names);

            correct = new string[] {
                "PE_RollupAllPartsInDB", "PART", "PART", "PART", "PART_GOAL", "PART", "PART", "PART", "PART_GOAL", "PART", "PART_BOM",
                "PART_GOAL", "PART_GOAL", "PART", "PART", "PART_GOAL", "PART", "PART", "PART_GOAL", "PART", "PART_BOM",
                "ind_tmp_BOMS_TO_USE_source_id", "ind_tmp_BOMS_TO_USE_related_id", "PART", "PART", "PART_GOAL", "PART_GOAL", "PART_GOAL",
                "PART_BOM", "PART", "PART", "PART", "PART_GOAL", "PART_GOAL", "PART_GOAL", "PART_GOAL", "PART_BOM", "PART", "PART", "PART", "PART_GOAL"
            };

            names = DependencyAnalyzer.GetInnovatorNames(@"/*
name: PE_RollupAllPartsInDB
solution: PLM
created: 06-OCT-2006
purpose: Rollup all Parts cost and weight in DB
notes:
*/

CREATE PROCEDURE PE_RollupAllPartsInDB
AS
BEGIN
  -- 1. Set cost to NULL on Parts with no Part Goal for cost
  UPDATE PART
  SET cost=NULL, cost_basis=NULL
  FROM PART all_parts
    INNER JOIN
      (SELECT p.id id
       FROM PART p LEFT OUTER JOIN PART_GOAL pg ON p.id=pg.source_id
       WHERE (pg.goal IS NULL) OR (pg.goal != 'Cost')) no_cost
    ON all_parts.id=no_cost.id;
  
  -- 2. Set weight to NULL on Parts with no Part Goal for weight
  UPDATE PART
  SET weight=NULL, weight_basis=NULL
  FROM PART all_parts
    INNER JOIN
      (SELECT p.id id
       FROM PART p LEFT OUTER JOIN PART_GOAL pg ON p.id=pg.source_id
       WHERE (pg.goal IS NULL) OR (pg.goal != 'Weight')) no_weight
    ON all_parts.id=no_weight.id;
  
  DECLARE @TMP_PARTS TABLE(id CHAR(32) COLLATE database_default PRIMARY KEY);
  
  -- 3. Find leaf Parts
  INSERT INTO @TMP_PARTS(id)
  SELECT p.id
  FROM PART p LEFT OUTER JOIN PART_BOM pb ON p.id=pb.source_id
  WHERE pb.id IS NULL;
  
  -- 4. In all leaf Part Goals calculated_value must be NULL
  UPDATE PART_GOAL
  SET calculated_value=NULL
  FROM PART_GOAL pg INNER JOIN @TMP_PARTS p ON p.id=pg.source_id;
  
  -- 5. Set correct costs on leaf Parts
  UPDATE PART
  SET cost=new_cost.new_value, cost_basis=new_cost.new_basis
  FROM PART p
    INNER JOIN
      (SELECT p.id id, ISNULL(actual_value,ISNULL(estimated_value,ISNULL(guess_value,target_value))) new_value,
         CASE
           WHEN actual_value IS NOT NULL THEN 'Actual'
           WHEN estimated_value IS NOT NULL THEN 'Estimated'
           WHEN guess_value IS NOT NULL THEN 'Guess'
           WHEN target_value IS NOT NULL THEN 'Target'
           ELSE NULL
         END new_basis
       FROM @TMP_PARTS p INNER JOIN PART_GOAL pg ON p.id=pg.source_id
       WHERE pg.goal='Cost') new_cost
    ON p.id=new_cost.id;
  
  -- 6. Set correct weights on leaf Parts
  UPDATE PART
  SET weight=new_weight.new_value, cost_basis=new_weight.new_basis
  FROM PART p
    INNER JOIN
      (SELECT p.id id, ISNULL(actual_value,ISNULL(estimated_value,ISNULL(guess_value,target_value))) new_value,
         CASE
           WHEN actual_value IS NOT NULL THEN 'Actual'
           WHEN estimated_value IS NOT NULL THEN 'Estimated'
           WHEN guess_value IS NOT NULL THEN 'Guess'
           WHEN target_value IS NOT NULL THEN 'Target'
           ELSE NULL
         END new_basis
       FROM @TMP_PARTS p INNER JOIN PART_GOAL pg ON p.id=pg.source_id
       WHERE pg.goal='Weight') new_weight
    ON p.id=new_weight.id;
  
  DELETE FROM @TMP_PARTS;
  
  -- 3. Update all parts and check for infinite loop
  CREATE TABLE #tmp_PARTS_TO_USE(id CHAR(32) COLLATE database_default PRIMARY KEY);
  INSERT INTO #tmp_PARTS_TO_USE(id)
  SELECT id
  FROM PART;
  
  IF (@@ROWCOUNT = 0) /* there are no Parts in DB */
  BEGIN
    GOTO finish;
  END
  
  CREATE TABLE #tmp_BOMS_TO_USE(id CHAR(32) COLLATE database_default PRIMARY KEY,
                               source_id CHAR(32) COLLATE database_default,
                               related_id CHAR(32) COLLATE database_default);
  
  INSERT INTO #tmp_BOMS_TO_USE(id, source_id, related_id)
  SELECT id, source_id, related_id
  FROM PART_BOM
  WHERE related_id IS NOT NULL;
  
  IF (@@ROWCOUNT > 0) /* there are Part BOMs in DB */
  BEGIN
    CREATE INDEX ind_tmp_BOMS_TO_USE_source_id ON #tmp_BOMS_TO_USE(source_id);
    CREATE INDEX ind_tmp_BOMS_TO_USE_related_id ON #tmp_BOMS_TO_USE(related_id);
  END
  
  /* +++ iterate over leaf Parts. And calculate their costs. Check for infinite loop also. */
  DECLARE @PARTS_TO_ROLLUP INT;
  DECLARE @CURRENT_PARTS TABLE(id CHAR(32) COLLATE database_default PRIMARY KEY);
  
  WHILE (1=1)
  BEGIN
    DECLARE @LEAF_PARTS_COUNT INT;
    
    /* find leaf nodes */
    INSERT INTO @TMP_PARTS(id)
    SELECT p.id
    FROM #tmp_PARTS_TO_USE p LEFT OUTER JOIN #tmp_BOMS_TO_USE pb ON p.id=pb.source_id
    WHERE pb.id IS NULL;
    
    SET @LEAF_PARTS_COUNT = @@ROWCOUNT;
    
    IF (@LEAF_PARTS_COUNT = 0) /* there are no leaf nodes any more */
    BEGIN
      DECLARE @infinitive_loop_parent_id CHAR(32); /* id of some ""parent"" Part from infinite loop */
      DECLARE @infinitive_loop_child_id CHAR(32);  /* id of ""child"" Part from infinite loop */
      
      SELECT TOP 1 @infinitive_loop_parent_id = pb.source_id, @infinitive_loop_child_id=pb.related_id
      FROM #tmp_BOMS_TO_USE pb INNER JOIN #tmp_PARTS_TO_USE p ON pb.source_id=p.id;
      
      IF (@infinitive_loop_parent_id IS NULL) /* there is no infinite loop. There no Parts any more. */
      BEGIN
        BREAK;
      END
      
      DECLARE @parent_part_keyed_name VARCHAR(128);
      DECLARE @child_part_keyed_name VARCHAR(128);
      
      SELECT @parent_part_keyed_name=ISNULL(keyed_name,id)
      FROM PART
      WHERE id=@infinitive_loop_parent_id;
      
      SELECT @child_part_keyed_name=ISNULL(keyed_name,id)
      FROM PART
      WHERE id=@infinitive_loop_child_id;
      
      DECLARE @infiniteLoopMsg VARCHAR(2000); /* 2000>>128+32+128+32 */
      DECLARE @infiniteLoopSeverity INT;     /* the user-defined severity level associated with this message */
      DECLARE @infiniteLoopState INT;        /* Is an arbitrary integer from 1 through 127 that represents information about the invocation state of the error. */
      
      SET @infiniteLoopMsg = '<B>The BOM structure contains circular references</B>. Please check dependency between Part ""' + 
        @parent_part_keyed_name + '"" (' + @infinitive_loop_parent_id + ') and ""' +
        @child_part_keyed_name + '"" (' + @infinitive_loop_child_id + ').';
      SET @infiniteLoopSeverity = 16; /* Severity Levels 11 through 16: These messages indicate errors that can be corrected by the user. */
      SET @infiniteLoopState = 1;
      
      RAISERROR(@infiniteLoopMsg, @infiniteLoopSeverity, @infiniteLoopState)
      RETURN @@ERROR;
    END
    
    DELETE FROM @CURRENT_PARTS;
    
    INSERT INTO @CURRENT_PARTS(id)
    SELECT DISTINCT pb.source_id
    FROM #tmp_BOMS_TO_USE pb INNER JOIN @TMP_PARTS p ON p.id=pb.related_id;
    
    -- . Update calculated cost value on Part Goals
    UPDATE PART_GOAL
    SET calculated_value=new_cost.new_val
    FROM PART_GOAL pg
      INNER JOIN
        (SELECT pg.id id,
           CASE
             WHEN SUM(
                    CASE child_p.cost_basis
                      WHEN 'Actual' THEN 0
                      WHEN 'Calculated' THEN 0
                      WHEN 'Estimated' THEN 0
                      ELSE ABS(child_pb.QUANTITY)
                    END
                  ) > 0 THEN NULL
             ELSE SUM( ISNULL(child_p.cost,0)*ISNULL(child_pb.quantity, 0) )
           END new_val
         FROM @CURRENT_PARTS current_p
           INNER JOIN PART_GOAL pg ON pg.source_id=current_p.id
           INNER JOIN PART_BOM child_pb ON child_pb.source_id=current_p.id
           INNER JOIN PART child_p ON child_pb.related_id=child_p.id
         WHERE pg.goal='Cost'
         GROUP BY pg.id) new_cost
      ON pg.id=new_cost.id;
      
    -- . Set correct costs on current Parts
    UPDATE PART
    SET cost=new_cost.new_value, cost_basis=new_cost.new_basis
    FROM PART p
      INNER JOIN
        (SELECT p.id id, ISNULL(actual_value,ISNULL(calculated_value,ISNULL(estimated_value,ISNULL(guess_value,target_value)))) new_value,
           CASE
             WHEN actual_value IS NOT NULL THEN 'Actual'
             WHEN calculated_value IS NOT NULL THEN 'Calculated'
             WHEN estimated_value IS NOT NULL THEN 'Estimated'
             WHEN guess_value IS NOT NULL THEN 'Guess'
             WHEN target_value IS NOT NULL THEN 'Target'
             ELSE NULL
           END new_basis
         FROM @CURRENT_PARTS p INNER JOIN PART_GOAL pg ON p.id=pg.source_id
         WHERE pg.goal='Cost') new_cost
      ON p.id=new_cost.id;
    
    -- . Update calculated weight value on Part Goals
    UPDATE PART_GOAL
    SET calculated_value=new_weight.new_val
    FROM PART_GOAL pg
      INNER JOIN
        (SELECT pg.id id,
           CASE
             WHEN SUM(
                    CASE child_p.weight_basis
                      WHEN 'Actual' THEN 0
                      WHEN 'Calculated' THEN 0
                      WHEN 'Estimated' THEN 0
                      ELSE 1
                    END
                  ) > 0 THEN NULL
             ELSE SUM( ISNULL(child_p.weight,0)*ISNULL(child_pb.quantity, 0) )
           END new_val
         FROM @CURRENT_PARTS current_p
           INNER JOIN PART_GOAL pg ON pg.source_id=current_p.id
           INNER JOIN PART_BOM child_pb ON child_pb.source_id=current_p.id
           INNER JOIN PART child_p ON child_pb.related_id=child_p.id
         WHERE pg.goal='Weight'
         GROUP BY pg.id) new_weight
      ON pg.id=new_weight.id;
    
    -- . Set correct weights on current Parts
    UPDATE PART
    SET weight=new_weight.new_value, weight_basis=new_weight.new_basis
    FROM PART p
      INNER JOIN
        (SELECT p.id id, ISNULL(actual_value,ISNULL(calculated_value,ISNULL(estimated_value,ISNULL(guess_value,target_value)))) new_value,
           CASE
             WHEN actual_value IS NOT NULL THEN 'Actual'
             WHEN calculated_value IS NOT NULL THEN 'Calculated'
             WHEN estimated_value IS NOT NULL THEN 'Estimated'
             WHEN guess_value IS NOT NULL THEN 'Guess'
             WHEN target_value IS NOT NULL THEN 'Target'
             ELSE NULL
           END new_basis
         FROM @CURRENT_PARTS p INNER JOIN PART_GOAL pg ON p.id=pg.source_id
         WHERE pg.goal='Weight') new_weight
      ON p.id=new_weight.id;
    
    /* delete BOMs pointing to leaf Parts */
    DELETE FROM #tmp_BOMS_TO_USE
    WHERE related_id IN (SELECT id FROM @TMP_PARTS);
    
    /* delete leaf Parts */
    DELETE FROM #tmp_PARTS_TO_USE
    WHERE id IN (SELECT id FROM @TMP_PARTS);

    DELETE FROM @TMP_PARTS;
  END
  DROP TABLE #tmp_BOMS_TO_USE;
  DROP TABLE #tmp_PARTS_TO_USE;
  /* +++ iterate over leaf Parts */

finish:
  SELECT 1 success;
END")
                    .Select(n => n.FullName).ToArray();
            CollectionAssert.AreEqual(correct, names);
        }
Beispiel #28
0
        // ReSharper disable once UnusedMember.Local
        private void OnExecute()
        {
            var loggerFactory = new LoggerFactory()
                                .AddConsole(Verbosity);
            var analyzer = new DependencyAnalyzer(loggerFactory);
            var graph    = analyzer.Analyze(Project, Framework);

            Application.Init();

            var top = new CustomWindow();

            var left = new FrameView("Dependencies")
            {
                Width  = Dim.Percent(50),
                Height = Dim.Fill(1)
            };
            var right = new View()
            {
                X      = Pos.Right(left),
                Width  = Dim.Fill(),
                Height = Dim.Fill(1)
            };
            var helpText = new Label("Use arrow keys and Tab to move around, Esc to quit.")
            {
                Y = Pos.AnchorEnd(1)
            };

            var runtimeDepends = new FrameView("Runtime depends")
            {
                Width  = Dim.Fill(),
                Height = Dim.Percent(33f)
            };
            var packageDepends = new FrameView("Package depends")
            {
                Y      = Pos.Bottom(runtimeDepends),
                Width  = Dim.Fill(),
                Height = Dim.Percent(50f)
            };
            var reverseDepends = new FrameView("Reverse depends")
            {
                Y      = Pos.Bottom(packageDepends),
                Width  = Dim.Fill(),
                Height = Dim.Fill()
            };

            var orderedDependencyList = graph.Nodes.OrderBy(x => x.Id).ToImmutableList();
            var dependenciesView      = new ListView(orderedDependencyList)
            {
                CanFocus      = true,
                AllowsMarking = false
            };

            left.Add(dependenciesView);
            var runtimeDependsView = new ListView(Array.Empty <Node>())
            {
                CanFocus      = true,
                AllowsMarking = false
            };

            runtimeDepends.Add(runtimeDependsView);
            var packageDependsView = new ListView(Array.Empty <Node>())
            {
                CanFocus      = true,
                AllowsMarking = false
            };

            packageDepends.Add(packageDependsView);
            var reverseDependsView = new ListView(Array.Empty <Node>())
            {
                CanFocus      = true,
                AllowsMarking = false
            };

            reverseDepends.Add(reverseDependsView);

            right.Add(runtimeDepends, packageDepends, reverseDepends);
            top.Add(left, right, helpText);
            Application.Top.Add(top);

            dependenciesView.SelectedItem = 0;
            UpdateLists();

            dependenciesView.SelectedChanged += UpdateLists;

            Application.Run();

            void UpdateLists()
            {
                var selectedNode = orderedDependencyList[dependenciesView.SelectedItem];

                runtimeDependsView.SetSource(graph.Edges.Where(x => x.Start.Equals(selectedNode) && x.End is AssemblyReferenceNode)
                                             .Select(x => x.End).ToImmutableList());
                packageDependsView.SetSource(graph.Edges.Where(x => x.Start.Equals(selectedNode) && x.End is PackageReferenceNode)
                                             .Select(x => $"{x.End}{(string.IsNullOrEmpty(x.Label) ? string.Empty : " (Wanted: " + x.Label + ")")}").ToImmutableList());
                reverseDependsView.SetSource(graph.Edges.Where(x => x.End.Equals(selectedNode))
                                             .Select(x => $"{x.Start}{(string.IsNullOrEmpty(x.Label) ? string.Empty : " (Wanted: " + x.Label + ")")}").ToImmutableList());
            }
        }
Beispiel #29
0
        public static void Main(string[] args)
        {
            var commandLineApplication = new CommandLineApplication(false);
            var directory            = commandLineApplication.Argument("directory", "The directory to search for assemblies");
            var dgmlExport           = commandLineApplication.Option("-dg|--dgml <filename>", "Export to a dgml file", CommandOptionType.SingleValue);
            var nonsystem            = commandLineApplication.Option("-n|--nonsystem", "Ignore 'System' assemblies", CommandOptionType.NoValue);
            var all                  = commandLineApplication.Option("-a|--all", "List all assemblies and references.", CommandOptionType.NoValue);
            var noconsole            = commandLineApplication.Option("-nc|--noconsole", "Do not show references on console.", CommandOptionType.NoValue);
            var silent               = commandLineApplication.Option("-s|--silent", "Do not show any message, only warnings and errors will be shown.", CommandOptionType.NoValue);
            var bindingRedirect      = commandLineApplication.Option("-b|--bindingredirect", "Create binding-redirects", CommandOptionType.NoValue);
            var referencedStartsWith = commandLineApplication.Option("-rsw|--referencedstartswith", "Referenced Assembly should start with <string>. Will only analyze assemblies if their referenced assemblies starts with the given value.", CommandOptionType.SingleValue);

            commandLineApplication.HelpOption("-? | -h | --help");
            commandLineApplication.OnExecute(() =>
            {
                var consoleLogger = new ConsoleLogger(!silent.HasValue());

                var directoryPath = directory.Value;
                if (!Directory.Exists(directoryPath))
                {
                    consoleLogger.LogMessage(string.Format(CultureInfo.InvariantCulture, "Directory: '{0}' does not exist.", directoryPath));
                    return(-1);
                }

                var onlyConflicts = !all.HasValue();
                var skipSystem    = nonsystem.HasValue();

                var directoryInfo = new DirectoryInfo(directoryPath);
                var fileList      = directoryInfo.GetFiles("*.dll").Concat(directoryInfo.GetFiles("*.exe"));

                IDependencyAnalyzer analyzer = new DependencyAnalyzer(fileList);

                consoleLogger.LogMessage(string.Format(CultureInfo.InvariantCulture, "Check assemblies in: {0}", directoryInfo));

                var result = analyzer.Analyze(consoleLogger);

                if (!noconsole.HasValue())
                {
                    IDependencyVisualizer visualizer = new ConsoleVisualizer(result)
                    {
                        SkipSystem = skipSystem, OnlyConflicts = onlyConflicts, ReferencedStartsWith = referencedStartsWith.HasValue() ? referencedStartsWith.Value() : string.Empty
                    };
                    visualizer.Visualize();
                }

                if (dgmlExport.HasValue())
                {
                    IDependencyVisualizer export = new DgmlExport(result, string.IsNullOrWhiteSpace(dgmlExport.Value()) ? Path.Combine(directoryInfo.FullName, "references.dgml") : dgmlExport.Value(), consoleLogger);
                    export.Visualize();
                }

                if (bindingRedirect.HasValue())
                {
                    IDependencyVisualizer bindingRedirects = new BindingRedirectExport(result, string.IsNullOrWhiteSpace(dgmlExport.Value()) ? Path.Combine(directoryInfo.FullName, "bindingRedirects.xml") : dgmlExport.Value(), consoleLogger);
                    bindingRedirects.Visualize();
                }

                return(0);
            });
            try
            {
                if (args == null || args.Length == 0)
                {
                    commandLineApplication.ShowHelp();
                }
                else
                {
                    commandLineApplication.Execute(args);
                }
            }
            catch (CommandParsingException cpe)
            {
                Console.WriteLine(cpe.Message);
                commandLineApplication.ShowHelp();
            }
        }
Beispiel #30
0
        public static int Main(string[] args)
        {
            var commandLineApplication = new CommandLineApplication(throwOnUnexpectedArg: true);
            var directoryOrFile        = commandLineApplication.Argument("directoryOrFile", "The directory to search for assemblies or file path to a single assembly");

            var silent = commandLineApplication.Option("-s|--silent", "Do not show any message, only warnings and errors will be shown.", CommandOptionType.NoValue);

            var nonsystem            = commandLineApplication.Option("-n|--nonsystem", "Ignore 'System' assemblies", CommandOptionType.NoValue);
            var all                  = commandLineApplication.Option("-a|--all", "List all assemblies and references.", CommandOptionType.NoValue);
            var referencedStartsWith = commandLineApplication.Option("-rsw|--referencedstartswith", "Referenced Assembly should start with <string>. Will only analyze assemblies if their referenced assemblies starts with the given value.", CommandOptionType.SingleValue);
            var excludeAssemblies    = commandLineApplication.Option("-e|--exclude", "A partial assembly name which should be excluded. This option can be provided multiple times", CommandOptionType.MultipleValue);

            var includeSubDirectories = commandLineApplication.Option("-i|--includesub", "Include subdirectories in search", CommandOptionType.NoValue);
            var configurationFile     = commandLineApplication.Option("-c|--configurationFile", "Use the binding redirects of the given configuration file (Web.config or App.config)", CommandOptionType.SingleValue);
            var failOnMissing         = commandLineApplication.Option("-f|--failOnMissing", "Whether to exit with an error code when AsmSpy detected Assemblies which could not be found", CommandOptionType.NoValue);

            var dependencyVisualizers = GetDependencyVisualizers();

            foreach (var visualizer in dependencyVisualizers)
            {
                visualizer.CreateOption(commandLineApplication);
            }

            commandLineApplication.HelpOption("-? | -h | --help");

            commandLineApplication.OnExecute(() =>
            {
                try
                {
                    var visualizerOptions = new VisualizerOptions
                    {
                        SkipSystem           = nonsystem.HasValue(),
                        OnlyConflicts        = !all.HasValue(),
                        ReferencedStartsWith = referencedStartsWith.HasValue() ? referencedStartsWith.Value() : string.Empty,
                        Exclude = excludeAssemblies.HasValue() ? excludeAssemblies.Values : new List <string>()
                    };

                    var consoleLogger = new ConsoleLogger(!silent.HasValue());

                    var finalResult = GetFileList(directoryOrFile, includeSubDirectories, consoleLogger)
                                      .Bind(x => GetAppDomainWithBindingRedirects(configurationFile)
                                            .Map(appDomain => DependencyAnalyzer.Analyze(
                                                     x.FileList,
                                                     appDomain,
                                                     consoleLogger,
                                                     visualizerOptions,
                                                     x.RootFileName)))
                                      .Map(result => RunVisualizers(result, consoleLogger, visualizerOptions))
                                      .Bind(FailOnMissingAssemblies);

                    switch (finalResult)
                    {
                    case Failure <bool> fail:
                        consoleLogger.LogError(fail.Message);
                        return(-1);

                    case Success <bool> succeed:
                        return(0);

                    default:
                        throw new InvalidOperationException("Unexpected result type");
                    }

                    DependencyAnalyzerResult RunVisualizers(DependencyAnalyzerResult dependencyAnalyzerResult, ILogger logger, VisualizerOptions options)
                    {
                        foreach (var visualizer in dependencyVisualizers.Where(x => x.IsConfigured()))
                        {
                            visualizer.Visualize(dependencyAnalyzerResult, logger, options);
                        }
                        return(dependencyAnalyzerResult);
                    }

                    Result <bool> FailOnMissingAssemblies(DependencyAnalyzerResult dependencyAnalyzerResult)
                    => failOnMissing.HasValue() && dependencyAnalyzerResult.MissingAssemblies.Any()
                            ? "Missing Assemblies"
                            : Result <bool> .Succeed(true);
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.ToString());
                    return(-1);
                }
            });

            try
            {
                if (args == null || args.Length == 0)
                {
                    commandLineApplication.ShowHelp();
                    return(0);
                }

                return(commandLineApplication.Execute(args));
            }
            catch (CommandParsingException cpe)
            {
                Console.WriteLine(cpe.Message);
                commandLineApplication.ShowHelp();
                return(-1);
            }
            catch (Exception)
            {
                return(-1);
            }
        }
 public void SetUp()
 {
     analyzer = new DependencyAnalyzer();
 }
Beispiel #32
0
        private void RewriteComponentFile(string inputFile, string outputFile, string ownerExecutableName)
        {
            EcmaModule inputModule = NodeFactory.TypeSystemContext.GetModuleFromPath(inputFile);

            Directory.CreateDirectory(Path.GetDirectoryName(outputFile));

            ReadyToRunFlags flags =
                ReadyToRunFlags.READYTORUN_FLAG_Component |
                ReadyToRunFlags.READYTORUN_FLAG_NonSharedPInvokeStubs;

            if (inputModule.IsPlatformNeutral)
            {
                flags |= ReadyToRunFlags.READYTORUN_FLAG_PlatformNeutralSource;
            }

            flags |= _nodeFactory.CompilationModuleGroup.GetReadyToRunFlags() & ReadyToRunFlags.READYTORUN_FLAG_MultiModuleVersionBubble;

            CopiedCorHeaderNode copiedCorHeader = new CopiedCorHeaderNode(inputModule);
            // Re-written components shouldn't have any additional diagnostic information - only information about the forwards.
            // Even with all of this, we might be modifying the image in a silly manner - adding a directory when if didn't have one.
            DebugDirectoryNode debugDirectory   = new DebugDirectoryNode(inputModule, outputFile, shouldAddNiPdb: false, shouldGeneratePerfmap: false);
            NodeFactory        componentFactory = new NodeFactory(
                _nodeFactory.TypeSystemContext,
                _nodeFactory.CompilationModuleGroup,
                null,
                _nodeFactory.NameMangler,
                copiedCorHeader,
                debugDirectory,
                win32Resources: new Win32Resources.ResourceData(inputModule),
                flags,
                _nodeFactory.OptimizationFlags,
                _nodeFactory.ImageBase);

            IComparer <DependencyNodeCore <NodeFactory> > comparer       = new SortableDependencyNode.ObjectNodeComparer(CompilerComparer.Instance);
            DependencyAnalyzerBase <NodeFactory>          componentGraph = new DependencyAnalyzer <NoLogStrategy <NodeFactory>, NodeFactory>(componentFactory, comparer);

            componentGraph.AddRoot(componentFactory.Header, "Component module R2R header");
            OwnerCompositeExecutableNode ownerExecutableNode = new OwnerCompositeExecutableNode(_nodeFactory.Target, ownerExecutableName);

            componentGraph.AddRoot(ownerExecutableNode, "Owner composite executable name");
            componentGraph.AddRoot(copiedCorHeader, "Copied COR header");
            componentGraph.AddRoot(debugDirectory, "Debug directory");
            if (componentFactory.Win32ResourcesNode != null)
            {
                componentGraph.AddRoot(componentFactory.Win32ResourcesNode, "Win32 resources");
            }
            componentGraph.ComputeMarkedNodes();
            componentFactory.Header.Add(Internal.Runtime.ReadyToRunSectionType.OwnerCompositeExecutable, ownerExecutableNode, ownerExecutableNode);
            ReadyToRunObjectWriter.EmitObject(
                outputFile,
                componentModule: inputModule,
                inputFiles: new string[] { inputFile },
                componentGraph.MarkedNodeList,
                componentFactory,
                generateMapFile: false,
                generateMapCsvFile: false,
                generatePdbFile: false,
                pdbPath: null,
                generatePerfMapFile: false,
                perfMapPath: null,
                perfMapFormatVersion: _perfMapFormatVersion,
                generateProfileFile: false,
                _profileData.CallChainProfile,
                customPESectionAlignment: 0);
        }