Ejemplo n.º 1
0
        private void _buildEvents_OnBuildDone_Internal(vsBuildScope scope, vsBuildAction action)
        {
            Solution solution = _workspace.CurrentSolution;

            if (action == vsBuildAction.vsBuildActionClean)
            {
                DefaultHtmlClientProxyCleaner cleaner = new DefaultHtmlClientProxyCleaner(new DefaultBitCodeGeneratorMappingsProvider(new DefaultBitConfigProvider()));
                cleaner.GetType().GetTypeInfo().GetMethod(nameof(DefaultHtmlClientProxyCleaner.DeleteCodes))
                .Invoke(cleaner, new object[] { _workspace, solution, _isBeingBuiltProjects });

                Log("Generated codes were deleted");
            }
            else
            {
                Stopwatch watch = Stopwatch.StartNew();

                IProjectDtoControllersProvider controllersProvider = new DefaultProjectDtoControllersProvider();
                IProjectDtosProvider           dtosProvider        = new DefaultProjectDtosProvider(controllersProvider);

                DefaultHtmlClientProxyGenerator generator = new DefaultHtmlClientProxyGenerator(new DefaultBitCodeGeneratorOrderedProjectsProvider(),
                                                                                                new DefaultBitCodeGeneratorMappingsProvider(new DefaultBitConfigProvider()), dtosProvider
                                                                                                , new DefaultHtmlClientProxyDtoGenerator(), new DefaultHtmlClientContextGenerator(), controllersProvider, new DefaultProjectEnumTypesProvider(controllersProvider, dtosProvider));

                generator.GetType().GetTypeInfo().GetMethod(nameof(DefaultHtmlClientProxyGenerator.GenerateCodes))
                .Invoke(generator, new object[] { _workspace, solution, _isBeingBuiltProjects });

                watch.Stop();

                Log($"Code Generation Completed in {watch.ElapsedMilliseconds} milli seconds");
            }
        }
Ejemplo n.º 2
0
        static StringBuilder Display(Microsoft.CodeAnalysis.Solution solution)
        {
            StringBuilder sb = new StringBuilder();

            // Print the root of the solution

            sb.AppendLine(Path.GetFileName(solution.FilePath));

            sb.AppendLine("Projects:");

            foreach (var project in solution.Projects)
            {
                sb.AppendLine("  - " + project.Name);
            }

            // Get dependency graph to perform a sort

            var dGraph = solution.GetProjectDependencyGraph();
            var ds     = dGraph.GetDependencySets();

            //var ddotp = dGraph.GetProjectsThatDirectlyDependOnThisProject();
            //var tdotp = dGraph.GetProjectsThatTransitivelyDependOnThisProject();

            //var tpddo = dGraph.GetProjectsThatThisProjectDirectlyDependsOn();
            //var tptdo = dGraph.GetProjectsThatThisProjectTransitivelyDependsOn);

            var tsp = dGraph.GetTopologicallySortedProjects();

            // Print all projects, their documents, and references

            foreach (var p in tsp)
            {
                var project = solution.GetProject(p);

                sb.AppendLine("> " + project.Name);

                sb.AppendLine("  > MetadataReferences");

                foreach (var reference in project.MetadataReferences)
                {
                    sb.AppendLine("     - " + reference.Display);
                }

                sb.AppendLine("  > ProjectReferences");

                foreach (var reference in project.ProjectReferences)
                {
                    sb.AppendLine("     - " + solution.GetProject(reference.ProjectId).Name);
                }

                sb.AppendLine("  > Documents");

                foreach (var document in project.Documents)
                {
                    sb.AppendLine("    - " + document.Name + " " + document.GetType().ToString());
                }
            }

            return(sb);
        }
Ejemplo n.º 3
0
        static StringBuilder Display(Microsoft.CodeAnalysis.Project project)
        {
            StringBuilder sb = new StringBuilder();

            // Print the root of the solution

            sb.AppendLine(Path.GetFileName(project.FilePath));

            sb.AppendLine("> " + project.Name);

            sb.AppendLine("  > MetadataReferences");

            foreach (var reference in project.MetadataReferences)
            {
                sb.AppendLine("     - " + reference.Display);
            }

            //sb.AppendLine("  > ProjectReferences");

            Microsoft.CodeAnalysis.Solution solution = project.Solution;

            foreach (var reference in project.ProjectReferences)
            {
                sb.AppendLine("     - " + solution.GetProject(reference.ProjectId).Name);
            }

            sb.AppendLine("  > Documents");

            foreach (var document in project.Documents)
            {
                sb.AppendLine("    - " + document.Name + " " + document.GetType().ToString());
            }

            return(sb);
        }
