public async Task CheckPEReferencesSameAfterSolutionChangedTest()
        {
            using (var ws = new AdhocWorkspace())
            {
                var projectInfo = ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    VersionStamp.Create(),
                    "TestProject",
                    "TestProject",
                    LanguageNames.CSharp,
                    metadataReferences: ImmutableArray.Create<MetadataReference>(PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location)));

                var project = ws.AddProject(projectInfo);

                // get original references
                var compilation1 = await project.GetCompilationAsync();
                var references1 = compilation1.ExternalReferences;

                // just some arbitary action to create new snpahost that doesnt affect references
                var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "code.cs");
                var document = ws.AddDocument(info);

                // get new compilation
                var compilation2 = await document.Project.GetCompilationAsync();
                var references2 = compilation2.ExternalReferences;

                Assert.Equal(references1, references2);
            }
        }
 public void TestAddProject_NameAndLanguage()
 {
     using (var ws = new AdhocWorkspace())
     {
         var project = ws.AddProject("TestProject", LanguageNames.CSharp);
         Assert.Same(project, ws.CurrentSolution.Projects.FirstOrDefault());
         Assert.Equal("TestProject", project.Name);
         Assert.Equal(LanguageNames.CSharp, project.Language);
     }
 }
        public async Task CreateSolutionSnapshotId_Project_Serialization()
        {
            var solution = new AdhocWorkspace().CurrentSolution;
            var project = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp);

            var snapshotService = (new SolutionChecksumServiceFactory()).CreateService(solution.Workspace.Services) as ISolutionChecksumService;
            using (var snapshot = await snapshotService.CreateChecksumAsync(project.Solution, CancellationToken.None).ConfigureAwait(false))
            {
                await VerifySnapshotSerializationAsync(snapshotService, solution, snapshot.SolutionChecksum).ConfigureAwait(false);
            }
        }
        public void AcquireCompletionService()
        {
            var workspace = new AdhocWorkspace();

            var document = workspace
                .AddProject("TestProject", LanguageNames.CSharp)
                .AddDocument("TestDocument.cs", "");

            var service = CompletionService.GetService(document);
            Assert.NotNull(service);
        }
        public void TestAddDocument_DocumentInfo()
        {
            using (var ws = new AdhocWorkspace())
            {
                var project = ws.AddProject("TestProject", LanguageNames.CSharp);
                var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "code.cs");
                var doc = ws.AddDocument(info);

                Assert.Equal(ws.CurrentSolution.GetDocument(info.Id), doc);
                Assert.Equal(info.Name, doc.Name);
            }
        }
Beispiel #6
0
        public async Task CheckCrossLanguageReferencesSameAfterSolutionChangedTest()
        {
            using var ws = new AdhocWorkspace();
            var referenceInfo = ProjectInfo.Create(
                ProjectId.CreateNewId(),
                VersionStamp.Create(),
                "ReferenceProject",
                "ReferenceProject",
                LanguageNames.VisualBasic,
                metadataReferences: ImmutableArray.Create <MetadataReference>(PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location)));

            var referenceProject = ws.AddProject(referenceInfo);

            var projectInfo = ProjectInfo.Create(
                ProjectId.CreateNewId(),
                VersionStamp.Create(),
                "TestProject",
                "TestProject",
                LanguageNames.CSharp,
                projectReferences: ImmutableArray.Create <ProjectReference>(new ProjectReference(referenceInfo.Id)),
                metadataReferences: ImmutableArray.Create <MetadataReference>(PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location)));

            var project = ws.AddProject(projectInfo);

            // get original references
            var compilation1 = await project.GetCompilationAsync();

            var references1 = compilation1.ExternalReferences;

            // just some arbitrary action to create new snpahost that doesnt affect references
            var info     = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "code.cs");
            var document = ws.AddDocument(info);

            // get new compilation
            var compilation2 = await document.Project.GetCompilationAsync();

            var references2 = compilation2.ExternalReferences;

            Assert.Equal(references1, references2);
        }
        public async Task UpdaterService()
        {
            var hostServices = s_composition.GetHostServices();

            using var workspace = new AdhocWorkspace(hostServices);

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

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

            var listenerProvider = (
                (IMefHostExportProvider)hostServices
                ).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, change document
            workspace.AddSolution(
                SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default)
                );
            var project  = workspace.AddProject("proj", LanguageNames.CSharp);
            var document = workspace.AddDocument(project.Id, "doc.cs", SourceText.From("code"));

            workspace.ApplyTextChanges(
                document.Id,
                new[] { new TextChange(new TextSpan(0, 1), "abc") },
                CancellationToken.None
                );

            // 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();
        }
Beispiel #8
0
        public void LinkedFiles()
        {
            // We want to assert that if the open document is linked into multiple projects, we
            // update all documents at the same time with the changed text. Otherwise things will get
            // out of sync.
            var exportProvider = TestExportProvider.MinimumExportProviderFactoryWithCSharpAndVisualBasic.CreateExportProvider();

            using var workspace = new AdhocWorkspace();
            var textBufferFactoryService = exportProvider.GetExportedValue <ITextBufferFactoryService>();
            var buffer = textBufferFactoryService.CreateTextBuffer("Hello", textBufferFactoryService.TextContentType);
            var sourceTextContainer = buffer.AsTextContainer();

            // We're going to add two projects that both consume the same file
            const string FilePath    = "Z:\\Foo.cs";
            var          documentIds = new List <DocumentId>();

            for (var i = 0; i < 2; i++)
            {
                var projectId  = workspace.AddProject($"Project{i}", LanguageNames.CSharp).Id;
                var documentId = DocumentId.CreateNewId(projectId);
                workspace.AddDocument(DocumentInfo.Create(documentId, "Foo.cs", filePath: FilePath));
                workspace.OnDocumentOpened(documentId, sourceTextContainer);

                documentIds.Add(documentId);
            }

            // Confirm the files have been linked by file path. This isn't the core part of this test but without it
            // nothing else will work.
            Assert.Equal(documentIds, workspace.CurrentSolution.GetDocumentIdsWithFilePath(FilePath));
            Assert.Equal(new[] { documentIds.Last() }, workspace.CurrentSolution.GetDocument(documentIds.First()).GetLinkedDocumentIds());

            // Now the core test: first, if we make a modified version of the source text, and attempt to get the document for it,
            // both copies should be updated.
            var originalSnapshot = buffer.CurrentSnapshot;

            buffer.Insert(5, ", World!");

            var newDocumentWithChanges = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();

            // Since we're calling this on the current snapshot and we observed the text edit synchronously,
            // no forking actually should have happened.
            Assert.Same(workspace.CurrentSolution, newDocumentWithChanges.Project.Solution);
            Assert.Equal("Hello, World!", newDocumentWithChanges.GetTextSynchronously(CancellationToken.None).ToString());
            Assert.Equal("Hello, World!", newDocumentWithChanges.GetLinkedDocuments().Single().GetTextSynchronously(CancellationToken.None).ToString());

            // Now let's fetch back for the original snapshot. Both linked copies should be updated.
            var originalDocumentWithChanges = originalSnapshot.GetOpenDocumentInCurrentContextWithChanges();

            Assert.NotSame(workspace.CurrentSolution, originalDocumentWithChanges.Project.Solution);
            Assert.Equal("Hello", originalDocumentWithChanges.GetTextSynchronously(CancellationToken.None).ToString());
            Assert.Equal("Hello", originalDocumentWithChanges.GetLinkedDocuments().Single().GetTextSynchronously(CancellationToken.None).ToString());
        }
        public static Workspace Create(string text, string language = LanguageNames.CSharp)
        {
            var workspace = new AdhocWorkspace();

            var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "TestProject", "TestProject", language,
                                                 filePath: "D:\\Test.proj",
                                                 metadataReferences: new[] { s_corlibReference, s_systemCoreReference, s_systemReference });
            Project project = workspace.AddProject(projectInfo);

            workspace.AddDocument(project.Id, "TestDocument", SourceText.From(text));

            return(workspace);
        }
