MSBuildWorkspaceTests.cs 186.6 KB
Newer Older
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
P
Pilchie 已提交
2 3 4

using System;
using System.Collections.Generic;
M
Matt Warren 已提交
5
using System.Collections.Immutable;
P
Pilchie 已提交
6 7
using System.IO;
using System.Linq;
8
using System.Reflection;
9
using System.Text;
P
Pilchie 已提交
10
using System.Threading;
11
using System.Threading.Tasks;
12
using System.Xml.Linq;
13
using Microsoft.CodeAnalysis.Diagnostics;
14 15
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
16
using Microsoft.CodeAnalysis.MSBuild.Build;
P
Pilchie 已提交
17 18
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
19
using Microsoft.CodeAnalysis.UnitTests;
20
using Microsoft.CodeAnalysis.UnitTests.TestFiles;
P
Pilchie 已提交
21 22 23
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
24
using static Microsoft.CodeAnalysis.MSBuild.UnitTests.SolutionGeneration;
P
Pilchie 已提交
25 26 27
using CS = Microsoft.CodeAnalysis.CSharp;
using VB = Microsoft.CodeAnalysis.VisualBasic;

28
namespace Microsoft.CodeAnalysis.MSBuild.UnitTests
P
Pilchie 已提交
29
{
30
    public class MSBuildWorkspaceTests : MSBuildWorkspaceTestBase
P
Pilchie 已提交
31
    {
32
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
33
        public void TestCreateMSBuildWorkspace()
P
Pilchie 已提交
34
        {
35 36 37 38 39 40 41 42 43 44 45
            using (var workspace = CreateMSBuildWorkspace())
            {
                Assert.NotNull(workspace);
                Assert.NotNull(workspace.Services);
                Assert.NotNull(workspace.Services.Workspace);
                Assert.Equal(workspace, workspace.Services.Workspace);
                Assert.NotNull(workspace.Services.HostServices);
                Assert.NotNull(workspace.Services.PersistentStorage);
                Assert.NotNull(workspace.Services.TemporaryStorage);
                Assert.NotNull(workspace.Services.TextFactory);
            }
P
Pilchie 已提交
46 47
        }

48
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
49
        public async Task TestOpenSolution_SingleProjectSolution()
P
Pilchie 已提交
50 51
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
52
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
53

54 55 56 57 58 59 60 61
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = solution.Projects.First();
                var document = project.Documents.First();
                var tree = await document.GetSyntaxTreeAsync();
                var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent;
                Assert.NotNull(type);
D
Dustin Campbell 已提交
62
                Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal);
63
            }
P
Pilchie 已提交
64 65
        }

66
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
67
        public async Task TestOpenSolution_MultiProjectSolution()
P
Pilchie 已提交
68 69
        {
            CreateFiles(GetMultiProjectSolutionFiles());
70
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
71

72 73 74 75
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var vbProject = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic);
P
Pilchie 已提交
76

77 78 79 80
                // verify the dependent project has the correct metadata references (and does not include the output for the project references)
                var references = vbProject.MetadataReferences.ToList();
                Assert.Equal(4, references.Count);
                var fileNames = new HashSet<string>(references.Select(r => Path.GetFileName(((PortableExecutableReference)r).FilePath)));
D
Dustin Campbell 已提交
81 82 83 84
                Assert.Contains("System.Core.dll", fileNames);
                Assert.Contains("System.dll", fileNames);
                Assert.Contains("Microsoft.VisualBasic.dll", fileNames);
                Assert.Contains("mscorlib.dll", fileNames);
85 86 87 88 89 90

                // the compilation references should have the metadata reference to the csharp project skeleton assembly
                var compilation = await vbProject.GetCompilationAsync();
                var compReferences = compilation.References.ToList();
                Assert.Equal(5, compReferences.Count);
            }
P
Pilchie 已提交
91 92
        }

93
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
94
        [WorkItem(2824, "https://github.com/dotnet/roslyn/issues/2824")]
95
        public async Task Test_OpenProjectReferencingPortableProject()
96
        {
97
            var files = new FileSet(
98 99 100 101
                (@"CSharpProject\ReferencesPortableProject.csproj", Resources.ProjectFiles.CSharp.ReferencesPortableProject),
                (@"CSharpProject\Program.cs", Resources.SourceFiles.CSharp.CSharpClass),
                (@"CSharpProject\PortableProject.csproj", Resources.ProjectFiles.CSharp.PortableProject),
                (@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass));
102 103 104

            CreateFiles(files);

105 106 107 108 109 110 111 112
            var projectFilePath = GetSolutionFileName(@"CSharpProject\ReferencesPortableProject.csproj");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                var hasFacades = project.MetadataReferences.OfType<PortableExecutableReference>().Any(r => r.FilePath.Contains("Facade"));
                Assert.True(hasFacades);
            }
113 114
        }

115
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
116
        public async Task Test_SharedMetadataReferences()
117 118
        {
            CreateFiles(GetMultiProjectSolutionFiles());
119
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
120

121 122 123 124 125
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var p0 = solution.Projects.ElementAt(0);
                var p1 = solution.Projects.ElementAt(1);
126

127
                Assert.NotSame(p0, p1);
128

129 130
                var p0mscorlib = GetMetadataReference(p0, "mscorlib");
                var p1mscorlib = GetMetadataReference(p1, "mscorlib");
131

132 133
                Assert.NotNull(p0mscorlib);
                Assert.NotNull(p1mscorlib);
134

135 136 137
                // metadata references to mscorlib in both projects are the same
                Assert.Same(p0mscorlib, p1mscorlib);
            }
138 139
        }

140
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
141 142
        [WorkItem(546171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546171")]
        public async Task Test_SharedMetadataReferencesWithAliases()
143 144 145
        {
            var projPath1 = @"CSharpProject\CSharpProject_ExternAlias.csproj";
            var projPath2 = @"CSharpProject\CSharpProject_ExternAlias2.csproj";
146

147
            var files = new FileSet(
148 149 150
                (projPath1, Resources.ProjectFiles.CSharp.ExternAlias),
                (projPath2, Resources.ProjectFiles.CSharp.ExternAlias2),
                (@"CSharpProject\CSharpExternAlias.cs", Resources.SourceFiles.CSharp.CSharpExternAlias));
151 152 153

            CreateFiles(files);

154 155 156
            var fullPath1 = GetSolutionFileName(projPath1);
            var fullPath2 = GetSolutionFileName(projPath2);
            using (var workspace = CreateMSBuildWorkspace())
157
            {
158 159
                var proj1 = await workspace.OpenProjectAsync(fullPath1);
                var proj2 = await workspace.OpenProjectAsync(fullPath2);
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188

                var p1Sys1 = GetMetadataReferenceByAlias(proj1, "Sys1");
                var p1Sys2 = GetMetadataReferenceByAlias(proj1, "Sys2");
                var p2Sys1 = GetMetadataReferenceByAlias(proj2, "Sys1");
                var p2Sys3 = GetMetadataReferenceByAlias(proj2, "Sys3");

                Assert.NotNull(p1Sys1);
                Assert.NotNull(p1Sys2);
                Assert.NotNull(p2Sys1);
                Assert.NotNull(p2Sys3);

                // same filepath but different alias so they are not the same instance
                Assert.NotSame(p1Sys1, p1Sys2);
                Assert.NotSame(p2Sys1, p2Sys3);

                // same filepath and alias so they are the same instance
                Assert.Same(p1Sys1, p2Sys1);

                var mdp1Sys1 = GetMetadata(p1Sys1);
                var mdp1Sys2 = GetMetadata(p1Sys2);
                var mdp2Sys1 = GetMetadata(p2Sys1);
                var mdp2Sys3 = GetMetadata(p2Sys1);

                Assert.NotNull(mdp1Sys1);
                Assert.NotNull(mdp1Sys2);
                Assert.NotNull(mdp2Sys1);
                Assert.NotNull(mdp2Sys3);

                // all references to System.dll share the same metadata bytes
189 190 191
                Assert.Same(mdp1Sys1.Id, mdp1Sys2.Id);
                Assert.Same(mdp1Sys1.Id, mdp2Sys1.Id);
                Assert.Same(mdp1Sys1.Id, mdp2Sys3.Id);
192 193 194
            }
        }

195 196 197 198 199 200 201 202 203 204 205 206 207 208
        private static MetadataReference GetMetadataReference(Project project, string name)
            => project.MetadataReferences
                .OfType<PortableExecutableReference>()
                .SingleOrDefault(mr => mr.FilePath.Contains(name));

        private static MetadataReference GetMetadataReferenceByAlias(Project project, string aliasName)
            => project.MetadataReferences
                .OfType<PortableExecutableReference>()
                .SingleOrDefault(mr =>
                    !mr.Properties.Aliases.IsDefault &&
                    mr.Properties.Aliases.Contains(aliasName));

        private static Metadata GetMetadata(MetadataReference metadataReference)
            => ((PortableExecutableReference)metadataReference).GetMetadata();
209

210
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
211 212
        [WorkItem(552981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552981")]
        public async Task TestOpenSolution_DuplicateProjectGuids()
213 214
        {
            CreateFiles(GetSolutionWithDuplicatedGuidFiles());
215
            var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln");
216

217 218 219 220
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
            }
221 222
        }

223
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
224
        [WorkItem(831379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831379")]
D
Dustin Campbell 已提交
225
        public async Task GetCompilationWithCircularProjectReferences()
226 227
        {
            CreateFiles(GetSolutionWithCircularProjectReferences());
D
Dustin Campbell 已提交
228
            var solutionFilePath = GetSolutionFileName("CircularSolution.sln");
229

230 231 232 233 234 235
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);

                // Verify we can get compilations for both projects
                var projects = solution.Projects.ToArray();
236

237 238 239
                // Exactly one of them should have a reference to the other. Which one it is, is unspecced
                Assert.True(projects[0].ProjectReferences.Any(r => r.ProjectId == projects[1].Id) ||
                            projects[1].ProjectReferences.Any(r => r.ProjectId == projects[0].Id));
240

241 242
                var compilation1 = await projects[0].GetCompilationAsync();
                var compilation2 = await projects[1].GetCompilationAsync();
243

244 245 246 247
                // Exactly one of them should have a compilation to the other. Which one it is, is unspecced
                Assert.True(compilation1.References.OfType<CompilationReference>().Any(c => c.Compilation == compilation2) ||
                            compilation2.References.OfType<CompilationReference>().Any(c => c.Compilation == compilation1));
            }
248 249
        }

250
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
251
        public async Task TestOutputFilePaths()
P
Pilchie 已提交
252 253
        {
            CreateFiles(GetMultiProjectSolutionFiles());
254
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
255

256 257 258 259 260
            using (var workspace = CreateMSBuildWorkspace())
            {
                var sol = await workspace.OpenSolutionAsync(solutionFilePath);
                var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp);
                var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic);
P
Pilchie 已提交
261

262 263 264
                Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.OutputFilePath));
                Assert.Equal("VisualBasicProject.dll", Path.GetFileName(p2.OutputFilePath));
            }
P
Pilchie 已提交
265 266
        }

267
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
268
        public async Task TestCrossLanguageReferencesUsesInMemoryGeneratedMetadata()
P
Pilchie 已提交
269 270
        {
            CreateFiles(GetMultiProjectSolutionFiles());
271
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
272

273 274 275 276 277
            using (var workspace = CreateMSBuildWorkspace())
            {
                var sol = await workspace.OpenSolutionAsync(solutionFilePath);
                var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp);
                var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic);
P
Pilchie 已提交
278

279 280
                // prove there is no existing metadata on disk for this project
                Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.OutputFilePath));
D
Dustin Campbell 已提交
281
                Assert.False(File.Exists(p1.OutputFilePath));
P
Pilchie 已提交
282

283
                // prove that vb project refers to csharp project via generated metadata (skeleton) assembly.
284 285 286 287 288
                // it should be a MetadataImageReference
                var c2 = await p2.GetCompilationAsync();
                var pref = c2.References.OfType<PortableExecutableReference>().FirstOrDefault(r => r.Display == "CSharpProject");
                Assert.NotNull(pref);
            }
P
Pilchie 已提交
289 290
        }

291
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
292
        public async Task TestCrossLanguageReferencesWithOutOfDateMetadataOnDiskUsesInMemoryGeneratedMetadata()
P
Pilchie 已提交
293
        {
294 295
            await PrepareCrossLanguageProjectWithEmittedMetadataAsync();
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
296 297

            // recreate the solution so it will reload from disk
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
            using (var workspace = CreateMSBuildWorkspace())
            {
                var sol = await workspace.OpenSolutionAsync(solutionFilePath);
                var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp);

                // update project with top level change that should now invalidate use of metadata from disk
                var d1 = p1.Documents.First();
                var root = await d1.GetSyntaxRootAsync();
                var decl = root.DescendantNodes().OfType<CS.Syntax.ClassDeclarationSyntax>().First();
                var newDecl = decl.WithIdentifier(CS.SyntaxFactory.Identifier("Pogrom").WithLeadingTrivia(decl.Identifier.LeadingTrivia).WithTrailingTrivia(decl.Identifier.TrailingTrivia));
                var newRoot = root.ReplaceNode(decl, newDecl);
                var newDoc = d1.WithSyntaxRoot(newRoot);
                p1 = newDoc.Project;
                var p2 = p1.Solution.Projects.First(p => p.Language == LanguageNames.VisualBasic);

                // we should now find a MetadataImageReference that was generated instead of a MetadataFileReference
                var c2 = await p2.GetCompilationAsync();
                var pref = c2.References.OfType<PortableExecutableReference>().FirstOrDefault(r => r.Display == "EmittedCSharpProject");
                Assert.NotNull(pref);
            }
P
Pilchie 已提交
318 319
        }

320
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
321
        public async Task TestInternalsVisibleToSigned()
322
        {
323
            var solution = await SolutionAsync(
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
                Project(
                    ProjectName("Project1"),
                    Sign,
                    Document(string.Format(
@"using System.Runtime.CompilerServices;
[assembly:InternalsVisibleTo(""Project2, PublicKey={0}"")]
class C1
{{
}}", PublicKey))),
                Project(
                    ProjectName("Project2"),
                    Sign,
                    ProjectReference("Project1"),
                    Document(@"class C2 : C1 { }")));

            var project2 = solution.GetProjectsByName("Project2").First();
340
            var compilation = await project2.GetCompilationAsync();
341 342 343 344
            var diagnostics = compilation.GetDiagnostics()
                .Where(d => d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning)
                .ToArray();

D
Dustin Campbell 已提交
345
            Assert.Empty(diagnostics);
346 347
        }

348
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
349
        public async Task TestVersions()
P
Pilchie 已提交
350 351
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
352
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
353

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var sversion = solution.Version;
                var latestPV = solution.GetLatestProjectVersion();
                var project = solution.Projects.First();
                var pversion = project.Version;
                var document = project.Documents.First();
                var dversion = await document.GetTextVersionAsync();
                var latestDV = await project.GetLatestDocumentVersionAsync();

                // update document
                var solution1 = solution.WithDocumentText(document.Id, SourceText.From("using test;"));
                var document1 = solution1.GetDocument(document.Id);
                var dversion1 = await document1.GetTextVersionAsync();
                Assert.NotEqual(dversion, dversion1); // new document version
D
Dustin Campbell 已提交
370
                Assert.True(dversion1.TestOnly_IsNewerThan(dversion));
371 372 373 374
                Assert.Equal(solution.Version, solution1.Version); // updating document should not have changed solution version
                Assert.Equal(project.Version, document1.Project.Version); // updating doc should not have changed project version
                var latestDV1 = await document1.Project.GetLatestDocumentVersionAsync();
                Assert.NotEqual(latestDV, latestDV1);
D
Dustin Campbell 已提交
375
                Assert.True(latestDV1.TestOnly_IsNewerThan(latestDV));
376 377 378 379 380 381 382 383
                Assert.Equal(latestDV1, await document1.GetTextVersionAsync()); // projects latest doc version should be this doc's version

                // update project
                var solution2 = solution1.WithProjectCompilationOptions(project.Id, project.CompilationOptions.WithOutputKind(OutputKind.NetModule));
                var document2 = solution2.GetDocument(document.Id);
                var dversion2 = await document2.GetTextVersionAsync();
                Assert.Equal(dversion1, dversion2); // document didn't change, so version should be the same.
                Assert.NotEqual(document1.Project.Version, document2.Project.Version); // project did change, so project versions should be different
D
Dustin Campbell 已提交
384
                Assert.True(document2.Project.Version.TestOnly_IsNewerThan(document1.Project.Version));
385 386 387 388 389 390
                Assert.Equal(solution1.Version, solution2.Version); // solution didn't change, just individual project.

                // update solution
                var pid2 = ProjectId.CreateNewId();
                var solution3 = solution2.AddProject(pid2, "foo", "foo", LanguageNames.CSharp);
                Assert.NotEqual(solution2.Version, solution3.Version); // solution changed, added project.
D
Dustin Campbell 已提交
391
                Assert.True(solution3.Version.TestOnly_IsNewerThan(solution2.Version));
392 393 394
            }
        }

395
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
396
        public async Task TestOpenSolution_LoadMetadataForReferencedProjects()
P
Pilchie 已提交
397 398
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
399
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
P
Pilchie 已提交
400

401 402 403 404 405 406 407 408 409 410 411
            using (var workspace = CreateMSBuildWorkspace())
            {
                workspace.LoadMetadataForReferencedProjects = true;

                var project = await workspace.OpenProjectAsync(projectFilePath);
                var document = project.Documents.First();
                var tree = await document.GetSyntaxTreeAsync();
                var expectedFileName = GetSolutionFileName(@"CSharpProject\CSharpClass.cs");
                Assert.Equal(expectedFileName, tree.FilePath);
                var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent;
                Assert.NotNull(type);
D
Dustin Campbell 已提交
412
                Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal);
413
            }
P
Pilchie 已提交
414 415
        }

416
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
417
        [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")]
418
        public async Task TestOpenProject_CSharp_WithoutPrefer32BitAndConsoleApplication()
P
Pilchie 已提交
419 420
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
421
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutPrefer32Bit));
422
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
P
Pilchie 已提交
423

424 425 426 427
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                var compilation = await project.GetCompilationAsync();
428
                Assert.Equal(Platform.AnyCpu, compilation.Options.Platform);
429
            }
P
Pilchie 已提交
430 431
        }

432
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
433
        [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")]
434
        public async Task TestOpenProject_CSharp_WithoutPrefer32BitAndLibrary()
P
Pilchie 已提交
435 436
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
437
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutPrefer32Bit)
P
Pilchie 已提交
438
                .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "Library"));
439
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
P
Pilchie 已提交
440

441 442 443 444 445 446
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                var compilation = await project.GetCompilationAsync();
                Assert.Equal(Platform.AnyCpu, compilation.Options.Platform);
            }
P
Pilchie 已提交
447 448
        }

449
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
450
        [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")]
451
        public async Task TestOpenProject_CSharp_WithPrefer32BitAndConsoleApplication()
P
Pilchie 已提交
452 453
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
454
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit));
455
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
P
Pilchie 已提交
456

457 458 459 460 461 462
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                var compilation = await project.GetCompilationAsync();
                Assert.Equal(Platform.AnyCpu32BitPreferred, compilation.Options.Platform);
            }
P
Pilchie 已提交
463 464
        }

