Beispiel #1
0
        private static void Main()
        {
            // Рабочее пространство Roslyn
            var workspace = MSBuildWorkspace.Create();

            // Откроем решение, которое хотим анализировать
            var solutionToAnalyze = workspace.OpenSolutionAsync(PathToSolution).Result;

            // Получим проект, который хотим анализировать
            var projectToAnalyze = solutionToAnalyze.Projects.FirstOrDefault(project => project.Name == ProjectName);

            // Получим объект компиляции проекта
            Debug.Assert(projectToAnalyze != null, "projectToAnalyze != null");
            var compilationToAnalyze = projectToAnalyze.GetCompilationAsync().Result;
            //var typeNames = compilationToAnalyze.Assembly.TypeNames;
            //var classToAnalyze = typeNames.Where(typeName => typeName == ClassName);

            var classToAnalyze = compilationToAnalyze.GetTypeByMetadataName(ClassName);

            Debug.Assert(classToAnalyze != null);

            var fullNamespace = classToAnalyze.GetFullNamespace();

            WriteLine("Full namespace: {0}", fullNamespace);

            var propertySymbol = classToAnalyze.GetMembers("MySimpleProperty").FirstOrDefault() as IPropertySymbol;

            WriteLine("Fetched property: {0}", propertySymbol?.Name ?? "None");

            var eventSymbol = classToAnalyze.GetMembers("MySimpleEvent").FirstOrDefault() as IEventSymbol;

            WriteLine("Event name: {0}", eventSymbol?.Name ?? "None");

            var methodSymbol    = classToAnalyze.GetMembers("MySimpleMethod").FirstOrDefault() as IMethodSymbol;
            var methodSignature = methodSymbol.GetMethodSignature();

            WriteLine(methodSignature);

            var attrData    = classToAnalyze.GetAttributes().FirstOrDefault();
            var intProperty = attrData.GetAttributeConstructorValueByParameterName("intProp");

            WriteLine("Attribute's intProp = {0}", intProperty);
            var stringProperty = attrData.GetAttributeConstructorValueByParameterName("stringProp");

            WriteLine("Attrubute's string property = {0}", stringProperty);
        }