Beispiel #10
0
        private async Task HighlightCSharpishAsync(RichTextBox rtf, string code)
        {
            code = code.Replace("\r\n", "\n");

            var ws     = new AdhocWorkspace();
            var proj   = ws.AddProject("Adhoc", "C#");
            var doc    = proj.AddDocument("decompiled.cs", code);
            var start  = 0;
            var length = code.Length;
            var res    = await Classifier.GetClassifiedSpansAsync(doc, TextSpan.FromBounds(start, start + length));

            Highlight(rtf, 0, res.ToArray());
        }
Beispiel #11
0
        public static Solution CreateSolution(string file)
        {
            var workspace = new AdhocWorkspace();
            var project   = workspace.AddProject("MethodTest", "C#");

            foreach (var assembly in resolver.AndroidAssemblies)
            {
                project = project.AddMetadataReference(MetadataReference.CreateFromFile(assembly.Location));
            }
            var document = project.AddDocument("Class1.cs", file);

            return(document.Project.Solution);
        }
Beispiel #12
0
        private static Project CreateEmptyProject()
        {
            var solution = new AdhocWorkspace(MefHostServices.Create(MefHostServices.DefaultAssemblies.Add(typeof(NoCompilationConstants).Assembly))).CurrentSolution;

            return(solution.AddProject(
                       ProjectInfo.Create(
                           ProjectId.CreateNewId(),
                           VersionStamp.Default,
                           name: "TestProject",
                           assemblyName: "TestProject",
                           language: LanguageNames.CSharp,
                           parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview))).Projects.Single());
        }
Beispiel #13
0
    private static Document CreateDocument(string filename)
    {
        var workspace    = new AdhocWorkspace();
        var projectId    = ProjectId.CreateNewId();
        var versionStamp = VersionStamp.Create();
        var projectInfo  = ProjectInfo.Create(projectId, versionStamp, "NewProject", "projName", LanguageNames.CSharp);
        var newProject   = workspace.AddProject(projectInfo);
        var sourcePath   = $@"..\..\..\{filename}";
        var source       = File.ReadAllText(sourcePath);
        var sourceText   = SourceText.From(source);

        return(workspace.AddDocument(newProject.Id, filename, sourceText));
    }
Beispiel #14
0
        public TestHelper(string source)
        {
            Workspace = new AdhocWorkspace();

            string projName     = "NewProject";
            var    projectId    = ProjectId.CreateNewId();
            var    versionStamp = VersionStamp.Create();
            var    projectInfo  = ProjectInfo.Create(projectId, versionStamp, projName, projName, LanguageNames.CSharp);
            var    newProject   = Workspace.AddProject(projectInfo);
            var    sourceText   = SourceText.From(source);

            Document = Workspace.AddDocument(newProject.Id, "NewFile.cs", sourceText);
        }
Beispiel #15
0
 public static void InitWorkspace(AdhocWorkspace workspace, string code, int position)
 {
     string projName     = "NewProject";
     var    projectId    = ProjectId.CreateNewId();
     var    versionStamp = VersionStamp.Create();
     var    mscorlib     = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
     var    systemCore   = MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location);
     var    references   = new[] { mscorlib, systemCore };
     var    projectInfo  = ProjectInfo.Create(projectId, versionStamp, projName, projName, LanguageNames.CSharp, metadataReferences: references);
     var    newProject   = workspace.AddProject(projectInfo);
     var    sourceText   = SourceText.From(code);
     var    newDocument  = workspace.AddDocument(newProject.Id, "NewFile.cs", sourceText);
 }
    public static async Task ScanHardcodedFromText(string documentName, string text, Action <SyntaxNodeOrToken, string> scannedFunction)
    {
        if (text == null)
        {
            throw new ArgumentNullException("text");
        }

        AdhocWorkspace ws      = new AdhocWorkspace();
        var            project = ws.AddProject(documentName + "Project", LanguageNames.CSharp);

        ws.AddDocument(project.Id, documentName, SourceText.From(text));
        await ScanHardcoded(ws, scannedFunction);
    }
        public async Task TestAddDocument_NameAndTextAsync()
        {
            using (var ws = new AdhocWorkspace())
            {
                var project = ws.AddProject("TestProject", LanguageNames.CSharp);
                var name    = "code.cs";
                var source  = "class C {}";
                var doc     = ws.AddDocument(project.Id, name, SourceText.From(source));

                Assert.Equal(name, doc.Name);
                Assert.Equal(source, (await doc.GetTextAsync()).ToString());
            }
        }
        public void TestAddDocument_NameAndText()
        {
            using (var ws = new AdhocWorkspace())
            {
                var project = ws.AddProject("TestProject", LanguageNames.CSharp);
                var name = "code.cs";
                var source = "class C {}";
                var doc = ws.AddDocument(project.Id, name, SourceText.From(source));

                Assert.Equal(name, doc.Name);
                Assert.Equal(source, doc.GetTextAsync().Result.ToString());
            }
        }
