コード例 #1
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();
        }
コード例 #2
0
        public async Task Init(SolutionModel solutionModel)
        {
            IList <ProjectInfo> projectInfos = new List <ProjectInfo>(solutionModel.Projects.Count);

            foreach (var projectModel in solutionModel.Projects)
            {
                var projectId          = ProjectId.CreateFromSerialized(projectModel.Id);
                var documentInfos      = new List <DocumentInfo>(projectModel.Documents.Count);
                var projectReferences  = new List <ProjectReference>(projectModel.ProjectToProjectReferences.Count);
                var metadataReferences = new List <MetadataReference>(projectModel.ProjectAssemblyReferences.Count);

                foreach (var documentModel in projectModel.Documents)
                {
                    documentInfos.Add(DocumentInfo.Create(DocumentId.CreateNewId(projectId), documentModel.Name, null, SourceCodeKind.Regular, null, documentModel.Path));
                }
                foreach (var projectReference in projectModel.ProjectToProjectReferences)
                {
                    projectReferences.Add(new ProjectReference(ProjectId.CreateFromSerialized(projectReference.Id)));
                }
                foreach (var projectAssemblyReference in projectModel.ProjectAssemblyReferences)
                {
                    metadataReferences.Add(MetadataReference.CreateFromFile(projectAssemblyReference.LibraryPath));
                }

                var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Default, projectModel.Name,
                                                     projectModel.AssemblyName, LanguageNames.CSharp, projectModel.FilePath, null, null, null,
                                                     documentInfos, projectReferences, metadataReferences, null);
                projectInfos.Add(projectInfo);
            }
            _adhocWorkspace.AddSolution(SolutionInfo.Create(SolutionId.CreateFromSerialized(solutionModel.Id),
                                                            VersionStamp.Default, solutionModel.FilePath, projectInfos));
        }
コード例 #3
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());
        }
コード例 #4
0
ファイル: SolutionSizeTests.cs プロジェクト: khm1600/CJing
        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);
        }
コード例 #5
0
        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);
        }
コード例 #6
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("");
        }
コード例 #7
0
        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"));
                }
            }
        }
コード例 #8
0
        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());
        }
コード例 #9
0
        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();
        }
コード例 #10
0
 private Solution DummySolution()
 {
     using (var ws = new AdhocWorkspace())
     {
         return(ws.AddSolution(InitializeWorkspace(ProjectId.CreateNewId(), "temp.cs", "class temp{}", LanguageNames.CSharp)));
     }
 }
コード例 #11
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;
            }
        }
コード例 #12
0
 protected void Init()
 {
     try
     {
         Workspace = new AdhocWorkspace();
         Workspace.AddSolution(SolutionInfo.Create(MSSolutionID.CreateNewId(), VersionStamp.Default));
         References = new List <string>(DefaultReferences);
     }
     catch (ReflectionTypeLoadException ex)
     {
         StringBuilder sb = new StringBuilder();
         foreach (Exception exSub in ex.LoaderExceptions)
         {
             sb.AppendLine(exSub.Message);
             if (exSub is FileNotFoundException exFileNotFound)
             {
                 if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                 {
                     sb.AppendLine("Fusion Log:");
                     sb.AppendLine(exFileNotFound.FusionLog);
                 }
             }
             sb.AppendLine();
         }
         string errorMessage = sb.ToString();
         //Display or log the error based on your application.
         throw;
     }
 }
コード例 #13
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);
        }
コード例 #14
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);
        }
コード例 #15
0
        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 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());
        }
コード例 #17
0
        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();
        }
コード例 #18
0
        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);
            }
        }
コード例 #19
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);
        }
コード例 #20
0
        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>();
        }
コード例 #21
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();
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: jmarolf/WorkspaceLoadTest
            private static Workspace CreateWorkspaceFromCommandlineArgs(CommandLineArguments[] commandlines)
            {
                var workspace = new AdhocWorkspace();

                workspace.AddSolution(CreateSolutionInfo(commandlines));
                return(workspace);
            }
コード例 #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 {}}");
        }
コード例 #24
0
        static ScriptComplierEngine()
        {
            _workSpace = new AdhocWorkspace();
            _workSpace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId("formatter"), VersionStamp.Default));

            NSucceed.Enabled = false;
            NWarning.Enabled = false;
        }
