private void FindDependentProjectsRecursively(ProjectDependencyGraph graph, Dictionary <ProjectId, AnalysisResult> results, int distance)
        {
            if (distance > _distanceHardLimit)
            {
                throw new InvalidOperationException($"Project recursion depth exceeded hard limit of {_distanceHardLimit}");
            }

            ++distance;
            int startingProjectCount = results.Values.Count;
            var ancestors            = results.Values.Where(r => r.Distance == distance - 1).ToList();

            foreach (var project in ancestors)
            {
                var projectObj             = _loader.Solution.Projects.SingleOrDefault(p => p.FilePath.Equals(project.FilePath, StringComparison.OrdinalIgnoreCase));
                var dependentProjectIds    = graph.GetProjectsThatDirectlyDependOnThisProject(projectObj.Id);
                var newDependentProjectIds = dependentProjectIds.Where(id => !results.ContainsKey(id));
                var newDependentProjects   = _loader.Solution.Projects.Where(p => newDependentProjectIds.Contains(p.Id));
                foreach (var newProject in newDependentProjects)
                {
                    results.Add(newProject.Id, CreateAnalysisResult(newProject, distance));
                }
            }

            // As long as we keep finding projects, keep searching.
            if (startingProjectCount < results.Values.Count)
            {
                FindDependentProjectsRecursively(graph, results, distance);
            }
        }
                protected override bool TryTakeAnyWork_NoLock(
                    ProjectId?preferableProjectId,
                    ProjectDependencyGraph dependencyGraph,
                    IDiagnosticAnalyzerService?service,
                    out WorkItem workItem
                    )
                {
                    // there must be at least one item in the map when this is called unless host is shutting down.
                    if (_documentWorkQueue.Count == 0)
                    {
                        workItem = default;
                        return(false);
                    }

                    var documentId = GetBestDocumentId_NoLock(
                        preferableProjectId,
                        dependencyGraph,
                        service
                        );

                    if (TryTake_NoLock(documentId, out workItem))
                    {
                        return(true);
                    }

                    throw ExceptionUtilities.Unreachable;
                }
Exemple #3
0
 private static IEnumerable <ProjectId> GetProjectsThatCouldReferenceType(
     ProjectDependencyGraph dependencyGraph, Project project)
 {
     // Get all the projects that depend on 'project' as well as 'project' itself.
     return(dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(project.Id)
            .Concat(project.Id));
 }
Exemple #4
0
                private DocumentId GetBestDocumentId_NoLock(
                    ProjectId preferableProjectId, ProjectDependencyGraph dependencyGraph, IDiagnosticAnalyzerService analyzerService)
                {
                    var projectId = GetBestProjectId_NoLock(_documentWorkQueue, preferableProjectId, dependencyGraph, analyzerService);

                    var documentMap = _documentWorkQueue[projectId];

                    // explicitly iterate so that we can use struct enumerator.
                    // Return the first normal priority work item we find.  If we don't
                    // find any, then just return the first low prio item we saw.
                    DocumentId lowPriorityDocumentId = null;

                    foreach (var pair in documentMap)
                    {
                        var workItem = pair.Value;
                        if (workItem.IsLowPriority)
                        {
                            lowPriorityDocumentId = pair.Key;
                        }
                        else
                        {
                            return(pair.Key);
                        }
                    }

                    Contract.ThrowIfNull(lowPriorityDocumentId);
                    return(lowPriorityDocumentId);
                }
        public static async Task <ImmutableArray <Diagnostic> > GetDiagnosticsInScopeAsync(this FixAllContext context)
        {
            switch (context.Scope)
            {
            case FixAllScope.Document:
                return(await context.GetDocumentDiagnosticsAsync(context.Document).ConfigureAwait(false));

            case FixAllScope.Project:
                return(await context.GetAllDiagnosticsAsync(context.Project).ConfigureAwait(false));

            case FixAllScope.Solution:
                Solution solution = context.Solution;
                ProjectDependencyGraph dependencyGraph = solution.GetProjectDependencyGraph();

                // Walk through each project in topological order, determining and applying the diagnostics for each
                // project.  We do this in topological order so that the compilations for successive projects are readily
                // available as we just computed them for dependent projects.  If we were to do it out of order, we might
                // start with a project that has a ton of dependencies, and we'd spend an inordinate amount of time just
                // building the compilations for it before we could proceed.
                //
                // By processing one project at a time, we can also let go of a project once done with it, allowing us to
                // reclaim lots of the memory so we don't overload the system while processing a large solution.
                //
                // Note: we have to filter down to projects of the same language as the FixAllContext points at a
                // CodeFixProvider, and we can't call into providers of different languages with diagnostics from a
                // different language.
                IEnumerable <Project?> sortedProjects = dependencyGraph.GetTopologicallySortedProjects(context.CancellationToken)
                                                        .Select(solution.GetProject)
                                                        .Where(p => p.Language == context.Project.Language);
                return((await Task.WhenAll(sortedProjects.Select(context.GetAllDiagnosticsAsync)).ConfigureAwait(false)).SelectMany(diag => diag).ToImmutableArray());

            default:
                return(ImmutableArray <Diagnostic> .Empty);
            }
        }
 public bool TryTakeAnyWork(
     ProjectId?preferableProjectId,
     ProjectDependencyGraph dependencyGraph,
     IDiagnosticAnalyzerService?analyzerService,
     out WorkItem workItem,
     out CancellationToken cancellationToken
     )
 {
     lock (_gate)
     {
         // there must be at least one item in the map when this is called unless host is shutting down.
         if (
             TryTakeAnyWork_NoLock(
                 preferableProjectId,
                 dependencyGraph,
                 analyzerService,
                 out workItem
                 )
             )
         {
             cancellationToken = GetNewCancellationToken_NoLock(workItem.Key);
             workItem.AsyncToken.Dispose();
             return(true);
         }
         else
         {
             cancellationToken = CancellationToken.None;
             return(false);
         }
     }
 }