Ejemplo n.º 4
0
 public static void AddAllItemsInSolutionToTree(Solution solution, ref SolutionNode tree)
 {
     ProjectTreeBuilder.AddDocumentsToProjects(solution, ref tree);
     if (!tree.Childs.Any())
         throw new NoCsharpProjectsFoundException();
     ClassTreeBuilder.AddClassesInProjectsToTree(tree);
 }
Ejemplo n.º 5
0
 private void Setup()
 {
     _configuration    = ProjectData.Configuration.AnalyzeConfiguration;
     _solution         = ProjectData.Project.Solution;
     _analyzeDocuments = ProjectData.Project.Documents.Where(o => _configuration.DocumentSelectionPredicate(o))
                         .ToImmutableHashSet();
     _analyzeProjects = new[] { ProjectData.Project }.ToImmutableHashSet();
 }
        protected override ICollection <Document> GetDocumentsToProcess(Solution solution)
        {
            var dte             = (DTE)ServiceProvider.GetService(typeof(DTE));
            var selectedProject = dte.SelectedItems.Item(1).Project;
            var projectCsFiles  = selectedProject.GetAllCsFiles().Select(x => x.GetProperty(ProjectItemPropertiesConstants.FullPath));

            return(solution.Projects.Single(x => x.Name == selectedProject.Name).Documents?.Where(x => projectCsFiles.Contains(x.FilePath)).ToList());
        }
Ejemplo n.º 7
0
        async void load()
        {
            Microsoft.CodeAnalysis.Solution solution = await IDE.Workspace.OpenSolutionAsync(path, IDE.ProgressLogger);

            solutionFile = SolutionFile.Parse(path);
            UserConfig   = new Configuration(path + ".user");

            ActiveConfiguration = solutionFile.GetDefaultConfigurationName();
            ActivePlatform      = solutionFile.GetDefaultPlatformName();
        }
Ejemplo n.º 8
0
        private static void SetupReadonlyProjectAndSolution()
        {
            if (_readOnlyProject != null)
            {
                return;
            }

            _readOnlyProject  = OpenProject();
            _readOnlySolution = OpenSolution();
        }
        protected override ICollection <Document> GetDocumentsToProcess(Solution solution)
        {
            var allDocuments = solution.Projects.SelectMany(p => p.Documents).ToList();

            var dte                = (DTE)ServiceProvider.GetService(typeof(DTE));
            var selectedFolder     = dte.SelectedItems.Item(1).ProjectItem;
            var allCsFilesInFolder = selectedFolder.GetAllCsFiles();

            return(allCsFilesInFolder
                   .Select(f => allDocuments.SingleOrDefault(d => d.FilePath == f.GetProperty(ProjectItemPropertiesConstants.FullPath)))
                   .ToList());
        }
 private static async Task<ISymbol[]> GatherSymbolsAsync(ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, CancellationToken token)
 {
     var implementations = await SymbolFinder.FindImplementationsAsync(symbol, solution, null, token).ConfigureAwait(false);
     var result = new ISymbol[implementations.Count() + 1];
     result[0] = symbol;
     var i = 1;
     foreach (var item in implementations)
     {
         result[i++] = item;
     }
     return result;
 }
        private static async Task <ISymbol[]> GatherSymbolsAsync(ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, CancellationToken token)
        {
#pragma warning disable CA2007 // Consider calling ConfigureAwait on the awaited task
            var implementations = await SymbolFinder.FindImplementationsAsync(symbol, solution, null, token);

#pragma warning restore CA2007 // Consider calling ConfigureAwait on the awaited task
            var result = new ISymbol[implementations.Count() + 1];
            result[0] = symbol;
            var i = 1;
            foreach (var item in implementations)
            {
                result[i++] = item;
            }
            return(result);
        }