コード例 #25
0
        private async Task <Solution> GetSolutionAsync(IRemotableDataService service, PinnedRemotableDataScope syncScope)
        {
            var(solutionInfo, _) = await SolutionInfoCreator.CreateSolutionInfoAndOptionsAsync(new AssetProvider(service), syncScope.SolutionChecksum, CancellationToken.None).ConfigureAwait(false);

            var workspace = new AdhocWorkspace();

            return(workspace.AddSolution(solutionInfo));
        }
コード例 #26
0
        private void Given_a_solution_with_projects_and_classes()
        {
            _workspace = new AdhocWorkspace();
            var si = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default);

            _workspace.AddSolution(si);
            _sln = _workspace.CurrentSolution;
        }
コード例 #27
0
        public async Task ShouldCheckForInterfaceMembers()
        {
            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 interface Foo
                    {
                        Bar DoStuff();
                    }

                    internal class Baz 
                    {
                        public Fizz { get; set; }
                    }

                    public class Fizz {}

                    public class Bar 
                    {
                       public int Prop { get; set; }
                    }
                }
            ");

            workspace.AddDocument(libProject.Id, "Lib.cs", sourceText);
            var uiProject = workspace.AddProject(ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "UI", "UI", LanguageNames.CSharp,
                                                                    projectReferences: new [] { new ProjectReference(libProject.Id) }));

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

                namespace UI
                {
                    public static class Program 
                    {
                        public static void Main(string[] args)
                        {
                            Foo foo = null;
                        }
                    }
                }
            ");
            workspace.AddDocument(uiProject.Id, "UI.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());
        }
コード例 #28
0
        public async Task InternalsVisibleToTest()
        {
            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;
                using System.Runtime.CompilerServices;
                
                [assembly: InternalsVisibleTo(""UI"")]
                namespace Lib 
                {
                    public class Foo 
                    {
                        public int Prop { get; set; }
                    }

                    public class Bar 
                    {
                       public int Prop { get; set; }
                    }
                }
            ");

            workspace.AddDocument(libProject.Id, "Lib.cs", sourceText);
            var uiProject = workspace.AddProject(ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "UI", "UI", LanguageNames.CSharp,
                                                                    projectReferences: new [] { new ProjectReference(libProject.Id) }));

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

                namespace UI
                {
                    public static class Program 
                    {
                        public static void Main(string[] args)
                        {
                            var foo = new Foo();
                            foo.Prop = 1;
                        }
                    }
                }
            ");
            workspace.AddDocument(uiProject.Id, "UI.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());


            Assert.AreEqual("Bar", internalSymbols.OrderBy(s => s.Name).First().Name);
            Assert.AreEqual("Foo", internalSymbols.OrderBy(s => s.Name).Last().Name);
        }
コード例 #29
0
        public Solution CreateSolution()
        {
            var workspace = new AdhocWorkspace();
            var solution  = workspace.AddSolution(SolutionInfo.Create(
                                                      SolutionId.CreateNewId(),
                                                      VersionStamp.Default
                                                      ));

            return(solution);
        }