Exemple #7
0
        public async Task Init()
        {
            this.projectFrameworks = new Dictionary <FileInfoKey, string>();
            if (this.solution != null)
            {
                throw new InvalidOperationException();
            }

            this.workspace.WorkspaceFailed += (sender, args) =>
            {
                if (args.Diagnostic.Kind == WorkspaceDiagnosticKind.Warning)
                {
                    this.logger.Warning(args.Diagnostic.Message);
                }
                else
                {
                    this.logger.Error(args.Diagnostic.Message);
                }
            };

            var projLoadHandler = new Progress <ProjectLoadProgress>(
                progress => { this.projectFrameworks[new FileInfoKey(progress.FilePath)] = progress.TargetFramework; });

            this.solution = await this.workspace.OpenSolutionAsync(this.solutionFile.FullName, null,
                                                                   projLoadHandler, CancellationToken.None);

            this.solutionGraph = this.solution.GetProjectDependencyGraph();
        }
Exemple #8
0
                public bool TryTakeAnyWork(
                    ProjectId preferableProjectId,
                    ProjectDependencyGraph dependencyGraph,
                    IDiagnosticAnalyzerService analyzerService,
                    out WorkItem workItem, out CancellationTokenSource source)
                {
                    lock (_gate)
                    {
                        // there must be at least one item in the map when this is called unless host is shutting down.
                        if (TryTakeAnyWork_NoLock(preferableProjectId, dependencyGraph, analyzerService, out workItem))
                        {
                            if (!HasAnyWork_NoLock)
                            {
                                // last work is done.
                                _progressReporter.Stop();
                            }

                            source = GetNewCancellationSource_NoLock(workItem.Key);
                            workItem.AsyncToken.Dispose();
                            return(true);
                        }
                        else
                        {
                            source = null;
                            return(false);
                        }
                    }
                }
