public void Should_Add_InternalToVisible_To_AllReferencedProjects()
        {
            // arrange
            const string expectedAttribute = @"System.Runtime.CompilerServices.InternalsVisibleTo(""Tests.dll_COVERAGE.dll"")";
            const string sourceCode = "class SampleClass{}";
            SyntaxNode node = CSharpSyntaxTree.ParseText(sourceCode).GetRoot();

            var workspace = new AdhocWorkspace();

            var referencedProject1 = workspace.AddProject("foo2.dll", LanguageNames.CSharp);
            workspace.AddDocument(referencedProject1.Id, "1.cs", SourceText.From(""));

            var testsProject = workspace.AddProject("Tests.dll", LanguageNames.CSharp);

            var solution = workspace.CurrentSolution.AddProjectReference(testsProject.Id, new ProjectReference(referencedProject1.Id));

            _auditVariablesRewriterMock.Rewrite(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<SyntaxNode>()).
                Returns(new RewrittenDocument(node.SyntaxTree, null, false));

            // act
            RewriteResult result = _solutionRewriter.RewriteAllClasses(solution.Projects);
            List<RewrittenDocument> projectItems1 = result.Items.Values.First();
            var attributes = projectItems1[0].SyntaxTree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().ToArray();

            // assert
            Assert.That(result.Items.Count, Is.EqualTo(1));
            Assert.That(projectItems1.Count, Is.EqualTo(1));

            Assert.That(attributes.Length, Is.EqualTo(1));
            Assert.That(attributes[0].ToString(), Is.EqualTo(expectedAttribute));
        }
        public void Should_RewriteOneDocument()
        {
            // arrange
            const string sourceCode = "class SampleClass{}";
            SyntaxNode node = CSharpSyntaxTree.ParseText(sourceCode).GetRoot();

            var workspace = new AdhocWorkspace();
            var project = workspace.AddProject("foo.dll", LanguageNames.CSharp);
            string documentPath = "c:\\helloworld.cs";
            DocumentInfo documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "HelloWorld.cs",
                filePath: documentPath);
            Document document = workspace.AddDocument(documentInfo);

            _auditVariablesRewriterMock.Rewrite(Arg.Any<string>(), documentPath, Arg.Any<SyntaxNode>()).
                Returns(new RewrittenDocument(node.SyntaxTree, null, false));

            // act
            RewriteResult result = _solutionRewriter.RewriteAllClasses(workspace.CurrentSolution.Projects);

            // assert
            Assert.That(result.Items.Count, Is.EqualTo(1));
            Assert.That(result.Items.Keys.First().Id, Is.EqualTo(project.Id));

            Assert.That(result.Items.Values.First().Count, Is.EqualTo(1));
        }
		internal static Document CreateDocument(string code, string fileName,
			Func<Solution, ProjectId, Solution> modifySolution)
		{
			var projectName = "Test";
			var projectId = ProjectId.CreateNewId(projectName);

			var solution = new AdhocWorkspace()
				 .CurrentSolution
				 .AddProject(projectId, projectName, projectName, LanguageNames.CSharp)
				 .AddMetadataReference(projectId,
					MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
				 .AddMetadataReference(projectId,
					MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location))
				 .AddMetadataReference(projectId,
					MetadataReference.CreateFromFile(typeof(CSharpCompilation).Assembly.Location))
				 .AddMetadataReference(projectId,
					MetadataReference.CreateFromFile(typeof(Compilation).Assembly.Location));

			var documentId = DocumentId.CreateNewId(projectId);
			solution = solution.AddDocument(documentId, fileName, SourceText.From(code));

			if(modifySolution != null)
			{
				solution = modifySolution(solution, projectId);
			}

			return solution.GetProject(projectId).Documents.First();
		}
Exemple #4
0
        public static async Task AssertEnforcementAsync(
            IStyleRule rule, string originalText, string expectedText, Func<OptionSet, OptionSet> applyOptions)
        {
            using (var workspace = new AdhocWorkspace())
            {
                workspace.Options = applyOptions(workspace.Options);

                Project project = workspace.AddProject(BuildProject());
                Document document = workspace.AddDocument(project.Id, "TestFile.cs", SourceText.From(originalText));

                Solution enforcedSolution = await rule.EnforceAsync(document);
                Document enforcedDocument = enforcedSolution.GetDocument(document.Id);

                if (document.Equals(enforcedDocument))
                {
                    Assert.Fail("Expected enforcement, but no changes were made to the document");
                }

                SyntaxTree enforcedSyntax = await enforcedDocument.GetSyntaxTreeAsync();
                SyntaxTree expectedSyntax = SyntaxFactory.ParseCompilationUnit(expectedText).SyntaxTree;
                List<TextChange> unexpectedChanges = expectedSyntax.GetChanges(enforcedSyntax).ToList();
                if (unexpectedChanges.Count > 0)
                {
                    Console.WriteLine("Unexpected changes:");
                    List<TextChange> changes = (await enforcedDocument.GetTextChangesAsync(document)).ToList();
                    foreach (TextChange change in changes)
                    {
                        Console.WriteLine($"\t{change}");
                    }

                    Assert.Fail($"Enforced document has {changes.Count} unexpected changes");
                }
            }
        }