465
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
466
        [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")]
467
        public async Task TestOpenProject_CSharp_WithPrefer32BitAndLibrary()
P
Pilchie 已提交
468 469
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
470
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit)
P
Pilchie 已提交
471
                .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "Library"));
472
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
P
Pilchie 已提交
473

474 475 476 477 478 479
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                var compilation = await project.GetCompilationAsync();
                Assert.Equal(Platform.AnyCpu, compilation.Options.Platform);
            }
P
Pilchie 已提交
480 481
        }

482
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
483
        [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")]
484
        public async Task TestOpenProject_CSharp_WithPrefer32BitAndWinMDObj()
P
Pilchie 已提交
485 486
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
487
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit)
P
Pilchie 已提交
488
                .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "winmdobj"));
489
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
P
Pilchie 已提交
490

491 492 493 494 495 496
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                var compilation = await project.GetCompilationAsync();
                Assert.Equal(Platform.AnyCpu, compilation.Options.Platform);
            }
P
Pilchie 已提交
497 498
        }

499
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
500
        public async Task TestOpenProject_CSharp_WithoutOutputPath()
501 502 503
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
                .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputPath", ""));
504
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
505

506 507 508 509 510
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                Assert.NotEmpty(project.OutputFilePath);
            }
511 512
        }

513
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
514
        public async Task TestOpenProject_CSharp_WithoutAssemblyName()
515 516 517
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
                .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "AssemblyName", ""));
518
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
519

520 521 522 523 524
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                Assert.NotEmpty(project.OutputFilePath);
            }
525 526
        }

527
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
D
Dustin Campbell 已提交
528
        public async Task TestOpenSolution_CSharp_WithoutCSharpTargetsImported_DocumentsArePickedUp()
529 530
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
531
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutCSharpTargetsImported));
532
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");
533

534 535 536 537
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = solution.Projects.First();
D
Dustin Campbell 已提交
538
                Assert.NotEmpty(project.Documents);
539
            }
540 541
        }

542
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
543
        public async Task TestOpenProject_VisualBasic_WithoutVBTargetsImported_DocumentsArePickedUp()
544
        {
545
            CreateFiles(GetMultiProjectSolutionFiles()
546
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutVBTargetsImported));
547
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
548

549 550 551
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
D
Dustin Campbell 已提交
552
                Assert.NotEmpty(project.Documents);
553
            }
554 555
        }

556
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
557
        [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")]
558
        public async Task TestOpenProject_VisualBasic_WithoutPrefer32BitAndConsoleApplication()
P
Pilchie 已提交
559
        {
560
            CreateFiles(GetMultiProjectSolutionFiles()
561
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutPrefer32Bit));
562
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
P
Pilchie 已提交
563

564 565 566 567
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                var compilation = await project.GetCompilationAsync();
568
                Assert.Equal(Platform.AnyCpu, compilation.Options.Platform);
569
            }
P
Pilchie 已提交
570 571
        }

572
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
573
        [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")]
574
        public async Task TestOpenProject_VisualBasic_WithoutPrefer32BitAndLibrary()
P
Pilchie 已提交
575
        {
576
            CreateFiles(GetMultiProjectSolutionFiles()
577
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutPrefer32Bit)
P
Pilchie 已提交
578
                .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "Library"));
579
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
P
Pilchie 已提交
580

581 582 583 584 585 586
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                var compilation = await project.GetCompilationAsync();
                Assert.Equal(Platform.AnyCpu, compilation.Options.Platform);
            }
P
Pilchie 已提交
587 588
        }

589
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
590
        [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")]
591
        public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndConsoleApplication()
P
Pilchie 已提交
592
        {
593
            CreateFiles(GetMultiProjectSolutionFiles()
594
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit));
595
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
P
Pilchie 已提交
596

597 598 599 600 601 602
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                var compilation = await project.GetCompilationAsync();
                Assert.Equal(Platform.AnyCpu32BitPreferred, compilation.Options.Platform);
            }
P
Pilchie 已提交
603 604
        }

605
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
606
        [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")]
607
        public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndLibrary()
P
Pilchie 已提交
608
        {
609
            CreateFiles(GetMultiProjectSolutionFiles()
610
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit)
P
Pilchie 已提交
611
                .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "Library"));
612
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
P
Pilchie 已提交
613

614 615 616 617 618 619
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                var compilation = await project.GetCompilationAsync();
                Assert.Equal(Platform.AnyCpu, compilation.Options.Platform);
            }
P
Pilchie 已提交
620 621
        }

622
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
623
        [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")]
624
        public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndWinMDObj()
P
Pilchie 已提交
625
        {
626
            CreateFiles(GetMultiProjectSolutionFiles()
627
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit)
P
Pilchie 已提交
628
                .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "winmdobj"));
629
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
P
Pilchie 已提交
630

631 632 633 634 635 636
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                var compilation = await project.GetCompilationAsync();
                Assert.Equal(Platform.AnyCpu, compilation.Options.Platform);
            }
P
Pilchie 已提交
637 638
        }

639
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
640
        public async Task TestOpenProject_VisualBasic_WithoutOutputPath()
641
        {
642
            CreateFiles(GetMultiProjectSolutionFiles()
643
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit)
644
                .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputPath", ""));
645
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
646

647 648 649 650 651
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                Assert.NotEmpty(project.OutputFilePath);
            }
652 653
        }

654
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
655
        public async Task TestOpenProject_VisualBasic_WithLanguageVersion15_3()
656 657 658
        {
            CreateFiles(GetMultiProjectSolutionFiles()
                .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "LangVersion", "15.3"));
659
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
660

661 662 663 664 665
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                Assert.Equal(VB.LanguageVersion.VisualBasic15_3, ((VB.VisualBasicParseOptions)project.ParseOptions).LanguageVersion);
            }
666 667
        }

668
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
669
        public async Task TestOpenProject_VisualBasic_WithLatestLanguageVersion()
670 671 672
        {
            CreateFiles(GetMultiProjectSolutionFiles()
                .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "LangVersion", "Latest"));
673
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
674

675 676 677 678 679 680
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                Assert.Equal(VB.LanguageVersionFacts.MapSpecifiedToEffectiveVersion(VB.LanguageVersion.Latest), ((VB.VisualBasicParseOptions)project.ParseOptions).LanguageVersion);
                Assert.Equal(VB.LanguageVersion.Latest, ((VB.VisualBasicParseOptions)project.ParseOptions).SpecifiedLanguageVersion);
            }
681 682
        }

683
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
684
        public async Task TestOpenProject_VisualBasic_WithoutAssemblyName()
685
        {
686
            CreateFiles(GetMultiProjectSolutionFiles()
687
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit)
688
                .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "AssemblyName", ""));
689
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
690

691 692 693
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
694
                Assert.Empty(workspace.Diagnostics);
695 696
                Assert.NotEmpty(project.OutputFilePath);
            }
697 698
        }

699
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
700 701 702 703
        public async Task Test_Respect_ReferenceOutputassembly_Flag()
        {
            var projFile = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
            CreateFiles(GetSimpleCSharpSolutionFiles()
704 705 706
                .WithFile(@"VisualBasicProject_Circular_Top.vbproj", Resources.ProjectFiles.VisualBasic.Circular_Top)
                .WithFile(@"VisualBasicProject_Circular_Target.vbproj", Resources.ProjectFiles.VisualBasic.Circular_Target));
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject_Circular_Top.vbproj");
707

708 709 710 711 712
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                Assert.Empty(project.ProjectReferences);
            }
713 714
        }

715
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
716
        public async Task TestOpenProject_WithXaml()
P
Pilchie 已提交
717 718
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
719 720 721 722 723
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithXaml)
                .WithFile(@"CSharpProject\App.xaml", Resources.SourceFiles.Xaml.App)
                .WithFile(@"CSharpProject\App.xaml.cs", Resources.SourceFiles.CSharp.App)
                .WithFile(@"CSharpProject\MainWindow.xaml", Resources.SourceFiles.Xaml.MainWindow)
                .WithFile(@"CSharpProject\MainWindow.xaml.cs", Resources.SourceFiles.CSharp.MainWindow));
724
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
P
Pilchie 已提交
725

726 727
            // Ensure the Xaml compiler does not run in a separate appdomain. It appears that this won't work within xUnit.
            using (var workspace = CreateMSBuildWorkspace(("AlwaysCompileMarkupFilesInSeparateDomain", "false")))
728 729 730
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                var documents = project.Documents.ToList();
P
Pilchie 已提交
731

732 733
                // AssemblyInfo.cs, App.xaml.cs, MainWindow.xaml.cs, App.g.cs, MainWindow.g.cs, + unusual AssemblyAttributes.cs
                Assert.Equal(6, documents.Count);
P
Pilchie 已提交
734

735
                // both xaml code behind files are documents
D
Dustin Campbell 已提交
736 737
                Assert.Contains(documents, d => d.Name == "App.xaml.cs");
                Assert.Contains(documents, d => d.Name == "MainWindow.xaml.cs");
P
Pilchie 已提交
738

739
                // prove no xaml files are documents
D
Dustin Campbell 已提交
740
                Assert.DoesNotContain(documents, d => d.Name.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase));
P
Pilchie 已提交
741

742
                // prove that generated source files for xaml files are included in documents list
D
Dustin Campbell 已提交
743 744
                Assert.Contains(documents, d => d.Name == "App.g.cs");
                Assert.Contains(documents, d => d.Name == "MainWindow.g.cs");
745
            }
P
Pilchie 已提交
746 747
        }

748
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
749
        public async Task TestMetadataReferenceHasBadHintPath()
P
Pilchie 已提交
750
        {
751
            // prove that even with bad hint path for metadata reference the workspace can succeed at finding the correct metadata reference.
P
Pilchie 已提交
752
            CreateFiles(GetSimpleCSharpSolutionFiles()
753
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadHintPath));
754
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");
P
Pilchie 已提交
755

756 757 758 759 760 761 762 763
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = solution.Projects.First();
                var refs = project.MetadataReferences.ToList();
                var csharpLib = refs.OfType<PortableExecutableReference>().FirstOrDefault(r => r.FilePath.Contains("Microsoft.CSharp"));
                Assert.NotNull(csharpLib);
            }
P
Pilchie 已提交
764 765
        }

766
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
767
        [WorkItem(531631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531631")]
768
        public async Task TestOpenProject_AssemblyNameIsPath()
P
Pilchie 已提交
769
        {
770
            // prove that even if assembly name is specified as a path instead of just a name, workspace still succeeds at opening project.
P
Pilchie 已提交
771
            CreateFiles(GetSimpleCSharpSolutionFiles()
772
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.AssemblyNameIsPath));
P
Pilchie 已提交
773

774 775 776 777 778 779 780 781 782 783 784
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = solution.Projects.First();
                var comp = await project.GetCompilationAsync();
                Assert.Equal("ReproApp", comp.AssemblyName);
                var expectedOutputPath = GetParentDirOfParentDirOfContainingDir(project.FilePath);
                Assert.Equal(expectedOutputPath, Path.GetDirectoryName(project.OutputFilePath));
            }
P
Pilchie 已提交
785 786
        }

787
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
788
        [WorkItem(531631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531631")]
789
        public async Task TestOpenProject_AssemblyNameIsPath2()
P
Pilchie 已提交
790 791
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
792
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.AssemblyNameIsPath2));
P
Pilchie 已提交
793

794 795 796 797 798 799 800 801 802 803 804
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = solution.Projects.First();
                var comp = await project.GetCompilationAsync();
                Assert.Equal("ReproApp", comp.AssemblyName);
                var expectedOutputPath = Path.Combine(Path.GetDirectoryName(project.FilePath), @"bin");
                Assert.Equal(expectedOutputPath, Path.GetDirectoryName(Path.GetFullPath(project.OutputFilePath)));
            }
P
Pilchie 已提交
805 806
        }

807
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
808
        public async Task TestOpenProject_WithDuplicateFile()
P
Pilchie 已提交
809 810 811
        {
            // Verify that we don't throw in this case
            CreateFiles(GetSimpleCSharpSolutionFiles()
812
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.DuplicateFile));
P
Pilchie 已提交
813

814 815 816 817 818 819
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = solution.Projects.First();
D
Dustin Campbell 已提交
820 821
                var documents = project.Documents.Where(d => d.Name == "CSharpClass.cs").ToList();
                Assert.Equal(2, documents.Count);
822
            }
P
Pilchie 已提交
823 824
        }

825
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
826 827
        public void TestOpenProject_WithInvalidFileExtension()
        {
C
Charles Stoner 已提交
828
            // make sure the file does in fact exist, but with an unrecognized extension
829
            const string projFileName = @"CSharpProject\CSharpProject.csproj.nyi";
830
            CreateFiles(GetSimpleCSharpSolutionFiles()
831
                .WithFile(projFileName, Resources.ProjectFiles.CSharp.CSharpProject));
832

833
            AssertEx.Throws<InvalidOperationException>(delegate
834
            {
835
                MSBuildWorkspace.Create().OpenProjectAsync(GetSolutionFileName(projFileName)).Wait();
836 837 838
            },
            (e) =>
            {
839 840
                var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, GetSolutionFileName(projFileName), ".nyi");
                Assert.Equal(expected, e.Message);
841 842 843
            });
        }

844
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
845
        public void TestOpenProject_ProjectFileExtensionAssociatedWithUnknownLanguage()
P
Pilchie 已提交
846 847
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
848 849
            var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
            var language = "lingo";
850
            AssertEx.Throws<InvalidOperationException>(delegate
P
Pilchie 已提交
851 852
            {
                var ws = MSBuildWorkspace.Create();
853 854
                ws.AssociateFileExtensionWithLanguage("csproj", language); // non-existent language
                ws.OpenProjectAsync(projFileName).Wait();
855 856 857 858
            },
            (e) =>
            {
                // the exception should tell us something about the language being unrecognized.
859 860
                var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projFileName, language);
                Assert.Equal(expected, e.Message);
P
Pilchie 已提交
861 862 863
            });
        }

864
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
865
        public async Task TestOpenProject_WithAssociatedLanguageExtension1()
866 867 868 869
        {
            // make a CSharp solution with a project file having the incorrect extension 'vbproj', and then load it using the overload the lets us
            // specify the language directly, instead of inferring from the extension
            CreateFiles(GetSimpleCSharpSolutionFiles()
870
                .WithFile(@"CSharpProject\CSharpProject.vbproj", Resources.ProjectFiles.CSharp.CSharpProject));
871
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.vbproj");
872

873 874 875 876 877 878
            using (var workspace = CreateMSBuildWorkspace())
            {
                workspace.AssociateFileExtensionWithLanguage("vbproj", LanguageNames.CSharp);
                var project = await workspace.OpenProjectAsync(projectFilePath);
                var document = project.Documents.First();
                var tree = await document.GetSyntaxTreeAsync();
D
Dustin Campbell 已提交
879 880
                var diagnostics = tree.GetDiagnostics();
                Assert.Empty(diagnostics);
881
            }
882 883
        }

884
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
885
        public async Task TestOpenProject_WithAssociatedLanguageExtension2_IgnoreCase()
886 887 888 889
        {
            // make a CSharp solution with a project file having the incorrect extension 'anyproj', and then load it using the overload the lets us
            // specify the language directly, instead of inferring from the extension
            CreateFiles(GetSimpleCSharpSolutionFiles()
890
                .WithFile(@"CSharpProject\CSharpProject.anyproj", Resources.ProjectFiles.CSharp.CSharpProject));
891
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.anyproj");
892

893 894 895 896 897 898 899
            using (var workspace = CreateMSBuildWorkspace())
            {
                // prove that the association works even if the case is different
                workspace.AssociateFileExtensionWithLanguage("ANYPROJ", LanguageNames.CSharp);
                var project = await workspace.OpenProjectAsync(projectFilePath);
                var document = project.Documents.First();
                var tree = await document.GetSyntaxTreeAsync();
D
Dustin Campbell 已提交
900 901
                var diagnostics = tree.GetDiagnostics();
                Assert.Empty(diagnostics);
902
            }
903 904
        }

905
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
906 907 908
        public void TestOpenSolution_WithNonExistentSolutionFile_Fails()
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
909
            var solutionFilePath = GetSolutionFileName("NonExistentSolution.sln");
910

911
            AssertEx.Throws<FileNotFoundException>(() =>
912
            {
913 914 915 916
                using (var workspace = CreateMSBuildWorkspace())
                {
                    workspace.OpenSolutionAsync(solutionFilePath).Wait();
                }
917 918 919
            });
        }

920
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
921 922 923
        public void TestOpenSolution_WithInvalidSolutionFile_Fails()
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
924
            var solutionFilePath = GetSolutionFileName(@"http://localhost/Invalid/InvalidSolution.sln");
925

926
            AssertEx.Throws<InvalidOperationException>(() =>
927
            {
928 929 930 931
                using (var workspace = CreateMSBuildWorkspace())
                {
                    workspace.OpenSolutionAsync(solutionFilePath).Wait();
                }
932 933 934
            });
        }

935
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
936
        public async Task TestOpenSolution_WithTemporaryLockedFile_SucceedsWithoutFailureEvent()