Beispiel #19
0
        public static (Workspace workspace, Project project) CreateWorkspaceAndProject(string language)
        {
            var workspace = new AdhocWorkspace(ProxyGenerator.CreateHost());
            var project   = workspace.AddProject("code", language)
                            .WithCompilationOptions(language == LanguageNames.CSharp ?
                                                    (CompilationOptions) new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) :
                                                    (CompilationOptions) new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                            .WithMetadataReferences(ReferencePaths.Paths
                                                    .Select(path => MetadataReference.CreateFromFile(path)))
                            .AddMetadataReference(MetadataReference.CreateFromFile(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName));

            return(workspace, project);
        }
Beispiel #20
0
        Microsoft.CodeAnalysis.Document GetAnalysisDocument(string text)
        {
            var workspace = new AdhocWorkspace();

            string projectName  = "TestProject";
            var    projectId    = ProjectId.CreateNewId();
            var    versionStamp = VersionStamp.Create();
            var    projectInfo  = ProjectInfo.Create(projectId, versionStamp, projectName, projectName, LanguageNames.CSharp);
            var    sourceText   = SourceText.From(text);
            var    project      = workspace.AddProject(projectInfo);

            return(workspace.AddDocument(project.Id, "Program.cs", sourceText));
        }
Beispiel #21
0
 private void Given_the_solution_has_projects()
 {
     // TODO: Generate random data.
     _projs = new[] {
         ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "ProjectName", "ProjectName", "C#"),
         ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "ProjectName2", "ProjectName2", "C#")
     };
     foreach (var proj in _projs)
     {
         _workspace.AddProject(proj);
     }
     _sln = _workspace.CurrentSolution;
 }
        private static Document CreateDocumentWithoutText()
        {
            var project = ProjectInfo
                          .Create(ProjectId.CreateNewId(), VersionStamp.Default, "TestProject", "TestAssembly", LanguageNames.CSharp)
                          .WithFilePath("/TestProject.csproj");
            var workspace = new AdhocWorkspace();

            workspace.AddProject(project);
            var documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "Test.cshtml");
            var document     = workspace.AddDocument(documentInfo);

            return(document);
        }
Beispiel #23
0
        public async Task does_not_trigger_completion(string code)
        {
            var hostServices = MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(
                                                          new[]
            {
                typeof(CompletionService).Assembly,
                typeof(ResourceCompletionProvider).Assembly,
            }));

            var workspace = new AdhocWorkspace(hostServices);
            var document  = workspace
                            .AddProject("TestProject", LanguageNames.CSharp)
                            .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                            .WithMetadataReferences(Directory
                                                    .EnumerateFiles("MonoAndroid", "*.dll")
                                                    .Select(dll => MetadataReference.CreateFromFile(dll)))
                            .AddDocument("Resource.designer.cs", @"[assembly: global::Android.Runtime.ResourceDesignerAttribute(""MyApp.Resource"", IsApplication=true)]
namespace MyApp
{
    [System.CodeDom.Compiler.GeneratedCodeAttribute(""Xamarin.Android.Build.Tasks"", ""1.0.0.0"")]
    public partial class Resource
    {
        public partial class String
        {
            public const int app_name = 2130968578;
            public const int app_title = 2130968579;
        }
        public partial class Style
        {
            public const int AppTheme = 2131034114;
        }
    }
}")
                            .Project
                            .AddDocument("TestDocument.cs", code.Replace("`", ""));

            var service = CompletionService.GetService(document);

            Assert.NotNull(service);

            var caret = code.IndexOf('`');

            Assert.NotEqual(-1, caret);

            var completions = await service.GetCompletionsAsync(document, caret);

            if (completions != null)
            {
                Assert.DoesNotContain(completions.Items, x => x.Tags.Contains("Xamarin"));
            }
        }
Beispiel #24
0
        public async Task <CompletionResult> CompleteAsync(string sourceCode, int position, char?triggerChar)
        {
            _CancellationTokenSource?.Cancel();
            _CancellationTokenSource?.Dispose();
            _CancellationTokenSource = new CancellationTokenSource();

            try
            {
                var workspace = new AdhocWorkspace(_Host);

                var projectInfo = ProjectInfo
                                  .Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Project", "Project", LanguageNames.CSharp)
                                  .WithMetadataReferences(new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) });
                var project  = workspace.AddProject(projectInfo);
                var document = workspace.AddDocument(project.Id, "File.cs", SourceText.From(sourceCode));

                var completionService = CompletionService.GetService(document);
                var completionTrigger = GetCompletionTrigger(triggerChar);
                var data = await completionService.GetCompletionsAsync(document, position, completionTrigger, null, null, _CancellationTokenSource.Token)
                           .ConfigureAwait(false);

                if (data == null || data.Items == null)
                {
                    return(new CompletionResult(Array.Empty <CompleteData>()));
                }

                var helper = CompletionHelper.GetHelper(document);
                var text   = await document.GetTextAsync(_CancellationTokenSource.Token).ConfigureAwait(false);

                var textSpanToText = new Dictionary <TextSpan, string>();

                var items =
                    data.Items
                    .Where(item => MatchesFilterText(helper, item, text, textSpanToText))
                    .OrderBy(x => x.DisplayText)
                    .Distinct(x => x.DisplayText)
                    .Select(x =>
                            new CompleteData(
                                x,
                                completionService,
                                document)
                            ).ToArray();

                return(new CompletionResult(items));
            }
            catch (OperationCanceledException)
            {
                return(new CompletionResult(Array.Empty <CompleteData>()));
            }
        }
Beispiel #25
0
        public void InitialiseProject()
        {
            var host = MefHostServices.Create(MefHostServices.DefaultAssemblies);

            Workspace = new AdhocWorkspace(host);
            var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "MyProject",
                                                 "MyProject",
                                                 LanguageNames.CSharp)
                              //isSubmission: true)
                              .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication))
                              .WithMetadataReferences(AssemblyCache.Current.GetAllMetadataReferences());

            Project = Workspace.AddProject(projectInfo);
        }
