/// <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; }
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 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(); }
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); }
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);
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 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; } } }
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); }
private void RunAPIChecker() { outpane.Clear(); outpane.OutputString("===================Running API and Privilege Checker================ \n"); APICheckerWindowTaskProvider taskWindow = APICheckerWindowTaskProvider.CreateProvider(this.ServiceProvider); taskWindow.ClearError(); symbolMap = new Dictionary <ISymbol, string>(); var componentModel = (IComponentModel)this.ServiceProvider.GetService(typeof(SComponentModel)); var workspace = componentModel?.GetService <Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace>(); var soln = workspace.CurrentSolution; if (soln == null) { outpane.OutputString("Select a solution\n"); return; } ProjectDependencyGraph projectGraph = soln.GetProjectDependencyGraph(); foreach (ProjectId projectId in projectGraph.GetTopologicallySortedProjects()) { Project proj = soln.GetProject(projectId); List <string> privilegeList = new List <string>(); string apiversion = ""; var projFile = proj.FilePath; var projPath = projFile.Substring(0, projFile.LastIndexOf("\\") + 1); var manifestPath = projPath + "tizen-manifest.xml"; if (File.Exists(manifestPath)) { XmlDocument XDoc = new XmlDocument(); XDoc.Load(manifestPath); XmlNodeList nodes = XDoc.GetElementsByTagName("privilege"); foreach (XmlNode node in nodes) { privilegeList.Add(node.InnerText); } nodes = XDoc.GetElementsByTagName("manifest"); if (nodes.Count > 0) { XmlAttributeCollection attribute = nodes[0].Attributes; for (int ii = 0; ii < attribute.Count; ++ii) { string name = attribute[ii].Name; if (name == "api-version") { apiversion = attribute[ii].Value; break; } } } } if (apiversion == "") { continue; } //Create a new Analyzer for this project. analyzer = new Analyzer(apiversion, privilegeList, manifestPath, this.ServiceProvider); //Get Compilation Compilation projectCompilation = proj.GetCompilationAsync().Result; if (null == projectCompilation || string.IsNullOrEmpty(projectCompilation.AssemblyName)) { continue; } //Run Analysis on each file in this project foreach (var syntaxTree in projectCompilation.SyntaxTrees) { SemanticModel model = projectCompilation.GetSemanticModel(syntaxTree); RunAnalysis(model, syntaxTree, apiversion, privilegeList); } analyzer.ReportUnusedPrivileges(); } outpane.OutputString("===================API and Privilege Completed================ \n"); }
// public static bool CompileSolution(Solution solution, string outputDir) { bool success = true; ProjectDependencyGraph projectGraph = solution.GetProjectDependencyGraph(); foreach (ProjectId projectId in projectGraph.GetTopologicallySortedProjects()) { Project project = solution.GetProject(projectId); AddFormatPrint("Building: {0}", project.FilePath); try { //MetadataReference[] references = new MetadataReference[] //{ // MetadataReference.CreateFromFile(typeof(object).Assembly.Location), // MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location) //}; Compilation projectCompilation = project.GetCompilationAsync().Result; //bug??: if sln has /* * <ItemGroup> * <ProjectReference Include="Trunk.Plugins.csproj"> * <Project>{2BBE5B18-F7D1-B358-6FC0-86A09DE3F912}</Project> * <Name>Trunk.Plugins</Name> * </ProjectReference> */ foreach (MetadataReference refs in projectCompilation.ExternalReferences) { AddFormatPrint("refs: {0}", refs.Display); break; } if (null != projectCompilation && !string.IsNullOrEmpty(projectCompilation.AssemblyName)) { string fileName = string.Format("{0}.dll", projectCompilation.AssemblyName); string fullPathName = string.Format("{0}\\{1}", outputDir, fileName); if (!OutputFiles.ContainsKey(fullPathName)) { OutputFiles.Add(fullPathName, true); } ImmutableArray <Diagnostic> diagnostics = projectCompilation.GetDiagnostics(); Diagnostic[] errorDiagnostics = diagnostics.Where(x => x.Severity == DiagnosticSeverity.Error).ToArray(); //Diagnostic []warnDiagnostics = diagnostics.Where(x => x.Severity == DiagnosticSeverity.Warning).ToArray(); //foreach (var e in errorDiagnostics.Concat(warnDiagnostics).ToArray()) //{ // AddFormatPrint("{0}: {1}", e.Severity.ToString(), e.ToString()); // break; //} if (errorDiagnostics.Any()) { OutputFiles[fullPathName] = false; AddFormatPrint("Build failed."); success = false; } else { AddFormatPrint("Build successfully."); if (string.IsNullOrEmpty(outputDir)) { //only test } else { using (var stream = new MemoryStream()) { EmitResult result = projectCompilation.Emit(stream); AddFormatPrint("{0} --> {1}", project.Name, fullPathName); if (result.Success) { using (FileStream file = File.Create(fullPathName)) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(file); } AddFormatPrint("Output successfully."); } else { OutputFiles[fullPathName] = false; AddFormatPrint("Output failed."); success = false; } } } } AddFormatPrint(); } else { AddFormatPrint("Build failed. {0}", project.FilePath); success = false; } } catch (AggregateException ex) { foreach (var ie in ex.InnerExceptions) { AddFormatPrint(ie.Message); } success = false; } catch (Exception ex) { AddFormatPrint(ex.Message); success = false; } AddFormatPrint(); } return(success); }
static void Main(string[] args) { // ** Only works if run from VSDev Command prompt ** // //var instances = MSBuildLocator.QueryVisualStudioInstances().ToList(); //var instanceToUse = instances.First(a => a.Version.Major == 15); //Environment.SetEnvironmentVariable("VSINSTALLDIR", instanceToUse.VisualStudioRootPath); Environment.SetEnvironmentVariable("VSINSTALLDIR", @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community"); Environment.SetEnvironmentVariable("VisualStudioVersion", "15.0"); string matterControlRoot = GetMatterControlDirectory(); var properties = new Dictionary <string, string> { { "Configuration", "Debug" }, { "Platform", "AnyCPU" } }; //var workspace = MSBuildWorkspace.Create(properties); var workspace = MSBuildWorkspace.Create(); workspace.WorkspaceFailed += (s, e) => Console.WriteLine(e.Diagnostic.Message); workspace.LoadMetadataForReferencedProjects = true; string solutionPath = Path.GetFullPath(Path.Combine(matterControlRoot, "..", "MatterControl.sln")); Solution solution = workspace.OpenSolutionAsync(solutionPath).Result; var translationStrings = new HashSet <string>(); DiagnosticAnalyzer analyzer = new LocalizeDetector((locstring) => { // Add detected Localize() strings to translations list translationStrings.AddLocalization(locstring); }); ProjectDependencyGraph projectGraph = solution.GetProjectDependencyGraph(); // Use Roslyn to find localize calls foreach (ProjectId projectId in projectGraph.GetTopologicallySortedProjects()) { var project = solution.GetProject(projectId); var compilationWithAnalyzers = project.GetCompilationAsync().Result.WithAnalyzers(ImmutableArray.Create(analyzer)); var diags = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result; } // Push properies.json results into newResults string json = File.ReadAllText(Path.Combine(matterControlRoot, "StaticData", "SliceSettings", "Properties.json")); foreach (var setting in JsonConvert.DeserializeObject <List <SettingItem> >(json)) { translationStrings.AddLocalization(setting.HelpText); translationStrings.AddLocalization(setting.PresentationName); if (!string.IsNullOrWhiteSpace(setting.Units)) { translationStrings.AddLocalization(setting.Units); } } // Push layouts.txt results into newResults foreach (var line in File.ReadAllLines(Path.Combine(matterControlRoot, "StaticData", "SliceSettings", "Layouts.txt")).Select(s => s.Trim())) { var isSliceSettingsKey = line.Contains("_") && !line.Contains(" "); if (!isSliceSettingsKey) { translationStrings.AddLocalization(line); } } string outputPath = Path.Combine(matterControlRoot, "StaticData", "Translations", "Master.txt"); using (var outstream = new StreamWriter(outputPath)) { foreach (var line in translationStrings.OrderBy(x => x).ToArray()) { outstream.WriteLine($"English:{line}"); outstream.WriteLine($"Translated:{line}"); outstream.WriteLine(""); } } System.Diagnostics.Process.Start(outputPath); //GenerateComparisonData(); }
static void Main(string[] args) { MSBuildLocator.RegisterDefaults(); string matterControlRoot = GetMatterControlDirectory(); var workspace = MSBuildWorkspace.Create(new Dictionary <string, string> { ["Configuration"] = "Debug", ["Platform"] = "AnyCPU" }); workspace.WorkspaceFailed += (s, e) => Console.WriteLine(e.Diagnostic.Message); workspace.LoadMetadataForReferencedProjects = true; string solutionPath = Path.GetFullPath(Path.Combine(matterControlRoot, "..", "MatterControl.sln")); Solution solution = workspace.OpenSolutionAsync(solutionPath).Result; var translationStrings = new HashSet <string>(); DiagnosticAnalyzer analyzer = new LocalizeDetector((locstring) => { // Add detected Localize() strings to translations list translationStrings.AddLocalization(locstring); }); ProjectDependencyGraph projectGraph = solution.GetProjectDependencyGraph(); // Use Roslyn to find localize calls foreach (ProjectId projectId in projectGraph.GetTopologicallySortedProjects()) { var project = solution.GetProject(projectId); var compilationWithAnalyzers = project.GetCompilationAsync().Result.WithAnalyzers(ImmutableArray.Create(analyzer)); var diags = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result; } // Push layouts.txt results into newResults foreach (var line in File.ReadAllLines(Path.Combine(matterControlRoot, "StaticData", "SliceSettings", "Layouts.txt")).Select(s => s.Trim())) { var isSliceSettingsKey = line.Contains("_") && !line.Contains(" "); if (!isSliceSettingsKey) { translationStrings.AddLocalization(line); } } string outputPath = Path.Combine(matterControlRoot, "StaticData", "Translations", "Master.txt"); using (var outstream = new StreamWriter(outputPath)) { foreach (var line in translationStrings.OrderBy(x => x).ToArray()) { outstream.WriteLine($"English:{line}"); outstream.WriteLine($"Translated:{line}"); outstream.WriteLine(""); } } System.Diagnostics.Process.Start(outputPath); //GenerateComparisonData(); }