937 938 939 940 941
        {
            // when skipped we should see a diagnostic for the invalid project

            CreateFiles(GetSimpleCSharpSolutionFiles());

942
            using (var ws = CreateMSBuildWorkspace())
943
            {
944 945 946 947 948
                var failed = false;
                ws.WorkspaceFailed += (s, args) =>
                {
                    failed |= args.Diagnostic is DocumentDiagnostic;
                };
949

950 951 952 953 954 955 956
                // open source file so it cannot be read by workspace;
                var sourceFile = GetSolutionFileName(@"CSharpProject\CSharpClass.cs");
                var file = File.Open(sourceFile, FileMode.Open, FileAccess.Write, FileShare.None);
                try
                {
                    var solution = await ws.OpenSolutionAsync(GetSolutionFileName(@"TestSolution.sln"));
                    var doc = solution.Projects.First().Documents.First(d => d.FilePath == sourceFile);
957

958 959
                    // start reading text
                    var getTextTask = doc.GetTextAsync();
960

961 962 963
                    // wait 1 unit of retry delay then close file
                    var delay = TextDocumentState.RetryDelay;
                    await Task.Delay(delay).ContinueWith(t => file.Close(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
964

965 966
                    // finish reading text
                    var text = await getTextTask;
D
Dustin Campbell 已提交
967
                    Assert.NotEmpty(text.ToString());
968 969 970 971 972
                }
                finally
                {
                    file.Close();
                }
973

D
Dustin Campbell 已提交
974
                Assert.False(failed);
975
            }
976 977
        }

978
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
979
        public async Task TestOpenSolution_WithLockedFile_FailsWithFailureEvent()
980 981 982 983
        {
            // when skipped we should see a diagnostic for the invalid project

            CreateFiles(GetSimpleCSharpSolutionFiles());
984
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");
985

986
            using (var workspace = CreateMSBuildWorkspace())
987
            {
988 989 990 991 992
                var failed = false;
                workspace.WorkspaceFailed += (s, args) =>
                {
                    failed |= args.Diagnostic is DocumentDiagnostic;
                };
993

994 995 996 997 998 999 1000 1001
                // open source file so it cannot be read by workspace;
                var sourceFile = GetSolutionFileName(@"CSharpProject\CSharpClass.cs");
                var file = File.Open(sourceFile, FileMode.Open, FileAccess.Write, FileShare.None);
                try
                {
                    var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                    var doc = solution.Projects.First().Documents.First(d => d.FilePath == sourceFile);
                    var text = await doc.GetTextAsync();
D
Dustin Campbell 已提交
1002
                    Assert.Empty(text.ToString());
1003 1004 1005 1006 1007
                }
                finally
                {
                    file.Close();
                }
1008

D
Dustin Campbell 已提交
1009
                Assert.True(failed);
1010
            }
1011 1012 1013
        }


1014
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1015
        public async Task TestOpenSolution_WithInvalidProjectPath_SkipTrue_SucceedsWithFailureEvent()
1016 1017 1018 1019
        {
            // when skipped we should see a diagnostic for the invalid project

            CreateFiles(GetSimpleCSharpSolutionFiles()
1020 1021
                .WithFile(@"TestSolution.sln", Resources.SolutionFiles.InvalidProjectPath));

1022
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");
1023

1024
            using (var workspace = CreateMSBuildWorkspace())
1025
            {
1026 1027 1028 1029 1030
                var diagnostics = new List<WorkspaceDiagnostic>();
                workspace.WorkspaceFailed += (s, args) =>
                {
                    diagnostics.Add(args.Diagnostic);
                };
1031

1032
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
1033

D
Dustin Campbell 已提交
1034
                Assert.Single(diagnostics);
1035
            }
1036 1037
        }

J
Jared Parsons 已提交
1038
        [WorkItem(985906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/985906")]
1039
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1040
        public async Task HandleSolutionProjectTypeSolutionFolder()
1041 1042
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
1043
                .WithFile(@"TestSolution.sln", Resources.SolutionFiles.SolutionFolder));
1044 1045 1046
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");

            using (var workspace = CreateMSBuildWorkspace())
1047
            {
D
Dustin Campbell 已提交
1048
                var diagnostics = new List<WorkspaceDiagnostic>();
1049 1050
                workspace.WorkspaceFailed += (s, args) =>
                {
D
Dustin Campbell 已提交
1051
                    diagnostics.Add(args.Diagnostic);
1052
                };
1053

1054
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
D
Dustin Campbell 已提交
1055 1056

                Assert.Empty(diagnostics);
1057
            }
1058 1059
        }

1060
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1061 1062 1063 1064 1065
        public void TestOpenSolution_WithInvalidProjectPath_SkipFalse_Fails()
        {
            // when not skipped we should get an exception for the invalid project

            CreateFiles(GetSimpleCSharpSolutionFiles()
1066
                .WithFile(@"TestSolution.sln", Resources.SolutionFiles.InvalidProjectPath));
1067
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");
1068

1069
            using (var workspace = CreateMSBuildWorkspace())
1070
            {
1071 1072
                workspace.SkipUnrecognizedProjects = false;

1073
                AssertEx.Throws<InvalidOperationException>(() =>
1074 1075 1076 1077
                {
                    workspace.OpenSolutionAsync(solutionFilePath).Wait();
                });
            }
1078 1079
        }

1080
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1081
        public async Task TestOpenSolution_WithNonExistentProject_SkipTrue_SucceedsWithFailureEvent()
1082 1083 1084 1085
        {
            // when skipped we should see a diagnostic for the non-existent project

            CreateFiles(GetSimpleCSharpSolutionFiles()
1086
                .WithFile(@"TestSolution.sln", Resources.SolutionFiles.NonExistentProject));
1087
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");
1088

1089
            using (var workspace = CreateMSBuildWorkspace())
1090
            {
1091 1092 1093 1094 1095
                var diagnostics = new List<WorkspaceDiagnostic>();
                workspace.WorkspaceFailed += (s, args) =>
                {
                    diagnostics.Add(args.Diagnostic);
                };
1096

1097
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
1098

D
Dustin Campbell 已提交
1099
                Assert.Single(diagnostics);
1100
            }
1101 1102
        }

1103
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1104 1105 1106 1107 1108
        public void TestOpenSolution_WithNonExistentProject_SkipFalse_Fails()
        {
            // when skipped we should see an exception for the non-existent project

            CreateFiles(GetSimpleCSharpSolutionFiles()
1109
                .WithFile(@"TestSolution.sln", Resources.SolutionFiles.NonExistentProject));
1110
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");
1111

1112
            using (var workspace = CreateMSBuildWorkspace())
1113
            {
1114 1115
                workspace.SkipUnrecognizedProjects = false;

1116
                AssertEx.Throws<FileNotFoundException>(() =>
1117 1118 1119 1120
                {
                    workspace.OpenSolutionAsync(solutionFilePath).Wait();
                });
            }
1121 1122
        }

1123
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1124
        public async Task TestOpenSolution_WithUnrecognizedProjectFileExtension_Fails()
1125 1126 1127
        {
            // proves that for solution open, project type guid and extension are both necessary
            CreateFiles(GetSimpleCSharpSolutionFiles()
1128 1129
                .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectExtension)
                .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject));
1130
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");
1131

1132 1133 1134
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
D
Dustin Campbell 已提交
1135
                Assert.Empty(solution.ProjectIds);
1136
            }
1137
        }
1138

1139
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1140
        public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidButRecognizedExtension_Succeeds()
1141 1142 1143
        {
            // proves that if project type guid is not recognized, a known project file extension is all we need.
            CreateFiles(GetSimpleCSharpSolutionFiles()
1144
                .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuid));
1145
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");
1146

1147 1148 1149
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
D
Dustin Campbell 已提交
1150
                Assert.Single(solution.ProjectIds);
1151
            }
1152 1153
        }

1154
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1155
        public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidAndUnrecognizedExtension_WithSkipTrue_SucceedsWithFailureEvent()
1156 1157 1158
        {
            // proves that if both project type guid and file extension are unrecognized, then project is skipped.
            CreateFiles(GetSimpleCSharpSolutionFiles()
1159 1160
                .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension)
                .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject));
1161

1162
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");
1163

1164
            using (var workspace = CreateMSBuildWorkspace())
1165
            {
1166 1167 1168 1169 1170
                var diagnostics = new List<WorkspaceDiagnostic>();
                workspace.WorkspaceFailed += (s, args) =>
                {
                    diagnostics.Add(args.Diagnostic);
                };
1171

1172
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
1173

D
Dustin Campbell 已提交
1174 1175
                Assert.Single(diagnostics);
                Assert.Empty(solution.ProjectIds);
1176
            }
1177 1178
        }

1179
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1180 1181 1182
        public void TestOpenSolution_WithUnrecognizedProjectTypeGuidAndUnrecognizedExtension_WithSkipFalse_Fails()
        {
            // proves that if both project type guid and file extension are unrecognized, then open project fails.
1183
            const string noProjFileName = @"CSharpProject\CSharpProject.noproj";
1184
            CreateFiles(GetSimpleCSharpSolutionFiles()
1185 1186
                .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension)
                .WithFile(noProjFileName, Resources.ProjectFiles.CSharp.CSharpProject));
1187

1188
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");
1189

1190
            AssertEx.Throws<InvalidOperationException>(() =>
1191
            {
1192 1193 1194 1195 1196
                using (var workspace = CreateMSBuildWorkspace())
                {
                    workspace.SkipUnrecognizedProjects = false;
                    workspace.OpenSolutionAsync(solutionFilePath).Wait();
                }
1197 1198 1199
            },
            e =>
            {
1200 1201 1202
                var noProjFullFileName = GetSolutionFileName(noProjFileName);
                var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, noProjFullFileName, ".noproj");
                Assert.Equal(expected, e.Message);
1203 1204 1205
            });
        }

1206
        private IEnumerable<Assembly> _defaultAssembliesWithoutCSharp = MefHostServices.DefaultAssemblies.Where(a => !a.FullName.Contains("CSharp"));
1207

1208
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
M
Matt Warren 已提交
1209
        [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")]
1210 1211
        public void TestOpenSolution_WithMissingLanguageLibraries_WithSkipFalse_Throws()
        {
1212
            // proves that if the language libraries are missing then the appropriate error occurs
1213
            CreateFiles(GetSimpleCSharpSolutionFiles());
1214
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");
1215

1216
            AssertEx.Throws<InvalidOperationException>(() =>
1217
            {
1218
                using (var workspace = CreateMSBuildWorkspace(MefHostServices.Create(_defaultAssembliesWithoutCSharp)))
1219 1220 1221 1222
                {
                    workspace.SkipUnrecognizedProjects = false;
                    workspace.OpenSolutionAsync(solutionFilePath).Wait();
                }
1223 1224 1225
            },
            e =>
            {
1226 1227 1228
                var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
                var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projFileName, ".csproj");
                Assert.Equal(expected, e.Message);
1229 1230 1231
            });
        }

1232
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
M
Matt Warren 已提交
1233
        [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")]
1234
        public async Task TestOpenSolution_WithMissingLanguageLibraries_WithSkipTrue_SucceedsWithDiagnostic()
1235
        {
1236
            // proves that if the language libraries are missing then the appropriate error occurs
1237
            CreateFiles(GetSimpleCSharpSolutionFiles());
1238
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");
1239

1240
            using (var workspace = CreateMSBuildWorkspace(MefHostServices.Create(_defaultAssembliesWithoutCSharp)))
1241
            {
1242
                workspace.SkipUnrecognizedProjects = true;
1243

D
Dustin Campbell 已提交
1244
                var diagnostics = new List<WorkspaceDiagnostic>();
1245 1246
                workspace.WorkspaceFailed += delegate (object sender, WorkspaceDiagnosticEventArgs e)
                {
D
Dustin Campbell 已提交
1247
                    diagnostics.Add(e.Diagnostic);
1248 1249 1250
                };

                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
1251

D
Dustin Campbell 已提交
1252
                Assert.Single(diagnostics);
1253

1254 1255
                var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
                var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projFileName, ".csproj");
D
Dustin Campbell 已提交
1256
                Assert.Equal(expected, diagnostics[0].Message);
1257
            }
1258 1259
        }

1260
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
M
Matt Warren 已提交
1261
        [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")]
1262 1263
        public void TestOpenProject_WithMissingLanguageLibraries_Throws()
        {
1264
            // proves that if the language libraries are missing then the appropriate error occurs
1265
            CreateFiles(GetSimpleCSharpSolutionFiles());
1266
            var projectName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
1267

1268
            using (var workspace = MSBuildWorkspace.Create(MefHostServices.Create(_defaultAssembliesWithoutCSharp)))
1269
            {
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
                AssertEx.Throws<InvalidOperationException>(() =>
                {
                    var project = workspace.OpenProjectAsync(projectName).Result;
                },
                e =>
                {
                    var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projectName, ".csproj");
                    Assert.Equal(expected, e.Message);
                });
            }
1280 1281
        }

1282
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1283 1284 1285
        public void TestOpenProject_WithInvalidFilePath_Fails()
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
1286
            var projectFilePath = GetSolutionFileName(@"http://localhost/Invalid/InvalidProject.csproj");
1287

1288
            AssertEx.Throws<InvalidOperationException>(() =>
1289
            {
1290 1291 1292 1293
                using (var workspace = CreateMSBuildWorkspace())
                {
                    workspace.OpenProjectAsync(projectFilePath).Wait();
                }
1294 1295 1296
            });
        }

1297
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1298 1299 1300
        public void TestOpenProject_WithNonExistentProjectFile_Fails()
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
1301
            var projectFilePath = GetSolutionFileName(@"CSharpProject\NonExistentProject.csproj");
1302

1303
            AssertEx.Throws<FileNotFoundException>(() =>
1304
            {
1305 1306 1307 1308
                using (var workspace = CreateMSBuildWorkspace())
                {
                    workspace.OpenProjectAsync(projectFilePath).Wait();
                }
1309 1310 1311
            });
        }

1312
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1313
        public async Task TestOpenProject_WithInvalidProjectReference_SkipTrue_SucceedsWithEvent()
1314 1315
        {
            CreateFiles(GetMultiProjectSolutionFiles()
1316
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.InvalidProjectReference));
1317
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
1318

1319
            using (var workspace = CreateMSBuildWorkspace())
1320
            {
1321 1322 1323 1324 1325
                var diagnostics = new List<WorkspaceDiagnostic>();
                workspace.WorkspaceFailed += (s, args) =>
                {
                    diagnostics.Add(args.Diagnostic);
                };
1326

1327
                var project = await workspace.OpenProjectAsync(projectFilePath);
1328

D
Dustin Campbell 已提交
1329 1330 1331
                Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to invalid file path.
                Assert.Empty(project.ProjectReferences); // no resolved project references
                Assert.Single(project.AllProjectReferences); // dangling project reference
1332
            }
1333 1334
        }

1335
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1336
        public void TestOpenProject_WithInvalidProjectReference_SkipFalse_Fails()
P
Pilchie 已提交
1337 1338
        {
            CreateFiles(GetMultiProjectSolutionFiles()
1339
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.InvalidProjectReference));
1340
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
1341

1342
            AssertEx.Throws<InvalidOperationException>(() =>
1343
            {
1344 1345 1346 1347 1348
                using (var workspace = CreateMSBuildWorkspace())
                {
                    workspace.SkipUnrecognizedProjects = false;
                    workspace.OpenProjectAsync(projectFilePath).Wait();
                }
1349 1350 1351
            });
        }

1352
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1353
        public async Task TestOpenProject_WithNonExistentProjectReference_SkipTrue_SucceedsWithEvent()
1354 1355
        {
            CreateFiles(GetMultiProjectSolutionFiles()
1356
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.NonExistentProjectReference));
1357
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
1358

1359
            using (var workspace = CreateMSBuildWorkspace())
1360
            {
1361 1362 1363 1364 1365
                var diagnostics = new List<WorkspaceDiagnostic>();
                workspace.WorkspaceFailed += (s, args) =>
                {
                    diagnostics.Add(args.Diagnostic);
                };
1366

1367
                var project = await workspace.OpenProjectAsync(projectFilePath);
1368

D
Dustin Campbell 已提交
1369 1370 1371
                Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to invalid file path.
                Assert.Empty(project.ProjectReferences); // no resolved project references
                Assert.Single(project.AllProjectReferences); // dangling project reference
1372
            }
1373 1374
        }

1375
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1376 1377 1378
        public void TestOpenProject_WithNonExistentProjectReference_SkipFalse_Fails()
        {
            CreateFiles(GetMultiProjectSolutionFiles()
1379
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.NonExistentProjectReference));
1380
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
1381

1382
            AssertEx.Throws<FileNotFoundException>(() =>
1383
            {
1384 1385 1386 1387 1388
                using (var workspace = CreateMSBuildWorkspace())
                {
                    workspace.SkipUnrecognizedProjects = false;
                    workspace.OpenProjectAsync(projectFilePath).Wait();
                }
1389 1390 1391
            });
        }

1392
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1393
        public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_SkipTrue_SucceedsWithEvent()
1394 1395
        {
            CreateFiles(GetMultiProjectSolutionFiles()
1396 1397
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension)
                .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject));
1398
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
1399

1400
            using (var workspace = CreateMSBuildWorkspace())
1401
            {
1402 1403 1404 1405 1406
                var diagnostics = new List<WorkspaceDiagnostic>();
                workspace.WorkspaceFailed += (s, args) =>
                {
                    diagnostics.Add(args.Diagnostic);
                };
1407

1408
                var project = await workspace.OpenProjectAsync(projectFilePath);
1409

1410 1411 1412
                Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to unrecognized extension.
                Assert.Empty(project.ProjectReferences); // no resolved project references
                Assert.Single(project.AllProjectReferences); // dangling project reference
1413
            }
1414 1415
        }

1416
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1417 1418 1419
        public void TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_SkipFalse_Fails()
        {
            CreateFiles(GetMultiProjectSolutionFiles()
1420 1421
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension)
                .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject));
1422
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
1423

1424
            AssertEx.Throws<InvalidOperationException>(() =>
1425
            {
1426 1427 1428 1429 1430
                using (var workspace = CreateMSBuildWorkspace())
                {
                    workspace.SkipUnrecognizedProjects = false;
                    workspace.OpenProjectAsync(projectFilePath).Wait();
                }
1431 1432 1433
            });
        }

1434
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1435
        public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_WithMetadata_SkipTrue_SucceedsByLoadingMetadata()
1436 1437
        {
            CreateFiles(GetMultiProjectSolutionFiles()
1438 1439 1440
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension)
                .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)
                .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject));
1441
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
1442 1443 1444 1445

            // keep metadata reference from holding files open
            Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true;

1446 1447 1448
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
1449

D
Dustin Campbell 已提交
1450 1451 1452
                Assert.Single(project.Solution.ProjectIds);
                Assert.Empty(project.ProjectReferences);
                Assert.Empty(project.AllProjectReferences);
1453

1454
                var metaRefs = project.MetadataReferences.ToList();
D
Dustin Campbell 已提交
1455
                Assert.Contains(metaRefs, r => r is PortableExecutableReference && ((PortableExecutableReference)r).Display.Contains("CSharpProject.dll"));
1456
            }
1457 1458
        }

1459
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1460
        public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_WithMetadata_SkipFalse_SucceedsByLoadingMetadata()
1461 1462
        {
            CreateFiles(GetMultiProjectSolutionFiles()
1463 1464 1465
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension)
                .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)
                .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject));
1466
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
P
Pilchie 已提交
1467 1468 1469 1470

            // keep metadata reference from holding files open
            Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true;

1471 1472 1473 1474
            using (var workspace = CreateMSBuildWorkspace())
            {
                workspace.SkipUnrecognizedProjects = false;
                var project = await workspace.OpenProjectAsync(projectFilePath);
1475

1476 1477 1478 1479
                Assert.Single(project.Solution.ProjectIds);
                Assert.Empty(project.ProjectReferences);
                Assert.Empty(project.AllProjectReferences);
                Assert.Contains(project.MetadataReferences, r => r is PortableExecutableReference && ((PortableExecutableReference)r).Display.Contains("CSharpProject.dll"));
1480
            }
P
Pilchie 已提交
1481 1482
        }

1483
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1484
        public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_BadMsbuildProject_SkipTrue_SucceedsWithDanglingProjectReference()
1485 1486
        {
            CreateFiles(GetMultiProjectSolutionFiles()
1487 1488
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension)
                .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.Dlls.CSharpProject)); // use metadata file as stand-in for bad project file
1489

1490
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
1491 1492 1493 1494

            // keep metadata reference from holding files open
            Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true;

1495 1496 1497
            using (var workspace = CreateMSBuildWorkspace())
            {
                workspace.SkipUnrecognizedProjects = true;
M
Matt Warren 已提交
1498

1499
                var project = await workspace.OpenProjectAsync(projectFilePath);
1500

1501 1502 1503
                Assert.Single(project.Solution.ProjectIds);
                Assert.Empty(project.ProjectReferences);
                Assert.Single(project.AllProjectReferences);
1504

1505
                Assert.InRange(workspace.Diagnostics.Count, 2, 3);
1506
            }
1507 1508
        }

1509
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1510
        public async Task TestOpenProject_WithReferencedProject_LoadMetadata_ExistingMetadata_Succeeds()
P
Pilchie 已提交
1511
        {
1512
            CreateFiles(GetMultiProjectSolutionFiles()
1513
                .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject));
1514

1515
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
P
Pilchie 已提交
1516 1517 1518 1519

            // keep metadata reference from holding files open
            Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true;

