Exemple #1
0
        public static ISolution GetSolution(string _solutionPath)
        {
            if (!File.Exists(_solutionPath))
            {
                throw new InvalidOperationException("File not found (" + _solutionPath + ")");
            }

            IWorkspace workspace = null;

            switch (Path.GetExtension(_solutionPath).ToUpper())
            {
            case ".SLN":
                workspace = Workspace.LoadSolution(_solutionPath);
                break;

            case ".CSPROJ":
                workspace = Workspace.LoadStandAloneProject(_solutionPath);
                break;

            case ".CS":
                var solutionId = SolutionId.CreateNewId();
                workspace = Workspace.GetWorkspace(solutionId);
                var projectId  = ProjectId.CreateNewId(solutionId);
                var documentId = DocumentId.CreateNewId(projectId, Path.GetFileNameWithoutExtension(_solutionPath));
                workspace.AddExistingDocument(documentId, _solutionPath);
                break;

            default:
                throw new InvalidOperationException("file type not supported");
            }

            var solution = workspace.CurrentSolution;

            return(solution);
        }
Exemple #2
0
        public void TestP2PReference()
        {
            var workspace = new AdhocWorkspace();

            var project1     = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "proj1", "proj1", LanguageNames.CSharp);
            var project2     = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "proj2", "proj2", LanguageNames.CSharp, projectReferences: SpecializedCollections.SingletonEnumerable(new ProjectReference(project1.Id)));
            var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default, projects: new ProjectInfo[] { project1, project2 });

            var solution = workspace.AddSolution(solutionInfo);

            var instanceTracker = ObjectReference.CreateFromFactory(() => new object());

            var cacheService = new ProjectCacheService(workspace, TimeSpan.MaxValue);

            using (var cache = cacheService.EnableCaching(project2.Id))
            {
                instanceTracker.UseReference(r => cacheService.CacheObjectIfCachingEnabledForKey(project1.Id, (object)null, r));
                solution = null;

                workspace.OnProjectRemoved(project1.Id);
                workspace.OnProjectRemoved(project2.Id);
            }

            // make sure p2p reference doesn't go to implicit cache
            instanceTracker.AssertReleased();
        }
Exemple #3
0
        private static SolutionInfo GetInitialSolutionInfoWithP2P()
        {
            var projectId1 = ProjectId.CreateNewId();
            var projectId2 = ProjectId.CreateNewId();
            var projectId3 = ProjectId.CreateNewId();
            var projectId4 = ProjectId.CreateNewId();
            var projectId5 = ProjectId.CreateNewId();

            var solution = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
                                               projects: new[]
            {
                ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
                                   documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1") }),
                ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp,
                                   documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2") },
                                   projectReferences: new[] { new ProjectReference(projectId1) }),
                ProjectInfo.Create(projectId3, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp,
                                   documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId3), "D3") },
                                   projectReferences: new[] { new ProjectReference(projectId2) }),
                ProjectInfo.Create(projectId4, VersionStamp.Create(), "P4", "P4", LanguageNames.CSharp,
                                   documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId4), "D4") }),
                ProjectInfo.Create(projectId5, VersionStamp.Create(), "P5", "P5", LanguageNames.CSharp,
                                   documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId5), "D5") },
                                   projectReferences: new[] { new ProjectReference(projectId4) }),
            });

            return(solution);
        }