コード例 #30
0
    static async Task Main(string[] args)
    {
        var projectPath = "/Users/wk/Source/DotNetCodeFix/tests/MyApp/MyApp.csproj";
        var manager     = new AnalyzerManager();
        var project     = manager.GetProject(projectPath);
        var sources     = project.GetSourceFiles();

        var workspace     = new AdhocWorkspace();
        var roslynProject = project.AddToWorkspace(workspace, true);

        CancellationTokenSource cts = new CancellationTokenSource();

        var analyzers = GetAllAnalyzers();

        Console.WriteLine($"{string.Join(", ", analyzers.Select(x => x.GetType().Name))}");

        var codeFixers = GetAllCodeFixers().SelectMany(x => x.Value).Distinct();

        Console.WriteLine($"{string.Join(", ", codeFixers.Select(x => x.GetType().Name))}");

        var equivalenceGroups = new List <CodeFixEquivalenceGroup>();
        var diagnostics       = await GetAnalyzerDiagnosticsAsync(roslynProject, analyzers, cts.Token).ConfigureAwait(true);

        var empty    = new AdhocWorkspace();
        var solution = empty.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(DateTime.Now), "/Users/wk/Temp/MyApp.sln"));

        foreach (var codeFixer in codeFixers)
        {
            //Console.WriteLine($"{codeFixer.GetFixAllProvider().GetType().Name}");
            equivalenceGroups.AddRange(await CodeFixEquivalenceGroup.CreateAsync(codeFixer, diagnostics, solution, cts.Token).ConfigureAwait(true));
        }

        var stopwatch = new Stopwatch();


        foreach (var fix in equivalenceGroups)
        {
            try {
                stopwatch.Restart();
                Console.WriteLine($"Calculating fix for {fix.CodeFixEquivalenceKey} using {fix.FixAllProvider} for {fix.NumberOfDiagnostics} instances.");
                var rs = await fix.GetOperationsAsync(cts.Token).ConfigureAwait(true);

                foreach (var item in rs)
                {
                    Console.WriteLine($"Apply {item.Title}");
                    item.Apply(empty, cts.Token);
                }
                WriteLine($"Calculating changes completed in {stopwatch.ElapsedMilliseconds}ms. This is {fix.NumberOfDiagnostics / stopwatch.Elapsed.TotalSeconds:0.000} instances/second.", ConsoleColor.Yellow);
            } catch (Exception ex) {
                // Report thrown exceptions
                WriteLine($"The fix '{fix.CodeFixEquivalenceKey}' threw an exception after {stopwatch.ElapsedMilliseconds}ms:", ConsoleColor.Yellow);
                WriteLine(ex.ToString(), ConsoleColor.Yellow);
            }
        }
    }
コード例 #31
0
        private async Task<Solution> GetSolutionAsync(ISolutionSynchronizationService service, PinnedRemotableDataScope syncScope)
        {
            var workspace = new AdhocWorkspace();

            var solutionObject = await service.GetValueAsync<SolutionStateChecksums>(syncScope.SolutionChecksum);
            var solutionInfo = await service.GetValueAsync<SolutionInfo.SolutionAttributes>(solutionObject.Info).ConfigureAwait(false);

            var projects = new List<ProjectInfo>();
            foreach (var projectObject in solutionObject.Projects.ToProjectObjects(service))
            {
                var projectInfo = await service.GetValueAsync<ProjectInfo.ProjectAttributes>(projectObject.Info).ConfigureAwait(false);
                if (!workspace.Services.IsSupported(projectInfo.Language))
                {
                    continue;
                }

                var documents = new List<DocumentInfo>();
                foreach (var documentObject in projectObject.Documents.ToDocumentObjects(service))
                {
                    var documentInfo = await service.GetValueAsync<DocumentInfo.DocumentAttributes>(documentObject.Info).ConfigureAwait(false);
                    var text = await service.GetValueAsync<SourceText>(documentObject.Text).ConfigureAwait(false);

                    // TODO: do we need version?
                    documents.Add(
                        DocumentInfo.Create(
                            documentInfo.Id,
                            documentInfo.Name,
                            documentInfo.Folders,
                            documentInfo.SourceCodeKind,
                            TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create())),
                            documentInfo.FilePath,
                            documentInfo.IsGenerated));
                }

                var p2p = new List<ProjectReference>();
                foreach (var checksum in projectObject.ProjectReferences)
                {
                    var reference = await service.GetValueAsync<ProjectReference>(checksum).ConfigureAwait(false);
                    p2p.Add(reference);
                }

                var metadata = new List<MetadataReference>();
                foreach (var checksum in projectObject.MetadataReferences)
                {
                    var reference = await service.GetValueAsync<MetadataReference>(checksum).ConfigureAwait(false);
                    metadata.Add(reference);
                }

                var analyzers = new List<AnalyzerReference>();
                foreach (var checksum in projectObject.AnalyzerReferences)
                {
                    var reference = await service.GetValueAsync<AnalyzerReference>(checksum).ConfigureAwait(false);
                    analyzers.Add(reference);
                }

                var additionals = new List<DocumentInfo>();
                foreach (var documentObject in projectObject.AdditionalDocuments.ToDocumentObjects(service))
                {
                    var documentInfo = await service.GetValueAsync<DocumentInfo.DocumentAttributes>(documentObject.Info).ConfigureAwait(false);
                    var text = await service.GetValueAsync<SourceText>(documentObject.Text).ConfigureAwait(false);

                    // TODO: do we need version?
                    additionals.Add(
                        DocumentInfo.Create(
                            documentInfo.Id,
                            documentInfo.Name,
                            documentInfo.Folders,
                            documentInfo.SourceCodeKind,
                            TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create())),
                            documentInfo.FilePath,
                            documentInfo.IsGenerated));
                }

                var compilationOptions = await service.GetValueAsync<CompilationOptions>(projectObject.CompilationOptions).ConfigureAwait(false);
                var parseOptions = await service.GetValueAsync<ParseOptions>(projectObject.ParseOptions).ConfigureAwait(false);

                projects.Add(
                    ProjectInfo.Create(
                        projectInfo.Id, projectInfo.Version, projectInfo.Name, projectInfo.AssemblyName,
                        projectInfo.Language, projectInfo.FilePath, projectInfo.OutputFilePath,
                        compilationOptions, parseOptions,
                        documents, p2p, metadata, analyzers, additionals, projectInfo.IsSubmission));
            }

            return workspace.AddSolution(SolutionInfo.Create(solutionInfo.Id, solutionInfo.Version, solutionInfo.FilePath, projects));
        }