Ejemplo n.º 12
0
        public static void Rename(ILogger _logger, string solutionPath, string projectPath, List <PreRenameData> lstRenames, CancellationToken cancellationToken)
        {
            using (Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create())
            {
                // Open the solution within the workspace.
                Microsoft.CodeAnalysis.Solution solution = workspace.OpenSolutionAsync(solutionPath).Result;
                bool isProjectFound = false;
                foreach (Microsoft.CodeAnalysis.ProjectId projectId in solution.ProjectIds)
                {
                    // Look up the snapshot for the original project in the latest forked solution.
                    Microsoft.CodeAnalysis.Project project = solution.GetProject(projectId);
                    if (project.FilePath == projectPath)
                    {
                        isProjectFound = true;
                        foreach (Microsoft.CodeAnalysis.DocumentId documentId in project.DocumentIds)
                        {
                            // Look up the snapshot for the original document in the latest forked solution.
                            Microsoft.CodeAnalysis.Document document = solution.GetDocument(documentId);
                            //tg.RelativePathToGeneratedFile

                            // only in 'main' declaration files
                            //TODO implement based on knowledge of generated file ???
                            if (Path.GetDirectoryName(document.FilePath).EndsWith("ViewModels"))
                            {
                                if (Path.GetExtension(document.FilePath) == "cs")
                                {
                                    CodeAnalysisCSharp.Rename(_logger, solution, document, lstRenames, cancellationToken).Wait();
                                }
                                else if (Path.GetExtension(document.FilePath) == "vb")
                                {
                                    CodeAnalysisVisualBasic.Rename(solution, document, lstRenames, cancellationToken).Wait();
                                }
                                else
                                {
                                    throw new NotSupportedException();
                                }
                            }
                        }
                    }
                }
                if (!isProjectFound)
                {
                    throw new Exception("Project not found");
                }
            }
        }
Ejemplo n.º 13
0
        public static void AddProjectsToTree(Solution solution,ref Tree tree)
        {
            var projects = solution.Projects.ToList();
            var allreadyAddedProjects = tree.DescendantNodes().OfType<ProjectNode>().ToList();

            foreach (var project in projects)
            {
                var existingProject = allreadyAddedProjects.WithName(project.Name);
                if (existingProject != null)
                {
                    existingProject.Documents = project.Documents.ToList();
                }
                else
                {
                    existingProject = new ProjectNode(project);
                    tree.AddChild(existingProject);
                }
            }
        }
Ejemplo n.º 14
0
        public static void Compile(ILogger _logger, string solutionPath, CancellationToken cancellationToken)
        {
            //var lstBuilds = Microsoft.Build.Locator.MSBuildLocator.QueryVisualStudioInstances().ToList();
            //var build = lstBuilds[0];
            //Microsoft.Build.Locator.MSBuildLocator.RegisterInstance(build);
            //Microsoft.Build.Locator.VisualStudioInstanceQueryOptions.Default = new Microsoft.Build.Locator.VisualStudioInstanceQueryOptions() { DiscoveryType = Microsoft.Build.Locator.DiscoveryType.DotNetSdk };
            //Microsoft.Build.Locator.MSBuildLocator.RegisterDefaults();
            var properties = new Dictionary <string, string>
            {
                //{ "Configuration", "Release" },
                // Use the latest language version to force the full set of available analyzers to run on the project.
                { "LangVersion", "latest" },
            };

            using (Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(properties))
            //https://gist.github.com/DustinCampbell/32cd69d04ea1c08a16ae5c4cd21dd3a3
            //using (Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create())
            {
                _logger.LogInformation("Compiling solution {0}".FilePos(), solutionPath);
                Microsoft.CodeAnalysis.Solution solution = workspace.OpenSolutionAsync(solutionPath).Result;
                if (workspace.Diagnostics.Count > 0)
                {
                    var en = workspace.Diagnostics.GetEnumerator();
                    en.MoveNext();
                    if (en.Current.Kind == Microsoft.CodeAnalysis.WorkspaceDiagnosticKind.Failure)
                    {
                        throw new Exception(en.Current.Message);
                    }
                }
                foreach (var project in solution.Projects)
                {
                    var compilation = project.GetCompilationAsync().Result;
                    var diag        = compilation.GetDiagnostics();
                    var lst         = from p in diag where p.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error select p;
                    if (lst.Count() > 0)
                    {
                        throw new Exception("Compilation errors are found.\nSolution: " + solutionPath + "\nProject: " + project.FilePath);
                    }
                }
            }
        }