Exemple #5
0
        public static async Task AssertNoEnforcementAsync(
            IStyleRule rule, string documentText, Func<OptionSet, OptionSet> applyOptions)
        {
            using (var workspace = new AdhocWorkspace())
            {
                workspace.Options = applyOptions(workspace.Options);

                Project project = workspace.AddProject(BuildProject());
                Document document = workspace.AddDocument(project.Id, "TestFile.cs", SourceText.From(documentText));

                Solution enforcedSolution = await rule.EnforceAsync(document);
                Document enforcedDocument = enforcedSolution.GetDocument(document.Id);

                if (!document.Equals(enforcedDocument))
                {
                    List<TextChange> changes = (await enforcedDocument.GetTextChangesAsync(document)).ToList();
                    if (changes.Count == 0)
                    {
                        Assert.Fail("Solution mutated without document changes");
                    }

                    Console.WriteLine("Document changes:");
                    foreach (TextChange change in changes)
                    {
                        Console.WriteLine($"\t{change}");
                    }

                    Assert.Fail($"Enforced document has {changes.Count} changes; expected none");
                }
            }
        }
        public void TestInit()
        {
            try
            {
                workspace = new AdhocWorkspace();

                project = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "TestProj", "TestProj", LanguageNames.CSharp)
                    .WithMetadataReferences(new[] {
                        MetadataReference.CreateFromFile(typeof(DotvvmConfiguration).Assembly.Location),
                        MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
                    });
                workspace.AddProject(project);

                workspace.AddDocument(project.Id, "test", SourceText.From("class A {}"));

                context = new DothtmlCompletionContext()
                {
                    Configuration = DotvvmConfiguration.CreateDefault(),
                    RoslynWorkspace = workspace
                };

            }
            catch (ReflectionTypeLoadException ex)
            {
                throw new Exception(string.Join("\r\n", ex.LoaderExceptions.Select(e => e.ToString())));
            }
        }
        protected Project CreateProject(Dictionary<string, string> sources)
        {
            string fileNamePrefix = DefaultFilePathPrefix;
            string fileExt = CSharpDefaultFileExt;

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

            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp);

            foreach (var reference in References)
            {
                solution = solution.AddMetadataReference(projectId, reference);
            }

            int count = 0;
            foreach (var source in sources)
            {
                var newFileName = source.Key;
                var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName);
                solution = solution.AddDocument(documentId, newFileName, SourceText.From(source.Value));
                count++;
            }

            var project = solution.GetProject(projectId)
                .WithCompilationOptions(CompilationOptions);
            return project;
        }
        protected Solution CreateSolution(string[] sources, string[] preprocessorSymbols = null, string language = LanguageNames.CSharp)
        {
            string fileExtension = language == LanguageNames.CSharp ? CSharpFileExtension : VBFileExtension;
            var projectId = ProjectId.CreateNewId(TestProjectName);

            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, language)
                .AddMetadataReferences(projectId, GetSolutionMetadataReferences());

            if (preprocessorSymbols != null)
            {
                var project = solution.Projects.Single();
                project = project.WithParseOptions(
                    ((CSharpParseOptions)project.ParseOptions).WithPreprocessorSymbols(preprocessorSymbols));

                solution = project.Solution;
            }

            int count = 0;
            foreach (var source in sources)
            {
                var fileName = FileNamePrefix + count + fileExtension;
                var documentId = DocumentId.CreateNewId(projectId, fileName);
                solution = solution.AddDocument(documentId, fileName, SourceText.From(source));
            }

            return solution;
        }
        public TestHelper(string source)
        {
            Workspace = new AdhocWorkspace();

            string projName = "NewProject";
            var projectId = ProjectId.CreateNewId();
            var versionStamp = VersionStamp.Create();
            var projectInfo = ProjectInfo.Create(projectId, versionStamp, projName, projName, LanguageNames.CSharp);
            var newProject = Workspace.AddProject(projectInfo);
            var sourceText = SourceText.From(source);
            Document = Workspace.AddDocument(newProject.Id, "NewFile.cs", sourceText);
        }
        public async Task TestCodeGeneration(string resourceBaseName, Language language)
        {
            var inputResourceName = "BrightstarDB.CodeGeneration.Tests.GeneratorTestsResources." + resourceBaseName + "Input_" + language.ToString() + ".txt";
            var outputResourceName = "BrightstarDB.CodeGeneration.Tests.GeneratorTestsResources." + resourceBaseName + "Output_" + language.ToString() + ".txt";

            using (var inputStream = this.GetType().Assembly.GetManifestResourceStream(inputResourceName))
            using (var outputStream = this.GetType().Assembly.GetManifestResourceStream(outputResourceName))
            using (var outputStreamReader = new StreamReader(outputStream))
            {
                var workspace = new AdhocWorkspace();
                var projectId = ProjectId.CreateNewId();
                var versionStamp = VersionStamp.Create();
                var projectInfo = ProjectInfo.Create(
                    projectId,
                    versionStamp,
                    "AdhocProject",
                    "AdhocProject",
                    language.ToSyntaxGeneratorLanguageName(),
                    metadataReferences: new[]
                    {
                        MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                        MetadataReference.CreateFromFile(typeof(Uri).Assembly.Location),
                        MetadataReference.CreateFromFile(typeof(BrightstarException).Assembly.Location)
                    });
                var project = workspace.AddProject(projectInfo);
                workspace.AddDocument(projectId, "Source.cs", SourceText.From(inputStream));
                var solution = workspace.CurrentSolution;

                var results = await Generator
                    .GenerateAsync(
                        language,
                        solution,
                        "BrightstarDB.CodeGeneration.Tests",
                        interfacePredicate: x => true);
                var result = results
                    .Aggregate(
                        new StringBuilder(),
                        (current, next) => current.AppendLine(next.ToString()),
                        x => x.ToString());

                var expectedCode = outputStreamReader.ReadToEnd();

                // make sure version changes don't break the tests
                expectedCode = expectedCode.Replace("$VERSION$", typeof(BrightstarException).Assembly.GetName().Version.ToString());

                //// useful when converting generated code to something that can be pasted into an expectation file
                //var sanitisedResult = result.Replace("1.10.0.0", "$VERSION$");
                //System.Diagnostics.Debug.WriteLine(sanitisedResult);

                Assert.AreEqual(expectedCode, result);
            }
        }
        // TODO: VB is totally borked - calls to syntaxGenerator.WithStatements don't seem to add the statements! Will need to look into this at a later date
        //[InlineData("SimpleInterface", Language.VisualBasic)]
        //[InlineData("InterfaceWithGenericMethods", Language.VisualBasic)]
        //[InlineData("GenericInterface", Language.VisualBasic)]
        //[InlineData("InterfaceWithNonMockableMembers", Language.VisualBasic)]
        //[InlineData("PartialInterface", Language.VisualBasic)]
        //[InlineData("InheritingInterface", Language.VisualBasic)]
        public async Task can_generate_simple_mock(string resourceBaseName, Language language)
        {
            var inputResourceName = "PCLMock.UnitTests.CodeGeneration.GeneratorFixtureResources." + resourceBaseName + "Input_" + language.ToString() + ".txt";
            var outputResourceName = "PCLMock.UnitTests.CodeGeneration.GeneratorFixtureResources." + resourceBaseName + "Output_" + language.ToString() + ".txt";

            using (var inputStream = this.GetType().Assembly.GetManifestResourceStream(inputResourceName))
            using (var outputStream = this.GetType().Assembly.GetManifestResourceStream(outputResourceName))
            using (var outputStreamReader = new StreamReader(outputStream))
            {
                var workspace = new AdhocWorkspace();
                var projectId = ProjectId.CreateNewId();
                var versionStamp = VersionStamp.Create();
                var projectInfo = ProjectInfo.Create(
                    projectId,
                    versionStamp,
                    "AdhocProject",
                    "AdhocProject",
                    language.ToSyntaxGeneratorLanguageName(),
                    metadataReferences: new[]
                    {
                        MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                        MetadataReference.CreateFromFile(typeof(Uri).Assembly.Location),
                        MetadataReference.CreateFromFile(typeof(MockBase<>).Assembly.Location)
                    });
                var project = workspace.AddProject(projectInfo);
                workspace.AddDocument(projectId, "Source.cs", SourceText.From(inputStream));
                var solution = workspace.CurrentSolution;

                var results =
                    (await Generator.GenerateMocksAsync(
                        language,
                        solution,
                        x => true,
                        x => "The.Namespace",
                        x => "Mock"));
                var result = results
                    .Single()
                    .ToString();

                var expectedCode = outputStreamReader.ReadToEnd();

                // make sure version changes don't break the tests
                expectedCode = expectedCode.Replace("$VERSION$", typeof(MockBase<>).Assembly.GetName().Version.ToString());

                // useful when converting generated code to something that can be pasted into an expectation file
                var sanitisedResult = result.Replace(typeof(MockBase<>).Assembly.GetName().Version.ToString(), "$VERSION$");

                Assert.Equal(expectedCode, result);
            }
        }
            internal Options(
                IEnumerable<Project> projects = null,
                IEnumerable<string> projectPaths = null,
                IEnumerable<string> sourcePaths = null,
                IEnumerable<IEnumerable<string>> symbolConfigurations = null,
                IEnumerable<string> alwaysIgnoredSymbols = null,
                IEnumerable<string> alwaysDefinedSymbols = null,
                IEnumerable<string> alwaysDisabledSymbols = null,
                Tristate undefinedSymbolValue = default(Tristate),
                IAnalysisLogger logger = null)
            {
                if (projectPaths != null)
                {
                    projects = Task.WhenAll(from path in projectPaths select MSBuildWorkspace.Create().OpenProjectAsync(path, CancellationToken.None)).Result;
                }
                if (projects != null)
                {
                    Documents = GetSharedDocuments(projects);
                }

                if (projects == null && sourcePaths != null)
                {
                    var projectId = ProjectId.CreateNewId("AnalysisProject");
                    var solution = new AdhocWorkspace()
                        .CurrentSolution
                        .AddProject(projectId, "AnalysisProject", "AnalysisProject", LanguageNames.CSharp);

                    foreach (var path in sourcePaths)
                    {
                        var documentId = DocumentId.CreateNewId(projectId);
                        solution = solution.AddDocument(
                            documentId,
                            Path.GetFileName(path),
                            new FileTextLoader(path, defaultEncoding: Encoding.UTF8));
                    }

                    Documents = solution.Projects.Single().Documents.ToImmutableArray();
                }

                _symbolConfigurations = CalculateSymbolConfigurations(
                    alwaysDisabledSymbols,
                    alwaysDefinedSymbols,
                    alwaysIgnoredSymbols,
                    symbolConfigurations);

                _undefinedSymbolValue = undefinedSymbolValue;

                Logger = logger ?? new ConsoleAnalysisLogger();
            }
        public void CreateAndManipulateAdhocWorkspace_UnderstandingIsCorrect()
        {
            using (var adhocWorkspace = new AdhocWorkspace())
            {
                var solution = adhocWorkspace.CurrentSolution;
                var newProject = adhocWorkspace.AddProject("Project.Test", LanguageNames.CSharp);
                adhocWorkspace.AddDocument(newProject.Id, "TestFile.cs", SourceText.From("public class Bar { }"));

                Assert.AreEqual(1, adhocWorkspace.CurrentSolution.Projects.Count());
                var project = adhocWorkspace.CurrentSolution.Projects.Single();
                Assert.AreEqual("Project.Test", project.Name);
                Assert.AreEqual(1, project.Documents.Count());
                Assert.AreEqual("TestFile.cs", project.Documents.Single().Name);
            }
        }
        static Project CreateProject(string source)
        {
            var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);

            var projectId = ProjectId.CreateNewId();
            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, "TestProject", "TestProject", LanguageNames.CSharp)
                .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                .AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
                .AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location))
                .AddMetadataReference(projectId, MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")))
                .AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(ConstAttribute).Assembly.Location));
            var documentId = DocumentId.CreateNewId(projectId);
            solution = solution.AddDocument(documentId, "Test.cs", SourceText.From(source));
            return solution.GetProject(projectId);
        }