1520 1521 1522 1523
            using (var workspace = CreateMSBuildWorkspace())
            {
                workspace.LoadMetadataForReferencedProjects = true;
                var project = await workspace.OpenProjectAsync(projectFilePath);
1524

1525 1526 1527
                // referenced project got converted to a metadata reference
                var projRefs = project.ProjectReferences.ToList();
                var metaRefs = project.MetadataReferences.ToList();
D
Dustin Campbell 已提交
1528 1529
                Assert.Empty(projRefs);
                Assert.Contains(metaRefs, r => r is PortableExecutableReference && ((PortableExecutableReference)r).Display.Contains("CSharpProject.dll"));
1530
            }
P
Pilchie 已提交
1531 1532
        }

1533
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1534
        public async Task TestOpenProject_WithReferencedProject_LoadMetadata_NonExistentMetadata_LoadsProjectInstead()
P
Pilchie 已提交
1535 1536
        {
            CreateFiles(GetMultiProjectSolutionFiles());
1537
            var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
P
Pilchie 已提交
1538 1539 1540 1541

            // keep metadata reference from holding files open
            Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true;

1542 1543 1544
            using (var workspace = CreateMSBuildWorkspace())
            {
                workspace.LoadMetadataForReferencedProjects = true;
1545
                var project = await workspace.OpenProjectAsync(projectFilePath);
1546

1547 1548 1549
                // referenced project is still a project ref, did not get converted to metadata ref
                var projRefs = project.ProjectReferences.ToList();
                var metaRefs = project.MetadataReferences.ToList();
D
Dustin Campbell 已提交
1550 1551
                Assert.Single(projRefs);
                Assert.DoesNotContain(metaRefs, r => r.Properties.Aliases.Contains("CSharpProject"));
1552
            }
P
Pilchie 已提交
1553 1554
        }

1555
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1556
        public async Task TestOpenProject_UpdateExistingReferences()
1557 1558
        {
            CreateFiles(GetMultiProjectSolutionFiles()
1559
                .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject));
1560 1561
            var vbProjectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
            var csProjectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
1562 1563 1564 1565 1566

            // keep metadata reference from holding files open
            Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true;

            // first open vb project that references c# project, but only reference the c# project's built metadata
1567 1568 1569 1570
            using (var workspace = CreateMSBuildWorkspace())
            {
                workspace.LoadMetadataForReferencedProjects = true;
                var vbProject = await workspace.OpenProjectAsync(vbProjectFilePath);
1571

1572
                // prove vb project references c# project as a metadata reference
D
Dustin Campbell 已提交
1573 1574
                Assert.Empty(vbProject.ProjectReferences);
                Assert.Contains(vbProject.MetadataReferences, r => r is PortableExecutableReference && ((PortableExecutableReference)r).Display.Contains("CSharpProject.dll"));
1575

1576 1577
                // now explicitly open the c# project that got referenced as metadata
                var csProject = await workspace.OpenProjectAsync(csProjectFilePath);
1578

1579 1580
                // show that the vb project now references the c# project directly (not as metadata)
                vbProject = workspace.CurrentSolution.GetProject(vbProject.Id);
D
Dustin Campbell 已提交
1581 1582
                Assert.Single(vbProject.ProjectReferences);
                Assert.DoesNotContain(vbProject.MetadataReferences, r => r.Properties.Aliases.Contains("CSharpProject"));
1583
            }
1584 1585
        }

1586
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(Framework35Installed))]
D
Dustin Campbell 已提交
1587
        [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
1588
        [WorkItem(528984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528984")]
1589
        public async Task TestOpenProject_AddVBDefaultReferences()
1590
        {
1591 1592 1593 1594 1595 1596 1597
            var files = new FileSet(
                ("VisualBasicProject_3_5.vbproj", Resources.ProjectFiles.VisualBasic.VisualBasicProject_3_5),
                ("VisualBasicProject_VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass));

            CreateFiles(files);

            var projectFilePath = GetSolutionFileName("VisualBasicProject_3_5.vbproj");
1598 1599 1600 1601

            // keep metadata reference from holding files open
            Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true;

1602 1603 1604 1605 1606 1607
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);
                var compilation = await project.GetCompilationAsync();
                var diagnostics = compilation.GetDiagnostics();
            }
1608 1609
        }

1610
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1611
        public async Task TestCompilationOptions_CSharp_DebugType_Full()
P
Pilchie 已提交
1612 1613
        {
            CreateCSharpFilesWith("DebugType", "full");
1614
            await AssertCSParseOptionsAsync(0, options => options.Errors.Length);
P
Pilchie 已提交
1615 1616
        }

1617
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1618
        public async Task TestCompilationOptions_CSharp_DebugType_None()
P
Pilchie 已提交
1619 1620
        {
            CreateCSharpFilesWith("DebugType", "none");
1621
            await AssertCSParseOptionsAsync(0, options => options.Errors.Length);
P
Pilchie 已提交
1622 1623
        }

1624
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1625
        public async Task TestCompilationOptions_CSharp_DebugType_PDBOnly()
P
Pilchie 已提交
1626 1627
        {
            CreateCSharpFilesWith("DebugType", "pdbonly");
1628
            await AssertCSParseOptionsAsync(0, options => options.Errors.Length);
P
Pilchie 已提交
1629 1630
        }

1631
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1632
        public async Task TestCompilationOptions_CSharp_DebugType_Portable()
1633 1634
        {
            CreateCSharpFilesWith("DebugType", "portable");
1635
            await AssertCSParseOptionsAsync(0, options => options.Errors.Length);
1636 1637
        }

1638
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1639
        public async Task TestCompilationOptions_CSharp_DebugType_Embedded()
1640 1641
        {
            CreateCSharpFilesWith("DebugType", "embedded");
1642
            await AssertCSParseOptionsAsync(0, options => options.Errors.Length);
1643 1644
        }

1645
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1646
        public async Task TestCompilationOptions_CSharp_OutputKind_DynamicallyLinkedLibrary()
P
Pilchie 已提交
1647 1648
        {
            CreateCSharpFilesWith("OutputType", "Library");
1649
            await AssertCSCompilationOptionsAsync(OutputKind.DynamicallyLinkedLibrary, options => options.OutputKind);
P
Pilchie 已提交
1650 1651
        }

1652
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1653
        public async Task TestCompilationOptions_CSharp_OutputKind_ConsoleApplication()
P
Pilchie 已提交
1654 1655
        {
            CreateCSharpFilesWith("OutputType", "Exe");
1656
            await AssertCSCompilationOptionsAsync(OutputKind.ConsoleApplication, options => options.OutputKind);
P
Pilchie 已提交
1657 1658
        }

1659
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1660
        public async Task TestCompilationOptions_CSharp_OutputKind_WindowsApplication()
P
Pilchie 已提交
1661 1662
        {
            CreateCSharpFilesWith("OutputType", "WinExe");
1663
            await AssertCSCompilationOptionsAsync(OutputKind.WindowsApplication, options => options.OutputKind);
P
Pilchie 已提交
1664 1665
        }

1666
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1667
        public async Task TestCompilationOptions_CSharp_OutputKind_NetModule()
P
Pilchie 已提交
1668 1669
        {
            CreateCSharpFilesWith("OutputType", "Module");
1670
            await AssertCSCompilationOptionsAsync(OutputKind.NetModule, options => options.OutputKind);
P
Pilchie 已提交
1671 1672
        }

1673
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1674
        public async Task TestCompilationOptions_CSharp_OptimizationLevel_Release()
P
Pilchie 已提交
1675 1676
        {
            CreateCSharpFilesWith("Optimize", "True");
1677
            await AssertCSCompilationOptionsAsync(OptimizationLevel.Release, options => options.OptimizationLevel);
P
Pilchie 已提交
1678 1679
        }

1680
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1681
        public async Task TestCompilationOptions_CSharp_OptimizationLevel_Debug()
P
Pilchie 已提交
1682 1683
        {
            CreateCSharpFilesWith("Optimize", "False");
1684
            await AssertCSCompilationOptionsAsync(OptimizationLevel.Debug, options => options.OptimizationLevel);
P
Pilchie 已提交
1685 1686
        }

1687
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1688
        public async Task TestCompilationOptions_CSharp_MainFileName()
P
Pilchie 已提交
1689 1690
        {
            CreateCSharpFilesWith("StartupObject", "Foo");
1691
            await AssertCSCompilationOptionsAsync("Foo", options => options.MainTypeName);
P
Pilchie 已提交
1692 1693
        }

1694
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1695
        public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_Missing()
P
Pilchie 已提交
1696 1697
        {
            CreateCSharpFiles();
1698
            await AssertCSCompilationOptionsAsync(null, options => options.CryptoKeyFile);
P
Pilchie 已提交
1699 1700
        }

1701
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1702
        public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_False()
P
Pilchie 已提交
1703 1704
        {
            CreateCSharpFilesWith("SignAssembly", "false");
1705
            await AssertCSCompilationOptionsAsync(null, options => options.CryptoKeyFile);
P
Pilchie 已提交
1706 1707
        }

1708
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1709
        public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_True()
P
Pilchie 已提交
1710 1711
        {
            CreateCSharpFilesWith("SignAssembly", "true");
1712
            await AssertCSCompilationOptionsAsync("snKey.snk", options => Path.GetFileName(options.CryptoKeyFile));
P
Pilchie 已提交
1713 1714
        }

1715
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1716
        public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_DelaySign_False()
P
Pilchie 已提交
1717 1718
        {
            CreateCSharpFilesWith("DelaySign", "false");
1719
            await AssertCSCompilationOptionsAsync(null, options => options.DelaySign);
P
Pilchie 已提交
1720 1721
        }

1722
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1723
        public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_DelaySign_True()
P
Pilchie 已提交
1724 1725
        {
            CreateCSharpFilesWith("DelaySign", "true");
1726
            await AssertCSCompilationOptionsAsync(true, options => options.DelaySign);
P
Pilchie 已提交
1727 1728
        }

1729
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1730
        public async Task TestCompilationOptions_CSharp_CheckOverflow_True()
P
Pilchie 已提交
1731 1732
        {
            CreateCSharpFilesWith("CheckForOverflowUnderflow", "true");
1733
            await AssertCSCompilationOptionsAsync(true, options => options.CheckOverflow);
P
Pilchie 已提交
1734 1735
        }

1736
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1737
        public async Task TestCompilationOptions_CSharp_CheckOverflow_False()
P
Pilchie 已提交
1738 1739
        {
            CreateCSharpFilesWith("CheckForOverflowUnderflow", "false");
1740
            await AssertCSCompilationOptionsAsync(false, options => options.CheckOverflow);
P
Pilchie 已提交
1741 1742
        }

1743
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1744
        public async Task TestParseOptions_CSharp_Compatibility_ECMA1()
P
Pilchie 已提交
1745 1746
        {
            CreateCSharpFilesWith("LangVersion", "ISO-1");
1747
            await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp1, options => options.LanguageVersion);
P
Pilchie 已提交
1748 1749
        }

1750
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1751
        public async Task TestParseOptions_CSharp_Compatibility_ECMA2()
P
Pilchie 已提交
1752 1753
        {
            CreateCSharpFilesWith("LangVersion", "ISO-2");
1754
            await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp2, options => options.LanguageVersion);
P
Pilchie 已提交
1755 1756
        }

1757
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1758
        public async Task TestParseOptions_CSharp_Compatibility_None()
P
Pilchie 已提交
1759 1760
        {
            CreateCSharpFilesWith("LangVersion", "3");
1761
            await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp3, options => options.LanguageVersion);
P
Pilchie 已提交
1762 1763
        }

1764
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1765
        public async Task TestParseOptions_CSharp_LanguageVersion_Default()
P
Pilchie 已提交
1766 1767
        {
            CreateCSharpFiles();
1768
            await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp7, options => options.LanguageVersion);
P
Pilchie 已提交
1769 1770
        }

1771
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1772
        public async Task TestParseOptions_CSharp_PreprocessorSymbols()
P
Pilchie 已提交
1773 1774
        {
            CreateCSharpFilesWith("DefineConstants", "DEBUG;TRACE;X;Y");
1775
            await AssertCSParseOptionsAsync("DEBUG,TRACE,X,Y", options => string.Join(",", options.PreprocessorSymbolNames));
P
Pilchie 已提交
1776 1777
        }

1778
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1779
        public async Task TestConfigurationDebug()
P
Pilchie 已提交
1780 1781
        {
            CreateCSharpFiles();
1782
            await AssertCSParseOptionsAsync("DEBUG,TRACE", options => string.Join(",", options.PreprocessorSymbolNames));
P
Pilchie 已提交
1783 1784
        }

1785
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1786
        public async Task TestConfigurationRelease()
P
Pilchie 已提交
1787 1788
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
1789
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
1790

1791 1792 1793 1794 1795
            using (var workspace = CreateMSBuildWorkspace(("Configuration", "Release")))
            {
                var sol = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = sol.Projects.First();
                var options = project.ParseOptions;
P
Pilchie 已提交
1796

D
Dustin Campbell 已提交
1797 1798
                Assert.DoesNotContain(options.PreprocessorSymbolNames, name => name == "DEBUG");
                Assert.Contains(options.PreprocessorSymbolNames, name => name == "TRACE");
1799
            }
P
Pilchie 已提交
1800 1801
        }

1802
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1803
        public async Task TestCompilationOptions_VisualBasic_DebugType_Full()
P
Pilchie 已提交
1804 1805
        {
            CreateVBFilesWith("DebugType", "full");
1806
            await AssertVBParseOptionsAsync(0, options => options.Errors.Length);
P
Pilchie 已提交
1807 1808
        }

1809
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1810
        public async Task TestCompilationOptions_VisualBasic_DebugType_None()
P
Pilchie 已提交
1811 1812
        {
            CreateVBFilesWith("DebugType", "none");
1813
            await AssertVBParseOptionsAsync(0, options => options.Errors.Length);
P
Pilchie 已提交
1814 1815
        }

1816
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1817
        public async Task TestCompilationOptions_VisualBasic_DebugType_PDBOnly()
P
Pilchie 已提交
1818 1819
        {
            CreateVBFilesWith("DebugType", "pdbonly");
1820
            await AssertVBParseOptionsAsync(0, options => options.Errors.Length);
P
Pilchie 已提交
1821 1822
        }

1823
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1824
        public async Task TestCompilationOptions_VisualBasic_DebugType_Portable()
1825 1826
        {
            CreateVBFilesWith("DebugType", "portable");
1827
            await AssertVBParseOptionsAsync(0, options => options.Errors.Length);
1828 1829
        }

1830
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1831
        public async Task TestCompilationOptions_VisualBasic_DebugType_Embedded()
1832 1833
        {
            CreateVBFilesWith("DebugType", "embedded");
1834
            await AssertVBParseOptionsAsync(0, options => options.Errors.Length);
1835 1836
        }

1837
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1838
        public async Task TestCompilationOptions_VisualBasic_VBRuntime_Embed()
P
Pilchie 已提交
1839 1840
        {
            CreateFiles(GetMultiProjectSolutionFiles()
1841
                .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.Embed));
1842
            await AssertVBCompilationOptionsAsync(true, options => options.EmbedVbCoreRuntime);
P
Pilchie 已提交
1843 1844
        }

1845
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1846
        public async Task TestCompilationOptions_VisualBasic_OutputKind_DynamicallyLinkedLibrary()
P
Pilchie 已提交
1847 1848
        {
            CreateVBFilesWith("OutputType", "Library");
1849
            await AssertVBCompilationOptionsAsync(OutputKind.DynamicallyLinkedLibrary, options => options.OutputKind);
P
Pilchie 已提交
1850 1851
        }

1852
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1853
        public async Task TestCompilationOptions_VisualBasic_OutputKind_ConsoleApplication()
P
Pilchie 已提交
1854 1855
        {
            CreateVBFilesWith("OutputType", "Exe");
1856
            await AssertVBCompilationOptionsAsync(OutputKind.ConsoleApplication, options => options.OutputKind);
P
Pilchie 已提交
1857 1858
        }

1859
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1860
        public async Task TestCompilationOptions_VisualBasic_OutputKind_WindowsApplication()
P
Pilchie 已提交
1861 1862
        {
            CreateVBFilesWith("OutputType", "WinExe");
1863
            await AssertVBCompilationOptionsAsync(OutputKind.WindowsApplication, options => options.OutputKind);
P
Pilchie 已提交
1864 1865
        }

1866
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1867
        public async Task TestCompilationOptions_VisualBasic_OutputKind_NetModule()
P
Pilchie 已提交
1868 1869
        {
            CreateVBFilesWith("OutputType", "Module");
1870
            await AssertVBCompilationOptionsAsync(OutputKind.NetModule, options => options.OutputKind);
P
Pilchie 已提交
1871 1872
        }

1873
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1874
        public async Task TestCompilationOptions_VisualBasic_RootNamespace()
P
Pilchie 已提交
1875 1876
        {
            CreateVBFilesWith("RootNamespace", "Foo.Bar");
1877
            await AssertVBCompilationOptionsAsync("Foo.Bar", options => options.RootNamespace);
P
Pilchie 已提交
1878 1879
        }

1880
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1881
        public async Task TestCompilationOptions_VisualBasic_OptionStrict_On()
P
Pilchie 已提交
1882 1883
        {
            CreateVBFilesWith("OptionStrict", "On");
1884
            await AssertVBCompilationOptionsAsync(VB.OptionStrict.On, options => options.OptionStrict);
P
Pilchie 已提交
1885 1886
        }

1887
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1888
        public async Task TestCompilationOptions_VisualBasic_OptionStrict_Off()
P
Pilchie 已提交
1889 1890
        {
            CreateVBFilesWith("OptionStrict", "Off");
D
Dustin Campbell 已提交
1891 1892 1893 1894

            // The VBC MSBuild task specifies '/optionstrict:custom' rather than '/optionstrict-'
            // See https://github.com/dotnet/roslyn/blob/58f44c39048032c6b823ddeedddd20fa589912f5/src/Compilers/Core/MSBuildTask/Vbc.cs#L390-L418 for details.

1895
            await AssertVBCompilationOptionsAsync(VB.OptionStrict.Custom, options => options.OptionStrict);
1896 1897
        }

1898
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1899
        public async Task TestCompilationOptions_VisualBasic_OptionStrict_Custom()
1900
        {
1901
            CreateVBFilesWith("OptionStrictType", "Custom");
1902
            await AssertVBCompilationOptionsAsync(VB.OptionStrict.Custom, options => options.OptionStrict);
P
Pilchie 已提交
1903 1904
        }

1905
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1906
        public async Task TestCompilationOptions_VisualBasic_OptionInfer_True()
P
Pilchie 已提交
1907 1908
        {
            CreateVBFilesWith("OptionInfer", "On");
1909
            await AssertVBCompilationOptionsAsync(true, options => options.OptionInfer);
P
Pilchie 已提交
1910 1911
        }

1912
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1913
        public async Task TestCompilationOptions_VisualBasic_OptionInfer_False()
P
Pilchie 已提交
1914 1915
        {
            CreateVBFilesWith("OptionInfer", "Off");
1916
            await AssertVBCompilationOptionsAsync(false, options => options.OptionInfer);
P
Pilchie 已提交
1917 1918
        }

1919
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1920
        public async Task TestCompilationOptions_VisualBasic_OptionExplicit_True()
P
Pilchie 已提交
1921 1922
        {
            CreateVBFilesWith("OptionExplicit", "On");
1923
            await AssertVBCompilationOptionsAsync(true, options => options.OptionExplicit);
P
Pilchie 已提交
1924 1925
        }

1926
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1927
        public async Task TestCompilationOptions_VisualBasic_OptionExplicit_False()