Exemple #9
0
        /// <summary>
        /// Initializes the ChangeHandler with the given solution.
        /// </summary>
        /// <param name="solution">The solution.</param>
        /// <exception cref="ArgumentNullException">solution</exception>
        public async Task Initialize(Solution solution)
        {
            if (solution == null)
            {
                throw new ArgumentNullException(nameof(solution));
            }

            _logger.Debug($"Initializing solution {solution.FilePath}");

            _solution = solution;
            ProjectDependencyGraph projectGraph = solution.GetProjectDependencyGraph();

            _fileSyntaxNodeMap = new Dictionary <string, RoslynNode>();

            foreach (var projectId in projectGraph.GetTopologicallySortedProjects())
            {
                var project            = solution.GetProject(projectId);
                var projectCompilation = await project.GetCompilationAsync().ConfigureAwait(false);

                var diagnostics = projectCompilation.GetDiagnostics();

                foreach (var tree in projectCompilation.SyntaxTrees)
                {
                    _fileSyntaxNodeMap.TryAdd(tree.FilePath, new RoslynNode()
                    {
                        Project            = project,
                        ProjectCompilation = projectCompilation,
                        SyntaxTree         = tree
                    });
                }
            }

            _isInitialized = true;
        }
Exemple #10
0
        /// <summary>
        /// Iterates the types in the project
        /// </summary>
        /// <param name="visitor">The visitor for the iterator</param>
        public void IterateTypes(TypeVisitor visitor)
        {
            _visitor = visitor;
            Solution sol = _workspace.CurrentSolution;
            ProjectDependencyGraph graph = sol.GetProjectDependencyGraph();

            // Typescript projects show up with the same project path, so make sure it supports compilation
            Project mainProj = sol.Projects.Where(proj => proj.Id.Equals(_projectId) && proj.SupportsCompilation).FirstOrDefault();

            if (mainProj == null)
            {
                throw new InvalidOperationException($"Project with path {_projectId} does not exist.");
            }

            // Get a list of all classes being extracted
            Dictionary <string, Compilation> compilations = new Dictionary <string, Compilation>();

            AddCompiledProjects(sol, new List <ProjectId> {
                mainProj.Id
            }, compilations);
            AddCompiledProjects(sol, graph.GetProjectsThatThisProjectDirectlyDependsOn(mainProj.Id), compilations);
            AddCompiledProjects(sol, graph.GetProjectsThatThisProjectTransitivelyDependsOn(mainProj.Id), compilations);

            foreach (Compilation comp in compilations.Values)
            {
                CompilationParser parser = new CompilationParser(comp, _options);
                parser.IterateTypes(_visitor);
            }
        }
                private ProjectId GetBestProjectId_NoLock(ProjectId projectId, ProjectDependencyGraph dependencyGraph)
                {
                    if (projectId != null)
                    {
                        if (_documentWorkQueue.ContainsKey(projectId))
                        {
                            return(projectId);
                        }

                        // see if there is any project that depends on this project has work item queued. if there is any, use that project
                        // as next project to process
                        foreach (var dependingProjectId in dependencyGraph.GetProjectsThatDirectlyDependOnThisProject(projectId))
                        {
                            if (_documentWorkQueue.ContainsKey(dependingProjectId))
                            {
                                return(dependingProjectId);
                            }
                        }
                    }

                    // explicitly iterate so that we can use struct enumerator
                    foreach (var pair in _documentWorkQueue)
                    {
                        return(pair.Key);
                    }

                    return(Contract.FailWithReturn <ProjectId>("Shouldn't reach here"));
                }