Exemple #4
0
        /// <summary>
        /// Creates a new P# project using the specified references.
        /// </summary>
        /// <param name="references">MetadataReferences</param>
        /// <returns>Project</returns>
        private Project CreateProject(ISet <MetadataReference> references)
        {
            var workspace    = new AdhocWorkspace();
            var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create());
            var solution     = workspace.AddSolution(solutionInfo);
            var project      = workspace.AddProject("Test", "C#");

            CompilationOptions options = null;

            if (this.Configuration.OptimizationTarget == OptimizationTarget.Debug)
            {
                options = project.CompilationOptions.WithOptimizationLevel(OptimizationLevel.Debug);
            }
            else if (this.Configuration.OptimizationTarget == OptimizationTarget.Release)
            {
                options = project.CompilationOptions.WithOptimizationLevel(OptimizationLevel.Release);
            }

            project = project.WithCompilationOptions(options);
            project = project.AddMetadataReferences(references);

            workspace.TryApplyChanges(project.Solution);

            return(project);
        }
        protected Solution CreateOrOpenSolution(bool nullPaths = false)
        {
            var solutionFile = _persistentFolder.CreateOrOpenFile("Solution1.sln").WriteAllText("");

            var info = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), solutionFile.Path);

            var workspace = new AdhocWorkspace();

            workspace.AddSolution(info);

            var solution = workspace.CurrentSolution;

            var projectFile = _persistentFolder.CreateOrOpenFile("Project1.csproj").WriteAllText("");

            solution = solution.AddProject(ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Project1", "Project1", LanguageNames.CSharp,
                                                              filePath: nullPaths ? null : projectFile.Path));
            var project = solution.Projects.Single();

            var documentFile = _persistentFolder.CreateOrOpenFile("Document1.cs").WriteAllText("");

            solution = solution.AddDocument(DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "Document1",
                                                                filePath: nullPaths ? null : documentFile.Path));

            // Apply this to the workspace so our Solution is the primary branch ID, which matches our usual behavior
            workspace.TryApplyChanges(solution);

            return(workspace.CurrentSolution);
        }
        public void TestAddSolution_SolutionInfo()
        {
            using (var ws = new AdhocWorkspace())
            {
                var pinfo = ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    version: VersionStamp.Default,
                    name: "TestProject",
                    assemblyName: "TestProject.dll",
                    language: LanguageNames.CSharp);

                var sinfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default, projects: new ProjectInfo[] { pinfo });

                var solution = ws.AddSolution(sinfo);

                Assert.Same(ws.CurrentSolution, solution);
                Assert.Equal(solution.Id, sinfo.Id);

                Assert.Equal(sinfo.Projects.Count, solution.ProjectIds.Count);
                var project = solution.Projects.FirstOrDefault();
                Assert.NotNull(project);
                Assert.Equal(pinfo.Name, project.Name);
                Assert.Equal(pinfo.Id, project.Id);
                Assert.Equal(pinfo.AssemblyName, project.AssemblyName);
                Assert.Equal(pinfo.Language, project.Language);
            }
        }
        private Document CreateDocument(string code)
        {
            var docName    = "Test." + this.language == LanguageNames.CSharp ? "cs" : "vb";
            var solutionId = SolutionId.CreateNewId("TestSolution");
            var projectId  = ProjectId.CreateNewId(debugName: "TestProject");
            var documentId = DocumentId.CreateNewId(projectId, debugName: docName);

            var solution = Solution
                           .Create(solutionId)
                           .AddProject(projectId, "TestProject", "TestProject", this.language)
                           .AddMetadataReference(projectId, MetadataReference.CreateAssemblyReference("mscorlib"))
                           .AddMetadataReference(projectId, MetadataReference.CreateAssemblyReference("System.Core"));

            if (this.language == LanguageNames.VisualBasic)
            {
                solution = solution.AddMetadataReference(projectId, MetadataReference.CreateAssemblyReference("Microsoft.VisualBasic"));
            }

            var document = solution
                           .AddDocument(documentId, docName, SourceText.From(code))
                           .GetDocument(documentId);
            var diags = document.GetSemanticModelAsync().Result.GetDiagnostics().ToArray();

            foreach (var diag in diags)
            {
                Console.WriteLine(diag.ToString());
            }

            return(document);
        }
            public static SolutionInfo LoadSolutionInfo(string folderPath, SourceFileMatcher fileMatcher)
            {
                var absoluteFolderPath = Path.GetFullPath(folderPath, Directory.GetCurrentDirectory());

                var filePaths         = GetMatchingFilePaths(absoluteFolderPath, fileMatcher);
                var editorConfigPaths = EditorConfigFinder.GetEditorConfigPaths(folderPath);

                var projectInfos = ImmutableArray.CreateBuilder <ProjectInfo>(ProjectLoaders.Length);

                // Create projects for each of the supported languages.
                foreach (var loader in ProjectLoaders)
                {
                    var projectInfo = loader.LoadProjectInfo(folderPath, filePaths, editorConfigPaths);
                    if (projectInfo is null)
                    {
                        continue;
                    }

                    projectInfos.Add(projectInfo);
                }

                // Construct workspace from loaded project infos.
                return(SolutionInfo.Create(
                           SolutionId.CreateNewId(debugName: absoluteFolderPath),
                           version: default,
        public async Task UpdaterService()
        {
            var workspace = new AdhocWorkspace(TestHostServices.CreateHostServices());

            workspace.Options = workspace.Options.WithChangedOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS, 1);

            var analyzerReference = new AnalyzerFileReference(typeof(object).Assembly.Location, new NullAssemblyAnalyzerLoader());
            var service           = CreateRemoteHostClientService(workspace, SpecializedCollections.SingletonEnumerable <AnalyzerReference>(analyzerReference));

            service.Enable();

            // make sure client is ready
            var client = await service.GetRemoteHostClientAsync(CancellationToken.None);

            // add solution
            workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default));

            // TODO: use waiter to make sure workspace events and updater is ready.
            //       this delay is temporary until I set all .Next unit test hardness to setup correctly
            await Task.Delay(TimeSpan.FromSeconds(1));

            // checksum should already exist
            SolutionStateChecksums checksums;

            Assert.True(workspace.CurrentSolution.State.TryGetStateChecksums(out checksums));

            service.Disable();
        }