Exemple #15
0
    internal static Document Create(string code)
    {
      var projectName = "Test";
      var projectId = ProjectId.CreateNewId(projectName);

      var solution = new AdhocWorkspace()
         .CurrentSolution
         .AddProject(projectId, projectName, projectName, LanguageNames.CSharp)
         .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
         .AddMetadataReference(projectId, MetadataReference.CreateFromAssembly(typeof(object).Assembly))
         .AddMetadataReference(projectId, MetadataReference.CreateFromAssembly(typeof(Enumerable).Assembly))
         .AddMetadataReference(projectId, MetadataReference.CreateFromAssembly(typeof(CSharpCompilation).Assembly))
         .AddMetadataReference(projectId, MetadataReference.CreateFromAssembly(typeof(Compilation).Assembly))
         .AddMetadataReference(projectId, MetadataReference.CreateFromAssembly(typeof(BusinessBase<>).Assembly));

      var documentId = DocumentId.CreateNewId(projectId);
      solution = solution.AddDocument(documentId, "Test.cs", SourceText.From(code));

      return solution.GetProject(projectId).Documents.First();
    }
        public async Task Should_ReturnIgnoredSolutionTestProject_When_SolutionContainsTestProject_And_StoredSettingsAreUnavailable()
        {
            // arrange 
            var workspace = new AdhocWorkspace();
            var project = workspace.AddProject("foo", LanguageNames.CSharp);
            var testClass = CSharpSyntaxTree.ParseText(@"[TestFixtureViewModel]class MathHelperTests{ [Test]void Test(){}}");

            workspace.AddDocument(project.Id, "MathHelperTests.cs", SourceText.From(testClass.ToString()));

            _testExtractorMock.GetTestClasses(Arg.Any<SyntaxNode>()).Returns(new[] { testClass.GetRoot().GetClassDeclarationSyntax() });
            _solutionExplorerMock.Solution.Returns(workspace.CurrentSolution);

            // act
            TestProject[] projects = await _sut.GetAllTestProjectsAsync();

            // assert
            Assert.That(projects.Length, Is.EqualTo(1));
            Assert.That(projects[0].Project.Name, Is.EqualTo("foo"));
            Assert.IsFalse(projects[0].IsCoverageEnabled);
        }
        private Solution CreateSolution(string[] sources, string language = LanguageNames.CSharp)
        {
            string fileExtension = language == LanguageNames.CSharp ? CSharpFileExtension : VBFileExtension;
            var projectId = ProjectId.CreateNewId(TestProjectName);

            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, language)
                .AddMetadataReferences(projectId, GetSolutionMetadataReferences());

            int count = 0;
            foreach (var source in sources)
            {
                var fileName = FileNamePrefix + count + fileExtension;
                var documentId = DocumentId.CreateNewId(projectId, fileName);
                solution = solution.AddDocument(documentId, fileName, SourceText.From(source));
                count++;
            }

            return solution;
        }