P
Pilchie 已提交
1928 1929
        {
            CreateVBFilesWith("OptionExplicit", "Off");
1930
            await AssertVBCompilationOptionsAsync(false, options => options.OptionExplicit);
P
Pilchie 已提交
1931 1932
        }

1933
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1934
        public async Task TestCompilationOptions_VisualBasic_OptionCompareText_True()
P
Pilchie 已提交
1935 1936
        {
            CreateVBFilesWith("OptionCompare", "Text");
1937
            await AssertVBCompilationOptionsAsync(true, options => options.OptionCompareText);
P
Pilchie 已提交
1938 1939
        }

1940
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1941
        public async Task TestCompilationOptions_VisualBasic_OptionCompareText_False()
P
Pilchie 已提交
1942 1943
        {
            CreateVBFilesWith("OptionCompare", "Binary");
1944
            await AssertVBCompilationOptionsAsync(false, options => options.OptionCompareText);
P
Pilchie 已提交
1945 1946
        }

1947
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1948
        public async Task TestCompilationOptions_VisualBasic_OptionRemoveIntegerOverflowChecks_True()
P
Pilchie 已提交
1949 1950
        {
            CreateVBFilesWith("RemoveIntegerChecks", "true");
1951
            await AssertVBCompilationOptionsAsync(false, options => options.CheckOverflow);
P
Pilchie 已提交
1952 1953
        }

1954
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1955
        public async Task TestCompilationOptions_VisualBasic_OptionRemoveIntegerOverflowChecks_False()
P
Pilchie 已提交
1956 1957
        {
            CreateVBFilesWith("RemoveIntegerChecks", "false");
1958
            await AssertVBCompilationOptionsAsync(true, options => options.CheckOverflow);
P
Pilchie 已提交
1959 1960
        }

1961
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1962
        public async Task TestCompilationOptions_VisualBasic_OptionAssemblyOriginatorKeyFile_SignAssemblyFalse()
P
Pilchie 已提交
1963 1964
        {
            CreateVBFilesWith("SignAssembly", "false");
1965
            await AssertVBCompilationOptionsAsync(null, options => options.CryptoKeyFile);
P
Pilchie 已提交
1966 1967
        }

1968
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1969
        public async Task TestCompilationOptions_VisualBasic_GlobalImports()
P
Pilchie 已提交
1970 1971
        {
            CreateFiles(GetMultiProjectSolutionFiles());
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = solution.GetProjectsByName("VisualBasicProject").FirstOrDefault();
                var options = (VB.VisualBasicCompilationOptions)project.CompilationOptions;
                var imports = options.GlobalImports;

                AssertEx.Equal(
                    expected: new[]
                    {
                        "Microsoft.VisualBasic",
                        "System",
                        "System.Collections",
                        "System.Collections.Generic",
                        "System.Diagnostics",
                        "System.Linq",
                    },
                    actual: imports.Select(i => i.Name));
            }
P
Pilchie 已提交
1993 1994
        }

1995
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
1996
        public async Task TestParseOptions_VisualBasic_PreprocessorSymbols()
P
Pilchie 已提交
1997 1998 1999
        {
            CreateFiles(GetMultiProjectSolutionFiles()
                .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "DefineConstants", "X=1,Y=2,Z,T=-1,VBC_VER=123,F=false"));
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = solution.GetProjectsByName("VisualBasicProject").FirstOrDefault();
                var options = (VB.VisualBasicParseOptions)project.ParseOptions;
                var defines = new List<KeyValuePair<string, object>>(options.PreprocessorSymbols);
                defines.Sort((x, y) => x.Key.CompareTo(y.Key));

                AssertEx.Equal(
                    expected: new[]
                    {
                        new KeyValuePair<string, object>("_MyType", "Windows"),
                        new KeyValuePair<string, object>("CONFIG", "Debug"),
                        new KeyValuePair<string, object>("DEBUG", -1),
                        new KeyValuePair<string, object>("F", false),
                        new KeyValuePair<string, object>("PLATFORM", "AnyCPU"),
                        new KeyValuePair<string, object>("T", -1),
                        new KeyValuePair<string, object>("TARGET", "library"),
                        new KeyValuePair<string, object>("TRACE", -1),
                        new KeyValuePair<string, object>("VBC_VER", 123),
                        new KeyValuePair<string, object>("X", 1),
                        new KeyValuePair<string, object>("Y", 2),
                        new KeyValuePair<string, object>("Z", true),
                    },
                    actual: defines);
            }
P
Pilchie 已提交
2028 2029
        }

2030
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2031
        public async Task Test_VisualBasic_ConditionalAttributeEmitted()
P
Pilchie 已提交
2032 2033
        {
            CreateFiles(GetMultiProjectSolutionFiles()
2034
                .WithFile(@"VisualBasicProject\VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes)
P
Pilchie 已提交
2035
                .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "DefineConstants", "EnableMyAttribute"));
2036
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
2037

2038 2039 2040 2041 2042 2043
            using (var workspace = CreateMSBuildWorkspace())
            {
                var sol = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault();
                var options = (VB.VisualBasicParseOptions)project.ParseOptions;
                Assert.Equal(true, options.PreprocessorSymbolNames.Contains("EnableMyAttribute"));
P
Pilchie 已提交
2044

2045 2046 2047 2048 2049 2050
                var compilation = await project.GetCompilationAsync();
                var metadataBytes = compilation.EmitToArray();
                var mtref = MetadataReference.CreateFromImage(metadataBytes);
                var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref });
                var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref);
                var attrs = sym.GetAttributes();
P
Pilchie 已提交
2051

D
Dustin Campbell 已提交
2052
                Assert.Contains(attrs, ad => ad.AttributeClass.Name == "MyAttribute");
2053
            }
P
Pilchie 已提交
2054 2055
        }

2056
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2057
        public async Task Test_VisualBasic_ConditionalAttributeNotEmitted()
P
Pilchie 已提交
2058 2059
        {
            CreateFiles(GetMultiProjectSolutionFiles()
2060
                .WithFile(@"VisualBasicProject\VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes));
2061
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
2062

2063 2064 2065 2066 2067 2068
            using (var workspace = CreateMSBuildWorkspace())
            {
                var sol = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault();
                var options = (VB.VisualBasicParseOptions)project.ParseOptions;
                Assert.Equal(false, options.PreprocessorSymbolNames.Contains("EnableMyAttribute"));
P
Pilchie 已提交
2069

2070 2071 2072 2073 2074 2075
                var compilation = await project.GetCompilationAsync();
                var metadataBytes = compilation.EmitToArray();
                var mtref = MetadataReference.CreateFromImage(metadataBytes);
                var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref });
                var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref);
                var attrs = sym.GetAttributes();
P
Pilchie 已提交
2076

D
Dustin Campbell 已提交
2077
                Assert.DoesNotContain(attrs, ad => ad.AttributeClass.Name == "MyAttribute");
2078
            }
P
Pilchie 已提交
2079 2080
        }

2081
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2082
        public async Task Test_CSharp_ConditionalAttributeEmitted()
P
Pilchie 已提交
2083
        {
2084
            CreateFiles(GetSimpleCSharpSolutionFiles()
2085
                .WithFile(@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass_WithConditionalAttributes)
P
Pilchie 已提交
2086
                .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "DefineConstants", "EnableMyAttribute"));
2087
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
2088

2089 2090 2091 2092 2093
            using (var workspace = CreateMSBuildWorkspace())
            {
                var sol = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = sol.GetProjectsByName("CSharpProject").FirstOrDefault();
                var options = project.ParseOptions;
D
Dustin Campbell 已提交
2094
                Assert.Contains("EnableMyAttribute", options.PreprocessorSymbolNames);
P
Pilchie 已提交
2095

2096 2097 2098 2099 2100 2101
                var compilation = await project.GetCompilationAsync();
                var metadataBytes = compilation.EmitToArray();
                var mtref = MetadataReference.CreateFromImage(metadataBytes);
                var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref });
                var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref);
                var attrs = sym.GetAttributes();
P
Pilchie 已提交
2102

D
Dustin Campbell 已提交
2103
                Assert.Contains(attrs, ad => ad.AttributeClass.Name == "MyAttr");
2104
            }
P
Pilchie 已提交
2105 2106
        }

2107
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2108
        public async Task Test_CSharp_ConditionalAttributeNotEmitted()
P
Pilchie 已提交
2109
        {
2110
            CreateFiles(GetSimpleCSharpSolutionFiles()
2111
                .WithFile(@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass_WithConditionalAttributes));
2112
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
2113

2114 2115 2116 2117 2118
            using (var workspace = CreateMSBuildWorkspace())
            {
                var sol = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = sol.GetProjectsByName("CSharpProject").FirstOrDefault();
                var options = project.ParseOptions;
D
Dustin Campbell 已提交
2119
                Assert.DoesNotContain("EnableMyAttribute", options.PreprocessorSymbolNames);
P
Pilchie 已提交
2120

2121 2122 2123 2124 2125 2126
                var compilation = await project.GetCompilationAsync();
                var metadataBytes = compilation.EmitToArray();
                var mtref = MetadataReference.CreateFromImage(metadataBytes);
                var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref });
                var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref);
                var attrs = sym.GetAttributes();
P
Pilchie 已提交
2127

D
Dustin Campbell 已提交
2128
                Assert.DoesNotContain(attrs, ad => ad.AttributeClass.Name == "MyAttr");
2129
            }
P
Pilchie 已提交
2130 2131
        }

2132
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2133
        public async Task TestOpenProject_CSharp_WithLinkedDocument()
P
Pilchie 已提交
2134 2135
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
2136 2137 2138
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithLink)
                .WithFile(@"OtherStuff\Foo.cs", Resources.SourceFiles.CSharp.OtherStuff_Foo));

2139 2140 2141 2142 2143 2144 2145 2146
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault();
                var documents = project.Documents.ToList();
                var fooDoc = documents.Single(d => d.Name == "Foo.cs");
2147 2148
                var folder = Assert.Single(fooDoc.Folders);
                Assert.Equal("Blah", folder);
2149 2150

                // prove that the file path is the correct full path to the actual file
D
Dustin Campbell 已提交
2151 2152
                Assert.Contains("OtherStuff", fooDoc.FilePath);
                Assert.True(File.Exists(fooDoc.FilePath));
2153
                var text = File.ReadAllText(fooDoc.FilePath);
2154
                Assert.Equal(Resources.SourceFiles.CSharp.OtherStuff_Foo, text);
2155
            }
P
Pilchie 已提交
2156 2157
        }

2158
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2159
        public async Task TestAddDocumentAsync()
P
Pilchie 已提交
2160 2161
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
2162 2163 2164 2165 2166 2167
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault();
P
Pilchie 已提交
2168

2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
                var newText = SourceText.From("public class Bar { }");
                workspace.AddDocument(project.Id, new string[] { "NewFolder" }, "Bar.cs", newText);

                // check workspace current solution
                var solution2 = workspace.CurrentSolution;
                var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault();
                var documents = project2.Documents.ToList();
                Assert.Equal(4, documents.Count);
                var document2 = documents.Single(d => d.Name == "Bar.cs");
                var text2 = await document2.GetTextAsync();
                Assert.Equal(newText.ToString(), text2.ToString());
D
Dustin Campbell 已提交
2180
                Assert.Single(document2.Folders);
2181 2182 2183 2184 2185 2186 2187

                // check actual file on disk...
                var textOnDisk = File.ReadAllText(document2.FilePath);
                Assert.Equal(newText.ToString(), textOnDisk);

                // check project file on disk
                var projectFileText = File.ReadAllText(project2.FilePath);
D
Dustin Campbell 已提交
2188
                Assert.Contains(@"NewFolder\Bar.cs", projectFileText);
2189 2190 2191 2192 2193 2194 2195 2196 2197

                // reload project & solution to prove project file change was good
                using (var workspaceB = CreateMSBuildWorkspace())
                {
                    var solutionB = await workspaceB.OpenSolutionAsync(solutionFilePath);
                    var projectB = workspaceB.CurrentSolution.GetProjectsByName("CSharpProject").FirstOrDefault();
                    var documentsB = projectB.Documents.ToList();
                    Assert.Equal(4, documentsB.Count);
                    var documentB = documentsB.Single(d => d.Name == "Bar.cs");
D
Dustin Campbell 已提交
2198
                    Assert.Single(documentB.Folders);
2199 2200
                }
            }
P
Pilchie 已提交
2201 2202
        }

2203
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2204
        public async Task TestUpdateDocumentAsync()
P
Pilchie 已提交
2205 2206
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
2207 2208 2209 2210 2211 2212 2213 2214
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault();
                var document = project.Documents.Single(d => d.Name == "CSharpClass.cs");
                var originalText = await document.GetTextAsync();
P
Pilchie 已提交
2215

2216 2217
                var newText = SourceText.From("public class Bar { }");
                workspace.TryApplyChanges(solution.WithDocumentText(document.Id, newText, PreservationMode.PreserveIdentity));
P
Pilchie 已提交
2218

2219 2220 2221 2222 2223 2224 2225 2226
                // check workspace current solution
                var solution2 = workspace.CurrentSolution;
                var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault();
                var documents = project2.Documents.ToList();
                Assert.Equal(3, documents.Count);
                var document2 = documents.Single(d => d.Name == "CSharpClass.cs");
                var text2 = await document2.GetTextAsync();
                Assert.Equal(newText.ToString(), text2.ToString());
P
Pilchie 已提交
2227

2228 2229 2230
                // check actual file on disk...
                var textOnDisk = File.ReadAllText(document2.FilePath);
                Assert.Equal(newText.ToString(), textOnDisk);
P
Pilchie 已提交
2231

2232 2233
                // check original text in original solution did not change
                var text = await document.GetTextAsync();
P
Pilchie 已提交
2234

2235 2236
                Assert.Equal(originalText.ToString(), text.ToString());
            }
P
Pilchie 已提交
2237 2238
        }

2239
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2240
        public async Task TestRemoveDocumentAsync()
P
Pilchie 已提交
2241 2242
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
2243
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
2244

2245 2246 2247 2248 2249 2250
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault();
                var document = project.Documents.Single(d => d.Name == "CSharpClass.cs");
                var originalText = await document.GetTextAsync();
P
Pilchie 已提交
2251

2252
                workspace.RemoveDocument(document.Id);
P
Pilchie 已提交
2253

2254 2255 2256
                // check workspace current solution
                var solution2 = workspace.CurrentSolution;
                var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault();
D
Dustin Campbell 已提交
2257
                Assert.DoesNotContain(project2.Documents, d => d.Name == "CSharpClass.cs");
P
Pilchie 已提交
2258

2259 2260
                // check actual file on disk...
                Assert.False(File.Exists(document.FilePath));
P
Pilchie 已提交
2261

2262 2263 2264 2265
                // check original text in original solution did not change
                var text = await document.GetTextAsync();
                Assert.Equal(originalText.ToString(), text.ToString());
            }
P
Pilchie 已提交
2266 2267
        }

2268
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2269
        public async Task TestApplyChanges_UpdateDocumentText()
P
Pilchie 已提交
2270 2271
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
2272
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
2273

2274 2275 2276 2277 2278 2279 2280 2281
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var documents = solution.GetProjectsByName("CSharpProject").FirstOrDefault().Documents.ToList();
                var document = documents.Single(d => d.Name.Contains("CSharpClass"));
                var text = await document.GetTextAsync();
                var newText = SourceText.From("using System.Diagnostics;\r\n" + text.ToString());
                var newSolution = solution.WithDocumentText(document.Id, newText);
P
Pilchie 已提交
2282

2283
                workspace.TryApplyChanges(newSolution);
P
Pilchie 已提交
2284

2285 2286 2287 2288 2289
                // check workspace current solution
                var solution2 = workspace.CurrentSolution;
                var document2 = solution2.GetDocument(document.Id);
                var text2 = await document2.GetTextAsync();
                Assert.Equal(newText.ToString(), text2.ToString());
P
Pilchie 已提交
2290

2291 2292 2293 2294
                // check actual file on disk...
                var textOnDisk = File.ReadAllText(document.FilePath);
                Assert.Equal(newText.ToString(), textOnDisk);
            }
P
Pilchie 已提交
2295 2296
        }

2297
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2298
        public async Task TestApplyChanges_AddDocument()
P
Pilchie 已提交
2299 2300
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
2301
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
2302

2303 2304 2305 2306 2307 2308 2309
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault();
                var newDocId = DocumentId.CreateNewId(project.Id);
                var newText = SourceText.From("public class Bar { }");
                var newSolution = solution.AddDocument(newDocId, "Bar.cs", newText);
P
Pilchie 已提交
2310

2311
                workspace.TryApplyChanges(newSolution);
P
Pilchie 已提交
2312

2313 2314 2315 2316 2317
                // check workspace current solution
                var solution2 = workspace.CurrentSolution;
                var document2 = solution2.GetDocument(newDocId);
                var text2 = await document2.GetTextAsync();
                Assert.Equal(newText.ToString(), text2.ToString());
P
Pilchie 已提交
2318

2319 2320 2321 2322
                // check actual file on disk...
                var textOnDisk = File.ReadAllText(document2.FilePath);
                Assert.Equal(newText.ToString(), textOnDisk);
            }
P
Pilchie 已提交
2323 2324
        }

2325
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2326
        public async Task TestApplyChanges_NotSupportedChangesFail()
2327 2328 2329 2330 2331
        {
            var csharpProjPath = @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj";
            var vbProjPath = @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj";
            CreateFiles(GetAnalyzerReferenceSolutionFiles());

2332 2333 2334 2335 2336
            using (var workspace = CreateMSBuildWorkspace())
            {
                var csProjectFilePath = GetSolutionFileName(csharpProjPath);
                var csProject = await workspace.OpenProjectAsync(csProjectFilePath);
                var csProjectId = csProject.Id;
2337

2338 2339 2340
                var vbProjectFilePath = GetSolutionFileName(vbProjPath);
                var vbProject = await workspace.OpenProjectAsync(vbProjectFilePath);
                var vbProjectId = vbProject.Id;
2341

2342
                // adding additional documents not supported.
D
Dustin Campbell 已提交
2343
                Assert.False(workspace.CanApplyChange(ApplyChangesKind.AddAdditionalDocument));
2344 2345 2346 2347
                Assert.Throws<NotSupportedException>(delegate
                {
                    workspace.TryApplyChanges(workspace.CurrentSolution.AddAdditionalDocument(DocumentId.CreateNewId(csProjectId), "foo.xaml", SourceText.From("<foo></foo>")));
                });
2348

2349 2350
                var xaml = workspace.CurrentSolution.GetProject(csProjectId).AdditionalDocuments.FirstOrDefault(d => d.Name == "XamlFile.xaml");
                Assert.NotNull(xaml);
2351

2352
                // removing additional documents not supported
D
Dustin Campbell 已提交
2353
                Assert.False(workspace.CanApplyChange(ApplyChangesKind.RemoveAdditionalDocument));
2354 2355 2356 2357 2358
                Assert.Throws<NotSupportedException>(delegate
                {
                    workspace.TryApplyChanges(workspace.CurrentSolution.RemoveAdditionalDocument(xaml.Id));
                });
            }
2359 2360
        }

2361
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2362
        public async Task TestWorkspaceChangedEvent()
P
Pilchie 已提交
2363 2364
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
2365
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
2366

2367
            using (var workspace = CreateMSBuildWorkspace())