Exemple #10
0
        /// <summary>
        /// Creates a canonical Roslyn project for testing.
        /// </summary>
        /// <param name="references">Assembly references to include in the project.</param>
        /// <param name="includeBaseReferences">Whether to include references to the BCL assemblies.</param>
        public static Project CreateTestProject(IEnumerable <Assembly>?references, bool includeBaseReferences = true)
        {
#pragma warning disable SA1009 // Closing parenthesis should be spaced correctly
            var corelib    = Assembly.GetAssembly(typeof(object)) !.Location;
            var runtimeDir = Path.GetDirectoryName(corelib) !;
#pragma warning restore SA1009 // Closing parenthesis should be spaced correctly

            var refs = new List <MetadataReference>();
            if (includeBaseReferences)
            {
                refs.Add(MetadataReference.CreateFromFile(corelib));
                refs.Add(MetadataReference.CreateFromFile(Path.Combine(runtimeDir, "netstandard.dll")));
                refs.Add(MetadataReference.CreateFromFile(Path.Combine(runtimeDir, "System.Runtime.dll")));
            }

            if (references != null)
            {
                foreach (var r in references)
                {
                    refs.Add(MetadataReference.CreateFromFile(r.Location));
                }
            }

#pragma warning disable CA2000 // Dispose objects before losing scope
            return(new AdhocWorkspace()
                   .AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create()))
                   .AddProject("Test", "test.dll", "C#")
                   .WithMetadataReferences(refs)
                   .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithNullableContextOptions(NullableContextOptions.Enable)));

#pragma warning restore CA2000 // Dispose objects before losing scope
        }
        public async Task ShouldCheckFieldDeclaration()
        {
            var workspace  = new AdhocWorkspace();
            var solution   = workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default));
            var libProject = workspace.AddProject(ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "Lib", "Lib", LanguageNames.CSharp));

            var sourceText = SourceText.From(@"
                using System;
                
                namespace Lib 
                {

                    public class ProductsCollection {}

                    public class Foo 
                    {
                        public ProductsCollection Collection = new ProductsCollection();
                    }
                }
            ");

            workspace.AddDocument(libProject.Id, "Lib.cs", sourceText);

            var service         = _provider.GetRequiredService <IFindInternalTypesPort>();
            var source          = new CancellationTokenSource();
            var internalSymbols = await service.FindProjClassesWhichCanBeInternalAsync(workspace.CurrentSolution, libProject.Id, new Progress <FindInternalClassesProgress>(), source.Token);

            Assert.AreEqual(1, internalSymbols.Count());
        }