Beispiel #26
0
        public async Task TestStrongNameProviderEmpty()
        {
            using var workspace       = new AdhocWorkspace();
            using var remoteWorkspace = CreateRemoteWorkspace();

            var filePath = "testLocation";

            workspace.AddProject(
                ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    VersionStamp.Create(),
                    "test",
                    "test.dll",
                    LanguageNames.CSharp,
                    filePath: filePath,
                    outputFilePath: filePath
                    )
                );

            var assetProvider = await GetAssetProviderAsync(
                workspace,
                remoteWorkspace,
                workspace.CurrentSolution
                );

            var solutionChecksum = await workspace.CurrentSolution.State.GetChecksumAsync(
                CancellationToken.None
                );

            var solution = await remoteWorkspace.GetSolutionAsync(
                assetProvider,
                solutionChecksum,
                fromPrimaryBranch : false,
                workspaceVersion : -1,
                CancellationToken.None
                );

            var compilationOptions = solution.Projects.First().CompilationOptions;

            Assert.True(compilationOptions.StrongNameProvider is DesktopStrongNameProvider);
            Assert.True(compilationOptions.XmlReferenceResolver is XmlFileResolver);

            var array = new string[] { };

            Assert.Equal(
                Hash.CombineValues(array, StringComparer.Ordinal),
                compilationOptions.StrongNameProvider.GetHashCode()
                );
            Assert.Null(((XmlFileResolver)compilationOptions.XmlReferenceResolver).BaseDirectory);
        }
Beispiel #27
0
        private Project CreateProject(AdhocWorkspace workspace, List <IDocumentExtender> documentExtenders)
        {
            var projectInfo = CommandLineProject.CreateProjectInfo(CscArgs.OutputFileName, "C#", Environment.CommandLine, _precompilationCommandLineArgs.BaseDirectory, workspace);

            projectInfo = projectInfo
                          .WithCompilationOptions(CscArgs.CompilationOptions
                                                  .WithSourceReferenceResolver(new SourceFileResolver(CscArgs.SourcePaths, CscArgs.BaseDirectory, CscArgs.PathMap))) // required for path mapping support
                          .WithDocuments(
                projectInfo
                .Documents
                .Select(d => documentExtenders.Aggregate(d, (doc, ex) => ex.Extend(doc))));

            return(workspace.AddProject(projectInfo));
        }
Beispiel #28
0
        CreateAdHocLibraryProjectWorkspace(string classFileContets,
                                           params MetadataReference[] references)
        {
            var referencesCopy = references.ToArray();

            var resultWorkspace = new AdhocWorkspace();

            Document document = resultWorkspace
                                .AddProject(ProjectName, LanguageNames.CSharp)
                                .AddMetadataReferences(references)
                                .AddDocument(ClassFileName, classFileContets);

            return(resultWorkspace, document);
        }
Beispiel #29
0
        private Project CreateProject(AdhocWorkspace workspace)
        {
            var projectInfo = CommandLineProject.CreateProjectInfo(CscArgs.OutputFileName, "C#", Environment.CommandLine, _precompilationCommandLineArgs.BaseDirectory, workspace);

            projectInfo = projectInfo
                          .WithDocuments(
                projectInfo
                .Documents
                .Select(d => Path.GetExtension(d.FilePath) == ".cshtml"
                            ? d.WithTextLoader(new RazorParser(this, d.TextLoader, workspace))
                            : d));

            return(workspace.AddProject(projectInfo));
        }
Beispiel #30
0
        private static Document GetDocument(string code)
        {
            var ws           = new AdhocWorkspace();
            var emptyProject = ws.AddProject(
                ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    VersionStamp.Default,
                    "test",
                    "test.dll",
                    LanguageNames.CSharp,
                    metadataReferences: new[] { TestReferences.NetFx.v4_0_30319.mscorlib }));

            return(emptyProject.AddDocument("test.cs", code));
        }