Ejemplo n.º 15
0
        private void _buildEvents_OnBuildDone(vsBuildScope scope, vsBuildAction action)
        {
            try
            {
                Solution solution = _workspace.CurrentSolution;

                if (action == vsBuildAction.vsBuildActionClean)
                {
                    new DefaultHtmlClientProxyCleaner(new DefaultBitCodeGeneratorMappingsProvider(new DefaultBitConfigProvider()))
                    .DeleteCodes(_workspace, solution, _isBeingBuiltProjects);

                    Log("Generated codes were deleted");
                }
                else
                {
                    Stopwatch watch = Stopwatch.StartNew();

                    IProjectDtoControllersProvider controllersProvider = new DefaultProjectDtoControllersProvider();
                    IProjectDtosProvider           dtosProvider        = new DefaultProjectDtosProvider(controllersProvider);

                    new DefaultHtmlClientProxyGenerator(new DefaultBitCodeGeneratorOrderedProjectsProvider(),
                                                        new DefaultBitCodeGeneratorMappingsProvider(new DefaultBitConfigProvider()), dtosProvider
                                                        , new DefaultHtmlClientProxyDtoGenerator(), new DefaultHtmlClientContextGenerator(), controllersProvider, new DefaultProjectEnumTypesProvider(controllersProvider, dtosProvider))
                    .GenerateCodes(_workspace, solution, _isBeingBuiltProjects);

                    watch.Stop();

                    Log($"Code Generation Completed in {watch.ElapsedMilliseconds} milli seconds");
                }
            }
            catch (Exception ex)
            {
                Log(ex.ToString());
                throw;
            }
        }
Ejemplo n.º 16
0
        public static CGFParser ParseSolution(CGFParserReporter reporter, string solutionPath)
        {
            string fullSolutionPath = Path.GetFullPath(solutionPath);

            reporter.LogInfo($"CGFParser parsing {solutionPath} (FullPath: {fullSolutionPath})");

            if (!File.Exists(fullSolutionPath))
            {
                reporter.LogError($"{fullSolutionPath} does not exist.");
                return(null);
            }

            CGFParser cgfParser = new CGFParser(reporter);

            string[] documentsToExclude = { "AssemblyAttributes.cs" };

            reporter.LogInfo($"Opening solution {solutionPath}");

            IEnumerable <VisualStudioInstance> visualStudioInstances = MSBuildLocator.QueryVisualStudioInstances(new VisualStudioInstanceQueryOptions {
                DiscoveryTypes = DiscoveryType.VisualStudioSetup
            });
            VisualStudioInstance visualStudioInstance = visualStudioInstances.OrderByDescending(i => i.Version)
                                                        .Where(i => Directory.Exists(i.MSBuildPath))
                                                        .FirstOrDefault();

            if (string.IsNullOrEmpty(visualStudioInstance.MSBuildPath))
            {
                reporter.LogError($"Unable to find a proper VisualStudio instance. MSBuild workspace creation/solution parsing may fail");
            }
            else
            {
                MSBuildLocator.RegisterInstance(visualStudioInstance);
            }

            MSBuildWorkspace workspace = MSBuildWorkspace.Create();

            workspace.LoadMetadataForReferencedProjects = false;
            workspace.WorkspaceFailed         += cgfParser.Workspace_WorkspaceFailed;
            workspace.SkipUnrecognizedProjects = true;
            Microsoft.CodeAnalysis.Solution solution = workspace.OpenSolutionAsync(solutionPath).Result;

            reporter.LogInfo($"Solution opened");

            using (reporter.CreateContextScope(CGFParserReporterContext.Type.Solution, solution.FilePath))
            {
                reporter.LogInfo($"Parsing");
                List <CGFDocument> cgfDocuments = new List <CGFDocument>();
                foreach (Microsoft.CodeAnalysis.Project project in solution.Projects)
                {
                    List <Microsoft.CodeAnalysis.Document> documentsToProcess = new List <Microsoft.CodeAnalysis.Document>();

                    foreach (Microsoft.CodeAnalysis.Document document in project.Documents)
                    {
                        bool includeDocument = true;
                        foreach (string documentToExclude in documentsToExclude)
                        {
                            if (document.FilePath.EndsWith(documentToExclude, StringComparison.CurrentCultureIgnoreCase))
                            {
                                includeDocument = false;
                                break;
                            }
                        }

                        if (includeDocument)
                        {
                            documentsToProcess.Add(document);
                        }
                    }

                    cgfDocuments.AddRange(ProcessDocuments(reporter, documentsToProcess, project));
                }

                reporter.LogInfo($"Parsing complete");

                Dictionary <string, string>        typeNameToPathMap = new Dictionary <string, string>();
                Dictionary <string, CGFTypeSymbol> typeNameToTypeMap = new Dictionary <string, CGFTypeSymbol>();
                foreach (CGFDocument cgfDocument in cgfDocuments)
                {
                    using (reporter.CreateContextScope(CGFParserReporterContext.Type.File, cgfDocument.DocumentFilePath))
                    {
                        foreach (CGFTypeSymbol cgfType in cgfDocument.Types)
                        {
                            using (reporter.CreateContextScope(CGFParserReporterContext.Type.Type, cgfType.Name))
                            {
                                if (typeNameToPathMap.ContainsKey(cgfType.Name))
                                {
                                    reporter.LogError($"Duplicate type {cgfType.Name} found. Other instance found in {typeNameToPathMap[cgfType.Name]}");
                                }
                                else
                                {
                                    typeNameToPathMap.Add(cgfType.Name, cgfDocument.DocumentFilePath);
                                    typeNameToTypeMap.Add(cgfType.Name, cgfType);
                                }
                            }
                        }
                    }
                }

                foreach (CGFTypeSymbol type in typeNameToTypeMap.Values)
                {
                    foreach (CGFFieldSymbol field in type.Fields)
                    {
                        CGFTypeSymbol typeSymbol = null;
                        if (typeNameToTypeMap.TryGetValue(field.TypeName, out typeSymbol))
                        {
                            field.TypeSymbol = typeSymbol;
                        }
                    }
                }

                cgfParser.m_Documents         = cgfDocuments;
                cgfParser.m_TypeNameToPathMap = typeNameToPathMap;

                return(cgfParser);
            }
        }