Exemple #12
0
        internal Task <Compilation> CreateCompilationAsync(IEnumerable <string> paths, IEnumerable <string> preprocessors = null)
        {
            Console.WriteLine("Creating workspace...");

            var ws           = new AdhocWorkspace();
            var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default);

            ws.AddSolution(solutionInfo);
            var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "CSharpExample", "CSharpExample", "C#");

            ws.AddProject(projectInfo);
            foreach (var path in paths)
            {
                LoadFolderDocuments(path, ws, projectInfo.Id);
            }
            Console.WriteLine("Compiling...");
            string mscorlib = @"c:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll";
            var    project  = ws.CurrentSolution.Projects.Single();

            if (File.Exists(mscorlib))
            {
                project = project.WithParseOptions(new Microsoft.CodeAnalysis.CSharp.CSharpParseOptions(Microsoft.CodeAnalysis.CSharp.LanguageVersion.Latest, DocumentationMode.Parse, SourceCodeKind.Regular, preprocessors));
                var metaref = MetadataReference.CreateFromFile(mscorlib);
                project = project.AddMetadataReference(metaref);
            }

            return(project.GetCompilationAsync());
        }
        public void ShouldShowSortedOrder()
        {
            using (var workspace = new AdhocWorkspace())
            {
                workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), "c:\\ws\\app\\app.sln"));

                var p1 = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "A", "A.dll", "C#", "c:\\ws\\app\\src\\A\\A.csproj");
                var p2 = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "B", "Y.dll", "C#", "c:\\ws\\app\\src\\B\\B.csproj");

                using (var m = new MemoryStream())
                {
                    using (var sw = new StreamWriter(m))
                    {
                        using (var reporter = new JsonReporter(sw))
                        {
                            var a = workspace.AddProject(p1);
                            var b = workspace.AddProject(p2);
                            reporter.Report(a);
                            reporter.Report(b);
                        }
                        sw.Flush();
                    }

                    Assert.Equal(@"[
  { ""Name"": ""A"", ""Order"": 0, ""AssemblyName"": ""A.dll"", ""FilePathFromSolutionDir"": ""src\\A\\A.csproj"" },
  { ""Name"": ""B"", ""Order"": 1, ""AssemblyName"": ""Y.dll"", ""FilePathFromSolutionDir"": ""src\\B\\B.csproj"" }
]
".Replace("\r\n", "\n"), System.Text.Encoding.UTF8.GetString(m.ToArray()).Replace("\r\n", "\n"));
                }
            }
        }
        private async Task <AdhocWorkspace> BuildAsync(SolutionSource solutionSource)
        {
            var loader = new ProjectLoader(_fileSystem);

            foreach (var project in solutionSource.Projects.ToArray())
            {
                if (!await loader.LoadAsync(project))
                {
                    solutionSource.Projects.Remove(project);
                }
            }

            var projects = solutionSource.Projects.ToList();

            while (projects.Count > 0)
            {
                var validProjects = projects
                                    .Where(p => p.ProjectReferences.All(_projectInfos.ContainsKey))
                                    .ToArray();

                foreach (var project in validProjects)
                {
                    var info = CreateProjectInfo(project);
                    _projectInfos.Add(project.Path, info);
                    projects.Remove(project);
                }
            }

            var workspace = new AdhocWorkspace();

            var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default, solutionSource.FilePath, _projectInfos.Values);

            workspace.AddSolution(solutionInfo);
            return(workspace);
        }