コード例 #32
0
ファイル: SolutionService.cs プロジェクト: natidea/roslyn
        private async Task<Solution> CreateSolutionAsync(Checksum solutionChecksum, CancellationToken cancellationToken)
        {
            var solutionChecksumObject = await RoslynServices.AssetService.GetAssetAsync<SolutionChecksumObject>(solutionChecksum, cancellationToken).ConfigureAwait(false);

            // TODO: Make these to do work concurrently
            var workspace = new AdhocWorkspace(RoslynServices.HostServices);
            var solutionInfo = await RoslynServices.AssetService.GetAssetAsync<SolutionChecksumObjectInfo>(solutionChecksumObject.Info, cancellationToken).ConfigureAwait(false);

            var projects = new List<ProjectInfo>();
            foreach (var projectChecksum in solutionChecksumObject.Projects)
            {
                var projectSnapshot = await RoslynServices.AssetService.GetAssetAsync<ProjectChecksumObject>(projectChecksum, cancellationToken).ConfigureAwait(false);

                var documents = new List<DocumentInfo>();
                foreach (var documentChecksum in projectSnapshot.Documents)
                {
                    var documentSnapshot = await RoslynServices.AssetService.GetAssetAsync<DocumentChecksumObject>(documentChecksum, cancellationToken).ConfigureAwait(false);

                    var documentInfo = await RoslynServices.AssetService.GetAssetAsync<DocumentChecksumObjectInfo>(documentSnapshot.Info, cancellationToken).ConfigureAwait(false);

                    // TODO: do we need version?
                    documents.Add(
                        DocumentInfo.Create(
                            documentInfo.Id,
                            documentInfo.Name,
                            documentInfo.Folders,
                            documentInfo.SourceCodeKind,
                            new RemoteTextLoader(documentSnapshot.Text),
                            documentInfo.FilePath,
                            documentInfo.IsGenerated));
                }

                var p2p = new List<ProjectReference>();
                foreach (var checksum in projectSnapshot.ProjectReferences)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var reference = await RoslynServices.AssetService.GetAssetAsync<ProjectReference>(checksum, cancellationToken).ConfigureAwait(false);
                    p2p.Add(reference);
                }

                var metadata = new List<MetadataReference>();
                foreach (var checksum in projectSnapshot.MetadataReferences)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var reference = await RoslynServices.AssetService.GetAssetAsync<MetadataReference>(checksum, cancellationToken).ConfigureAwait(false);
                    metadata.Add(reference);
                }

                var analyzers = new List<AnalyzerReference>();
                foreach (var checksum in projectSnapshot.AnalyzerReferences)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var reference = await RoslynServices.AssetService.GetAssetAsync<AnalyzerReference>(checksum, cancellationToken).ConfigureAwait(false);
                    analyzers.Add(reference);
                }

                var additionals = new List<DocumentInfo>();
                foreach (var documentChecksum in projectSnapshot.AdditionalDocuments)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var documentSnapshot = await RoslynServices.AssetService.GetAssetAsync<DocumentChecksumObject>(documentChecksum, cancellationToken).ConfigureAwait(false);

                    var documentInfo = await RoslynServices.AssetService.GetAssetAsync<DocumentChecksumObjectInfo>(documentSnapshot.Info, cancellationToken).ConfigureAwait(false);

                    // TODO: do we need version?
                    additionals.Add(
                        DocumentInfo.Create(
                            documentInfo.Id,
                            documentInfo.Name,
                            documentInfo.Folders,
                            documentInfo.SourceCodeKind,
                            new RemoteTextLoader(documentSnapshot.Text),
                            documentInfo.FilePath,
                            documentInfo.IsGenerated));
                }

                var projectInfo = await RoslynServices.AssetService.GetAssetAsync<ProjectChecksumObjectInfo>(projectSnapshot.Info, cancellationToken).ConfigureAwait(false);
                var compilationOptions = await RoslynServices.AssetService.GetAssetAsync<CompilationOptions>(projectSnapshot.CompilationOptions, cancellationToken).ConfigureAwait(false);
                var parseOptions = await RoslynServices.AssetService.GetAssetAsync<ParseOptions>(projectSnapshot.ParseOptions, cancellationToken).ConfigureAwait(false);

                projects.Add(
                    ProjectInfo.Create(
                        projectInfo.Id, projectInfo.Version, projectInfo.Name, projectInfo.AssemblyName,
                        projectInfo.Language, projectInfo.FilePath, projectInfo.OutputFilePath,
                        compilationOptions, parseOptions,
                        documents, p2p, metadata, analyzers, additionals));
            }

            return workspace.AddSolution(SolutionInfo.Create(solutionInfo.Id, solutionInfo.Version, solutionInfo.FilePath, projects));
        }