P
Pilchie 已提交
2368
            {
2369
                await workspace.OpenSolutionAsync(solutionFilePath);
P
Pilchie 已提交
2370
                var expectedEventKind = WorkspaceChangeKind.DocumentChanged;
2371
                var originalSolution = workspace.CurrentSolution;
P
Pilchie 已提交
2372

2373
                using (var eventWaiter = workspace.VerifyWorkspaceChangedEvent(args =>
P
Pilchie 已提交
2374 2375 2376 2377 2378 2379 2380
                {
                    Assert.Equal(expectedEventKind, args.Kind);
                    Assert.NotNull(args.NewSolution);
                    Assert.NotSame(originalSolution, args.NewSolution);
                }))
                {
                    // change document text (should fire SolutionChanged event)
2381 2382 2383
                    var doc = workspace.CurrentSolution.Projects.First().Documents.First();
                    var text = await doc.GetTextAsync();
                    var newText = "/* new text */\r\n" + text.ToString();
P
Pilchie 已提交
2384

2385
                    workspace.TryApplyChanges(workspace.CurrentSolution.WithDocumentText(doc.Id, SourceText.From(newText), PreservationMode.PreserveIdentity));
P
Pilchie 已提交
2386

2387
                    Assert.True(eventWaiter.WaitForEventToFire(AsyncEventTimeout),
P
Pilchie 已提交
2388 2389
                        string.Format("event {0} was not fired within {1}",
                        Enum.GetName(typeof(WorkspaceChangeKind), expectedEventKind),
2390
                        AsyncEventTimeout));
P
Pilchie 已提交
2391 2392 2393 2394
                }
            }
        }

2395
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2396
        public async Task TestWorkspaceChangedWeakEvent()
P
Pilchie 已提交
2397 2398
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
2399
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
2400

2401
            using (var workspace = CreateMSBuildWorkspace())
P
Pilchie 已提交
2402
            {
2403
                await workspace.OpenSolutionAsync(solutionFilePath);
P
Pilchie 已提交
2404
                var expectedEventKind = WorkspaceChangeKind.DocumentChanged;
2405
                var originalSolution = workspace.CurrentSolution;
P
Pilchie 已提交
2406

2407
                using (var eventWanter = workspace.VerifyWorkspaceChangedEvent(args =>
P
Pilchie 已提交
2408 2409 2410 2411 2412 2413 2414
                {
                    Assert.Equal(expectedEventKind, args.Kind);
                    Assert.NotNull(args.NewSolution);
                    Assert.NotSame(originalSolution, args.NewSolution);
                }))
                {
                    // change document text (should fire SolutionChanged event)
2415 2416 2417
                    var doc = workspace.CurrentSolution.Projects.First().Documents.First();
                    var text = await doc.GetTextAsync();
                    var newText = "/* new text */\r\n" + text.ToString();
P
Pilchie 已提交
2418

2419 2420
                    workspace.TryApplyChanges(
                        workspace
P
Pilchie 已提交
2421 2422 2423 2424 2425 2426
                        .CurrentSolution
                        .WithDocumentText(
                            doc.Id,
                            SourceText.From(newText),
                            PreservationMode.PreserveIdentity));

2427
                    Assert.True(eventWanter.WaitForEventToFire(AsyncEventTimeout),
P
Pilchie 已提交
2428 2429
                        string.Format("event {0} was not fired within {1}",
                        Enum.GetName(typeof(WorkspaceChangeKind), expectedEventKind),
2430
                        AsyncEventTimeout));
P
Pilchie 已提交
2431 2432 2433 2434
                }
            }
        }

2435
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2436
        public async Task TestSemanticVersionCS()
P
Pilchie 已提交
2437 2438
        {
            CreateFiles(GetMultiProjectSolutionFiles());
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);

                var csprojectId = solution.Projects.First(p => p.Language == LanguageNames.CSharp).Id;
                var csdoc1 = solution.GetProject(csprojectId).Documents.Single(d => d.Name == "CSharpClass.cs");

                // add method
                var csdoc1Root = await csdoc1.GetSyntaxRootAsync();
                var startOfClassInterior = csdoc1Root.DescendantNodes().OfType<CS.Syntax.ClassDeclarationSyntax>().First().OpenBraceToken.FullSpan.End;
                var csdoc1Text = await csdoc1.GetTextAsync();
                var csdoc2 = AssertSemanticVersionChanged(csdoc1, csdoc1Text.Replace(new TextSpan(startOfClassInterior, 0), "public async Task M() {\r\n}\r\n"));

                // change interior of method
                var csdoc2Root = await csdoc2.GetSyntaxRootAsync();
                var startOfMethodInterior = csdoc2Root.DescendantNodes().OfType<CS.Syntax.MethodDeclarationSyntax>().First().Body.OpenBraceToken.FullSpan.End;
                var csdoc2Text = await csdoc2.GetTextAsync();
                var csdoc3 = AssertSemanticVersionUnchanged(csdoc2, csdoc2Text.Replace(new TextSpan(startOfMethodInterior, 0), "int x = 10;\r\n"));

                // add whitespace outside of method
                var csdoc3Text = await csdoc3.GetTextAsync();
                var csdoc4 = AssertSemanticVersionUnchanged(csdoc3, csdoc3Text.Replace(new TextSpan(startOfClassInterior, 0), "\r\n\r\n   \r\n"));

                // add field with initializer
                csdoc1Text = await csdoc1.GetTextAsync();
                var csdoc5 = AssertSemanticVersionChanged(csdoc1, csdoc1Text.Replace(new TextSpan(startOfClassInterior, 0), "\r\npublic int X = 20;\r\n"));

2468
                // change initializer value
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483
                var csdoc5Root = await csdoc5.GetSyntaxRootAsync();
                var literal = csdoc5Root.DescendantNodes().OfType<CS.Syntax.LiteralExpressionSyntax>().First(x => x.Token.ValueText == "20");
                var csdoc5Text = await csdoc5.GetTextAsync();
                var csdoc6 = AssertSemanticVersionUnchanged(csdoc5, csdoc5Text.Replace(literal.Span, "100"));

                // add const field with initializer
                csdoc1Text = await csdoc1.GetTextAsync();
                var csdoc7 = AssertSemanticVersionChanged(csdoc1, csdoc1Text.Replace(new TextSpan(startOfClassInterior, 0), "\r\npublic const int X = 20;\r\n"));

                // change constant initializer value
                var csdoc7Root = await csdoc7.GetSyntaxRootAsync();
                var literal7 = csdoc7Root.DescendantNodes().OfType<CS.Syntax.LiteralExpressionSyntax>().First(x => x.Token.ValueText == "20");
                var csdoc7Text = await csdoc7.GetTextAsync();
                var csdoc8 = AssertSemanticVersionChanged(csdoc7, csdoc7Text.Replace(literal7.Span, "100"));
            }
P
Pilchie 已提交
2484 2485
        }

2486
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2487
        public async Task TestSemanticVersionVB()
P
Pilchie 已提交
2488 2489
        {
            CreateFiles(GetMultiProjectSolutionFiles());
2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);

                var vbprojectId = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic).Id;
                var vbdoc1 = solution.GetProject(vbprojectId).Documents.Single(d => d.Name == "VisualBasicClass.vb");

                // add method
                var vbdoc1Root = await vbdoc1.GetSyntaxRootAsync();
                var startOfClassInterior = GetMethodInsertionPoint(vbdoc1Root.DescendantNodes().OfType<VB.Syntax.ClassBlockSyntax>().First());
                var vbdoc1Text = await vbdoc1.GetTextAsync();
                var vbdoc2 = AssertSemanticVersionChanged(vbdoc1, vbdoc1Text.Replace(new TextSpan(startOfClassInterior, 0), "\r\nPublic Sub M()\r\n\r\nEnd Sub\r\n"));

                // change interior of method
                var vbdoc2Root = await vbdoc2.GetSyntaxRootAsync();
                var startOfMethodInterior = vbdoc2Root.DescendantNodes().OfType<VB.Syntax.MethodBlockBaseSyntax>().First().BlockStatement.FullSpan.End;
                var vbdoc2Text = await vbdoc2.GetTextAsync();
                var vbdoc3 = AssertSemanticVersionUnchanged(vbdoc2, vbdoc2Text.Replace(new TextSpan(startOfMethodInterior, 0), "\r\nDim x As Integer = 10\r\n"));

                // add whitespace outside of method
                var vbdoc3Text = await vbdoc3.GetTextAsync();
                var vbdoc4 = AssertSemanticVersionUnchanged(vbdoc3, vbdoc3Text.Replace(new TextSpan(startOfClassInterior, 0), "\r\n\r\n   \r\n"));

                // add field with initializer
                vbdoc1Text = await vbdoc1.GetTextAsync();
                var vbdoc5 = AssertSemanticVersionChanged(vbdoc1, vbdoc1Text.Replace(new TextSpan(startOfClassInterior, 0), "\r\nPublic X As Integer = 20;\r\n"));

                // change initializer value
                var vbdoc5Root = await vbdoc5.GetSyntaxRootAsync();
                var literal = vbdoc5Root.DescendantNodes().OfType<VB.Syntax.LiteralExpressionSyntax>().First(x => x.Token.ValueText == "20");
                var vbdoc5Text = await vbdoc5.GetTextAsync();
                var vbdoc6 = AssertSemanticVersionUnchanged(vbdoc5, vbdoc5Text.Replace(literal.Span, "100"));

                // add const field with initializer
                vbdoc1Text = await vbdoc1.GetTextAsync();
                var vbdoc7 = AssertSemanticVersionChanged(vbdoc1, vbdoc1Text.Replace(new TextSpan(startOfClassInterior, 0), "\r\nPublic Const X As Integer = 20;\r\n"));

                // change constant initializer value
                var vbdoc7Root = await vbdoc7.GetSyntaxRootAsync();
                var literal7 = vbdoc7Root.DescendantNodes().OfType<VB.Syntax.LiteralExpressionSyntax>().First(x => x.Token.ValueText == "20");
                var vbdoc7Text = await vbdoc7.GetTextAsync();
                var vbdoc8 = AssertSemanticVersionChanged(vbdoc7, vbdoc7Text.Replace(literal7.Span, "100"));
            }
P
Pilchie 已提交
2535 2536
        }

2537
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2538 2539
        [WorkItem(529276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529276"), WorkItem(12086, "DevDiv_Projects/Roslyn")]
        public async Task TestOpenProject_LoadMetadataForReferenceProjects_NoMetadata()
P
Pilchie 已提交
2540 2541 2542 2543 2544 2545
        {
            var projPath = @"CSharpProject\CSharpProject_ProjectReference.csproj";
            var files = GetProjectReferenceSolutionFiles();

            CreateFiles(files);

2546 2547 2548
            var projectFullPath = GetSolutionFileName(projPath);

            using (var workspace = CreateMSBuildWorkspace())
P
Pilchie 已提交
2549
            {
2550 2551 2552
                workspace.LoadMetadataForReferencedProjects = true;

                var proj = await workspace.OpenProjectAsync(projectFullPath);
P
Pilchie 已提交
2553 2554

                // prove that project gets opened instead.
2555
                Assert.Equal(2, workspace.CurrentSolution.Projects.Count());
P
Pilchie 已提交
2556 2557

                // and all is well
2558
                var comp = await proj.GetCompilationAsync();
P
Pilchie 已提交
2559 2560 2561 2562 2563
                var errs = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error);
                Assert.Empty(errs);
            }
        }

2564
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2565
        [WorkItem(918072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918072")]
D
Dustin Campbell 已提交
2566
        public async Task TestAnalyzerReferenceLoadStandalone()
2567 2568 2569 2570 2571 2572
        {
            var projPaths = new[] { @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj", @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj" };
            var files = GetAnalyzerReferenceSolutionFiles();

            CreateFiles(files);

2573
            using (var workspace = CreateMSBuildWorkspace())
2574 2575 2576
            {
                foreach (var projectPath in projPaths)
                {
2577 2578 2579
                    var projectFullPath = GetSolutionFileName(projectPath);

                    var proj = await workspace.OpenProjectAsync(projectFullPath);
2580
                    Assert.Equal(1, proj.AnalyzerReferences.Count);
2581 2582
                    var analyzerReference = proj.AnalyzerReferences.First() as AnalyzerFileReference;
                    Assert.NotNull(analyzerReference);
2583
                    Assert.True(analyzerReference.FullPath.EndsWith("CSharpProject.dll", StringComparison.OrdinalIgnoreCase));
2584 2585 2586
                }

                // prove that project gets opened instead.
2587
                Assert.Equal(2, workspace.CurrentSolution.Projects.Count());
2588 2589 2590
            }
        }

2591
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
C
Cyrus Najmabadi 已提交
2592
        public async Task TestAdditionalFilesStandalone()
2593 2594 2595 2596 2597 2598
        {
            var projPaths = new[] { @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj", @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj" };
            var files = GetAnalyzerReferenceSolutionFiles();

            CreateFiles(files);

2599
            using (var workspace = CreateMSBuildWorkspace())
2600 2601 2602
            {
                foreach (var projectPath in projPaths)
                {
2603 2604 2605
                    var projectFullPath = GetSolutionFileName(projectPath);

                    var proj = await workspace.OpenProjectAsync(projectFullPath);
2606
                    var doc = Assert.Single(proj.AdditionalDocuments);
2607
                    Assert.Equal("XamlFile.xaml", doc.Name);
2608 2609
                    var text = await doc.GetTextAsync();
                    Assert.Contains("Window", text.ToString(), StringComparison.Ordinal);
2610 2611 2612 2613
                }
            }
        }

2614
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2615
        public async Task TestLoadTextSync()
M
Matt Warren 已提交
2616 2617 2618 2619 2620
        {
            var files = GetAnalyzerReferenceSolutionFiles();

            CreateFiles(files);

2621
            using (var workspace = new AdhocWorkspace(MSBuildMefHostServices.DefaultServices, WorkspaceKind.MSBuild))
M
Matt Warren 已提交
2622
            {
2623
                var projectFullPath = GetSolutionFileName(@"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj");
M
Matt Warren 已提交
2624

2625 2626
                var loader = new MSBuildProjectLoader(workspace);
                var infos = await loader.LoadProjectInfoAsync(projectFullPath);
M
Matt Warren 已提交
2627 2628

                var doc = infos[0].Documents[0];
2629
                var tav = doc.TextLoader.LoadTextAndVersionSynchronously(workspace, doc.Id, CancellationToken.None);
M
Matt Warren 已提交
2630 2631

                var adoc = infos[0].AdditionalDocuments.First(a => a.Name == "XamlFile.xaml");
2632
                var atav = adoc.TextLoader.LoadTextAndVersionSynchronously(workspace, adoc.Id, CancellationToken.None);
M
Matt Warren 已提交
2633 2634 2635 2636
                Assert.Contains("Window", atav.Text.ToString(), StringComparison.Ordinal);
            }
        }

2637
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2638
        public async Task TestGetTextSynchronously()
M
Matt Warren 已提交
2639 2640 2641 2642 2643
        {
            var files = GetAnalyzerReferenceSolutionFiles();

            CreateFiles(files);

2644
            using (var workspace = CreateMSBuildWorkspace())
M
Matt Warren 已提交
2645
            {
2646 2647
                var projectFullPath = GetSolutionFileName(@"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj");
                var proj = await workspace.OpenProjectAsync(projectFullPath);
M
Matt Warren 已提交
2648 2649

                var doc = proj.Documents.First();
M
Matt Warren 已提交
2650
                var text = doc.State.GetTextSynchronously(CancellationToken.None);
M
Matt Warren 已提交
2651 2652

                var adoc = proj.AdditionalDocuments.First(a => a.Name == "XamlFile.xaml");
M
Matt Warren 已提交
2653
                var atext = adoc.State.GetTextSynchronously(CancellationToken.None);
M
Matt Warren 已提交
2654 2655 2656 2657
                Assert.Contains("Window", atext.ToString(), StringComparison.Ordinal);
            }
        }

2658
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
D
Dustin Campbell 已提交
2659
        [WorkItem(546171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546171")]
2660
        public async Task TestCSharpExternAlias()
P
Pilchie 已提交
2661 2662
        {
            var projPath = @"CSharpProject\CSharpProject_ExternAlias.csproj";
2663
            var files = new FileSet(
2664 2665
                (projPath, Resources.ProjectFiles.CSharp.ExternAlias),
                (@"CSharpProject\CSharpExternAlias.cs", Resources.SourceFiles.CSharp.CSharpExternAlias));
P
Pilchie 已提交
2666 2667 2668

            CreateFiles(files);

2669 2670
            var fullPath = GetSolutionFileName(projPath);
            using (var workspace = CreateMSBuildWorkspace())
P
Pilchie 已提交
2671
            {
2672 2673
                var proj = await workspace.OpenProjectAsync(fullPath);
                var comp = await proj.GetCompilationAsync();
P
Pilchie 已提交
2674 2675 2676 2677
                comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
            }
        }

2678
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
D
Dustin Campbell 已提交
2679
        [WorkItem(530337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530337")]
2680
        public async Task TestProjectReferenceWithExternAlias()
P
Pilchie 已提交
2681 2682 2683 2684
        {
            var files = GetProjectReferenceSolutionFiles();
            CreateFiles(files);

2685 2686 2687
            var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln");

            using (var workspace = CreateMSBuildWorkspace())
P
Pilchie 已提交
2688
            {
2689
                var sol = await workspace.OpenSolutionAsync(fullPath);
P
Pilchie 已提交
2690
                var proj = sol.Projects.First();
2691
                var comp = await proj.GetCompilationAsync();
P
Pilchie 已提交
2692 2693 2694 2695
                comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
            }
        }

2696
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2697
        public async Task TestProjectReferenceWithReferenceOutputAssemblyFalse()
2698 2699 2700 2701 2702 2703 2704 2705 2706
        {
            var files = GetProjectReferenceSolutionFiles();
            files = VisitProjectReferences(files, r =>
            {
                r.Add(new XElement(XName.Get("ReferenceOutputAssembly", MSBuildNamespace), "false"));
            });

            CreateFiles(files);

2707 2708 2709
            var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln");

            using (var workspace = CreateMSBuildWorkspace())
2710
            {
2711
                var sol = await workspace.OpenSolutionAsync(fullPath);
2712 2713
                foreach (var project in sol.Projects)
                {
D
Dustin Campbell 已提交
2714
                    Assert.Empty(project.ProjectReferences);
2715 2716 2717 2718 2719 2720
                }
            }
        }

        private FileSet VisitProjectReferences(FileSet files, Action<XElement> visitProjectReference)
        {
2721 2722
            var result = new List<(string, object)>();
            foreach (var (fileName, fileContent) in files)
2723
            {
2724 2725
                var text = fileContent.ToString();
                if (fileName.EndsWith("proj", StringComparison.OrdinalIgnoreCase))
2726 2727 2728 2729
                {
                    text = VisitProjectReferences(text, visitProjectReference);
                }

2730
                result.Add((fileName, text));
2731 2732
            }

2733
            return new FileSet(result.ToArray());
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747
        }

        private string VisitProjectReferences(string projectFileText, Action<XElement> visitProjectReference)
        {
            var document = XDocument.Parse(projectFileText);
            var projectReferenceItems = document.Descendants(XName.Get("ProjectReference", MSBuildNamespace));
            foreach (var projectReferenceItem in projectReferenceItems)
            {
                visitProjectReference(projectReferenceItem);
            }

            return document.ToString();
        }

2748
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2749
        public async Task TestProjectReferenceWithNoGuid()
2750 2751 2752 2753 2754 2755 2756 2757 2758
        {
            var files = GetProjectReferenceSolutionFiles();
            files = VisitProjectReferences(files, r =>
            {
                r.Elements(XName.Get("Project", MSBuildNamespace)).Remove();
            });

            CreateFiles(files);

2759 2760 2761
            var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln");

            using (var workspace = CreateMSBuildWorkspace())
2762
            {
2763
                var sol = await workspace.OpenSolutionAsync(fullPath);
2764 2765 2766 2767 2768 2769 2770
                foreach (var project in sol.Projects)
                {
                    Assert.InRange(project.ProjectReferences.Count(), 0, 1);
                }
            }
        }

2771
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/23685"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2772
        [WorkItem(5668, "https://github.com/dotnet/roslyn/issues/5668")]
2773
        public async Task TestOpenProject_MetadataReferenceHasDocComments()
P
Pilchie 已提交
2774 2775
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
2776
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
2777

2778
            using (var workspace = CreateMSBuildWorkspace())
P
Pilchie 已提交
2779
            {
2780
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
P
Pilchie 已提交
2781
                var project = solution.Projects.First();
2782
                var comp = await project.GetCompilationAsync();
P
Pilchie 已提交
2783 2784 2785
                var symbol = comp.GetTypeByMetadataName("System.Console");
                var docComment = symbol.GetDocumentationCommentXml();
                Assert.NotNull(docComment);
D
Dustin Campbell 已提交
2786
                Assert.NotEmpty(docComment);
P
Pilchie 已提交
2787 2788 2789
            }
        }

2790
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2791
        public async Task TestOpenProject_CSharp_HasSourceDocComments()
P
Pilchie 已提交
2792 2793
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
2794
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
2795

2796
            using (var workspace = CreateMSBuildWorkspace())
P
Pilchie 已提交
2797
            {
2798
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
P
Pilchie 已提交
2799 2800 2801
                var project = solution.Projects.First();
                var parseOptions = (CS.CSharpParseOptions)project.ParseOptions;
                Assert.Equal(DocumentationMode.Parse, parseOptions.DocumentationMode);
2802
                var comp = await project.GetCompilationAsync();
P
Pilchie 已提交
2803 2804 2805
                var symbol = comp.GetTypeByMetadataName("CSharpProject.CSharpClass");
                var docComment = symbol.GetDocumentationCommentXml();
                Assert.NotNull(docComment);
D
Dustin Campbell 已提交
2806
                Assert.NotEmpty(docComment);
P
Pilchie 已提交
2807 2808 2809
            }
        }

2810
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2811
        public async Task TestOpenProject_VisualBasic_HasSourceDocComments()
P
Pilchie 已提交
2812 2813
        {
            CreateFiles(GetMultiProjectSolutionFiles());
2814
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
2815

2816
            using (var workspace = CreateMSBuildWorkspace())
P
Pilchie 已提交
2817
            {
2818
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
P
Pilchie 已提交
2819
                var project = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic);
A
angocke 已提交
2820
                var parseOptions = (VB.VisualBasicParseOptions)project.ParseOptions;
P
Pilchie 已提交
2821
                Assert.Equal(DocumentationMode.Diagnose, parseOptions.DocumentationMode);
2822
                var comp = await project.GetCompilationAsync();
P
Pilchie 已提交
2823 2824 2825
                var symbol = comp.GetTypeByMetadataName("VisualBasicProject.VisualBasicClass");
                var docComment = symbol.GetDocumentationCommentXml();
                Assert.NotNull(docComment);
D
Dustin Campbell 已提交
2826
                Assert.NotEmpty(docComment);
P
Pilchie 已提交
2827 2828 2829
            }
        }

2830
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2831
        public async Task TestOpenProject_CrossLanguageSkeletonReferenceHasDocComments()
P
Pilchie 已提交
2832 2833
        {
            CreateFiles(GetMultiProjectSolutionFiles());
2834
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
2835

2836
            using (var workspace = CreateMSBuildWorkspace())
P
Pilchie 已提交
2837
            {
2838 2839
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var csproject = workspace.CurrentSolution.Projects.First(p => p.Language == LanguageNames.CSharp);
P
Pilchie 已提交
2840 2841
                var csoptions = (CS.CSharpParseOptions)csproject.ParseOptions;
                Assert.Equal(DocumentationMode.Parse, csoptions.DocumentationMode);
2842
                var cscomp = await csproject.GetCompilationAsync();
P
Pilchie 已提交
2843 2844 2845 2846
                var cssymbol = cscomp.GetTypeByMetadataName("CSharpProject.CSharpClass");
                var cscomment = cssymbol.GetDocumentationCommentXml();
                Assert.NotNull(cscomment);

2847
                var vbproject = workspace.CurrentSolution.Projects.First(p => p.Language == LanguageNames.VisualBasic);
A
angocke 已提交
2848
                var vboptions = (VB.VisualBasicParseOptions)vbproject.ParseOptions;
P
Pilchie 已提交
2849
                Assert.Equal(DocumentationMode.Diagnose, vboptions.DocumentationMode);
2850
                var vbcomp = await vbproject.GetCompilationAsync();
P
Pilchie 已提交
2851 2852 2853 2854 2855 2856 2857 2858
                var vbsymbol = vbcomp.GetTypeByMetadataName("VisualBasicProject.VisualBasicClass");
                var parent = vbsymbol.BaseType; // this is the vb imported version of the csharp symbol
                var vbcomment = parent.GetDocumentationCommentXml();

                Assert.Equal(cscomment, vbcomment);
            }
        }

2859
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2860
        public void TestOpenProject_WithProjectFileLocked()
P
Pilchie 已提交
2861 2862 2863
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());

B
bkoelman 已提交
2864
            // open for read-write so no-one else can read
P
Pilchie 已提交
2865 2866 2867
            var projectFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
            using (File.Open(projectFile, FileMode.Open, FileAccess.ReadWrite))
            {
D
Dustin Campbell 已提交
2868
                AssertEx.Throws<IOException>(() =>
2869 2870 2871 2872 2873 2874
                    {
                        using (var workspace = CreateMSBuildWorkspace())
                        {
                            workspace.OpenProjectAsync(projectFile).Wait();
                        }
                    });
2875 2876
            }
        }
P
Pilchie 已提交
2877

2878
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2879
        public void TestOpenProject_WithNonExistentProjectFile()
2880
        {
2881 2882
            CreateFiles(GetSimpleCSharpSolutionFiles());

B
bkoelman 已提交
2883
            // open for read-write so no-one else can read
2884
            var projectFile = GetSolutionFileName(@"CSharpProject\NoProject.csproj");
D
Dustin Campbell 已提交
2885
            AssertEx.Throws<FileNotFoundException>(() =>
P
Pilchie 已提交
2886
                {
2887 2888 2889 2890
                    using (var workspace = CreateMSBuildWorkspace())
                    {
                        workspace.OpenProjectAsync(projectFile).Wait();
                    }
2891
                });
2892
        }
P
Pilchie 已提交
2893

2894
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2895 2896 2897
        public void TestOpenSolution_WithNonExistentSolutionFile()
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());
P
Pilchie 已提交
2898

B
bkoelman 已提交
2899
            // open for read-write so no-one else can read
2900
            var solutionFile = GetSolutionFileName(@"NoSolution.sln");
D
Dustin Campbell 已提交
2901
            AssertEx.Throws<FileNotFoundException>(() =>
2902 2903 2904 2905 2906 2907
                {
                    using (var workspace = CreateMSBuildWorkspace())
                    {
                        workspace.OpenSolutionAsync(solutionFile).Wait();
                    }
                });
P
Pilchie 已提交
2908 2909
        }