Beispiel #31
0
        public static List <SimplifiedClassificationSpan> GetClassifications(
            string path, Project project, IReadOnlyList <SimplifiedClassificationInfo> infos = null)
        {
            using (var logger = LogManager.GetLogger("Test execution"))
            {
                path = Path.Combine(project.ProjectPath.GetDirectoryName(), path);
                if (!File.Exists(path))
                {
                    logger.Warn("File {0} doesn't exist.", path);
                    return(_empty);
                }

                var compilationUnits = ExtractCompilationUnits(project);

                SemanticModel       semanticModel = null;
                ProgrammingLanguage language      = default;
                foreach (var unit in compilationUnits)
                {
                    var roslynCompilation = unit.Compilation;
                    var syntaxTree        = roslynCompilation.SyntaxTrees.FirstOrDefault(x => x.FilePath.EqualsNoCase(path));
                    if (!(syntaxTree is null))
                    {
                        semanticModel = roslynCompilation.GetSemanticModel(syntaxTree, true);
                        language      = unit.Language;
                        break;
                    }
                }

                if (semanticModel is null)
                {
                    logger.Warn("Project {0} doesn't have the file {1}. Check that it's included.", project.ProjectPath, path);
                    return(_empty);
                }

                List <ClassificationSpan> actualSpans = null;
                // TODO: cache workspaces by project
                using (var workspace = new AdhocWorkspace())
                {
                    var buffer       = new TextBuffer(GetContentType(language), new StringOperand(semanticModel.SyntaxTree.ToString()));
                    var snapshotSpan = new SnapshotSpan(buffer.CurrentSnapshot, 0, buffer.CurrentSnapshot.Length);

                    var newProject  = workspace.AddProject(project.ProjectName, LanguageNames.CSharp);
                    var newDocument = workspace.AddDocument(newProject.Id, Path.GetFileName(path), snapshotSpan.Snapshot.AsText());

                    var classifier = GetClassifier(language, infos);
                    actualSpans = classifier.GetClassificationSpans(workspace, semanticModel, snapshotSpan);
                }
                return(actualSpans.Select(x => new SimplifiedClassificationSpan(x.Span.Span, x.ClassificationType)).ToList());
            }
        }
    public async Task PublicOptions()
    {
        using var workspace = new AdhocWorkspace();
        var csProject  = workspace.AddProject("CS", LanguageNames.CSharp);
        var vbProject  = workspace.AddProject("VB", LanguageNames.VisualBasic);
        var csDocument = workspace.AddDocument(csProject.Id, "File.cs", SourceText.From("class C { }"));
        var vbDocument = workspace.AddDocument(vbProject.Id, "File.vb", SourceText.From("Class C : End Class"));

        var updatedOptions = GetOptionSetWithChangedPublicOptions(workspace.CurrentSolution.Options);

        // Validate that options are read from specified OptionSet:

        ValidateCSharpOptions((CSharpSyntaxFormattingOptions)(await Formatter.GetOptionsAsync(csDocument, updatedOptions, CancellationToken.None)).Syntax !);
        ValidateVisualBasicOptions((VisualBasicSyntaxFormattingOptions)(await Formatter.GetOptionsAsync(vbDocument, updatedOptions, CancellationToken.None)).Syntax !);

        // Validate that options are read from solution snapshot as a fallback (we have no editorconfig file, so all options should fall back):

        var solutionWithUpdatedOptions   = workspace.CurrentSolution.WithOptions(updatedOptions);
        var csDocumentWithUpdatedOptions = solutionWithUpdatedOptions.GetRequiredDocument(csDocument.Id);
        var vbDocumentWithUpdatedOptions = solutionWithUpdatedOptions.GetRequiredDocument(vbDocument.Id);

        ValidateCSharpOptions((CSharpSyntaxFormattingOptions)(await Formatter.GetOptionsAsync(csDocumentWithUpdatedOptions, optionSet: null, CancellationToken.None)).Syntax !);
        ValidateVisualBasicOptions((VisualBasicSyntaxFormattingOptions)(await Formatter.GetOptionsAsync(vbDocumentWithUpdatedOptions, optionSet: null, CancellationToken.None)).Syntax !);
Beispiel #33
0
        public async Task TestGetInteriorSymbolsDoesNotCrashOnSpeculativeSemanticModel()
        {
            var    markup = @"
class C
{
    void foo()
    {
        System.Func<int> lambda = () => 
        {
        int x;
        $$
        }
    }
}";
            int    position;
            string text;

            MarkupTestFile.GetPosition(markup, out text, out position);

            var sourceText = SourceText.From(text);
            var workspace  = new AdhocWorkspace();
            var project    = workspace.AddProject("Test", LanguageNames.CSharp);
            var document   = workspace.AddDocument(project.Id, "testdocument", sourceText);

            var firstModel = await document.GetSemanticModelAsync();

            var tree1 = await document.GetSyntaxTreeAsync();

            var basemethod1 = tree1.FindTokenOnLeftOfPosition(position, CancellationToken.None).GetAncestor <CSharp.Syntax.BaseMethodDeclarationSyntax>();

            // Modify the document so we can use the old semantic model as a base.
            var updated = sourceText.WithChanges(new TextChange(new TextSpan(position, 0), "insertion"));

            workspace.TryApplyChanges(document.WithText(updated).Project.Solution);

            document = workspace.CurrentSolution.GetDocument(document.Id);
            var tree2 = await document.GetSyntaxTreeAsync();

            var basemethod2 = tree2.FindTokenOnLeftOfPosition(position, CancellationToken.None).GetAncestor <CSharp.Syntax.BaseMethodDeclarationSyntax>();

            var           service = new CSharp.CSharpSemanticFactsService();
            SemanticModel testModel;
            var           m = service.TryGetSpeculativeSemanticModel(firstModel, basemethod1, basemethod2, out testModel);

            var xSymbol = testModel.LookupSymbols(position).First(s => s.Name == "x");

            // This should not throw an exception.
            Assert.NotNull(SymbolKey.Create(xSymbol));
        }
        static ValidateHelper()
        {
            //we have to build the trees of namespaces and classes for easy access for searching
            var host = MefHostServices.Create(MefHostServices.DefaultAssemblies);

            workspace = new AdhocWorkspace(host);

            /*
             * var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "MyProject", "MyProject", LanguageNames.CSharp);
             * var project = workspace.AddProject(projectInfo);
             * var document = workspace.AddDocument(project.Id, "MyFile.cs", SourceText.From(""));
             */


            //var scriptCode = "Guid.N";

            var compilationOptions = new CSharpCompilationOptions(
                OutputKind.DynamicallyLinkedLibrary,
                usings: new[] { "System", "System.Collections.Generic", "System.Text" });

            var scriptProjectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Script", "Script", LanguageNames.CSharp, isSubmission: false)
                                    .WithMetadataReferences(new[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
            })
                                    .WithCompilationOptions(compilationOptions);

            var scriptProject = workspace.AddProject(scriptProjectInfo);

            project = scriptProject.Id;

            /*
             * scriptDocumentInfo = DocumentInfo.Create(
             *  DocumentId.CreateNewId(scriptProject.Id), "Script",
             *  sourceCodeKind: SourceCodeKind.Script,
             *  loader: TextLoader.From(TextAndVersion.Create(SourceText.From(scriptCode), VersionStamp.Create())));
             * scriptDocument = workspace.AddDocument(scriptDocumentInfo);
             */


            // cursor position is at the end
            //var position = scriptCode.Length - 1;

            //var completionService = CompletionService.GetService(scriptDocument);

            //service = CompletionService.GetService(scriptDocument);

            //var results = await completionService.GetCompletionsAsync(scriptDocument, position);
        }
Beispiel #35
0
        static void Main(string[] args)
        {
#if DEBUG
            args = new string[] { Directory.GetParent(Directory.GetParent(Directory.GetParent(Environment.CurrentDirectory).FullName).FullName).FullName };
            args = new string[] { @"C:\Users\DvdKhl\Source\Repos\AVDump3" };
#endif

            if (args.Length != 1 || !Directory.Exists(args[0]))
            {
                Console.WriteLine(args.Length == 1 ? "Directory not found" : "Argumentcount needs to be 1");
                return;
            }

            var basePath = args[0];
            if (basePath.EndsWith(Path.DirectorySeparatorChar.ToString()) || basePath.EndsWith(Path.AltDirectorySeparatorChar.ToString()))
            {
                basePath = basePath.Substring(0, basePath.Length - 1);
            }

            foreach (var filePath in Directory.EnumerateFiles(basePath, "*.cs", SearchOption.AllDirectories))
            {
                var fileContent = File.ReadAllText(filePath);

                AdhocWorkspace workspace = new AdhocWorkspace();
                Project        project   = workspace.AddProject(nameof(NamespaceDirectorySync), LanguageNames.CSharp);
                Document       document  = project.AddDocument(Path.GetFileName(filePath), SourceText.From(fileContent));
                var            tree      = document.GetSyntaxTreeAsync().Result;

                var namespaces = tree.GetRoot().DescendantNodes().OfType <NamespaceDeclarationSyntax>().ToArray();

                if (namespaces.Length != 1)
                {
                    continue;
                }

                var destNamespace = Path.GetDirectoryName(filePath).Substring(basePath.Length)
                                    .Replace(Path.DirectorySeparatorChar, '.').Replace(Path.AltDirectorySeparatorChar, '.');

                if (destNamespace.StartsWith("."))
                {
                    destNamespace = destNamespace.Substring(1);
                }

                fileContent = fileContent.Remove(namespaces[0].Name.SpanStart, namespaces[0].Name.Span.Length).Insert(namespaces[0].Name.SpanStart, destNamespace);

                Console.WriteLine(filePath);
                File.WriteAllText(filePath, fileContent);
            }
        }
Beispiel #36
0
        /// <summary>
        /// Create a project using the inputted strings as sources.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source code is in</param>
        /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param>
        /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param>
        /// <returns>A Project created out of the Douments created from the source strings</returns>
        public static Project CreateProject(string[] sources,
                                            string language,
                                            LanguageVersion languageVersionCSharp,
                                            Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB)
        {
            var          fileNamePrefix = DefaultFilePathPrefix;
            string       fileExt;
            ParseOptions parseOptions;

            if (language == LanguageNames.CSharp)
            {
                fileExt      = CSharpDefaultFileExt;
                parseOptions = new CSharpParseOptions(languageVersionCSharp);
            }
            else
            {
                fileExt      = VisualBasicDefaultExt;
                parseOptions = new Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions(languageVersionVB);
            }

            var projectId = ProjectId.CreateNewId(debugName: TestProjectName);

#pragma warning disable CC0022
            var workspace = new AdhocWorkspace();
#pragma warning restore CC0022

            var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Create(), TestProjectName,
                                                 TestProjectName, language,
                                                 parseOptions: parseOptions,
                                                 metadataReferences: ImmutableList.Create(
                                                     CorlibReference, SystemCoreReference, RegexReference,
                                                     CSharpSymbolsReference, CodeAnalysisReference, JsonNetReference));

            workspace.AddProject(projectInfo);

            var count = 0;
            foreach (var source in sources)
            {
                var newFileName = fileNamePrefix + count + "." + fileExt;
                workspace.AddDocument(projectId, newFileName, SourceText.From(source));
                count++;
            }

            var project = workspace.CurrentSolution.GetProject(projectId);
            var newCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(diagOptions);
            var newSolution           = workspace.CurrentSolution.WithProjectCompilationOptions(projectId, newCompilationOptions);
            var newProject            = newSolution.GetProject(projectId);
            return(newProject);
        }