Exemple #12
0
        public CompilationManager(string workDir)
        {
            workDirectory = workDir;

            LoadConfig(workDir);

            compilationOptions = new CSharpCompilationOptions(
                OutputKind.DynamicallyLinkedLibrary,
                allowUnsafe: true,
                optimizationLevel: OptimizationLevel.Debug,
                platform: Platform.AnyCpu,
                warningLevel: 4
                );

            var dirInfo      = new DirectoryInfo(workDir);
            var dirList      = dirInfo.GetDirectories("*.*", SearchOption.AllDirectories).ToList();
            var solutionlist = dirInfo.GetFiles("*.sln", SearchOption.AllDirectories).ToList();

            if (solutionlist.Count >= 0)
            {
                workspace = new AdhocWorkspace();

                LoadSolution(solutionlist[0].FullName);

                //foreach (WorkspaceDiagnostic diagnostic in workspace)
                //{
                //    Logger.Log(diagnostic.ToString());
                //}
                //Logger.Log("");

                // compile all project first to make sure all undependent file has references
                ProjectDependencyGraph dependencyGraph = solution.GetProjectDependencyGraph();
                foreach (ProjectId projectId in dependencyGraph.GetTopologicallySortedProjects())
                {
                    Project project = solution.GetProject(projectId);
                    CompileProject(project);
                }
            }
            else
            {
                Logger.Log("solution not found");
            }

            // load references
            List <MetadataReference> metadataReferences = new List <MetadataReference>();

            foreach (var reference in references)
            {
                string            path     = Helpers.GetAssemblyPath(reference);
                MetadataReference metadata = MetadataReference.CreateFromFile(path);

                metadataReferences.Add(metadata);
            }

            compilation = CSharpCompilation.Create(null, references: metadataReferences, options: compilationOptions);

            ShowCompilerConfig();
        }
                protected ProjectId GetBestProjectId_NoLock <T>(
                    Dictionary <ProjectId, T> workQueue,
                    ProjectId?projectId,
                    ProjectDependencyGraph dependencyGraph,
                    IDiagnosticAnalyzerService?analyzerService
                    )
                {
                    if (projectId != null)
                    {
                        if (workQueue.ContainsKey(projectId))
                        {
                            return(projectId);
                        }

                        // prefer project that directly depends on the given project and has diagnostics as next project to
                        // process
                        foreach (
                            var dependingProjectId in dependencyGraph.GetProjectsThatDirectlyDependOnThisProject(
                                projectId
                                )
                            )
                        {
                            if (
                                workQueue.ContainsKey(dependingProjectId) &&
                                analyzerService?.ContainsDiagnostics(
                                    Workspace,
                                    dependingProjectId
                                    ) == true
                                )
                            {
                                return(dependingProjectId);
                            }
                        }
                    }

                    // prefer a project that has diagnostics as next project to process.
                    foreach (var pendingProjectId in workQueue.Keys)
                    {
                        if (
                            analyzerService?.ContainsDiagnostics(Workspace, pendingProjectId)
                            == true
                            )
                        {
                            return(pendingProjectId);
                        }
                    }

                    // explicitly iterate so that we can use struct enumerator
                    foreach (var pair in workQueue)
                    {
                        return(pair.Key);
                    }

                    throw ExceptionUtilities.Unreachable;
                }
Exemple #14
0
        public Tuple <CompiledProjectAssembly, CompiledProjectAssembly> GetAssemblies()
        {
            var success = true;
            ProjectDependencyGraph projectGraph = _workspace.CurrentSolution.GetProjectDependencyGraph();

            if (_compiledAssemblies.Count == 0)
            {
                _compiledAssemblies.Clear();
                foreach (ProjectId projectId in projectGraph.GetTopologicallySortedProjects())
                {
                    var         project            = _workspace.CurrentSolution.GetProject(projectId);
                    Compilation projectCompilation = project.GetCompilationAsync().Result;
                    if (null != projectCompilation && !string.IsNullOrEmpty(projectCompilation.AssemblyName))
                    {
                        var dependencies       = new Dictionary <string, MetadataReference>();
                        var assemblyNames      = projectCompilation.ReferencedAssemblyNames.ToList();
                        var assembleReferences = projectCompilation.References.ToList();
                        for (int i = 0; i < assemblyNames.Count; i++)
                        {
                            dependencies.Add(assemblyNames[i].ToString(), assembleReferences[i]);
                        }
                        using (var ms = new MemoryStream()) {
                            EmitResult result = projectCompilation.Emit(ms);
                            if (result.Success)
                            {
                                ms.Seek(0, SeekOrigin.Begin);
                                Assembly assembly    = Assembly.Load(ms.ToArray());
                                var      projectPath = new FileInfo(project.FilePath).Directory.FullName;
                                _compiledAssemblies.Add(assembly.FullName, new CompiledProjectAssembly(assembly, projectPath, dependencies));
                            }
                            else
                            {
                                success = false;
                            }
                        }
                    }
                    else
                    {
                        success = false;
                    }
                }
            }
            // SPIKE: Get tests assembly if exist
            if (success)
            {
                var natuAssembly  = _compiledAssemblies.Values.SingleOrDefault(a => a.Assembly.FullName.Contains("automateit"));
                var testsAssembly = _compiledAssemblies.Values.SingleOrDefault(a => a.Assembly.FullName.Contains("km.tests.selenium"));
                if (natuAssembly == null || testsAssembly == null)
                {
                    return(null);
                }
                return(new Tuple <CompiledProjectAssembly, CompiledProjectAssembly>(natuAssembly, testsAssembly));
            }
            return(null);
        }
        private void VerifyTransitiveReferences(Solution solution, ProjectDependencyGraph projectDependencyGraph, string project, string[] expectedResults)
        {
            var projectId  = solution.GetProjectsByName(project).Single().Id;
            var projectIds = projectDependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(projectId);

            var actualResults = projectIds.Select(id => solution.GetRequiredProject(id).Name);

            Assert.Equal <string>(
                expectedResults.OrderBy(n => n),
                actualResults.OrderBy(n => n));
        }