2910
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2911
        public async Task TestOpenSolution_SolutionFileHasEmptyLinesAndWhitespaceOnlyLines()
P
Pilchie 已提交
2912
        {
2913
            var files = new FileSet(
2914 2915 2916 2917
                (@"TestSolution.sln", Resources.SolutionFiles.CSharp_EmptyLines),
                (@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.CSharpProject),
                (@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass),
                (@"CSharpProject\Properties\AssemblyInfo.cs", Resources.SourceFiles.CSharp.AssemblyInfo));
P
Pilchie 已提交
2918 2919

            CreateFiles(files);
2920
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
2921

2922 2923 2924 2925 2926
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                var project = solution.Projects.First();
            }
P
Pilchie 已提交
2927 2928
        }

2929
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
2930
        [WorkItem(531543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531543")]
2931
        public async Task TestOpenSolution_SolutionFileHasEmptyLineBetweenProjectBlock()
P
Pilchie 已提交
2932
        {
2933
            var files = new FileSet(
2934
                (@"TestSolution.sln", Resources.SolutionFiles.EmptyLineBetweenProjectBlock));
P
Pilchie 已提交
2935 2936

            CreateFiles(files);
2937
            var solutionFilePath = GetSolutionFileName("TestSolution.sln");
P
Pilchie 已提交
2938

2939 2940 2941 2942
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
            }
P
Pilchie 已提交
2943 2944
        }

2945
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "MSBuild parsing API throws InvalidProjectFileException")]
2946
        [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
2947
        [WorkItem(531283, "DevDiv")]
2948
        public async Task TestOpenSolution_SolutionFileHasMissingEndProject()
P
Pilchie 已提交
2949
        {
2950
            var files = new FileSet(
2951 2952 2953
                (@"TestSolution1.sln", Resources.SolutionFiles.MissingEndProject1),
                (@"TestSolution2.sln", Resources.SolutionFiles.MissingEndProject2),
                (@"TestSolution3.sln", Resources.SolutionFiles.MissingEndProject3));
P
Pilchie 已提交
2954 2955 2956

            CreateFiles(files);

2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solutionFilePath = GetSolutionFileName("TestSolution1.sln");
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
            }

            using (var workspace = CreateMSBuildWorkspace())
            {
                var solutionFilePath = GetSolutionFileName("TestSolution2.sln");
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
            }

            using (var workspace = CreateMSBuildWorkspace())
            {
                var solutionFilePath = GetSolutionFileName("TestSolution3.sln");
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
            }
P
Pilchie 已提交
2974 2975
        }

2976
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
2977
        [WorkItem(792912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792912")]
2978
        public async Task TestOpenSolution_WithDuplicatedGuidsBecomeSelfReferential()
P
Pilchie 已提交
2979
        {
2980
            var files = new FileSet(
2981 2982 2983
                (@"DuplicatedGuids.sln", Resources.SolutionFiles.DuplicatedGuidsBecomeSelfReferential),
                (@"ReferenceTest\ReferenceTest.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidsBecomeSelfReferential),
                (@"Library1\Library1.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary1));
P
Pilchie 已提交
2984 2985

            CreateFiles(files);
2986
            var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln");
P
Pilchie 已提交
2987

2988 2989 2990 2991
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                Assert.Equal(2, solution.ProjectIds.Count);
2992

2993 2994
                var testProject = solution.Projects.FirstOrDefault(p => p.Name == "ReferenceTest");
                Assert.NotNull(testProject);
D
Dustin Campbell 已提交
2995
                Assert.Single(testProject.AllProjectReferences);
2996

2997 2998
                var libraryProject = solution.Projects.FirstOrDefault(p => p.Name == "Library1");
                Assert.NotNull(libraryProject);
D
Dustin Campbell 已提交
2999
                Assert.Empty(libraryProject.AllProjectReferences);
3000
            }
P
Pilchie 已提交
3001 3002
        }

3003
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
3004
        [WorkItem(792912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792912")]
3005
        public async Task TestOpenSolution_WithDuplicatedGuidsBecomeCircularReferential()
P
Pilchie 已提交
3006
        {
3007
            var files = new FileSet(
3008 3009 3010 3011
                (@"DuplicatedGuids.sln", Resources.SolutionFiles.DuplicatedGuidsBecomeCircularReferential),
                (@"ReferenceTest\ReferenceTest.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidsBecomeCircularReferential),
                (@"Library1\Library1.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary3),
                (@"Library2\Library2.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary4));
P
Pilchie 已提交
3012 3013

            CreateFiles(files);
3014
            var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln");
P
Pilchie 已提交
3015

3016 3017 3018 3019
            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
                Assert.Equal(3, solution.ProjectIds.Count);
3020

3021 3022
                var testProject = solution.Projects.FirstOrDefault(p => p.Name == "ReferenceTest");
                Assert.NotNull(testProject);
D
Dustin Campbell 已提交
3023
                Assert.Single(testProject.AllProjectReferences);
3024

3025 3026
                var library1Project = solution.Projects.FirstOrDefault(p => p.Name == "Library1");
                Assert.NotNull(library1Project);
D
Dustin Campbell 已提交
3027
                Assert.Single(library1Project.AllProjectReferences);
3028

3029 3030
                var library2Project = solution.Projects.FirstOrDefault(p => p.Name == "Library2");
                Assert.NotNull(library2Project);
D
Dustin Campbell 已提交
3031
                Assert.Empty(library2Project.AllProjectReferences);
3032
            }
P
Pilchie 已提交
3033
        }
3034

3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
        public async Task TestOpenProject_CSharp_WithMissingDebugType()
        {
            CreateFiles(new FileSet(
                (@"ProjectLoadErrorOnMissingDebugType.sln", Resources.SolutionFiles.ProjectLoadErrorOnMissingDebugType),
                (@"ProjectLoadErrorOnMissingDebugType\ProjectLoadErrorOnMissingDebugType.csproj", Resources.ProjectFiles.CSharp.ProjectLoadErrorOnMissingDebugType)));
            var solutionFilePath = GetSolutionFileName(@"ProjectLoadErrorOnMissingDebugType.sln");

            using (var workspace = CreateMSBuildWorkspace())
            {
                await workspace.OpenSolutionAsync(solutionFilePath);
            }
        }

3049
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
3050
        [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")]
3051
        public async Task MSBuildProjectShouldHandleCodePageProperty()
3052
        {
3053
            var files = new FileSet(
3054
                ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>1254</CodePage>")),
3055
                ("class1.cs", "//\u201C"));
3056 3057 3058

            CreateFiles(files);

3059 3060 3061 3062 3063 3064 3065
            var projPath = GetSolutionFileName("Encoding.csproj");
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projPath);
                var document = project.Documents.First(d => d.Name == "class1.cs");
                var text = await document.GetTextAsync();
                Assert.Equal(Encoding.GetEncoding(1254), text.Encoding);
3066

3067 3068 3069 3070 3071 3072
                // The smart quote (“) in class1.cs shows up as "“" in codepage 1254. Do a sanity
                // check here to make sure this file hasn't been corrupted in a way that would
                // impact subsequent asserts.
                Assert.Equal("//\u00E2\u20AC\u0153".Length, 5);
                Assert.Equal("//\u00E2\u20AC\u0153".Length, text.Length);
            }
3073 3074
        }

3075
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
3076
        [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")]
3077
        public async Task MSBuildProjectShouldHandleInvalidCodePageProperty()
3078
        {
3079
            var files = new FileSet(
3080
                ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>-1</CodePage>")),
3081
                ("class1.cs", "//\u201C"));
3082 3083 3084

            CreateFiles(files);

3085
            var projPath = GetSolutionFileName("Encoding.csproj");
3086

3087 3088 3089 3090 3091 3092 3093
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projPath);
                var document = project.Documents.First(d => d.Name == "class1.cs");
                var text = await document.GetTextAsync();
                Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding);
            }
3094 3095
        }

3096
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
3097
        [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")]
3098
        public async Task MSBuildProjectShouldHandleInvalidCodePageProperty2()
3099
        {
3100
            var files = new FileSet(
3101
                ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>Broken</CodePage>")),
3102
                ("class1.cs", "//\u201C"));
3103 3104 3105

            CreateFiles(files);

3106
            var projPath = GetSolutionFileName("Encoding.csproj");
3107

3108 3109 3110 3111 3112 3113 3114
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projPath);
                var document = project.Documents.First(d => d.Name == "class1.cs");
                var text = await document.GetTextAsync();
                Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding);
            }
3115 3116
        }

3117
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
3118
        [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")]
3119
        public async Task MSBuildProjectShouldHandleDefaultCodePageProperty()
3120
        {
3121
            var files = new FileSet(
3122
                ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", string.Empty)),
3123
                ("class1.cs", "//\u201C"));
3124 3125 3126

            CreateFiles(files);

3127
            var projPath = GetSolutionFileName("Encoding.csproj");
3128

3129 3130 3131 3132 3133 3134 3135 3136
            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projPath);
                var document = project.Documents.First(d => d.Name == "class1.cs");
                var text = await document.GetTextAsync();
                Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding);
                Assert.Equal("//\u201C", text.ToString());
            }
3137
        }
3138

3139
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(x86)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
3140
        [WorkItem(981208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981208")]
3141
        [WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
3142 3143 3144 3145 3146 3147 3148 3149 3150 3151
        public void DisposeMSBuildWorkspaceAndServicesCollected()
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());

            var sol = MSBuildWorkspace.Create().OpenSolutionAsync(GetSolutionFileName("TestSolution.sln")).Result;
            var workspace = sol.Workspace;
            var project = sol.Projects.First();
            var document = project.Documents.First();
            var tree = document.GetSyntaxTreeAsync().Result;
            var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent;
3152
            var compilation = document.GetSemanticModelAsync().WaitAndGetResult_CanCallOnBackground(CancellationToken.None);
3153
            Assert.NotNull(type);
D
Dustin Campbell 已提交
3154
            Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal);
3155 3156
            Assert.NotNull(compilation);

3157 3158 3159 3160 3161
            // MSBuildWorkspace doesn't have a cache service
            Assert.Null(workspace.CurrentSolution.Services.CacheService);

            var weakSolution = ObjectReference.Create(sol);
            var weakCompilation = ObjectReference.Create(compilation);
3162 3163 3164 3165 3166 3167 3168 3169 3170

            sol.Workspace.Dispose();
            project = null;
            document = null;
            tree = null;
            type = null;
            sol = null;
            compilation = null;

3171 3172
            weakSolution.AssertReleased();
            weakCompilation.AssertReleased();
3173
        }
P
Pilchie 已提交
3174

3175
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
3176 3177
        [WorkItem(1088127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088127")]
        public async Task MSBuildWorkspacePreservesEncoding()
P
Pilchie 已提交
3178
        {
K
Kevin_H 已提交
3179
            var encoding = Encoding.BigEndianUnicode;
P
Pilchie 已提交
3180 3181
            var fileContent = @"//“
class C { }";
3182
            var files = new FileSet(
3183
                ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", string.Empty)),
3184
                ("class1.cs", encoding.GetBytesWithPreamble(fileContent)));
P
Pilchie 已提交
3185 3186

            CreateFiles(files);
3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234
            var projPath = GetSolutionFileName("Encoding.csproj");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projPath);

                var document = project.Documents.First(d => d.Name == "class1.cs");

                // update root without first looking at text (no encoding is known)
                var gen = Editing.SyntaxGenerator.GetGenerator(document);
                var doc2 = document.WithSyntaxRoot(gen.CompilationUnit()); // empty CU
                var doc2text = await doc2.GetTextAsync();
                Assert.Null(doc2text.Encoding);
                var doc2tree = await doc2.GetSyntaxTreeAsync();
                Assert.Null(doc2tree.Encoding);
                Assert.Null(doc2tree.GetText().Encoding);

                // observe original text to discover encoding
                var text = await document.GetTextAsync();
                Assert.Equal(encoding.EncodingName, text.Encoding.EncodingName);
                Assert.Equal(fileContent, text.ToString());

                // update root blindly again, after observing encoding, see that now encoding is known
                var doc3 = document.WithSyntaxRoot(gen.CompilationUnit()); // empty CU
                var doc3text = await doc3.GetTextAsync();
                Assert.NotNull(doc3text.Encoding);
                Assert.Equal(encoding.EncodingName, doc3text.Encoding.EncodingName);
                var doc3tree = await doc3.GetSyntaxTreeAsync();
                Assert.Equal(doc3text.Encoding, doc3tree.GetText().Encoding);
                Assert.Equal(doc3text.Encoding, doc3tree.Encoding);

                // change doc to have no encoding, still succeeds at writing to disk with old encoding
                var root = await document.GetSyntaxRootAsync();
                var noEncodingDoc = document.WithText(SourceText.From(text.ToString(), encoding: null));
                var noEncodingDocText = await noEncodingDoc.GetTextAsync();
                Assert.Null(noEncodingDocText.Encoding);

                // apply changes (this writes the changed document)
                var noEncodingSolution = noEncodingDoc.Project.Solution;
                Assert.True(noEncodingSolution.Workspace.TryApplyChanges(noEncodingSolution));

                // prove the written document still has the same encoding
                var filePath = GetSolutionFileName("Class1.cs");
                using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    var reloadedText = EncodedStringText.Create(stream);
                    Assert.Equal(encoding.EncodingName, reloadedText.Encoding.EncodingName);
                }
P
Pilchie 已提交
3235 3236
            }
        }
3237

3238
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
3239
        public async Task TestAddRemoveMetadataReference_GAC()
3240 3241 3242 3243 3244
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());

            var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
            var projFileText = File.ReadAllText(projFile);