Exemple #18
0
        public static DisposableResult BuildProjectTreeFromDocuments(params string[] documentContents)
        {
            var fakeWorkspace = new AdhocWorkspace();
            var project = fakeWorkspace.AddProject("ProjectA", LanguageNames.CSharp);
            var i = 0;
            foreach (var content in documentContents)
            {
                fakeWorkspace.AddDocument(project.Id, "doc" + i, SourceText.From(content));
                i++;
            }

            var projectA = new ProjectNode
            { Documents = fakeWorkspace.CurrentSolution
            .GetProject(project.Id).Documents };

            var tree = new SolutionNode();
            tree.AddChild(projectA);
            ClassTreeBuilder.AddClassesInProjectsToTree(tree);
            return new DisposableResult
            {Workspace = fakeWorkspace,
                result = projectA};
        }
Exemple #19
0
        public static AdhocWorkspace WithFakeDocument(
            this AdhocWorkspace workspace,
            string name,
            string filePath,
            string text)
        {
            if (workspace.CurrentSolution.ProjectIds.Count == 0)
            {
                workspace.WithFakeProject(
                    "FakeProject",
                    "FakeProjectAssembly");
            }

            workspace.AddDocument(DocumentInfo.Create(
                                      id:         DocumentId.CreateNewId(workspace.CurrentSolution.ProjectIds[0]),
                                      name:       name,
                                      filePath:   filePath,
                                      loader:     TextLoader.From(TextAndVersion.Create(
                                                                      version:    VersionStamp.Default,
                                                                      text:       SourceText.From(text)))));

            return(workspace);
        }
        private Project CreateSolution(string source)
        {
            var testProjectName = "Test";
            var projectId = ProjectId.CreateNewId(testProjectName);

            var references = new[]
                {
                    s_CorlibReference,
                    s_SystemCoreReference,
                    s_MSTestReference,
                    s_XunitReference
                };

            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, testProjectName, testProjectName, LanguageNames.CSharp)
                .AddMetadataReferences(projectId, references);

            var fileName = "File.cs";
            var documentId = DocumentId.CreateNewId(projectId, fileName);
            solution = solution.AddDocument(documentId, fileName, SourceText.From(source));
            return solution.GetProject(projectId);
        }