Exemple #16
0
        public Task CompileFullSolutionInBackgroundAndReportErrors(string slnPath, Action <string> writeOutput)
        {
            return(Task.Factory.StartNew(async() =>
            {
                try
                {
                    var workspace = MSBuildWorkspace.Create();

                    var solution = await workspace.OpenSolutionAsync(slnPath);

                    ProjectDependencyGraph projectGraph = solution.GetProjectDependencyGraph();

                    var projectIds = projectGraph.GetTopologicallySortedProjects().ToArray();
                    var success = true;
                    foreach (ProjectId projectId in projectIds)
                    {
                        var project = solution.GetProject(projectId);
                        writeOutput($"Compiling {project.Name}\r\n");
                        Compilation projectCompilation = await project.GetCompilationAsync();
                        if (projectCompilation == null)
                        {
                            writeOutput($"Error, could not get compilation of {project.Name}\r\n");
                            continue;
                        }

                        var diag = projectCompilation.GetDiagnostics().Where(x => x.IsSuppressed == false &&
                                                                             x.Severity == DiagnosticSeverity.Error);

                        if (diag.Any())
                        {
                            success = false;
                        }

                        foreach (var diagItem in diag)
                        {
                            writeOutput(diagItem.ToString() + "\r\n");
                        }
                    }

                    if (success)
                    {
                        writeOutput($"Compilation successful\r\n");
                    }
                    else
                    {
                        writeOutput($"Compilation erros found; You can double-click file path in this pane to open it in VS\r\n");
                    }
                }
                catch (Exception ex)
                {
                    writeOutput($"Error: {ex.Message}\r\n");
                }
            }));
        }
        // Almost there, I think, but not currently working.
        public static async Task <(bool OverallSuccess, EmitResult?TriggeringFailure)> CompileWithRosyln(string solutionUrl, CancellationToken cancel, string outputDir)
        {
            MSBuildWorkspace       workspace    = MSBuildWorkspace.Create();
            Solution               solution     = workspace.OpenSolutionAsync(solutionUrl).Result;
            ProjectDependencyGraph projectGraph = solution.GetProjectDependencyGraph();

            foreach (ProjectId projectId in projectGraph.GetTopologicallySortedProjects())
            {
                Compilation?compilation = await solution.GetProject(projectId) !.GetCompilationAsync();

                if (compilation == null || string.IsNullOrEmpty(compilation.AssemblyName))
                {
                    return(false, default);
        /// <summary>
        /// Links the solution project assemblies to the given P# project.
        /// </summary>
        private void LinkSolutionAssembliesToProject(Project project, ProjectDependencyGraph graph)
        {
            var projectPath = this.OutputDirectoryMap[project.AssemblyName];

            foreach (var projectId in graph.GetProjectsThatThisProjectTransitivelyDependsOn(project.Id))
            {
                var requiredProject = this.CompilationContext.GetSolution().GetProject(projectId);
                var assemblyPath    = this.ProjectAssemblyPathMap[requiredProject.AssemblyName];
                var fileName        = projectPath + Path.DirectorySeparatorChar + requiredProject.AssemblyName + ".dll";

                CopyAssembly(assemblyPath, fileName);
            }
        }
 public FindReferencesSearchEngine(
     Solution solution,
     IImmutableSet<Document> documents,
     ImmutableList<IReferenceFinder> finders,
     IFindReferencesProgress progress,
     CancellationToken cancellationToken)
 {
     this.documents = documents;
     this.solution = solution;
     this.finders = finders;
     this.progress = progress;
     this.cancellationToken = cancellationToken;
     this.dependencyGraph = solution.GetProjectDependencyGraph();
 }
Exemple #20
0
        /// <summary>
        /// Links the solution project assemblies to the given P# project.
        /// </summary>
        /// <param name="project">Project</param>
        /// <param name="graph">ProjectDependencyGraph</param>
        private static void LinkSolutionAssembliesToProject(Project project, ProjectDependencyGraph graph)
        {
            var projectPath = CompilationEngine.OutputDirectoryMap[project.AssemblyName];

            foreach (var projectId in graph.GetProjectsThatThisProjectTransitivelyDependsOn(project.Id))
            {
                var requiredProject = ProgramInfo.Solution.GetProject(projectId);
                var assemblyPath    = CompilationEngine.ProjectAssemblyPathMap[requiredProject.AssemblyName];
                var fileName        = projectPath + Path.DirectorySeparatorChar + requiredProject.AssemblyName + ".dll";

                File.Delete(fileName);
                File.Copy(assemblyPath, fileName);
            }
        }
 public FindReferencesSearchEngine(
     Solution solution,
     IImmutableSet<Document> documents,
     ImmutableArray<IReferenceFinder> finders,
     IFindReferencesProgress progress,
     CancellationToken cancellationToken)
 {
     _documents = documents;
     _solution = solution;
     _finders = finders;
     _progress = progress;
     _cancellationToken = cancellationToken;
     _dependencyGraph = solution.GetProjectDependencyGraph();
 }
Exemple #22
0
 public FindReferencesSearchEngine(
     Solution solution,
     IImmutableSet <Document> documents,
     ImmutableArray <IReferenceFinder> finders,
     IFindReferencesProgress progress,
     CancellationToken cancellationToken)
 {
     this.documents         = documents;
     this.solution          = solution;
     this.finders           = finders;
     this.progress          = progress;
     this.cancellationToken = cancellationToken;
     this.dependencyGraph   = solution.GetProjectDependencyGraph();
 }
Exemple #23
0
        public async void CompileSolution()
        {
            var _ = typeof(Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions);

            string solutionFileName = "C:\\MSBuildProjects-beta\\VStudio.sln";


            VSSolutionLoader rw = new VSSolutionLoader();

            System.Windows.Forms.TreeView vv = rw.LoadProject(solutionFileName);

            VSSolution vs = vv.Tag as VSSolution;

            MessageBox.Show("VSolution loaded.." + vs.Name);

            comp = new Dictionary <string, Compilation>();

            named = new Dictionary <string, List <INamespaceOrTypeSymbol> >();

            workspace = null;

            ProjectDependencyGraph projectGraph = null;

            Microsoft.CodeAnalysis.Solution solution = null;
            workspace = MSBuildWorkspace.Create();
            solution  = await workspace.OpenSolutionAsync(solutionFileName);

            projectGraph = solution.GetProjectDependencyGraph();

            foreach (ProjectId projectId in projectGraph.GetTopologicallySortedProjects())
            {
                Stopwatch sw = Stopwatch.StartNew();

                Compilation projectCompilation = solution.GetProject(projectId).GetCompilationAsync().Result;

                sw.Stop();

                System.Diagnostics.Debug.WriteLine("Time taken compilation creation: {0}ms", sw.Elapsed.TotalMilliseconds);

                Microsoft.CodeAnalysis.Project project = solution.GetProject(projectId);

                comp.Add(project.FilePath, projectCompilation);

                // List<INamespaceOrTypeSymbol> ns = GetAllTypes(project.FilePath);

                // named.Add(project.FilePath, ns);
            }
        }
        public FindReferencesSearchEngine(
            Solution solution,
            IImmutableSet<Document> documents,
            ImmutableArray<IReferenceFinder> finders,
            IStreamingFindReferencesProgress progress,
            CancellationToken cancellationToken)
        {
            _documents = documents;
            _solution = solution;
            _finders = finders;
            _progress = progress;
            _cancellationToken = cancellationToken;
            _dependencyGraph = solution.GetProjectDependencyGraph();

            _progressTracker = new StreamingProgressTracker(progress.ReportProgressAsync);
        }
Exemple #25
0
        public FindReferencesSearchEngine(
            Solution solution,
            IImmutableSet <Document> documents,
            ImmutableArray <IReferenceFinder> finders,
            IStreamingFindReferencesProgress progress,
            CancellationToken cancellationToken)
        {
            _documents         = documents;
            _solution          = solution;
            _finders           = finders;
            _progress          = progress;
            _cancellationToken = cancellationToken;
            _dependencyGraph   = solution.GetProjectDependencyGraph();

            _progressTracker = new StreamingProgressTracker(progress.ReportProgressAsync);
        }
Exemple #26
0
        public void BuildSolution(Solution solution)
        {
            _log.LogMessage($"Starting build of {solution.FilePath}");
            ProjectDependencyGraph projectGraph = solution.GetProjectDependencyGraph();

            foreach (var projectId in projectGraph.GetTopologicallySortedProjects())
            {
                if (!_seenProjects.TryAdd(solution.GetProject(projectId).FilePath, true))
                {
                    continue;
                }
                if (_projectResumeList != null && !_projectResumeList.AddIfNotContained(solution.GetProject(projectId).FilePath))
                {
                    _log.LogMessage($"Skipping {solution.GetProject(projectId).FilePath}, as it was processed in an earlier run.");
                    continue;
                }

                Compilation projectCompilation;
                try
                {
                    projectCompilation = solution.GetProject(projectId).GetCompilationAsync().Result;
                }
                catch (Exception ex)
                {
                    _log.LogMessage($"Exception occured while compiling project {projectId}. {ex.Message}: {ex.StackTrace}");
                    continue;
                }
                switch (projectCompilation)
                {
                case CSharpCompilation cSharpCompilation:
                    if (cSharpCompilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Any(d => d.GetMessage().Contains("Predefined type")))
                    {
                        _log.LogMessage($"Manually adding mscorelib to {solution.GetProject(projectId).Name}!");
                        cSharpCompilation = cSharpCompilation
                                            .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location));
                    }
                    foreach (var diagnostic in cSharpCompilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error))
                    {
                        _log.LogMessage($"Compilation issue diagnostic: {diagnostic.GetMessage()}");
                    }
                    _log.LogMessage($"Compilation completed for {solution.GetProject(projectId).Name}, running extraction...");

                    _compilationQueue.Add(cSharpCompilation);
                    break;
                }
            }
        }