M
Matt Warren 已提交
3245
            Assert.Equal(false, projFileText.Contains(@"System.Xaml"));
3246

3247
            using (var workspace = CreateMSBuildWorkspace())
3248
            {
3249 3250
                var solutionFilePath = GetSolutionFileName("TestSolution.sln");
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
3251 3252
                var project = solution.Projects.First();

3253
                var mref = MetadataReference.CreateFromFile(typeof(System.Xaml.XamlObjectReader).Assembly.Location);
3254 3255

                // add reference to System.Xaml
3256
                workspace.TryApplyChanges(project.AddMetadataReference(mref).Solution);
3257
                projFileText = File.ReadAllText(projFile);
D
Dustin Campbell 已提交
3258
                Assert.Contains(@"<Reference Include=""System.Xaml,", projFileText);
3259 3260

                // remove reference to System.Xaml
3261
                workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveMetadataReference(mref).Solution);
3262
                projFileText = File.ReadAllText(projFile);
D
Dustin Campbell 已提交
3263
                Assert.DoesNotContain(@"<Reference Include=""System.Xaml,", projFileText);
3264 3265
            }
        }
3266

3267
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled))]
D
Dustin Campbell 已提交
3268
        [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
3269
        public async Task TestAddRemoveMetadataReference_ReferenceAssembly()
M
Matt Warren 已提交
3270 3271
        {
            CreateFiles(GetMultiProjectSolutionFiles()
3272
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithSystemNumerics));
M
Matt Warren 已提交
3273 3274 3275 3276 3277 3278 3279 3280 3281

            var csProjFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
            var csProjFileText = File.ReadAllText(csProjFile);
            Assert.Equal(true, csProjFileText.Contains(@"<Reference Include=""System.Numerics"""));

            var vbProjFile = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
            var vbProjFileText = File.ReadAllText(vbProjFile);
            Assert.Equal(false, vbProjFileText.Contains(@"System.Numerics"));

3282
            using (var workspace = CreateMSBuildWorkspace())
M
Matt Warren 已提交
3283
            {
3284
                var solution = await workspace.OpenSolutionAsync(GetSolutionFileName("TestSolution.sln"));
M
Matt Warren 已提交
3285 3286 3287 3288 3289 3290
                var csProject = solution.Projects.First(p => p.Language == LanguageNames.CSharp);
                var vbProject = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic);

                var numericsMetadata = csProject.MetadataReferences.Single(m => m.Display.Contains("System.Numerics"));

                // add reference to System.Xaml
3291
                workspace.TryApplyChanges(vbProject.AddMetadataReference(numericsMetadata).Solution);
M
Matt Warren 已提交
3292
                var newVbProjFileText = File.ReadAllText(vbProjFile);
D
Dustin Campbell 已提交
3293
                Assert.Contains(@"<Reference Include=""System.Numerics""", newVbProjFileText);
M
Matt Warren 已提交
3294 3295

                // remove reference MyAssembly.dll
3296
                workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(vbProject.Id).RemoveMetadataReference(numericsMetadata).Solution);
M
Matt Warren 已提交
3297
                var newVbProjFileText2 = File.ReadAllText(vbProjFile);
D
Dustin Campbell 已提交
3298
                Assert.DoesNotContain(@"<Reference Include=""System.Numerics""", newVbProjFileText2);
M
Matt Warren 已提交
3299 3300 3301
            }
        }

3302
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
3303
        public async Task TestAddRemoveMetadataReference_NonGACorRefAssembly()
3304 3305
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
3306
                .WithFile(@"References\MyAssembly.dll", Resources.Dlls.EmptyLibrary));
3307 3308 3309

            var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
            var projFileText = File.ReadAllText(projFile);
M
Matt Warren 已提交
3310
            Assert.Equal(false, projFileText.Contains(@"MyAssembly"));
3311

3312
            using (var workspace = CreateMSBuildWorkspace())
3313
            {
3314 3315
                var solutionFilePath = GetSolutionFileName("TestSolution.sln");
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
3316 3317 3318 3319 3320 3321
                var project = solution.Projects.First();

                var myAssemblyPath = GetSolutionFileName(@"References\MyAssembly.dll");
                var mref = MetadataReference.CreateFromFile(myAssemblyPath);

                // add reference to MyAssembly.dll
3322
                workspace.TryApplyChanges(project.AddMetadataReference(mref).Solution);
3323
                projFileText = File.ReadAllText(projFile);
D
Dustin Campbell 已提交
3324 3325
                Assert.Contains(@"<Reference Include=""MyAssembly""", projFileText);
                Assert.Contains(@"<HintPath>..\References\MyAssembly.dll", projFileText);
3326 3327

                // remove reference MyAssembly.dll
3328
                workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveMetadataReference(mref).Solution);
3329
                projFileText = File.ReadAllText(projFile);
D
Dustin Campbell 已提交
3330 3331
                Assert.DoesNotContain(@"<Reference Include=""MyAssembly""", projFileText);
                Assert.DoesNotContain(@"<HintPath>..\References\MyAssembly.dll", projFileText);
3332 3333 3334
            }
        }

3335
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
3336
        public async Task TestAddRemoveAnalyzerReference()
3337 3338
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
3339
                .WithFile(@"Analyzers\MyAnalyzer.dll", Resources.Dlls.EmptyLibrary));
3340 3341 3342 3343 3344

            var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
            var projFileText = File.ReadAllText(projFile);
            Assert.Equal(false, projFileText.Contains(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll"));

3345
            using (var workspace = CreateMSBuildWorkspace())
3346
            {
3347 3348
                var solutionFilePath = GetSolutionFileName("TestSolution.sln");
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
3349 3350 3351
                var project = solution.Projects.First();

                var myAnalyzerPath = GetSolutionFileName(@"Analyzers\MyAnalyzer.dll");
T
Tom Meschter 已提交
3352
                var aref = new AnalyzerFileReference(myAnalyzerPath, new InMemoryAssemblyLoader());
3353 3354

                // add reference to MyAnalyzer.dll
3355
                workspace.TryApplyChanges(project.AddAnalyzerReference(aref).Solution);
3356
                projFileText = File.ReadAllText(projFile);
D
Dustin Campbell 已提交
3357
                Assert.Contains(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll", projFileText);
3358

C
Charles Stoner 已提交
3359
                // remove reference MyAnalyzer.dll
3360
                workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveAnalyzerReference(aref).Solution);
3361
                projFileText = File.ReadAllText(projFile);
D
Dustin Campbell 已提交
3362
                Assert.DoesNotContain(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll", projFileText);
3363 3364 3365
            }
        }

3366
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
3367
        public async Task TestAddRemoveProjectReference()
3368 3369 3370 3371 3372 3373 3374
        {
            CreateFiles(GetMultiProjectSolutionFiles());

            var projFile = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj");
            var projFileText = File.ReadAllText(projFile);
            Assert.Equal(true, projFileText.Contains(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">"));

3375
            using (var workspace = CreateMSBuildWorkspace())
3376
            {
3377 3378
                var solutionFilePath = GetSolutionFileName("TestSolution.sln");
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
3379 3380 3381 3382
                var project = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic);
                var pref = project.ProjectReferences.First();

                // remove project reference
3383
                workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveProjectReference(pref).Solution);
D
Dustin Campbell 已提交
3384
                Assert.Empty(workspace.CurrentSolution.GetProject(project.Id).ProjectReferences);
3385 3386

                projFileText = File.ReadAllText(projFile);
D
Dustin Campbell 已提交
3387
                Assert.DoesNotContain(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">", projFileText);
3388 3389

                // add it back
3390
                workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).AddProjectReference(pref).Solution);
D
Dustin Campbell 已提交
3391
                Assert.Single(workspace.CurrentSolution.GetProject(project.Id).ProjectReferences);
3392 3393

                projFileText = File.ReadAllText(projFile);
D
Dustin Campbell 已提交
3394
                Assert.Contains(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">", projFileText);
3395 3396
            }
        }
3397

3398
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
J
Jared Parsons 已提交
3399
        [WorkItem(1101040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101040")]
3400
        public async Task TestOpenProject_BadLink()
3401 3402
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
3403
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadLink));
3404

3405 3406 3407 3408 3409 3410 3411 3412
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var proj = await workspace.OpenProjectAsync(projectFilePath);
                var docs = proj.Documents.ToList();
                Assert.Equal(3, docs.Count);
            }
3413
        }
T
Tom Meschter 已提交
3414

3415
        [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
M
Matt Warren 已提交
3416 3417 3418
        public async Task TestOpenProject_BadElement()
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
3419
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadElement));
M
Matt Warren 已提交
3420

3421 3422 3423 3424 3425
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var proj = await workspace.OpenProjectAsync(projectFilePath);
M
Matt Warren 已提交
3426

3427 3428
                var diagnostic = Assert.Single(workspace.Diagnostics);
                Assert.StartsWith("Msbuild failed", diagnostic.Message);
M
Matt Warren 已提交
3429

D
Dustin Campbell 已提交
3430
                Assert.Empty(proj.DocumentIds);
3431
            }
M
Matt Warren 已提交
3432 3433
        }

3434
        [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
M
Matt Warren 已提交
3435 3436 3437
        public async Task TestOpenProject_BadTaskImport()
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
3438
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadTasks));
M
Matt Warren 已提交
3439

3440 3441 3442 3443 3444
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var proj = await workspace.OpenProjectAsync(projectFilePath);
M
Matt Warren 已提交
3445

3446 3447
                var diagnostic = Assert.Single(workspace.Diagnostics);
                Assert.StartsWith("Msbuild failed", diagnostic.Message);
M
Matt Warren 已提交
3448

D
Dustin Campbell 已提交
3449
                Assert.Empty(proj.DocumentIds);
3450
            }
M
Matt Warren 已提交
3451 3452
        }

3453
        [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
M
Matt Warren 已提交
3454 3455 3456
        public async Task TestOpenSolution_BadTaskImport()
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
3457
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadTasks));
M
Matt Warren 已提交
3458

3459 3460 3461 3462 3463
            var solutionFilePath = GetSolutionFileName(@"TestSolution.sln");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
M
Matt Warren 已提交
3464

3465 3466
                var diagnostic = Assert.Single(workspace.Diagnostics);
                Assert.StartsWith("Msbuild failed", diagnostic.Message);
M
Matt Warren 已提交
3467

3468 3469
                var project = Assert.Single(solution.Projects);
                Assert.Empty(project.DocumentIds);
3470
            }
M
Matt Warren 已提交
3471 3472
        }

3473
        [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
M
Matt Warren 已提交
3474 3475 3476
        public async Task TestOpenProject_MsbuildError()
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
3477
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.MsbuildError));
M
Matt Warren 已提交
3478

3479 3480 3481 3482 3483
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var proj = await workspace.OpenProjectAsync(projectFilePath);
M
Matt Warren 已提交
3484

3485 3486
                var diagnostic = Assert.Single(workspace.Diagnostics);
                Assert.StartsWith("Msbuild failed", diagnostic.Message);
3487
            }
M
Matt Warren 已提交
3488 3489
        }

3490
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
M
Matt Warren 已提交
3491 3492 3493
        public async Task TestOpenProject_WildcardsWithLink()
        {
            CreateFiles(GetSimpleCSharpSolutionFiles()
3494
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.Wildcards));
M
Matt Warren 已提交
3495

3496 3497 3498 3499 3500
            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var proj = await workspace.OpenProjectAsync(projectFilePath);
M
Matt Warren 已提交
3501

3502
                // prove that the file identified with a wildcard and remapped to a computed link is named correctly.
D
Dustin Campbell 已提交
3503
                Assert.Contains(proj.Documents, d => d.Name == "AssemblyInfo.cs");
3504
            }
M
Matt Warren 已提交
3505 3506
        }

3507
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
3508
        public async Task TestOpenProject_CommandLineArgsHaveNoErrors()
M
Matt Warren 已提交
3509 3510 3511
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());

3512 3513 3514 3515 3516
            using (var workspace = CreateMSBuildWorkspace())
            {
                var loader = workspace.Services
                    .GetLanguageServices(LanguageNames.CSharp)
                    .GetRequiredService<IProjectFileLoader>();
M
Matt Warren 已提交
3517

3518
                var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");
M
Matt Warren 已提交
3519

3520
                var properties = ImmutableDictionary<string, string>.Empty;
3521
                var buildManager = new ProjectBuildManager();
3522 3523
                buildManager.Start();

3524
                var projectFile = await loader.LoadProjectFileAsync(projectFilePath, properties, buildManager, CancellationToken.None);
3525
                var projectFileInfo = (await projectFile.GetProjectFileInfosAsync(CancellationToken.None)).Single();
3526
                buildManager.Stop();
M
Matt Warren 已提交
3527

3528 3529 3530
                var commandLineParser = workspace.Services
                    .GetLanguageServices(loader.Language)
                    .GetRequiredService<ICommandLineParserService>();
M
Matt Warren 已提交
3531

3532 3533 3534 3535 3536 3537
                var projectDirectory = Path.GetDirectoryName(projectFilePath);
                var commandLineArgs = commandLineParser.Parse(
                    arguments: projectFileInfo.CommandLineArgs,
                    baseDirectory: projectDirectory,
                    isInteractive: false,
                    sdkDirectory: System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory());
M
Matt Warren 已提交
3538

D
Dustin Campbell 已提交
3539
                Assert.Empty(commandLineArgs.Errors);
3540
            }
M
Matt Warren 已提交
3541 3542
        }

3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
        [WorkItem(29122, "https://github.com/dotnet/roslyn/issues/29122")]
        public async Task TestOpenSolution_ProjectReferencesWithUnconventionalOutputPaths()
        {
            CreateFiles(GetBaseFiles()
                .WithFile(@"TestVB2.sln", Resources.SolutionFiles.Issue29122_Solution)
                .WithFile(@"Proj1\ClassLibrary1.vbproj", Resources.ProjectFiles.VisualBasic.Issue29122_ClassLibrary1)
                .WithFile(@"Proj1\Class1.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass)
                .WithFile(@"Proj1\My Project\Application.Designer.vb", Resources.SourceFiles.VisualBasic.Application_Designer)
                .WithFile(@"Proj1\My Project\Application.myapp", Resources.SourceFiles.VisualBasic.Application)
                .WithFile(@"Proj1\My Project\AssemblyInfo.vb", Resources.SourceFiles.VisualBasic.AssemblyInfo)
                .WithFile(@"Proj1\My Project\Resources.Designer.vb", Resources.SourceFiles.VisualBasic.Resources_Designer)
                .WithFile(@"Proj1\My Project\Resources.resx", Resources.SourceFiles.VisualBasic.Resources)
                .WithFile(@"Proj1\My Project\Settings.Designer.vb", Resources.SourceFiles.VisualBasic.Settings_Designer)
                .WithFile(@"Proj1\My Project\Settings.settings", Resources.SourceFiles.VisualBasic.Settings)
                .WithFile(@"Proj2\ClassLibrary2.vbproj", Resources.ProjectFiles.VisualBasic.Issue29122_ClassLibrary2)
                .WithFile(@"Proj2\Class1.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass)
                .WithFile(@"Proj2\My Project\Application.Designer.vb", Resources.SourceFiles.VisualBasic.Application_Designer)
                .WithFile(@"Proj2\My Project\Application.myapp", Resources.SourceFiles.VisualBasic.Application)
                .WithFile(@"Proj2\My Project\AssemblyInfo.vb", Resources.SourceFiles.VisualBasic.AssemblyInfo)
                .WithFile(@"Proj2\My Project\Resources.Designer.vb", Resources.SourceFiles.VisualBasic.Resources_Designer)
                .WithFile(@"Proj2\My Project\Resources.resx", Resources.SourceFiles.VisualBasic.Resources)
                .WithFile(@"Proj2\My Project\Settings.Designer.vb", Resources.SourceFiles.VisualBasic.Settings_Designer)
                .WithFile(@"Proj2\My Project\Settings.settings", Resources.SourceFiles.VisualBasic.Settings));

3568
            var solutionFilePath = GetSolutionFileName(@"TestVB2.sln");
3569 3570 3571

            using (var workspace = CreateMSBuildWorkspace())
            {
3572
                var solution = await workspace.OpenSolutionAsync(solutionFilePath);
3573 3574 3575 3576 3577 3578 3579 3580 3581

                // Neither project should contain any unresolved metadata references
                foreach (var project in solution.Projects)
                {
                    Assert.DoesNotContain(project.MetadataReferences, mr => mr is UnresolvedMetadataReference);
                }
            }
        }

3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602
        [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
        [WorkItem(29494, "https://github.com/dotnet/roslyn/issues/29494")]
        public async Task TestOpenProjectAsync_MalformedAdditionalFilePath()
        {
            var files = GetSimpleCSharpSolutionFiles()
                .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.MallformedAdditionalFilePath)
                .WithFile(@"CSharpProject\ValidAdditionalFile.txt", Resources.SourceFiles.Text.ValidAdditionalFile);

            CreateFiles(files);

            var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj");

            using (var workspace = CreateMSBuildWorkspace())
            {
                var project = await workspace.OpenProjectAsync(projectFilePath);

                // Project should open without an exception being thrown.
                Assert.NotNull(project);
            }
        }

T
Tom Meschter 已提交
3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614
        private class InMemoryAssemblyLoader : IAnalyzerAssemblyLoader
        {
            public void AddDependencyLocation(string fullPath)
            {
            }

            public Assembly LoadFromPath(string fullPath)
            {
                var bytes = File.ReadAllBytes(fullPath);
                return Assembly.Load(bytes);
            }
        }
P
Pilchie 已提交
3615
    }
J
Jared Parsons 已提交
3616
}