Exemple #21
0
        public void TestFrozenPartialProjectAlwaysIsIncomplete()
        {
            var workspace = new AdhocWorkspace();
            var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp);

            var project2 = workspace.AddProject(
                ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    VersionStamp.Create(),
                    "VisualBasicProject",
                    "VisualBasicProject",
                    LanguageNames.VisualBasic,
                    projectReferences: new[] { new ProjectReference(project1.Id) }));

            var document = workspace.AddDocument(project2.Id, "Test.cs", SourceText.From(""));

            // Nothing should have incomplete references, and everything should build
            var frozenSolution = document.WithFrozenPartialSemanticsAsync(CancellationToken.None).Result.Project.Solution;

            Assert.True(frozenSolution.GetProject(project1.Id).HasCompleteReferencesAsync().Result);
            Assert.True(frozenSolution.GetProject(project2.Id).HasCompleteReferencesAsync().Result);
        }
Exemple #22
0
        public void TestProjectWithBrokenCrossLanguageReferenceHasIncompleteReferences()
        {
            var workspace = new AdhocWorkspace();
            var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp);
            workspace.AddDocument(project1.Id, "Broken.cs", SourceText.From("class "));

            var project2 = workspace.AddProject(
                ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    VersionStamp.Create(),
                    "VisualBasicProject",
                    "VisualBasicProject",
                    LanguageNames.VisualBasic,
                    projectReferences: new[] { new ProjectReference(project1.Id) }));

            Assert.True(project1.HasCompleteReferencesAsync().Result);
            Assert.False(project2.HasCompleteReferencesAsync().Result);
            Assert.Empty(project2.GetCompilationAsync().Result.ExternalReferences);
        }