Exemple #27
0
        public BuildNode(ProjectDependencyGraph graph,
                         TaskEngine.TaskEngine taskEngine,
                         IBuildLog buildLog,
                         string name,
                         string target)
        {
            if (graph == null)
            {
                throw new ArgumentNullException("graph");
            }
            if (taskEngine == null)
            {
                throw new ArgumentNullException("taskEngine");
            }
            if (buildLog == null)
            {
                throw new ArgumentNullException("buildLog");
            }
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("A non-empty/whitespace name must be given", "name");
            }
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            _graph      = graph;
            _taskEngine = taskEngine;
            _buildLog   = buildLog;
            _name       = name;
            _target     = target;
            _thread     = new Thread(Run)
            {
                IsBackground = true,
                Name         = name
            };
            _thread.Start();
        }
Exemple #28
0
        public async static void TestThis()
        {
            MSBuildWorkspace workspace = MSBuildWorkspace.Create();
            string           path      = @"C:\Users\Dave\Documents\Visual Studio 2015\Projects\TestWebApp\TestWebApp.sln";
            //string path = @"C:\Users\Dave\Documents\Visual Studio 2015\Projects\TestProject\TestProject.sln";
            Solution sol = await workspace.OpenSolutionAsync(path);

            Project pro = await workspace.OpenProjectAsync(@"C:\Users\Dave\Documents\Visual Studio 2015\Projects\TestWebApp\TestWebApp\TestWebApp.csproj");


            ProjectDependencyGraph graph = sol.GetProjectDependencyGraph();

            foreach (Project proj in sol.Projects)
            {
                Console.WriteLine(proj.Name);
            }
        }
        /// <summary>
        /// Links the external references to the given P# compilation.
        /// </summary>
        private void LinkExternalAssembliesToProject(Project project, ProjectDependencyGraph graph)
        {
            var projectPath = this.OutputDirectoryMap[project.AssemblyName];

            foreach (var projectId in graph.GetProjectsThatThisProjectTransitivelyDependsOn(project.Id))
            {
                var requiredProject = this.CompilationContext.GetSolution().GetProject(projectId);
                foreach (var reference in requiredProject.MetadataReferences)
                {
                    // if (!(reference is PortableExecutableReference))
                    // {
                    //    continue;
                    // }
                    var fileName = Path.Combine(projectPath, Path.GetFileName(reference.Display));
                    CopyAssembly(reference.Display, fileName);
                }
            }
        }