Exemple #15
0
        public async Task UpdaterService()
        {
            var exportProvider = TestHostServices.CreateMinimalExportProvider();

            var workspace = new AdhocWorkspace(TestHostServices.CreateHostServices(exportProvider));

            workspace.Options = workspace.Options.WithChangedOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS, 1);

            var listenerProvider  = exportProvider.GetExportedValue <AsynchronousOperationListenerProvider>();
            var analyzerReference = new AnalyzerFileReference(typeof(object).Assembly.Location, new NullAssemblyAnalyzerLoader());

            var service = CreateRemoteHostClientService(workspace, SpecializedCollections.SingletonEnumerable <AnalyzerReference>(analyzerReference), listenerProvider);

            service.Enable();

            // make sure client is ready
            var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None);

            // add solution
            workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default));

            // wait for listener
            var workspaceListener = listenerProvider.GetWaiter(FeatureAttribute.Workspace);
            await workspaceListener.CreateWaitTask();

            var listener = listenerProvider.GetWaiter(FeatureAttribute.RemoteHostClient);
            await listener.CreateWaitTask();

            // checksum should already exist
            Assert.True(workspace.CurrentSolution.State.TryGetStateChecksums(out var checksums));

            service.Disable();
        }
            public static async Task <SolutionInfo> LoadSolutionInfoAsync(string folderPath, ImmutableHashSet <string> filesToInclude, CancellationToken cancellationToken)
            {
                var absoluteFolderPath = Path.IsPathFullyQualified(folderPath)
                    ? folderPath
                    : Path.GetFullPath(folderPath, Directory.GetCurrentDirectory());

                var projectInfos = ImmutableArray.CreateBuilder <ProjectInfo>(ProjectLoaders.Length);

                // Create projects for each of the supported languages.
                foreach (var loader in ProjectLoaders)
                {
                    var projectInfo = await loader.LoadProjectInfoAsync(folderPath, filesToInclude, cancellationToken);

                    if (projectInfo is null)
                    {
                        continue;
                    }

                    projectInfos.Add(projectInfo);
                }

                // Construct workspace from loaded project infos.
                return(SolutionInfo.Create(
                           SolutionId.CreateNewId(debugName: absoluteFolderPath),
                           version: default,
Exemple #17
0
        static public void FindMissingUsingsCanonical()
        {
            var workspace    = new AdhocWorkspace();
            var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create());
            var solution     = workspace.AddSolution(solutionInfo);
            var project      = workspace.AddProject("NewProj", "C#");

            var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);

            project = project.AddMetadataReference(mscorlib);
            workspace.TryApplyChanges(project.Solution);
            string text = @"class Test
            {
                void Foo()
                {
                    Console.Write();
                }
            }";

            var sourceText = SourceText.From(text);
            //Add document to project
            var doc        = workspace.AddDocument(project.Id, "NewDoc", sourceText);
            var model      = doc.GetSemanticModelAsync().Result;
            var unresolved = doc.GetSyntaxRootAsync().Result.DescendantNodes()
                             .OfType <IdentifierNameSyntax>()
                             .Where(x => model.GetSymbolInfo(x).Symbol == null)
                             .ToArray();

            foreach (var identifier in unresolved)
            {
                var candidateUsings = SymbolFinder.FindDeclarationsAsync(doc.Project, identifier.Identifier.ValueText, ignoreCase: false).Result;
            }
        }
        public async Task ShouldNotSkipIfTypeUsedInsidePublicMethod()
        {
            var workspace  = new AdhocWorkspace();
            var solution   = workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default));
            var libProject = workspace.AddProject(ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "Lib", "Lib", LanguageNames.CSharp));

            var sourceText = SourceText.From(@"
                using System;
                
                namespace Lib 
                {
                    public class Foo 
                    {
                        public abstract void Foo()
                        {
                            var b = Bar.One;
                        }
                    }

                    public enum Bar { One, Two }
                }
            ");

            workspace.AddDocument(libProject.Id, "Lib.cs", sourceText);

            var service         = _provider.GetRequiredService <IFindInternalTypesPort>();
            var source          = new CancellationTokenSource();
            var internalSymbols = await service.FindProjClassesWhichCanBeInternalAsync(workspace.CurrentSolution, libProject.Id, new Progress <FindInternalClassesProgress>(), source.Token);

            Assert.AreEqual(2, internalSymbols.Count());
        }
        protected SolutionInfo InitializeWorkspace(ProjectId projectId, string fileName, string code, string language)
        {
            var solutionId = SolutionId.CreateNewId();
            var documentId = DocumentId.CreateNewId(projectId);

            return(SolutionInfo.Create(
                       solutionId,
                       VersionStamp.Create(),
                       projects: new ProjectInfo[]
            {
                ProjectInfo.Create(
                    id: projectId,
                    version: VersionStamp.Create(),
                    name: "Project1",
                    assemblyName: "Project1",
                    filePath: $@"C:\project1.{ProjectFileExtension}",
                    language: language,
                    documents: new DocumentInfo[]
                {
                    DocumentInfo.Create(
                        documentId,
                        fileName,
                        loader: TextLoader.From(TextAndVersion.Create(SourceText.From(code),
                                                                      VersionStamp.Create())),
                        filePath: fileName)
                })
            }));
        }
        static ScriptComplieEngine()
        {
            _workSpace = new AdhocWorkspace();
            _workSpace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId("formatter"), VersionStamp.Default));


            //初始化路径
            LibPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lib");


            //处理目录
            if (Directory.Exists(LibPath))
            {
                Directory.Delete(LibPath, true);
            }
            Directory.CreateDirectory(LibPath);


            //程序集缓存
            var _ref = DependencyContext.Default.CompileLibraries
                       .SelectMany(cl => cl.ResolveReferencePaths())
                       .Select(asm => MetadataReference.CreateFromFile(asm));


            DynamicDlls  = new ConcurrentDictionary <string, Assembly>();
            References   = new ConcurrentBag <PortableExecutableReference>(_ref);
            ClassMapping = new ConcurrentDictionary <string, Assembly>();
        }