Exemple #23
0
        public void TestEncodingRetainedAfterTreeChanged()
        {
            var ws = new AdhocWorkspace();
            var proj = ws.AddProject("proj", LanguageNames.CSharp);
            var doc = ws.AddDocument(proj.Id, "a.cs", SourceText.From("public class c { }", Encoding.UTF32));

            Assert.Equal(Encoding.UTF32, doc.GetTextAsync().Result.Encoding);

            // updating root doesn't change original encoding
            var root = doc.GetSyntaxRootAsync().Result;
            var newRoot = root.WithLeadingTrivia(root.GetLeadingTrivia().Add(CS.SyntaxFactory.Whitespace("    ")));
            var newDoc = doc.WithSyntaxRoot(newRoot);

            Assert.Equal(Encoding.UTF32, newDoc.GetTextAsync().Result.Encoding);
        }
        private static Project CreateProject(string[] sources, string language = LanguageNames.VisualBasic)
#endif
        {
            string fileNamePrefix = DefaultFilePathPrefix;
            string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;

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

            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, language)
#if CSHARP
                .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
#elif VISUAL_BASIC
                .WithProjectCompilationOptions(projectId, new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
#endif
                .AddMetadataReference(projectId, CorlibReference)
                .AddMetadataReference(projectId, SystemCoreReference)
#if CSHARP
                .AddMetadataReference(projectId, CSharpSymbolsReference)
#elif VISUAL_BASIC
                .AddMetadataReference(projectId, VisualBasicSymbolsReference)
#endif
                .AddMetadataReference(projectId, CodeAnalysisReference)
                .AddMetadataReference(projectId, FakeItEasyReference);

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

            return solution.GetProject(projectId);
        }
Exemple #25
0
        public async Task TestGetInteriorSymbolsDoesNotCrashOnSpeculativeSemanticModel()
        {
            var markup = @"
class C
{
    void foo()
    {
        System.Func<int> lambda = () => 
        {
        int x;
        $$
        }
    }
}";
            int position;
            string text;
            MarkupTestFile.GetPosition(markup, out text, out position);

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

            var firstModel = await document.GetSemanticModelAsync();
            var tree1 = await document.GetSyntaxTreeAsync();
            var basemethod1 = tree1.FindTokenOnLeftOfPosition(position, CancellationToken.None).GetAncestor<CSharp.Syntax.BaseMethodDeclarationSyntax>();

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

            document = workspace.CurrentSolution.GetDocument(document.Id);
            var tree2 = await document.GetSyntaxTreeAsync();
            var basemethod2 = tree2.FindTokenOnLeftOfPosition(position, CancellationToken.None).GetAncestor<CSharp.Syntax.BaseMethodDeclarationSyntax>();

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

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

            // This should not throw an exception.
            Assert.NotNull(SymbolKey.Create(xSymbol));
        }
        public void Should_RewriteTwoDocumentsFromDifferentProjects()
        {
            const string sourceCode = "class SampleClass{}";
            SyntaxNode node = CSharpSyntaxTree.ParseText(sourceCode).GetRoot();

            var workspace = new AdhocWorkspace();
            var project1 = workspace.AddProject("foo.dll", LanguageNames.CSharp);
            var project2 = workspace.AddProject("foo2.dll", LanguageNames.CSharp);

            DocumentInfo documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(project1.Id), "HelloWorld.cs",
                filePath: "c:\\helloworld.cs");
            DocumentInfo documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(project2.Id), "HelloWorld2.cs",
                filePath: "c:\\helloworld2.cs");

            workspace.AddDocument(documentInfo1);
            workspace.AddDocument(documentInfo2);

            _auditVariablesRewriterMock.Rewrite(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<SyntaxNode>()).
                Returns(new RewrittenDocument(node.SyntaxTree, null, false));

            RewriteResult result = _solutionRewriter.RewriteAllClasses(workspace.CurrentSolution.Projects);

            Assert.That(result.Items.Count, Is.EqualTo(2));
            Assert.That(result.Items.Keys.First().Id, Is.EqualTo(project1.Id));
            Assert.That(result.Items.Keys.Last().Id, Is.EqualTo(project2.Id));
        }
        /// <summary>
        /// Create a project using the inputted strings as sources.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source code is in</param>
        /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param>
        /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param>
        /// <returns>A Project created out of the Douments created from the source strings</returns>
        public static Project CreateProject(string[] sources,
            string language,
            LanguageVersion languageVersionCSharp,
            Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB)
        {
            var fileNamePrefix = DefaultFilePathPrefix;
            string fileExt;
            ParseOptions parseOptions;
            if (language == LanguageNames.CSharp)
            {
                fileExt = CSharpDefaultFileExt;
                parseOptions = new CSharpParseOptions(languageVersionCSharp);
            }
            else
            {
                fileExt = VisualBasicDefaultExt;
                parseOptions = new Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions(languageVersionVB);
            }

            var projectId = ProjectId.CreateNewId(debugName: TestProjectName);
#pragma warning disable CC0022
            var workspace = new AdhocWorkspace();
#pragma warning restore CC0022

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

            workspace.AddProject(projectInfo);

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

            var project = workspace.CurrentSolution.GetProject(projectId);
            var newCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(diagOptions);
            var newSolution = workspace.CurrentSolution.WithProjectCompilationOptions(projectId, newCompilationOptions);
            var newProject = newSolution.GetProject(projectId);
            return newProject;
        }
        /// <summary>
        /// Create a project using the inputted strings as sources.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source code is in</param>
        /// <returns>A Project created out of the Documents created from the source strings</returns>
        private static Project CreateProject(string[] sources)
        {
            string TestProjectName = "TestProject";

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

            var solution = new AdhocWorkspace()
                    .CurrentSolution
                    .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp)
                    .AddMetadataReference(projectId, CorlibReference)
                    .AddMetadataReference(projectId, SystemCoreReference)
                    .AddMetadataReference(projectId, CSharpSymbolsReference)
                    .AddMetadataReference(projectId, CodeAnalysisReference)
                    .AddMetadataReference(projectId, EntityReference)
                    .AddMetadataReference(projectId, UtilitiesReference);

            int count = 0;
            foreach (var source in sources)
            {
                var newFileName = "Test" + count + ".cs";
                var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName);
                solution = solution.AddDocument(documentId, newFileName, SourceText.From(source));
                count++;
            }
            return solution.GetProject(projectId);
        }