Exemple #30
0
                protected override bool TryTakeAnyWork_NoLock(
                    ProjectId preferableProjectId, ProjectDependencyGraph dependencyGraph, IDiagnosticAnalyzerService service,
                    out WorkItem workItem)
                {
                    // there must be at least one item in the map when this is called unless host is shutting down.
                    if (_documentWorkQueue.Count == 0)
                    {
                        workItem = default;
                        return(false);
                    }

                    var documentId = GetBestDocumentId_NoLock(preferableProjectId, dependencyGraph, service);

                    if (TryTake_NoLock(documentId, out workItem))
                    {
                        return(true);
                    }

                    return(Contract.FailWithReturn <bool>("how?"));
                }
        private static bool CompileSolution(string solutionUrl, string outputDir)
        {
            bool success = true;

            MSBuildWorkspace            workspace    = MSBuildWorkspace.Create();
            Solution                    solution     = workspace.OpenSolutionAsync(solutionUrl).Result;
            ProjectDependencyGraph      projectGraph = solution.GetProjectDependencyGraph();
            Dictionary <string, Stream> assemblies   = new Dictionary <string, Stream>();

            foreach (ProjectId projectId in projectGraph.GetTopologicallySortedProjects())
            {
                Compilation projectCompilation = solution.GetProject(projectId).GetCompilationAsync().Result;
                if (null != projectCompilation && !string.IsNullOrEmpty(projectCompilation.AssemblyName))
                {
                    using (var stream = new MemoryStream())
                    {
                        EmitResult result = projectCompilation.Emit(stream);
                        if (result.Success)
                        {
                            string fileName = string.Format("{0}.dll", projectCompilation.AssemblyName);

                            using (FileStream file = File.Create(outputDir + '\\' + fileName))
                            {
                                stream.Seek(0, SeekOrigin.Begin);
                                stream.CopyTo(file);
                            }
                        }
                        else
                        {
                            success = false;
                        }
                    }
                }
                else
                {
                    success = false;
                }
            }

            return(success);
        }
        public DependencyOrder(Solution solution, ProjectDependencyGraph solutionGraph,
                               Dictionary <FileInfoKey, Project> allProjects, DependencySortOrder sortOrder, ILogger logger)
        {
            this.solution      = solution;
            this.solutionGraph = solutionGraph;
            this.sortOrder     = sortOrder;
            if (sortOrder == DependencySortOrder.DateModified)
            {
                this.AllSortedProjectIds = this.solution.Projects
                                           .OrderBy(p => GetProjectTime(p.FilePath, logger)).Select(p => p.Id)
                                           .ToArray();
                //this.AllSortedProjectIds = this.solution.Projects
                //    .GroupBy(p => Path.GetDirectoryName(p.FilePath))
                //    .SelectMany(g => g.Count()>1 ? g.SelectMany(i => (dir) g.AsEnumerable())
                //    .ToArray());
            }
            else
            {
                this.AllSortedProjectIds = this.solutionGraph.GetTopologicallySortedProjects()//.Reverse()
                                           .ToArray();
            }

            this.idToProject = allProjects.Values.ToDictionary(p => p.Id, p => p);
        }
Exemple #33
0
 protected abstract bool TryTakeAnyWork_NoLock(ProjectId preferableProjectId, ProjectDependencyGraph dependencyGraph, IDiagnosticAnalyzerService service, out WorkItem workItem);
Exemple #34
0
 private static IEnumerable<ProjectId> GetProjectsThatCouldReferenceType(
     ProjectDependencyGraph dependencyGraph, Project project)
 {
     // Get all the projects that depend on 'project' as well as 'project' itself.
     return dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(project.Id)
                                        .Concat(project.Id);
 }