Exemple #21
0
        private static Solution CreateSolution(int solutionSize)
        {
            var info = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create());

            var workspace = new AdhocWorkspace();

            workspace.AddSolution(info);

            var solution = workspace.CurrentSolution;
            var project  = solution.AddProject("proj1", "proj1", LanguageNames.CSharp);

            var current = 0;

            for (var i = 0; true; i++)
            {
                var size = current + 1234;
                if (current + size >= solutionSize)
                {
                    break;
                }

                project  = project.AddDocument("doc" + i, new string('a', size)).Project;
                current += size;
            }

            var left = solutionSize - current;

            if (left > 0)
            {
                project = project.AddDocument("docLast", new string('a', left)).Project;
            }

            return(project.Solution);
        }
Exemple #22
0
        public void Create_Projects()
        {
            var solutionId  = SolutionId.CreateNewId();
            var version     = VersionStamp.Default;
            var projectInfo = ProjectInfo.Create(
                ProjectId.CreateNewId(),
                version,
                "proj",
                "assembly",
                "C#"
                );

            var info1 = SolutionInfo.Create(solutionId, version, projects: new[] { projectInfo });

            Assert.Same(projectInfo, ((ImmutableArray <ProjectInfo>)info1.Projects).Single());

            var info2 = SolutionInfo.Create(solutionId, version);

            Assert.True(((ImmutableArray <ProjectInfo>)info2.Projects).IsEmpty);

            var info3 = SolutionInfo.Create(solutionId, version, projects: new ProjectInfo[0]);

            Assert.True(((ImmutableArray <ProjectInfo>)info3.Projects).IsEmpty);

            var info4 = SolutionInfo.Create(
                solutionId,
                version,
                projects: ImmutableArray <ProjectInfo> .Empty
                );

            Assert.True(((ImmutableArray <ProjectInfo>)info4.Projects).IsEmpty);
        }