コード例 #33
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 doesnt go to implicit cache
            CollectGarbage();
            Assert.False(weak.IsAlive);

        }
コード例 #34
0
ファイル: SolutionSizeTests.cs プロジェクト: GloryChou/roslyn
        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;
        }
コード例 #35
0
        private Solution CreateOrOpenSolution()
        {
            string solutionFile = Path.Combine(_persistentFolder, "Solution1.sln");
            bool newSolution;
            if (newSolution = !File.Exists(solutionFile))
            {
                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)
            {
                string projectFile = Path.Combine(Path.GetDirectoryName(solutionFile), "Project1.csproj");
                File.WriteAllText(projectFile, "");
                solution = solution.AddProject(ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Project1", "Project1", LanguageNames.CSharp, projectFile));
                var project = solution.Projects.Single();

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

            return solution;
        }
コード例 #36
0
ファイル: SolutionService.cs プロジェクト: genlu/roslyn
        private async Task<Solution> CreateSolutionAsync(Checksum solutionChecksum, CancellationToken cancellationToken)
        {
            // synchronize whole solution first
            await _assetService.SynchronizeSolutionAssetsAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);

            var solutionChecksumObject = await _assetService.GetAssetAsync<SolutionStateChecksums>(solutionChecksum, cancellationToken).ConfigureAwait(false);

            var workspace = new AdhocWorkspace(RoslynServices.HostServices, workspaceKind: WorkspaceKind_RemoteWorkspace);
            var solutionInfo = await _assetService.GetAssetAsync<SolutionInfo.SolutionAttributes>(solutionChecksumObject.Info, cancellationToken).ConfigureAwait(false);

            var projects = new List<ProjectInfo>();
            foreach (var projectChecksum in solutionChecksumObject.Projects)
            {
                var projectSnapshot = await _assetService.GetAssetAsync<ProjectStateChecksums>(projectChecksum, cancellationToken).ConfigureAwait(false);
                var projectInfo = await _assetService.GetAssetAsync<ProjectInfo.ProjectAttributes>(projectSnapshot.Info, cancellationToken).ConfigureAwait(false);
                if (!workspace.Services.IsSupported(projectInfo.Language))
                {
                    // only add project our workspace supports. 
                    // workspace doesn't allow creating project with unknown languages
                    continue;
                }

                var documents = new List<DocumentInfo>();
                foreach (var documentChecksum in projectSnapshot.Documents)
                {
                    var documentSnapshot = await _assetService.GetAssetAsync<DocumentStateChecksums>(documentChecksum, cancellationToken).ConfigureAwait(false);
                    var documentInfo = await _assetService.GetAssetAsync<DocumentInfo.DocumentAttributes>(documentSnapshot.Info, cancellationToken).ConfigureAwait(false);

                    var textLoader = TextLoader.From(
                        TextAndVersion.Create(
                            new ChecksumSourceText(
                                documentSnapshot.Text,
                                await _assetService.GetAssetAsync<SourceText>(documentSnapshot.Text, cancellationToken).ConfigureAwait(false)),
                            VersionStamp.Create(),
                            documentInfo.FilePath));

                    // TODO: do we need version?
                    documents.Add(
                        DocumentInfo.Create(
                            documentInfo.Id,
                            documentInfo.Name,
                            documentInfo.Folders,
                            documentInfo.SourceCodeKind,
                            textLoader,
                            documentInfo.FilePath,
                            documentInfo.IsGenerated));
                }

                var p2p = new List<ProjectReference>();
                foreach (var checksum in projectSnapshot.ProjectReferences)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var reference = await _assetService.GetAssetAsync<ProjectReference>(checksum, cancellationToken).ConfigureAwait(false);
                    p2p.Add(reference);
                }

                var metadata = new List<MetadataReference>();
                foreach (var checksum in projectSnapshot.MetadataReferences)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var reference = await _assetService.GetAssetAsync<MetadataReference>(checksum, cancellationToken).ConfigureAwait(false);
                    metadata.Add(reference);
                }

                var analyzers = new List<AnalyzerReference>();
                foreach (var checksum in projectSnapshot.AnalyzerReferences)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var reference = await _assetService.GetAssetAsync<AnalyzerReference>(checksum, cancellationToken).ConfigureAwait(false);
                    analyzers.Add(reference);
                }

                var additionals = new List<DocumentInfo>();
                foreach (var documentChecksum in projectSnapshot.AdditionalDocuments)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var documentSnapshot = await _assetService.GetAssetAsync<DocumentStateChecksums>(documentChecksum, cancellationToken).ConfigureAwait(false);
                    var documentInfo = await _assetService.GetAssetAsync<DocumentInfo.DocumentAttributes>(documentSnapshot.Info, cancellationToken).ConfigureAwait(false);

                    var textLoader = TextLoader.From(
                        TextAndVersion.Create(
                            new ChecksumSourceText(
                                documentSnapshot.Text,
                            await _assetService.GetAssetAsync<SourceText>(documentSnapshot.Text, cancellationToken).ConfigureAwait(false)),
                            VersionStamp.Create(),
                            documentInfo.FilePath));

                    // TODO: do we need version?
                    additionals.Add(
                        DocumentInfo.Create(
                            documentInfo.Id,
                            documentInfo.Name,
                            documentInfo.Folders,
                            documentInfo.SourceCodeKind,
                            textLoader,
                            documentInfo.FilePath,
                            documentInfo.IsGenerated));
                }

                var compilationOptions = await _assetService.GetAssetAsync<CompilationOptions>(projectSnapshot.CompilationOptions, cancellationToken).ConfigureAwait(false);
                var parseOptions = await _assetService.GetAssetAsync<ParseOptions>(projectSnapshot.ParseOptions, cancellationToken).ConfigureAwait(false);

                projects.Add(
                    ProjectInfo.Create(
                        projectInfo.Id, projectInfo.Version, projectInfo.Name, projectInfo.AssemblyName,
                        projectInfo.Language, projectInfo.FilePath, projectInfo.OutputFilePath,
                        compilationOptions, parseOptions,
                        documents, p2p, metadata, analyzers, additionals, projectInfo.IsSubmission));
            }

            return workspace.AddSolution(SolutionInfo.Create(solutionInfo.Id, solutionInfo.Version, solutionInfo.FilePath, projects));
        }