Exemple #29
0
        public async Task Run()
        {
            var op = new AzureAsyncOperation();
            var restOp = new RestException();

            var files = Settings.Instance.FileSystem.GetFiles(Settings.Instance.OutputDirectory, "*.cs",
                    SearchOption.AllDirectories).
                ToDictionary(each => each, each => Settings.Instance.FileSystem.ReadFileAsText(each));

            var projectId = ProjectId.CreateNewId();
            var solution = new AdhocWorkspace().CurrentSolution
                .AddProject(projectId, "MyProject", "MyProject", LanguageNames.CSharp)
                .AddMetadataReference(projectId, Mscorlib)
                .AddMetadataReference(projectId, AppDomain.CurrentDomain.GetAssemblies()
                    .Where(
                        a =>
                            string.Compare(a.GetName().Name, "Microsoft.Rest.ClientRuntime.Azure",
                                StringComparison.OrdinalIgnoreCase) == 0)
                    .Select(a => MetadataReference.CreateFromFile(a.Location)).Single())
                .AddMetadataReference(projectId, AppDomain.CurrentDomain.GetAssemblies()
                    .Where(
                        a =>
                            string.Compare(a.GetName().Name, "Microsoft.Rest.ClientRuntime",
                                StringComparison.OrdinalIgnoreCase) == 0)
                    .Select(a => MetadataReference.CreateFromFile(a.Location)).Single())
                .AddMetadataReference(projectId, AppDomain.CurrentDomain.GetAssemblies()
                    .Where(a => string.Compare(a.GetName().Name, "System", StringComparison.OrdinalIgnoreCase) == 0)
                    .Select(a => MetadataReference.CreateFromFile(a.Location)).Single());

            // Add existing files
            foreach (var file in files.Keys)
            {
                var documentId = DocumentId.CreateNewId(projectId);
                solution = solution.AddDocument(documentId, file, SourceText.From(files[file]));
            }

            // Simplify docs and add to 
            foreach (var proj in solution.Projects)
            {
                foreach (var document in proj.Documents)
                {
                    var newRoot = await document.GetSyntaxRootAsync();

                    // get the namespaces used in the file
                    var names = new GetQualifiedNames().GetNames(newRoot);

                    // add the usings that we found
                    newRoot = new AddUsingsRewriter(names).Visit(newRoot);

                    // tell roslyn to simplify where it can
                    newRoot = new SimplifyNamesRewriter().Visit(newRoot);
                    var doc = document.WithSyntaxRoot(newRoot);

                    // reduce the code 
                    var text = Simplifier.ReduceAsync(doc)
                        .Result.GetTextAsync()
                        .Result.ToString()
                        // get rid of any BOMs 
                        .Trim('\x00EF', '\x00BB', '\x00BF', '\uFEFF', '\u200B');


                    // special cases the simplifier can't handle.
                    text = text.
                        Replace("[Newtonsoft.Json.JsonConverter(", "[JsonConverter(").
                        Replace("[System.Runtime.Serialization.EnumMember(", "[EnumMember(").
                        Replace("[Newtonsoft.Json.JsonProperty(", "[JsonProperty(").
                        Replace("[Newtonsoft.Json.JsonProperty]", "[JsonProperty]").
                        Replace("[Newtonsoft.Json.JsonObject]", "[JsonObject]").
                        Replace("[Microsoft.Rest.Serialization.JsonTransformation]", "[JsonTransformation]").
                        Replace("[Newtonsoft.Json.JsonExtensionData]", "[JsonExtensionData]");

                        // Write out the files back to their original location
                        var output = Path.Combine(Settings.Instance.FileSystem.CurrentDirectory, document.Name);
                        Settings.Instance.FileSystem.WriteFile(output, text);
                }
            }
        }
        /// <summary>
        /// Create a project using the inputted strings as sources.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source code is in</param>
        /// <returns>A Project created out of the Documents created from the source strings</returns>
        private static Project CreateProject(string[] sources, string language = LanguageNames.CSharp)
        {
            string fileNamePrefix = DefaultFilePathPrefix;
            string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;

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

            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, language)
                .AddMetadataReference(projectId, CorlibReference)
                .AddMetadataReference(projectId, SystemCoreReference)
                .AddMetadataReference(projectId, CSharpSymbolsReference)
                .AddMetadataReference(projectId, CodeAnalysisReference);

            int count = 0;
            foreach (var source in sources)
            {
                var newFileName = fileNamePrefix + count + "." + fileExt;
                var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName);
                solution = solution.AddDocument(documentId, newFileName, SourceText.From(source));
                count++;
            }
            return solution.GetProject(projectId);
        }
        /// <summary>
        /// Create a project using the inputted strings as sources.
        /// </summary>
        /// <param name="fileSources">Classes in the form of MvxTestFileSources</param>
        /// <returns>A Solution created out of the Documents created from the source strings</returns>
        private static Solution CreateSolution(MvxTestFileSource[] fileSources)
        {
            string fileNamePrefix = DefaultFilePathPrefix;

            _coreProjectId = ProjectId.CreateNewId(debugName: TestCoreProjectName);
            _droidProjectId = ProjectId.CreateNewId(debugName: TestDroidProjectName);
            _iosProjectId = ProjectId.CreateNewId(debugName: TestIosProjectName);

            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(_coreProjectId, TestCoreProjectName, TestCoreProjectName, LanguageNames.CSharp)
                .AddProject(_droidProjectId, TestDroidProjectName, TestDroidProjectName, LanguageNames.CSharp)
                .AddProject(_iosProjectId, TestIosProjectName, TestIosProjectName, LanguageNames.CSharp)
                .AddMetadataReference(_coreProjectId, _corlibReference)
                .AddMetadataReference(_coreProjectId, _systemCoreReference)
                .AddMetadataReference(_coreProjectId, _cSharpSymbolsReference)
                .AddMetadataReference(_coreProjectId, _codeAnalysisReference)
                .AddMetadataReference(_coreProjectId, _mvvmCrossCoreReference)
                .AddMetadataReference(_coreProjectId, _mvvmCrossPlatformReference)
                .AddMetadataReference(_coreProjectId, _componentModelReference)
                .AddMetadataReference(_coreProjectId, _objectModelReference)
                .AddMetadataReference(_coreProjectId, _runtimeReference)
                .AddMetadataReference(_droidProjectId, _corlibReference)
                .AddMetadataReference(_droidProjectId, _systemCoreReference)
                .AddMetadataReference(_droidProjectId, _cSharpSymbolsReference)
                .AddMetadataReference(_droidProjectId, _codeAnalysisReference)
                .AddMetadataReference(_droidProjectId, _mvvmCrossCoreReference)
                .AddMetadataReference(_droidProjectId, _mvvmCrossDroidReference)
                .AddMetadataReference(_droidProjectId, _componentModelReference)
                .AddMetadataReference(_droidProjectId, _objectModelReference)
                .AddProjectReference(_droidProjectId, new ProjectReference(_coreProjectId))
                .AddMetadataReference(_iosProjectId, _corlibReference)
                .AddMetadataReference(_iosProjectId, _systemCoreReference)
                .AddMetadataReference(_iosProjectId, _cSharpSymbolsReference)
                .AddMetadataReference(_iosProjectId, _codeAnalysisReference)
                .AddMetadataReference(_iosProjectId, _mvvmCrossCoreReference)
                .AddMetadataReference(_iosProjectId, _mvvmCrossIosReference)
                .AddMetadataReference(_iosProjectId, _componentModelReference)
                .AddMetadataReference(_iosProjectId, _objectModelReference)
                .AddProjectReference(_iosProjectId, new ProjectReference(_coreProjectId));

            int count = 0;
            foreach (var fileSource in fileSources)
            {
                var newFileName = fileNamePrefix + count + "." + CSharpDefaultFileExt;
                var documentId = DocumentId.CreateNewId(GetProjectId(fileSource), debugName: newFileName);
                solution = solution.AddDocument(documentId, newFileName, SourceText.From(fileSource.Source));
                count++;
            }

            return solution;
        }