Exemple #23
0
        public TestWorkspace(string tempDir)
        {
            CopyFile(TestProjectDir, "TestPage.xaml", tempDir);
            CopyFile(TestProjectDir, "TestPage.xaml.cs", tempDir);
            CopyFile(TestAutogenDir, "TestPage.xaml.g.cs", tempDir);
            CopyFile(TestProjectDir, "NoXAMLTestContentPage.cs", tempDir);
            CopyFile(TestProjectDir, "NoXAMLTestContentView.cs", tempDir);
            CopyFile(TestProjectDir, "NoXAMLTestInheritanceContentView.cs", tempDir);
            workspace = new AdhocWorkspace();
            var solution = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default);

            workspace.AddSolution(solution);
            var projectId    = ProjectId.CreateNewId();
            var versionStamp = VersionStamp.Create();
            var projectInfo  = ProjectInfo.Create(projectId, versionStamp, "TestProject", "TestProject", LanguageNames.CSharp);
            var testProject  = workspace.AddProject(projectInfo);

            AddReferences(testProject);
            AddDocument(testProject, tempDir, "TestPage.xaml.cs");
            AddDocument(testProject, tempDir, "TestPage.xaml");
            AddDocument(testProject, tempDir, "TestPage.xaml.g.cs");
            AddDocument(testProject, tempDir, "NoXAMLTestContentPage.cs");
            AddDocument(testProject, tempDir, "NoXAMLTestContentView.cs");
            AddDocument(testProject, tempDir, "NoXAMLTestInheritanceContentView.cs");
            // Define a stub type for ContentPage and ConentView so they resolve to a type and not to an ErrorType
            // as the Xamarin.Forms types are not defined in this workspae
            AddDocument(testProject, tempDir, "ContentPage.cs", @"namespace Xamarin.Forms { class ContentPage: Page {}}");
            AddDocument(testProject, tempDir, "ContentPage.cs", @"namespace Xamarin.Forms { class ContentView: View {}}");
        }
        public async Task UpdaterService()
        {
            var exportProvider = TestHostServices.CreateMinimalExportProvider();

            using var workspace = new AdhocWorkspace(TestHostServices.CreateHostServices(exportProvider));

            var options = workspace.CurrentSolution.Options
                          .WithChangedOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS, 1)
                          .WithChangedOption(RemoteTestHostOptions.RemoteHostTest, true);

            workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options));

            var listenerProvider = exportProvider.GetExportedValue <AsynchronousOperationListenerProvider>();

            var checksumUpdater = new SolutionChecksumUpdater(workspace, listenerProvider, CancellationToken.None);
            var service         = workspace.Services.GetRequiredService <IRemoteHostClientProvider>();

            // make sure client is ready
            using var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None);

            // add solution
            workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default));

            // wait for listener
            var workspaceListener = listenerProvider.GetWaiter(FeatureAttribute.Workspace);
            await workspaceListener.ExpeditedWaitAsync();

            var listener = listenerProvider.GetWaiter(FeatureAttribute.SolutionChecksumUpdater);
            await listener.ExpeditedWaitAsync();

            // checksum should already exist
            Assert.True(workspace.CurrentSolution.State.TryGetStateChecksums(out _));

            checksumUpdater.Shutdown();
        }
Exemple #25
0
        protected Solution CreateOrOpenSolution(bool nullPaths = false)
        {
            var solutionFile = Path.Combine(_persistentFolder, "Solution1.sln");
            var newSolution  = !File.Exists(solutionFile);

            if (newSolution)
            {
                File.WriteAllText(solutionFile, "");
            }

            var info = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), solutionFile);

            var workspace = new AdhocWorkspace();

            workspace.AddSolution(info);

            var solution = workspace.CurrentSolution;

            if (newSolution)
            {
                var projectFile = Path.Combine(Path.GetDirectoryName(solutionFile), "Project1.csproj");
                File.WriteAllText(projectFile, "");
                solution = solution.AddProject(ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Project1", "Project1", LanguageNames.CSharp,
                                                                  filePath: nullPaths ? null : projectFile));
                var project = solution.Projects.Single();

                var documentFile = Path.Combine(Path.GetDirectoryName(projectFile), "Document1.cs");
                File.WriteAllText(documentFile, "");
                solution = solution.AddDocument(DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "Document1",
                                                                    filePath: nullPaths ? null : documentFile));
            }

            return(solution);
        }