コード例 #37
0
        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);
            }
        }
コード例 #38
0
        private async Task<Solution> GetSolutionAsync(ISolutionChecksumService service, ChecksumScope snapshot)
        {
            var workspace = new AdhocWorkspace();

            var solutionInfo = await GetValueAsync<SolutionChecksumObjectInfo>(service, snapshot.SolutionChecksum.Info, WellKnownChecksumObjects.SolutionChecksumObjectInfo).ConfigureAwait(false);

            var projects = new List<ProjectInfo>();
            foreach (var projectSnapshot in snapshot.SolutionChecksum.Projects.ToProjectObjects(service))
            {
                var documents = new List<DocumentInfo>();
                foreach (var documentSnapshot in projectSnapshot.Documents.ToDocumentObjects(service))
                {
                    var documentInfo = await GetValueAsync<DocumentChecksumObjectInfo>(service, documentSnapshot.Info, WellKnownChecksumObjects.DocumentChecksumObjectInfo).ConfigureAwait(false);
                    var text = await GetValueAsync<SourceText>(service, documentSnapshot.Text, WellKnownChecksumObjects.SourceText).ConfigureAwait(false);

                    // TODO: do we need version?
                    documents.Add(
                        DocumentInfo.Create(
                            documentInfo.Id,
                            documentInfo.Name,
                            documentInfo.Folders,
                            documentInfo.SourceCodeKind,
                            TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create())),
                            documentInfo.FilePath,
                            documentInfo.IsGenerated));
                }

                var p2p = new List<ProjectReference>();
                foreach (var checksum in projectSnapshot.ProjectReferences)
                {
                    var reference = await GetValueAsync<ProjectReference>(service, checksum, WellKnownChecksumObjects.ProjectReference).ConfigureAwait(false);
                    p2p.Add(reference);
                }
                var metadata = new List<MetadataReference>();
                foreach (var checksum in projectSnapshot.MetadataReferences)
                {
                    var reference = await GetValueAsync<MetadataReference>(service, checksum, WellKnownChecksumObjects.MetadataReference).ConfigureAwait(false);
                    metadata.Add(reference);
                }

                var analyzers = new List<AnalyzerReference>();
                foreach (var checksum in projectSnapshot.AnalyzerReferences)
                {
                    var reference = await GetValueAsync<AnalyzerReference>(service, checksum, WellKnownChecksumObjects.AnalyzerReference).ConfigureAwait(false);
                    analyzers.Add(reference);
                }

                var additionals = new List<DocumentInfo>();
                foreach (var documentSnapshot in projectSnapshot.AdditionalDocuments.ToDocumentObjects(service))
                {
                    var documentInfo = await GetValueAsync<DocumentChecksumObjectInfo>(service, documentSnapshot.Info, WellKnownChecksumObjects.DocumentChecksumObjectInfo).ConfigureAwait(false);
                    var text = await GetValueAsync<SourceText>(service, documentSnapshot.Text, WellKnownChecksumObjects.SourceText).ConfigureAwait(false);

                    // TODO: do we need version?
                    additionals.Add(
                        DocumentInfo.Create(
                            documentInfo.Id,
                            documentInfo.Name,
                            documentInfo.Folders,
                            documentInfo.SourceCodeKind,
                            TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create())),
                            documentInfo.FilePath,
                            documentInfo.IsGenerated));
                }

                var projectInfo = await GetValueAsync<ProjectChecksumObjectInfo>(service, projectSnapshot.Info, WellKnownChecksumObjects.ProjectChecksumObjectInfo).ConfigureAwait(false);
                var compilationOptions = await GetValueAsync<CompilationOptions>(service, projectSnapshot.CompilationOptions, WellKnownChecksumObjects.CompilationOptions).ConfigureAwait(false);
                var parseOptions = await GetValueAsync<ParseOptions>(service, projectSnapshot.ParseOptions, WellKnownChecksumObjects.ParseOptions).ConfigureAwait(false);

                projects.Add(
                    ProjectInfo.Create(
                        projectInfo.Id, projectInfo.Version, projectInfo.Name, projectInfo.AssemblyName,
                        projectInfo.Language, projectInfo.FilePath, projectInfo.OutputFilePath,
                        compilationOptions, parseOptions,
                        documents, p2p, metadata, analyzers, additionals));
            }

            return workspace.AddSolution(SolutionInfo.Create(solutionInfo.Id, solutionInfo.Version, solutionInfo.FilePath, projects));
        }