Beispiel #37
0
        private Solution GetSolution(params string[] sources)
        {
            var ws = new AdhocWorkspace();
            var pid = ProjectId.CreateNewId();

            var docs = sources.Select((s, i) =>
                DocumentInfo.Create(
                    DocumentId.CreateNewId(pid),
                    name: "code" + i,
                    loader: TextLoader.From(TextAndVersion.Create(SourceText.From(s), VersionStamp.Default)))).ToList();

            var proj = ProjectInfo.Create(pid, VersionStamp.Default, "test", "test.dll", LanguageNames.CSharp, documents: docs,
                metadataReferences: new[] { TestReferences.NetFx.v4_0_30319.mscorlib });

            return ws.AddProject(proj).Solution;
        }
        public async Task CreateSolutionSnapshotId_Project()
        {
            var solution = new AdhocWorkspace().CurrentSolution;
            var project = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp);

            var snapshotService = (new SolutionChecksumServiceFactory()).CreateService(solution.Workspace.Services) as ISolutionChecksumService;
            using (var snapshot = await snapshotService.CreateChecksumAsync(project.Solution, CancellationToken.None).ConfigureAwait(false))
            {
                var solutionId = snapshot.SolutionChecksum;
                VerifyChecksumObjectInService(snapshotService, solutionId);
                VerifyChecksumInService(snapshotService, solutionId.Info, WellKnownChecksumObjects.SolutionChecksumObjectInfo);
                VerifyChecksumObjectInService(snapshotService, solutionId.Projects);

                Assert.Equal(solutionId.Projects.Count, 1);
                VerifySnapshotInService(snapshotService, solutionId.Projects.ToProjectObjects(snapshotService)[0], 0, 0, 0, 0, 0);
            }
        }
        public void TestAddProject_ProjectInfo()
        {
            var info = ProjectInfo.Create(
                ProjectId.CreateNewId(),
                version: VersionStamp.Default,
                name: "TestProject",
                assemblyName: "TestProject.dll",
                language: LanguageNames.CSharp);

            using (var ws = new AdhocWorkspace())
            {
                var project = ws.AddProject(info);
                Assert.Equal(project, ws.CurrentSolution.Projects.FirstOrDefault());
                Assert.Equal(info.Name, project.Name);
                Assert.Equal(info.Id, project.Id);
                Assert.Equal(info.AssemblyName, project.AssemblyName);
                Assert.Equal(info.Language, project.Language);
            }
        }
        public void AcquireCompletionService()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Concat(
                    new[]
                    {
                        typeof(CompletionService).Assembly,
                        typeof(CSharpCompletionService).Assembly
                    }));

            var workspace = new AdhocWorkspace(hostServices);

            var document = workspace
                .AddProject("TestProject", LanguageNames.CSharp)
                .AddDocument("TestDocument.cs", "");

            var service = CompletionService.GetService(document);
            Assert.NotNull(service);
        }
        public void TestUpdatedDocumentHasTextVersion()
        {
            var pid = ProjectId.CreateNewId();
            var text = SourceText.From("public class C { }");
            var version = VersionStamp.Create();
            var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version)));
            var projInfo = ProjectInfo.Create(
                pid,
                version: VersionStamp.Default,
                name: "TestProject",
                assemblyName: "TestProject.dll",
                language: LanguageNames.CSharp,
                documents: new[] { docInfo });

            using (var ws = new AdhocWorkspace())
            {
                ws.AddProject(projInfo);

                SourceText currentText;
                VersionStamp currentVersion;

                var doc = ws.CurrentSolution.GetDocument(docInfo.Id);
                Assert.Equal(false, doc.TryGetText(out currentText));
                Assert.Equal(false, doc.TryGetTextVersion(out currentVersion));

                // cause text to load and show that TryGet now works for text and version
                currentText = doc.GetTextAsync().Result;
                Assert.Equal(true, doc.TryGetText(out currentText));
                Assert.Equal(true, doc.TryGetTextVersion(out currentVersion));
                Assert.Equal(version, currentVersion);

                // change document
                var root = doc.GetSyntaxRootAsync().Result;
                var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation());
                Assert.NotSame(root, newRoot);
                var newDoc = doc.WithSyntaxRoot(newRoot);
                Assert.NotSame(doc, newDoc);

                // text is now unavailable since it must be constructed from tree
                Assert.Equal(false, newDoc.TryGetText(out currentText));

                // version is available because it is cached
                Assert.Equal(true, newDoc.TryGetTextVersion(out currentVersion));

                // access it the hard way
                var actualVersion = newDoc.GetTextVersionAsync().Result;

                // version is the same 
                Assert.Equal(currentVersion, actualVersion);

                // accessing text version did not cause text to be constructed.
                Assert.Equal(false, newDoc.TryGetText(out currentText));

                // now access text directly (force it to be constructed)
                var actualText = newDoc.GetTextAsync().Result;
                actualVersion = newDoc.GetTextVersionAsync().Result;

                // prove constructing text did not introduce a new version
                Assert.Equal(currentVersion, actualVersion);
            }
        }