Beispiel #2
0
        static public void Analisys(string analisysProjectPath, string outGraphPath)
        {
            AnalisysCode analisys = new AnalisysCode("FieldBase");


            //путь к анализируемому csproj файлу
            string projectPath = analisysProjectPath;

            //по указанному пути получаем проджект
            MSBuildWorkspace msWorkspace = MSBuildWorkspace.Create();
            var Project = msWorkspace.OpenProjectAsync(projectPath).Result;

            analisys.ProjectAnalysis(Project);

            var diagnostics = msWorkspace.Diagnostics;

            foreach (var diagnostic in diagnostics)
            {
                Console.WriteLine(diagnostic.Message);
            }

            var         entityInfos = analisys.entityInfos;
            T4Generator t           = new T4Generator(entityInfos);
            String      tText       = t.TransformText();

            Console.WriteLine(tText);

            System.IO.File.WriteAllText(outGraphPath, tText);

            foreach (var a in analisys.entityInfos)
            {
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine(a.className);
                Console.WriteLine(a.baseClassName);
                foreach (var b in a.lFieldInfo.Keys)
                {
                    Console.WriteLine(b + "       " + a.lFieldInfo[b].TypeField);
                    foreach (var c in a.lFieldInfo[b].lParamInfo)
                    {
                        Console.WriteLine(c.FieldName + "     " + c.FieldType + "     " + c.ParamName);
                    }
                    Console.WriteLine();
                }
            }
        }
        /// <inheritdoc />
        public IEnumerable <Component> FindComponents()
        {
            MSBuildWorkspace msWorkspace = MSBuildWorkspace.Create();

            Solution    solution    = msWorkspace.OpenSolutionAsync(PathToSolution).Result;
            Project     project     = solution.Projects.Where(p => p.Name == ProjectName).First();
            Compilation compilation = project.GetCompilationAsync().Result;

            foreach (Component component in ComponentFinder.Container.Components)
            {
                foreach (CodeElement codeElement in component.CodeElements)
                {
                    try
                    {
                        string           type   = codeElement.Type.Substring(0, component.Type.IndexOf(',')); // remove the assembly name from the type
                        INamedTypeSymbol symbol = compilation.GetTypeByMetadataName(type);
                        foreach (Microsoft.CodeAnalysis.Location location in symbol.Locations)
                        {
                            if (location.IsInSource)
                            {
                                codeElement.Url   = new Uri(location.SourceTree.FilePath).AbsoluteUri;
                                codeElement.Size += location.SourceTree.GetText().Lines.Count;
                                component.Size   += codeElement.Size;
                            }
                        }

                        if (codeElement.Role == CodeElementRole.Primary)
                        {
                            string xml = symbol.GetDocumentationCommentXml();
                            if (xml != null && xml.Trim().Length > 0)
                            {
                                XDocument xdoc    = XDocument.Parse(xml);
                                string    comment = xdoc.Descendants("summary").First().Value.Trim();
                                component.Description = comment;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Could not get summary comment for " + component.Name + ": " + e.Message);
                    }
                }
            }

            return(new HashSet <Component>());
        }
        public async Task WriteDto_ExistingSolution_CityDTORewrite2()
        {
            var msWorkspace = MSBuildWorkspace.Create();
            var solution    = msWorkspace.OpenSolutionAsync(this.TestSolution.FullName).Result;

            solution = solution.GetIsolatedSolution();

            var cityDoc = solution.Projects
                          .SelectMany(p => p.Documents)
                          .Where(p => p.Name == "City.cs")
                          .FirstOrDefault();

            var existingDto = solution.Projects
                              .SelectMany(p => p.Documents)
                              .Where(p => p.Name == "CityDTO.cs")
                              .FirstOrDefault();

            var dtoLocation = solution.GetMostLikelyDtoLocation();
            var vm          = await PropertySelectorViewModel.Create(cityDoc, "CityDTO", dtoLocation, existingDto);

            var countryProp = vm.EntityModel.Properties.Where(p => p.Name == "Country").FirstOrDefault();

            Assert.IsNotNull(countryProp);

            Assert.IsTrue(countryProp.RelatedEntity.Properties.Where(p => p.Name == "Code").Any(p => p.IsSelected));
            Assert.IsFalse(countryProp.RelatedEntity.Properties.Where(p => p.Name == "Name").Any(p => p.IsSelected));

            var modifiedSolution = await solution.WriteDto(dtoLocation, vm.GetMetadata(), true, false, false);

            Assert.IsNotNull(modifiedSolution);

            var cityDto = modifiedSolution.GetChanges(solution)
                          .GetProjectChanges().Single()
                          .GetChangedDocuments()
                          .Select(p => modifiedSolution.GetProject(p.ProjectId).GetDocument(p))
                          .Where(p => p.Name == "CityDTO.cs")
                          .FirstOrDefault();

            Assert.IsNotNull(cityDto);

            var source = await cityDto.GetTextAsync();

            var sourceCode = source.ToString();

            Assert.IsTrue(sourceCode.Contains("public string CountryCode { get; set; }"));
        }
        public async Task WriteDto_ExistingSolution_FishWithIdOverride()
        {
            var msWorkspace = MSBuildWorkspace.Create();
            var solution    = msWorkspace.OpenSolutionAsync(this.TestSolution.FullName).Result;

            solution = solution.GetIsolatedSolution();

            var fishClassDoc = solution.Projects
                               .SelectMany(p => p.Documents)
                               .Where(p => p.Name == "Fish.cs")
                               .FirstOrDefault();

            var vm = await EntityViewModel.CreateRecursive(fishClassDoc);

            vm.DtoName = "FishDTO";
            var dtoLocation = solution.GetMostLikelyDtoLocation();

            var modifiedSolution = await solution.WriteDto(dtoLocation, vm.ConvertToMetadata(), true, false, false);

            Assert.IsNotNull(modifiedSolution);

            var changeSet = modifiedSolution.GetChanges(solution);

            Assert.AreEqual(1, changeSet.GetProjectChanges().Count());

            var projectChanges = changeSet.GetProjectChanges().Single();

            Assert.AreEqual(2, projectChanges.GetAddedDocuments().Count());

            var addedDocs = projectChanges
                            .GetAddedDocuments()
                            .Select(p => modifiedSolution.GetProject(p.ProjectId).GetDocument(p));

            var fishDto = addedDocs
                          .Where(p => p.Name == "FishDTO.cs")
                          .FirstOrDefault();

            Assert.IsNotNull(fishDto);

            var source = await fishDto.GetTextAsync();

            var sourceCode = source.ToString();

            Assert.IsTrue(sourceCode.IndexOf("public int Id { get; set; }") > 0);
            Assert.AreEqual(sourceCode.IndexOf("public int Id { get; set; }"), sourceCode.LastIndexOf("public int Id { get; set; }"));
        }
Beispiel #6
0
    static void Main(string[] args)
    {
        // The test solution is copied to the output directory when you build this sample.
        MSBuildWorkspace workspace = MSBuildWorkspace.Create();

        // Open the solution within the workspace.
        Solution originalSolution = workspace.OpenSolutionAsync(@"TestSolutionForCSharp\Test.sln").Result;

        // Declare a variable to store the intermediate solution snapshot at each step.
        Solution newSolution = originalSolution;

        // Note how we can't simply iterate over originalSolution.Projects or project.Documents
        // because it will return objects from the unmodified originalSolution, not from the newSolution.
        // We need to use the ProjectIds and DocumentIds (that don't change) to look up the corresponding
        // snapshots in the newSolution.
        foreach (ProjectId projectId in originalSolution.ProjectIds)
        {
            // Look up the snapshot for the original project in the latest forked solution.
            Project project = newSolution.GetProject(projectId);

            foreach (DocumentId documentId in project.DocumentIds)
            {
                // Look up the snapshot for the original document in the latest forked solution.
                Document document = newSolution.GetDocument(documentId);

                // Get a transformed version of the document (a new solution snapshot is created
                // under the covers to contain it - none of the existing objects are modified).
                Document newDocument = Formatter.FormatAsync(document).Result;

                // Store the solution implicitly constructed in the previous step as the latest
                // one so we can continue building it up in the next iteration.
                newSolution = newDocument.Project.Solution;
            }
        }

        // Actually apply the accumulated changes and save them to disk. At this point
        // workspace.CurrentSolution is updated to point to the new solution.
        if (workspace.TryApplyChanges(newSolution))
        {
            Console.WriteLine("Solution updated.");
        }
        else
        {
            Console.WriteLine("Update failed!");
        }
    }
Beispiel #7
0
        public static async Task <Document> FixSourceAsync(string documentPath, string diagnosticId)
        {
            if (documentPath is null)
            {
                throw new ArgumentNullException(nameof(documentPath));
            }

            using var workspace = MSBuildWorkspace.Create();
            var project = await workspace.OpenProjectAsync(TestProjectPath).ConfigureAwait(false);

            var projectId = project.Id;

            var       diagnosticFixed = false;
            var       solution        = workspace.CurrentSolution;
            const int MAX_TRIES       = 100;
            var       fixAttempts     = 0;

            do
            {
                fixAttempts++;
                diagnosticFixed = false;
                project         = solution.GetProject(projectId) !;
                var diagnostics = await GetDiagnosticsFromProjectAsync(project, documentPath, diagnosticId).ConfigureAwait(false);

                foreach (var diagnostic in diagnostics)
                {
                    var doc           = project.GetDocument(diagnostic.Location.SourceTree) !;
                    var fixedSolution = await TryFixDiagnosticAsync(diagnostic, doc).ConfigureAwait(false);

                    if (fixedSolution != null)
                    {
                        solution        = fixedSolution;
                        diagnosticFixed = true;
                        break;
                    }
                }

                if (fixAttempts + 1 == MAX_TRIES)
                {
                    Assert.True(false, $"The code fixers were unable to resolve the following diagnostic(s):{Environment.NewLine}   {string.Join(',', diagnostics.Select(d => d.Id))}");
                }
            }while (diagnosticFixed);

            project = solution.GetProject(projectId) !;
            return(project.Documents.First(d => documentPath.Equals(Path.GetFileName(d.FilePath), StringComparison.Ordinal)));
        }
Beispiel #8
0
        public async Task MeasureSolutionAnalysisPerformance()
        {
            using (var workspace = MSBuildWorkspace.Create())
            {
                var path     = @"..\..\..\..\archimetrics.sln".GetLowerCaseFullPath();
                var solution = await workspace.OpenSolutionAsync(path).ConfigureAwait(false);

                var metrics = new metrics.Metrics();
                var timer   = metrics.Timer(GetType(), "test", TimeUnit.Seconds, TimeUnit.Seconds);
                for (var i = 0; i < 5; i++)
                {
                    var amount = timer.Time(() => PerformReview(solution).Result);
                }

                Assert.True(timer.Mean < 90.0);
            }
        }
Beispiel #9
0
        public static void ExampleOne()
        {
            var work = MSBuildWorkspace.Create();

            var solution = work.OpenSolutionAsync(@"..\..\..\RoslynPlayGround.sln").Result;
            var project  = solution.Projects.FirstOrDefault(p => p.Name == "Chapter3");

            if (project == null)
            {
                throw new Exception("Could not find the Chapter 3 project");
            }
            var compilation = project.GetCompilationAsync().Result;
            var targetType  = compilation.GetTypeByMetadataName("Chapter3.IGreetingProfile");
            var type        = Symbols.FindClassesDerivedOrImplementedByType(compilation, targetType);

            Console.WriteLine(type.First().Identifier.ToFullString());
        }
        public async Task MeasureProjectAnalysisPerformance()
        {
            using (var workspace = MSBuildWorkspace.Create())
            {
                var path    = @"..\..\..\ArchiMetrics.Common\ArchiMetrics.Common.csproj".GetLowerCaseFullPath();
                var project = await workspace.OpenProjectAsync(path).ConfigureAwait(false);

                var metrics = new metrics.Metrics();
                var timer   = metrics.Timer(GetType(), "test", TimeUnit.Seconds, TimeUnit.Seconds);
                for (var i = 0; i < 5; i++)
                {
                    var amount = timer.Time(() => PerformReview(project).Result);
                }

                Assert.Less(timer.Mean, 90.0);
            }
        }
Beispiel #11
0
        private static async Task GenerateWithMSBuildLocatedAsync(
            FileInfo solutionOrProjectFile, ILsifJsonWriter lsifWriter, TextWriter logFile,
            Func <MSBuildWorkspace, Task <Solution> > openAsync)
        {
            await logFile.WriteLineAsync($"Loading {solutionOrProjectFile.FullName}...");

            var solutionLoadStopwatch = Stopwatch.StartNew();

            var msbuildWorkspace = MSBuildWorkspace.Create();

            msbuildWorkspace.WorkspaceFailed += (s, e) => logFile.WriteLine("Error while loading: " + e.Diagnostic.Message);

            var solution = await openAsync(msbuildWorkspace);

            await logFile.WriteLineAsync($"Load completed in {solutionLoadStopwatch.Elapsed.ToDisplayString()}.");

            var lsifGenerator = Generator.CreateAndWriteCapabilitiesVertex(lsifWriter);

            var totalTimeInGenerationAndCompilationFetchStopwatch = Stopwatch.StartNew();
            var totalTimeInGenerationPhase = TimeSpan.Zero;

            foreach (var project in solution.Projects)
            {
                if (project.SupportsCompilation && project.FilePath != null)
                {
                    var compilationCreationStopwatch = Stopwatch.StartNew();
                    var compilation = (await project.GetCompilationAsync()) !;

                    await logFile.WriteLineAsync($"Fetch of compilation for {project.FilePath} completed in {compilationCreationStopwatch.Elapsed.ToDisplayString()}.");

                    var generationForProjectStopwatch = Stopwatch.StartNew();
                    await lsifGenerator.GenerateForCompilationAsync(compilation, project.FilePath, project.LanguageServices, project.Solution.Options);

                    generationForProjectStopwatch.Stop();

                    totalTimeInGenerationPhase += generationForProjectStopwatch.Elapsed;

                    await logFile.WriteLineAsync($"Generation for {project.FilePath} completed in {generationForProjectStopwatch.Elapsed.ToDisplayString()}.");
                }
            }

            await logFile.WriteLineAsync($"Total time spent in the generation phase for all projects, excluding compilation fetch time: {totalTimeInGenerationPhase.ToDisplayString()}");

            await logFile.WriteLineAsync($"Total time spent in the generation phase for all projects, including compilation fetch time: {totalTimeInGenerationAndCompilationFetchStopwatch.Elapsed.ToDisplayString()}");
        }
Beispiel #12
0
        public ExtractMetadataWorker(ExtractMetadataInputModel input)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            if (string.IsNullOrEmpty(input.OutputFolder))
            {
                throw new ArgumentNullException(nameof(input.OutputFolder), "Output folder must be specified");
            }

            _files = input.Files?.Select(s => new FileInformation(s))
                     .GroupBy(f => f.Type)
                     .ToDictionary(s => s.Key, s => s.Distinct().ToList());
            _rebuild = input.ForceRebuild;

            var msbuildProperties = input.MSBuildProperties ?? new Dictionary <string, string>();

            if (!msbuildProperties.ContainsKey("Configuration"))
            {
                msbuildProperties["Configuration"] = "Release";
            }

            _options = new ExtractMetadataOptions
            {
                ShouldSkipMarkup          = input.ShouldSkipMarkup,
                PreserveRawInlineComments = input.PreserveRawInlineComments,
                FilterConfigFile          = input.FilterConfigFile != null ? new FileInformation(input.FilterConfigFile).NormalizedPath : null,
                MSBuildProperties         = msbuildProperties,
            };

            _useCompatibilityFileName = input.UseCompatibilityFileName;
            _outputFolder             = StringExtension.ToNormalizedFullPath(Path.Combine(EnvironmentContext.OutputDirectory, input.OutputFolder));

            _workspace = new Lazy <MSBuildWorkspace>(() =>
            {
                var workspace              = MSBuildWorkspace.Create(msbuildProperties);
                workspace.WorkspaceFailed += (s, e) =>
                {
                    Logger.LogWarning($"Workspace failed with: {e.Diagnostic}");
                };
                return(workspace);
            });
        }
        public async Task <IntertypeRelationGraph> GetDataStructure(TCSharpModel model, CancellationToken token)
        {
            var graph     = new IntertypeRelationGraph();
            var workspace = MSBuildWorkspace.Create(new Dictionary <string, string>
            {
                { "Configuration", settingsProvider.Configuration },
                { "Platform", settingsProvider.Platform }
            });

            var solution = await workspace.OpenSolutionAsync(model.AbsoluteSolutionPath, token);

            compilations = new List <Compilation>();

            var typeSymbols = new List <INamedTypeSymbol>();

            //Collect all types
            foreach (var project in solution.Projects)
            {
                token.ThrowIfCancellationRequested();

                var compilation = await project.GetCompilationAsync(token);

                compilations.Add(compilation);

                foreach (var namespaceSymbol in compilation.Assembly.GlobalNamespace.GetNamespaceMembers())
                {
                    AddNodeIfNotExists(namespaceSymbol, graph, typeSymbols);
                }
            }

            //Build edges
            var parallelOptions = new ParallelOptions
            {
                CancellationToken      = token,
                MaxDegreeOfParallelism = Environment.ProcessorCount
            };

            Parallel.ForEach(typeSymbols, parallelOptions, type =>
            {
                parallelOptions.CancellationToken.ThrowIfCancellationRequested();
                ProcessTypeSymbol(type, graph);
            });

            return(graph);
        }
        private static void Method6()
        {
            var work     = MSBuildWorkspace.Create();
            var solution = work.OpenSolutionAsync(@"..\..\..\RoslynPlayGround.sln").Result;
            var project  = solution.Projects.FirstOrDefault(p => p.Name == "CodeGenerationWithRoslyn");

            if (project == null)
            {
                throw new Exception("Could not find the CodeGenerationWithRoslyn Project");
            }

            var compilation = project.GetCompilationAsync().Result;

            // Do something with the compilation

            var memory = new MemoryStream();

            var results = compilation.Emit(memory);

            if (!results.Success)
            {
                foreach (var item in results.Diagnostics)
                {
                    if (item.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error)
                    {
                        Console.WriteLine(item.GetMessage());
                    }
                }
            }

            var assembly = Assembly.Load(memory.ToArray());
            var types    = assembly.GetTypes();

            var greetingRules = types.FirstOrDefault(t => t.Name == "GreetingRules");

            if (greetingRules == null)
            {
                throw new Exception("Could not find the type, GreetingRules");
            }

            foreach (var method in greetingRules.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
            {
                Console.WriteLine(method.Name);
            }
        }
Beispiel #15
0
        static void Main()
        {
            var @namespace   = NamespaceDeclaration(IdentifierName("HearthDb"));
            var header       = ParseLeadingTrivia(@"/* THIS CLASS WAS GENERATED BY HearthDb.CardIdGenerator. DO NOT EDIT. */");
            var cCardIds     = ClassDeclaration("CardIds").AddModifiers(Token(PublicKeyword)).WithLeadingTrivia(header);
            var cCollectible = ClassDeclaration("Collectible").AddModifiers(Token(PublicKeyword));

            cCollectible = SyntaxBuilder.GetCollectible(cCollectible);
            var cNonCollectible = SyntaxBuilder.GetNonCollectible();

            cCardIds   = cCardIds.AddMembers(cCollectible);
            cCardIds   = cCardIds.AddMembers(cNonCollectible);
            @namespace = @namespace.AddMembers(cCardIds);
            var root = Formatter.Format(@namespace, MSBuildWorkspace.Create());

            using (var sr = new StreamWriter(File))
                sr.Write(root.ToString());
        }
Beispiel #16
0
        // Note: $var with "Name" doesn't need to be path, but $var without "Name" should be the exact path
        public Utility(string sln, string testProjectName, string testFileName)
        {
            Debug.Assert(File.Exists(sln));
            this.workspace = MSBuildWorkspace.Create();
            this.solution  = workspace.OpenSolutionAsync(sln).Result;
            //Console.WriteLine(testProjectName);
            Document testClassDocument = FindDocumentByName(testProjectName, testFileName);

            //Environment.Exit(0);
            /**** DEBUG ****/
            Debug.Assert(testClassDocument != null);

            this.testClassEditor = DocumentEditor.CreateAsync(testClassDocument).Result;
            this.testClassTree   = testClassDocument.GetSyntaxTreeAsync().Result;
            SyntaxNode testClassRoot = testClassTree.GetRoot();

            this.testClassMethods = testClassRoot.DescendantNodes().OfType <MethodDeclarationSyntax>().ToList();
        }
Beispiel #17
0
        private static void SearchFeatureToggleKeywodInSolution(string solutionPath, string featureToggle)
        {
            var msWorkspace = MSBuildWorkspace.Create();

            var solution = msWorkspace.OpenSolutionAsync(solutionPath).Result;

            foreach (var project in solution.Projects)
            {
                foreach (var document in project.Documents)
                {
                    var syntaxRoot = document.GetSyntaxRootAsync();
                    if (syntaxRoot.ToString().Contains(featureToggle))
                    {
                        Console.WriteLine(project.Name + "\t\t\t" + document.FilePath);
                    }
                }
            }
        }
Beispiel #18
0
        public static async Task Main(string[] args)
        {
            MSBuildLocator.RegisterDefaults();

            var workspace = MSBuildWorkspace.Create();
            var proj      = await workspace.OpenProjectAsync(args[0]);

            foreach (var x in workspace.Diagnostics)
            {
                Debug.WriteLine(x);
            }
            proj = Mapping.ProcessProject(proj);
            if (!workspace.TryApplyChanges(proj.Solution))
            {
                Debug.Fail("");
            }
            ;
        }
Beispiel #19
0
        public void AssertCodeFixTransformsTo(string preCodeFix, string expectedPostCodeFix, Func <ClassDeclarationSyntax, ClassDeclarationSyntax> fixCode)
        {
            var workspace = MSBuildWorkspace.Create();

            SyntaxTree astPreCodeFix   = CSharpSyntaxTree.ParseText(preCodeFix);
            var        rootPreCodeFix  = ( CompilationUnitSyntax )astPreCodeFix.GetRoot();
            var        classPreCodeFix = rootPreCodeFix.ChildNodes().OfType <ClassDeclarationSyntax>().First();

            var classPostCodeFix           = fixCode(classPreCodeFix);
            var astPostCodeFixFormattedStr = Formatter.Format(classPostCodeFix, workspace).ToFullString();

            SyntaxTree astExpectedPostCodeFix             = CSharpSyntaxTree.ParseText(expectedPostCodeFix);
            var        rootExpectedPostCodeFix            = ( CompilationUnitSyntax )astExpectedPostCodeFix.GetRoot();
            var        expectedClassPostCodeFix           = rootExpectedPostCodeFix.ChildNodes().OfType <ClassDeclarationSyntax>().First();
            var        astExpectedPostCodeFixFormattedStr = Formatter.Format(expectedClassPostCodeFix, workspace).ToFullString();

            Assert.AreEqual(astExpectedPostCodeFixFormattedStr, astPostCodeFixFormattedStr);
        }
Beispiel #20
0
        private static void EnsureOtherAssembliesLoad()
        {
            // force load msbuild and get its location
            using var workspace = MSBuildWorkspace.Create();
            var msbuild         = AssemblyLoadContext.Default.Assemblies.Single(a => a.GetName().Name == "Microsoft.Build");
            var msBuildLocation = Path.GetDirectoryName(msbuild.Location) ?? string.Empty;

            // add a loader that will try and find the assembly in the same location if we didn't find it
            AssemblyLoadContext.Default.Resolving += (AssemblyLoadContext arg1, System.Reflection.AssemblyName arg2) =>
            {
                var attemptedLocation = Path.Combine(msBuildLocation, arg2.Name + ".dll");
                if (File.Exists(attemptedLocation))
                {
                    return(Assembly.LoadFrom(attemptedLocation));
                }
                return(null);
            };
        }
Beispiel #21
0
        public async Task TestTransformProject()
        {
            var workspace = MSBuildWorkspace.Create();
            var project   = await workspace.OpenProjectAsync(Path.Combine(AppContext.BaseDirectory, "../../../../TestAssembly/TestAssembly.csproj"));

            var ass = await SharpCompiler.CompileProject(project);

            Assert.NotNull(ass);
            Assert.Equal("TestAssembly.Py", ass.GetName().Name);

            var itemRecordType = ass.GetType("TestAssembly.item_record");

            Assert.NotNull(itemRecordType);

            Assert.NotNull(itemRecordType.GetProperty("name"));
            Assert.NotNull(itemRecordType.GetProperty("description"));
            Assert.NotNull(itemRecordType.GetProperty("current_ticks"));
        }
        public CompiledProject(string projectFilePath)
        {
            if (!File.Exists(projectFilePath))
            {
                var currentDirectory = Directory.GetCurrentDirectory();

                throw new ArgumentException($"No project file exists at '{projectFilePath}'.");
            }

            // https://stackoverflow.com/a/64766792/7176908
            MSBuildLocator.RegisterDefaults();

            this.Workspace = MSBuildWorkspace.Create();
            this.Workspace.LoadMetadataForReferencedProjects = true;
            this.Project = this.Workspace.OpenProjectAsync(projectFilePath).Result;

            this.Compilation = this.Project.GetCompilationAsync().Result;
        }
        public void Should_create_file_from_semantic_log_from_project()
        {
            var runner         = new T4TemplateRunner();
            var startDirectory = Path.Combine(FileSupport.ProjectPath(AppDomain.CurrentDomain.BaseDirectory), "..\\SemanticLogGenerationMetadata");

            startDirectory = Path.GetFullPath(startDirectory);
            var ws          = MSBuildWorkspace.Create();
            var projectPath = FileSupport.GetNearestCSharpProject(startDirectory);
            // For now: wait for the result
            var project = ws.OpenProjectAsync(projectPath).Result;
            var dict    = runner.CreateOutputStringsFromProject(project, "..\\Output");

            Assert.AreEqual(1, dict.Count());
            var actual = dict.First().Value;

            actual = StringUtilities.RemoveFileHeaderComments(actual);
            Assert.AreEqual(expected, actual);
        }
Beispiel #24
0
        private IEnumerable <string> GenerateDocumentsPaths()
        {
            var workspace = MSBuildWorkspace.Create();
            var solution  = workspace.OpenSolutionAsync(_solutionPath).Result;

            foreach (var project in solution.Projects)
            {
                string projectPath = Path.GetDirectoryName(project.FilePath);
                foreach (var document in project.Documents)
                {
                    string documentPath = Path.GetDirectoryName(document.FilePath);
                    if (projectPath == documentPath)
                    {
                        yield return(document.FilePath);
                    }
                }
            }
        }
Beispiel #25
0
        public FeatureLookup(string solutionPath, IEnumerable <IFeatureQuery> queries)
        {
            this.projectFilter = _ => true;

            this.queries = queries;

            var properties = new Dictionary <string, string>
            {
                // This property ensures that XAML files will be compiled in the current AppDomain
                // rather than a separate one. Any tasks isolated in AppDomains or tasks that create
                // AppDomains will likely not work due to https://github.com/Microsoft/MSBuildLocator/issues/16.
                { "AlwaysCompileMarkupFilesInSeparateDomain", bool.FalseString }
            };

            this.workspace = MSBuildWorkspace.Create(properties);
            this.workspace.WorkspaceFailed += Workspace_WorkspaceFailed;
            this.solution = this.workspace.OpenSolutionAsync(solutionPath, new ProgressReporter()).Result;
        }
Beispiel #26
0
        public async Task <HashSet <string> > GetRecursivelyReferencedProjects(string solutionFilePath, string[] rootProjectNames)
        {
            var workspace = MSBuildWorkspace.Create();

            var solution = workspace.OpenSolutionAsync(solutionFilePath).Result;

            var references = new ConcurrentDictionary <string, object>();

            var tasks = rootProjectNames
                        .Select(async(projName) =>
            {
                await FillReferencedProjectSetRecursively(solution, projName, references);
            });

            await Task.WhenAll(tasks);

            return(new HashSet <string>(references.Keys));
        }
        public void ShowThisSolutionStructure()
        {
            String           currentDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? ".";
            MSBuildWorkspace workspace  = MSBuildWorkspace.Create();
            Solution         solution   = workspace.OpenSolutionAsync(Path.Combine(currentDir, "..//..//..//SourceCodeAnalysis.sln")).Result;

            foreach (ProjectId projectId in solution.GetProjectDependencyGraph().GetTopologicallySortedProjects())
            {
                Project project     = solution.GetProject(projectId);
                String  projectRoot = Path.GetDirectoryName(project.FilePath) + "\\";
                Console.WriteLine("project : {0}, path : {1}", project.Name, project.FilePath);
                foreach (Document document in project.Documents)
                {
                    Console.WriteLine("    file : {0}", document.FilePath.Substring(projectRoot.Length));
                }
                Console.WriteLine();
            }
        }
        public static MSBuildWorkspace CreateMSBuildWorkspace()
        {
            try
            {
                MSBuildLocator.RegisterDefaults();
            }
            catch
            {
                Console.WriteLine("Workspace defaults already registered");
            }

            MSBuildWorkspace workspace = MSBuildWorkspace.Create(new Dictionary <string, string> {
                { "DebugSymbols", "False" }
            });

            workspace.WorkspaceFailed += (e, d) => Console.WriteLine(e.ToString() + ":" + d.ToString());
            return(workspace);
        }
Beispiel #29
0
        protected override async Task ExecuteAsync(string[] args)
        {
            _args = args;
            var      workspace        = MSBuildWorkspace.Create();
            var      solutionFileName = args[1];
            Solution originalSolution = await workspace.OpenSolutionAsync(solutionFileName);

            Solution newSolution = await ReplaceDocumentsAsync(originalSolution, ProcessDocumentAsync);

            if (workspace.TryApplyChanges(newSolution))
            {
                Console.WriteLine("Solution updated.");
            }
            else
            {
                Console.WriteLine("Update failed!");
            }
        }
Beispiel #30
0
        public static MSBuildWorkspace CreateWorkspace(Dictionary <string, string>?properties)
        {
            if (properties is null)
            {
                properties = new Dictionary <string, string>();
            }

#if NETCOREAPP
            // This property ensures that XAML files will be compiled in the current AppDomain
            // rather than a separate one. Any tasks isolated in AppDomains or tasks that create
            // AppDomains will likely not work due to https://github.com/Microsoft/MSBuildLocator/issues/16.
            properties["AlwaysCompileMarkupFilesInSeparateDomain"] = bool.FalseString;
#endif
            // Use the latest language version to force the full set of available analyzers to run on the project.
            properties["LangVersion"] = "latest";

            return(MSBuildWorkspace.Create(properties));
        }