Ejemplo n.º 17
0
        public async Task <IList <BaselineInfo> > CreateBaselineAsync(UnimaConfig config, Microsoft.CodeAnalysis.Solution solution)
        {
            LogTo.Info("Creating baseline and verifying solution/tests..");

            if (Directory.Exists(BaselineDirectoryPath))
            {
                Directory.Delete(BaselineDirectoryPath, true);
            }

            Directory.CreateDirectory(BaselineDirectoryPath);

            foreach (var mutationProject in config.MutationProjects)
            {
                var project = solution.Projects.FirstOrDefault(p => p.Name == mutationProject.Name);
                var result  = await _projectCompiler.CompileAsync(BaselineDirectoryPath, project);

                if (!result.IsSuccess)
                {
                    throw new BaselineException(
                              "Failed to compile base line.",
                              new CompilationException(result.Errors.Select(e => e.Message)));
                }
            }

            var baselineInfos = new List <BaselineInfo>();

            foreach (var testProject in config.TestProjects)
            {
                var result = await RunTestAsync(testProject, config.DotNetPath, config.MaxTestTimeMin);

                if (!result.IsSuccess)
                {
                    var failedTests = result.TestResults.Where(t => !t.IsSuccess);
                    LogTo.Error("Unit tests failed with base line");
                    LogTo.Error($"Name: {result.Name}");

                    foreach (var failedTest in failedTests)
                    {
                        LogTo.Error(JObject.FromObject(new { TestName = failedTest.Name, Message = failedTest.InnerText }).ToString());
                    }

                    throw new BaselineException("Failed to run all unit tests with baseline which make mutation testing impossible. See log for more details.");
                }

                LogTo.Info($"..done ({result.TestResults.Count(t => t.IsSuccess)} tests passed).");
                baselineInfos.Add(new BaselineInfo(testProject.Project.Name, result.ExecutionTime));
            }

            LogBaselineSummary(baselineInfos);

            LogTo.Info("Baseline completed.");
            return(baselineInfos);
        }
Ejemplo n.º 18
0
 protected abstract ICollection <Document> GetDocumentsToProcess(Solution solution);
Ejemplo n.º 19
0
 public ReadOnlyProjectAndSolution(Microsoft.CodeAnalysis.Project project, Microsoft.CodeAnalysis.Solution solution)
 {
     Project  = project;
     Solution = solution;
 }