Beispiel #42
0
        private static Document CreateDocument(string code, string language)
        {
            var solution = new AdhocWorkspace().CurrentSolution;
            var projectId = ProjectId.CreateNewId();
            var project = solution.AddProject(projectId, "Project", "Project.dll", language).GetProject(projectId);

            return project.AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib)
                          .AddDocument("Document", SourceText.From(code));
        }
        public async Task TestUpdateCSharpLanguageVersionAsync()
        {
            using (var ws = new AdhocWorkspace())
            {
                var projid = ws.AddProject("TestProject", LanguageNames.CSharp).Id;
                var docid1 = ws.AddDocument(projid, "A.cs", SourceText.From("public class A { }")).Id;
                var docid2 = ws.AddDocument(projid, "B.cs", SourceText.From("public class B { }")).Id;

                var pws = new WorkspaceWithPartialSemantics(ws.CurrentSolution);
                var proj = pws.CurrentSolution.GetProject(projid);
                var comp = await proj.GetCompilationAsync();

                // change language version
                var parseOptions = proj.ParseOptions as CS.CSharpParseOptions;
                pws.SetParseOptions(projid, parseOptions.WithLanguageVersion(CS.LanguageVersion.CSharp3));

                // get partial semantics doc
                var frozen = await pws.CurrentSolution.GetDocument(docid1).WithFrozenPartialSemanticsAsync(CancellationToken.None);
            }
        }
        public async Task TestOpenFileOnlyAnalyzerDiagnostics()
        {
            var workspace = new AdhocWorkspace();

            var project = workspace.AddProject(
                           ProjectInfo.Create(
                               ProjectId.CreateNewId(),
                               VersionStamp.Create(),
                               "CSharpProject",
                               "CSharpProject",
                               LanguageNames.CSharp));

            var document = workspace.AddDocument(project.Id, "Empty.cs", SourceText.From(""));

            // create listener/service/analyzer
            var listener = new AsynchronousOperationListener();
            var service = new MyDiagnosticAnalyzerService(new OpenFileOnlyAnalyzer(), listener);
            var analyzer = service.CreateIncrementalAnalyzer(workspace);

            // listen to events
            service.DiagnosticsUpdated += (s, a) =>
            {
                if (workspace.IsDocumentOpen(a.DocumentId))
                {
                    // check the diagnostics are reported
                    Assert.Equal(document.Id, a.DocumentId);
                    Assert.Equal(1, a.Diagnostics.Length);
                    Assert.Equal(OpenFileOnlyAnalyzer.s_syntaxRule.Id, a.Diagnostics[0].Id);
                }

                if (a.DocumentId == document.Id && !workspace.IsDocumentOpen(a.DocumentId))
                {
                    // check the diagnostics reported are cleared
                    Assert.Equal(0, a.Diagnostics.Length);
                }
            };

            // open document
            workspace.OpenDocument(document.Id);
            await analyzer.DocumentOpenAsync(document, CancellationToken.None).ConfigureAwait(false);

            // cause analysis
            await RunAllAnalysisAsync(analyzer, document).ConfigureAwait(false);

            // close document
            workspace.CloseDocument(document.Id);
            await analyzer.DocumentCloseAsync(document, CancellationToken.None).ConfigureAwait(false);

            await RunAllAnalysisAsync(analyzer, document).ConfigureAwait(false);

            // wait for all events to raised
            await listener.CreateWaitTask().ConfigureAwait(false);
        }
 private Document GetDocument(string code)
 {
     var ws = new AdhocWorkspace();
     var project = ws.AddProject("project", LanguageNames.CSharp);
     return project.AddDocument("code", SourceText.From(code));
 }
        public void TestOpenCloseAdditionalDocument()
        {
            var pid = ProjectId.CreateNewId();
            var text = SourceText.From("public class C { }");
            var version = VersionStamp.Create();
            var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version)));
            var projInfo = ProjectInfo.Create(
                pid,
                version: VersionStamp.Default,
                name: "TestProject",
                assemblyName: "TestProject.dll",
                language: LanguageNames.CSharp,
                additionalDocuments: new[] { docInfo });

            using (var ws = new AdhocWorkspace())
            {
                ws.AddProject(projInfo);

                SourceText currentText;
                VersionStamp currentVersion;

                var doc = ws.CurrentSolution.GetAdditionalDocument(docInfo.Id);
                Assert.Equal(false, doc.TryGetText(out currentText));

                ws.OpenAdditionalDocument(docInfo.Id);

                doc = ws.CurrentSolution.GetAdditionalDocument(docInfo.Id);
                Assert.Equal(true, doc.TryGetText(out currentText));
                Assert.Equal(true, doc.TryGetTextVersion(out currentVersion));
                Assert.Same(text, currentText);
                Assert.Equal(version, currentVersion);

                ws.CloseAdditionalDocument(docInfo.Id);

                doc = ws.CurrentSolution.GetAdditionalDocument(docInfo.Id);
                Assert.Equal(false, doc.TryGetText(out currentText));
            }
        }
        public void TestRemoveProject_TryApplyChanges()
        {
            var pid = ProjectId.CreateNewId();
            var info = ProjectInfo.Create(
                pid,
                version: VersionStamp.Default,
                name: "TestProject",
                assemblyName: "TestProject.dll",
                language: LanguageNames.CSharp);

            using (var ws = new AdhocWorkspace())
            {
                ws.AddProject(info);

                Assert.Equal(1, ws.CurrentSolution.Projects.Count());

                var newSolution = ws.CurrentSolution.RemoveProject(pid);
                Assert.Equal(0, newSolution.Projects.Count());

                var result = ws.TryApplyChanges(newSolution);
                Assert.Equal(true, result);

                Assert.Equal(0, ws.CurrentSolution.Projects.Count());
            }
        }
        private static Document GetDocumentFromIncompleteProject(AdhocWorkspace workspace)
        {
            var project = workspace.AddProject(
                            ProjectInfo.Create(
                                ProjectId.CreateNewId(),
                                VersionStamp.Create(),
                                "CSharpProject",
                                "CSharpProject",
                                LanguageNames.CSharp).WithHasAllInformation(hasAllInformation: false));

            return workspace.AddDocument(project.Id, "Empty.cs", SourceText.From(""));
        }
        public async Task SnapshotWithMissingReferencesTest()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Add(typeof(Host.TemporaryStorageServiceFactory.TemporaryStorageService).Assembly));

            var solution = new AdhocWorkspace(hostServices).CurrentSolution;
            var project1 = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp);

            var metadata = new MissingMetadataReference();
            var analyzer = new AnalyzerFileReference("missing_reference", new MissingAnalyzerLoader());

            project1 = project1.AddMetadataReference(metadata);
            project1 = project1.AddAnalyzerReference(analyzer);

            var snapshotService = (new SolutionChecksumServiceFactory()).CreateService(solution.Workspace.Services) as ISolutionChecksumService;
            using (var snapshot = await snapshotService.CreateChecksumAsync(project1.Solution, CancellationToken.None).ConfigureAwait(false))
            {
                // this shouldn't throw
                var recovered = await GetSolutionAsync(snapshotService, snapshot).ConfigureAwait(false);
            }
        }
        public async Task UnknownLanguageTest()
        {
            var hostServices = MefHostServices.Create(MefHostServices.DefaultAssemblies.Add(typeof(NullLanguageService).Assembly));

            var solution = new AdhocWorkspace(hostServices).CurrentSolution;

            var project1 = solution.AddProject("Project", "Project.dll", NullLanguageService.TestLanguage);

            var snapshotService = (new SolutionChecksumServiceFactory()).CreateService(solution.Workspace.Services) as ISolutionChecksumService;
            using (var snapshot = await snapshotService.CreateChecksumAsync(project1.Solution, CancellationToken.None).ConfigureAwait(false))
            {
                // this shouldn't throw
                var recovered = await GetSolutionAsync(snapshotService, snapshot).ConfigureAwait(false);
            }
        }
        public async Task CheckPEReferencesNotSameAfterReferenceChangedTest()
        {
            using (var ws = new AdhocWorkspace())
            {
                var projectInfo = ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    VersionStamp.Create(),
                    "TestProject",
                    "TestProject",
                    LanguageNames.CSharp,
                    metadataReferences: ImmutableArray.Create<MetadataReference>(PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location)));

                var project = ws.AddProject(projectInfo);

                // get original references
                var compilation1 = await project.GetCompilationAsync();
                var references1 = compilation1.ExternalReferences;

                // explicitly change references
                var forkedProject = project.WithMetadataReferences(ImmutableArray.Create<MetadataReference>(
                    PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location),
                    PortableExecutableReference.CreateFromFile(typeof(Workspace).Assembly.Location)));

                // get new compilation
                var compilation2 = await forkedProject.GetCompilationAsync();
                var references2 = compilation2.ExternalReferences;

                Assert.NotEqual(references1, references2);
            }
        }
        public void TestAddProject_CommandLineProject()
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());

            string commandLine = @"CSharpClass.cs /out:foo.dll /target:library";
            var baseDirectory = Path.Combine(this.SolutionDirectory.Path, "CSharpProject");

            using (var ws = new AdhocWorkspace())
            {
                var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, baseDirectory);
                ws.AddProject(info);
                var project = ws.CurrentSolution.GetProject(info.Id);

                Assert.Equal("TestProject", project.Name);
                Assert.Equal("foo", project.AssemblyName);
                Assert.Equal(OutputKind.DynamicallyLinkedLibrary, project.CompilationOptions.OutputKind);

                Assert.Equal(1, project.Documents.Count());

                var fooDoc = project.Documents.First(d => d.Name == "CSharpClass.cs");
                Assert.Equal(0, fooDoc.Folders.Count);
                var expectedPath = Path.Combine(baseDirectory, "CSharpClass.cs");
                Assert.Equal(expectedPath, fooDoc.FilePath);

                var text = fooDoc.GetTextAsync().Result.ToString();
                Assert.NotEqual("", text);

                var tree = fooDoc.GetSyntaxRootAsync().Result;
                Assert.Equal(false, tree.ContainsDiagnostics);

                var compilation = project.GetCompilationAsync().Result;
            }
        }
        public void CheckUpdatedDocumentTextIsObservablyConstant(AdhocWorkspace ws)
        {
            var pid = ProjectId.CreateNewId();
            var text = SourceText.From("public class C { }");
            var version = VersionStamp.Create();
            var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version)));
            var projInfo = ProjectInfo.Create(
                pid,
                version: VersionStamp.Default,
                name: "TestProject",
                assemblyName: "TestProject.dll",
                language: LanguageNames.CSharp,
                documents: new[] { docInfo });

            ws.AddProject(projInfo);
            var doc = ws.CurrentSolution.GetDocument(docInfo.Id);

            // change document
            var root = doc.GetSyntaxRootAsync().Result;
            var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation());
            Assert.NotSame(root, newRoot);
            var newDoc = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot).GetDocument(doc.Id);
            Assert.NotSame(doc, newDoc);

            var newDocText = newDoc.GetTextAsync().Result;
            var sameText = newDoc.GetTextAsync().Result;
            Assert.Same(newDocText, sameText);

            var newDocTree = newDoc.GetSyntaxTreeAsync().Result;
            var treeText = newDocTree.GetText();
            Assert.Same(newDocText, treeText);
        }
        public async Task ExtractMethod_Argument2()
        {
            var solution = new AdhocWorkspace().CurrentSolution;
            var projectId = ProjectId.CreateNewId();
            var project = solution.AddProject(projectId, "Project", "Project.dll", LanguageNames.CSharp).GetProject(projectId);

            var document = project.AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib)
                                  .AddDocument("Document", SourceText.From(""));

            var service = new CSharpExtractMethodService() as IExtractMethodService;

            await service.ExtractMethodAsync(document, default(TextSpan));
        }