Exemple #26
0
        private void LoadSolution(string path)
        {
            Logger.Log("loading solution: " + path);
            string dir = Path.GetDirectoryName(path);

            SolutionId   solutionId   = SolutionId.CreateNewId();
            VersionStamp version      = VersionStamp.Create();
            SolutionInfo solutionInfo = SolutionInfo.Create(solutionId, version, path);

            solution = workspace.AddSolution(solutionInfo);

            using (FileStream file = File.OpenRead(path))
            {
                using StreamReader reader = new StreamReader(file);
                while (reader.EndOfStream == false)
                {
                    string line = reader.ReadLine();
                    if (line.StartsWith("Project"))
                    {
                        string pattern = @"^Project\(""\{.+?\}""\) = ""(\w+?)"", ""(.+?)"", ""\{(.+?)\}""";
                        Match  match   = Regex.Match(line, pattern);

                        string projectName = match.Groups[1].Value;
                        string projectPath = Path.Combine(dir, match.Groups[2].Value);
                        string projectGuid = match.Groups[3].Value;

                        LoadProject(projectName, projectPath, ProjectId.CreateFromSerialized(Guid.Parse(projectGuid)));
                    }
                }
            }

            Logger.Log("");
        }
        public void TestRemoteWorkspaceCircularReferences()
        {
            using (var tempRoot = new Microsoft.CodeAnalysis.Test.Utilities.TempRoot())
            {
                var file = tempRoot.CreateDirectory().CreateFile("p1.dll");
                file.CopyContentFrom(typeof(object).Assembly.Location);

                var p1 = ProjectId.CreateNewId();
                var p2 = ProjectId.CreateNewId();

                var solutionInfo = SolutionInfo.Create(
                    SolutionId.CreateNewId(), VersionStamp.Create(), "",
                    new[]
                {
                    ProjectInfo.Create(
                        p1, VersionStamp.Create(), "p1", "p1", LanguageNames.CSharp, outputFilePath: file.Path,
                        projectReferences: new [] { new ProjectReference(p2) }),
                    ProjectInfo.Create(
                        p2, VersionStamp.Create(), "p2", "p2", LanguageNames.CSharp,
                        metadataReferences: new [] { MetadataReference.CreateFromFile(file.Path) })
                });

                var remoteWorkspace = new RemoteWorkspace(workspaceKind: "test");

                // this shouldn't throw exception
                remoteWorkspace.TryAddSolutionIfPossible(solutionInfo, workspaceVersion: 1, out var solution);
                Assert.NotNull(solution);
            }
        }
Exemple #28
0
        public void TestP2PReference()
        {
            var workspace = new AdhocWorkspace();

            var project1     = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "proj1", "proj1", LanguageNames.CSharp);
            var project2     = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "proj2", "proj2", LanguageNames.CSharp, projectReferences: SpecializedCollections.SingletonEnumerable(new ProjectReference(project1.Id)));
            var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default, projects: new ProjectInfo[] { project1, project2 });

            var solution = workspace.AddSolution(solutionInfo);

            var instance = new object();
            var weak     = new WeakReference(instance);

            var cacheService = new ProjectCacheService(workspace, int.MaxValue);

            using (var cache = cacheService.EnableCaching(project2.Id))
            {
                cacheService.CacheObjectIfCachingEnabledForKey(project1.Id, (object)null, instance);
                instance = null;
                solution = null;

                workspace.OnProjectRemoved(project1.Id);
                workspace.OnProjectRemoved(project2.Id);
            }

            // make sure p2p reference doesn't go to implicit cache
            CollectGarbage();
            Assert.False(weak.IsAlive);
        }
Exemple #29
0
        private static SolutionInfo GetInitialSolutionInfo(TestWorkspace workspace)
        {
            var projectId1 = ProjectId.CreateNewId();
            var projectId2 = ProjectId.CreateNewId();

            return(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
                                       projects: new[]
            {
                ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
                                   documents: new[]
                {
                    DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1"),
                    DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D2"),
                    DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D3"),
                    DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D4"),
                    DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D5")
                }),
                ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp,
                                   documents: new[]
                {
                    DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D1"),
                    DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2"),
                    DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D3"),
                    DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D4"),
                    DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D5")
                })
            }));
        }
Exemple #30
0
        protected static Project CreateProject(string[] sources, string language = LanguageNames.CSharp)
        {
            string fileNamePrefix = DefaultFilePathPrefix;
            string fileExt        = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;

            var solutionId = SolutionId.CreateNewId("TestSolution");
            var projectId  = ProjectId.CreateNewId(debugName: TestProjectName);

            var solution = new CustomWorkspace(solutionId)
                           .CurrentSolution
                           .AddProject(projectId, TestProjectName, TestProjectName, language)
                           .AddMetadataReference(projectId, CorlibReference)
                           .AddMetadataReference(projectId, CSharpSymbolsReference)
                           .AddMetadataReference(projectId, TestBase.SystemRef);

            int count = 0;

            foreach (var source in sources)
            {
                var newFileName = fileNamePrefix + count + "." + fileExt;
                var documentId  = DocumentId.CreateNewId(projectId, debugName: newFileName);
                solution = solution.AddDocument(documentId, newFileName, SourceText.From(source));
                count++;
            }

            return(solution.GetProject(projectId));
        }