/// <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 Douments 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 CustomWorkspace()
                .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);
        }
Esempio n. 2
0
        private Project CreateProject()
        {
            var projectId = ProjectId.CreateNewId(debugName: projectName);

            var solution = new CustomWorkspace()
                .CurrentSolution
                .AddProject(projectId, projectName, projectName, LanguageNames.CSharp)
                .AddMetadataReference(projectId, CorlibReference)
                .AddMetadataReference(projectId, SystemCoreReference)
                .AddMetadataReference(projectId, CSharpSymbolsReference)
                .AddMetadataReference(projectId, CodeAnalysisReference);

            foreach (var file in files)
            {
                var documentId = DocumentId.CreateNewId(projectId, debugName: file.Path);
                solution = solution.AddDocument(documentId, file.Path, SourceText.From(file.Content));
            }
            return solution.GetProject(projectId);
        }
Esempio n. 3
0
        public void TestGetProjectForAssemblySymbol()
        {
            var pid1 = ProjectId.CreateNewId("p1");
            var pid2 = ProjectId.CreateNewId("p2");
            var pid3 = ProjectId.CreateNewId("p3");
            var did1 = DocumentId.CreateNewId(pid1);
            var did2 = DocumentId.CreateNewId(pid2);
            var did3 = DocumentId.CreateNewId(pid3);

            var text1 = @"
Public Class A
End Class";

            var text2 = @"
Public Class B
End Class
";

            var text3 = @"
public class C : B {
}
";

            var text4 = @"
public class C : A {
}
";

            var solution = new CustomWorkspace().CurrentSolution
                .AddProject(pid1, "FooA", "Foo.dll", LanguageNames.VisualBasic)
                .AddDocument(did1, "A.vb", text1)
                .AddMetadataReference(pid1, mscorlib)
                .AddProject(pid2, "FooB", "Foo2.dll", LanguageNames.VisualBasic)
                .AddDocument(did2, "B.vb", text2)
                .AddMetadataReference(pid2, mscorlib)
                .AddProject(pid3, "Bar", "Bar.dll", LanguageNames.CSharp)
                .AddDocument(did3, "C.cs", text3)
                .AddMetadataReference(pid3, mscorlib)
                .AddProjectReference(pid3, new ProjectReference(pid1))
                .AddProjectReference(pid3, new ProjectReference(pid2));

            var project3 = solution.GetProject(pid3);
            var comp3 = project3.GetCompilationAsync().Result;
            var classC = comp3.GetTypeByMetadataName("C");
            var projectForBaseType = solution.GetProject(classC.BaseType.ContainingAssembly);
            Assert.Equal(pid2, projectForBaseType.Id);

            // switch base type to A then try again
            var solution2 = solution.WithDocumentText(did3, SourceText.From(text4));
            project3 = solution2.GetProject(pid3);
            comp3 = project3.GetCompilationAsync().Result;
            classC = comp3.GetTypeByMetadataName("C");
            projectForBaseType = solution2.GetProject(classC.BaseType.ContainingAssembly);
            Assert.Equal(pid1, projectForBaseType.Id);
        }
        public void PinvokeMethodReferences_VB()
        {  
            var tree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(
                @"
Module Module1
        Declare Function CreateDirectory Lib ""kernel32"" Alias ""CreateDirectoryA"" (ByVal lpPathName As String) As Integer
 
        Private prop As Integer
        Property Prop1 As Integer
            Get
                Return prop
            End Get
            Set(value As Integer)
                CreateDirectory(""T"")  ' Method Call 1
                prop = value
                prop = Nothing
            End Set
        End Property

        Sub Main()
          CreateDirectory(""T"") 'Method Call 2            
          NormalMethod() ' Method Call 1
          NormalMethod() ' Method Call 2
       End Sub

       Sub NormalMethod()
       End Sub
 End Module
            ");

            ProjectId prj1Id = ProjectId.CreateNewId();
            DocumentId docId = DocumentId.CreateNewId(prj1Id);

            Microsoft.CodeAnalysis.Solution sln = new CustomWorkspace().CurrentSolution
                .AddProject(prj1Id, "testDeclareReferences", "testAssembly", LanguageNames.VisualBasic)
                .AddMetadataReference(prj1Id, MscorlibRef)                
                .AddDocument(docId, "testFile", tree.GetText());

            Microsoft.CodeAnalysis.Project prj = sln.GetProject(prj1Id).WithCompilationOptions(new VisualBasic.VisualBasicCompilationOptions(OutputKind.ConsoleApplication, embedVbCoreRuntime: true));
            tree = (SyntaxTree)prj.GetDocument(docId).GetSyntaxTreeAsync().Result;
            Compilation comp = prj.GetCompilationAsync().Result;
            
            SemanticModel semanticModel = comp.GetSemanticModel(tree);

            SyntaxNode declareMethod = tree.GetRoot().DescendantNodes().OfType<Microsoft.CodeAnalysis.VisualBasic.Syntax.DeclareStatementSyntax>().FirstOrDefault();
            SyntaxNode normalMethod = tree.GetRoot().DescendantNodes().OfType<Microsoft.CodeAnalysis.VisualBasic.Syntax.MethodStatementSyntax>().ToList()[1];

            // declared method calls
            var symbol = semanticModel.GetDeclaredSymbol(declareMethod);
            var references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;
            Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());

            // normal method calls
            symbol = semanticModel.GetDeclaredSymbol(normalMethod);
            references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;
            Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());
        }
        public void PinvokeMethodReferences_CS()
        {
            var tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(
                @"

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.InteropServices;
static class Module1
{
	[DllImport(""kernel32"", EntryPoint = ""CreateDirectoryA"", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
    public static extern int CreateDirectory(string lpPathName);

        private static int prop;
        public static int Prop1
        {
            get { return prop; }
            set
            {
                CreateDirectory(""T"");
                // Method Call 1
                prop = value;
                prop = null;
            }
        }

        public static void Main()
        {
            CreateDirectory(""T""); // Method Call 2            
            NormalMethod(); // Method Call 1
            NormalMethod(); // Method Call 2
        }

        public static void NormalMethod()
        {
        }
    }
                ");

            ProjectId prj1Id = ProjectId.CreateNewId();
            DocumentId docId = DocumentId.CreateNewId(prj1Id);

            var sln = new CustomWorkspace().CurrentSolution
                .AddProject(prj1Id, "testDeclareReferences", "testAssembly", LanguageNames.CSharp)
                .AddMetadataReference(prj1Id, MscorlibRef)
                .AddDocument(docId, "testFile", tree.GetText());

            Microsoft.CodeAnalysis.Project prj = sln.GetProject(prj1Id).WithCompilationOptions(new CSharp.CSharpCompilationOptions(OutputKind.ConsoleApplication));
            tree = (SyntaxTree)prj.GetDocument(docId).GetSyntaxTreeAsync().Result;
            Compilation comp = prj.GetCompilationAsync().Result;

            SemanticModel semanticModel = comp.GetSemanticModel(tree);

            List<Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax> methodlist = tree.GetRoot().DescendantNodes().OfType<Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax>().ToList();
            SyntaxNode declareMethod = methodlist.ElementAt(0);
            SyntaxNode normalMethod = methodlist.ElementAt(2);

            // pinvoke method calls
            var symbol = semanticModel.GetDeclaredSymbol(declareMethod);
            var references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;
            Assert.Equal(2, references.ElementAt(0).Locations.Count());

            // normal method calls
            symbol = semanticModel.GetDeclaredSymbol(normalMethod);
            references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;
            Assert.Equal(2, references.ElementAt(0).Locations.Count());
        }
Esempio n. 6
0
        public void FindAllReferencesToAMethodInASolution()
        {
            var source1 = @"
namespace NS
{
    public class C
    {
        public void MethodThatWeAreTryingToFind()
        {
        }
        public void AnotherMethod()
        {
            MethodThatWeAreTryingToFind(); // First Reference.
        }
    }
}";
            var source2 = @"
using NS;
using Alias=NS.C;
class Program
{
    static void Main()
    {
        var c1 = new C();
        c1.MethodThatWeAreTryingToFind(); // Second Reference.
        c1.AnotherMethod();
        var c2 = new Alias();
        c2.MethodThatWeAreTryingToFind(); // Third Reference.
    }
}";
            var project1Id = ProjectId.CreateNewId();
            var project2Id = ProjectId.CreateNewId();
            var document1Id = DocumentId.CreateNewId(project1Id);
            var document2Id = DocumentId.CreateNewId(project2Id);

            var solution = new CustomWorkspace().CurrentSolution
                .AddProject(project1Id, "Project1", "Project1", LanguageNames.CSharp)
                .AddMetadataReference(project1Id, Mscorlib)
                .AddDocument(document1Id, "File1.cs", source1)
                .WithProjectCompilationOptions(project1Id, 
                    new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                .AddProject(project2Id, "Project2", "Project2", LanguageNames.CSharp)
                .AddMetadataReference(project2Id, Mscorlib)
                .AddProjectReference(project2Id, new ProjectReference(project1Id))
                .AddDocument(document2Id, "File2.cs", source2);
            
            // If you wish to try against a real solution you could use code like
            // var solution = Solution.Load("<Path>");
            // OR var solution = Workspace.LoadSolution("<Path>").CurrentSolution;

            var project1 = solution.GetProject(project1Id);
            var document1 = project1.GetDocument(document1Id);
            
            // Get MethodDeclarationSyntax corresponding to the 'MethodThatWeAreTryingToFind'.
            MethodDeclarationSyntax methodDeclaration = document1.GetSyntaxRootAsync().Result
                .DescendantNodes().OfType<MethodDeclarationSyntax>()
                .Single(m => m.Identifier.ValueText == "MethodThatWeAreTryingToFind");

            // Get MethodSymbol corresponding to the 'MethodThatWeAreTryingToFind'.
            var method = (IMethodSymbol)document1.GetSemanticModelAsync().Result
                .GetDeclaredSymbol(methodDeclaration);

            // Find all references to the 'MethodThatWeAreTryingToFind' in the solution.
            IEnumerable<ReferencedSymbol> methodReferences = SymbolFinder.FindReferencesAsync(method, solution).Result;
            Assert.AreEqual(1, methodReferences.Count());
            ReferencedSymbol methodReference = methodReferences.Single();
            Assert.AreEqual(3, methodReference.Locations.Count());

            var methodDefinition = (IMethodSymbol)methodReference.Definition;
            Assert.AreEqual("MethodThatWeAreTryingToFind", methodDefinition.Name);
            Assert.IsTrue(methodReference.Definition.Locations.Single().IsInSource);
            Assert.AreEqual("File1.cs", methodReference.Definition.Locations.Single().SourceTree.FilePath);

            Assert.IsTrue(methodReference.Locations
                .All(referenceLocation => referenceLocation.Location.IsInSource));
            Assert.AreEqual(1, methodReference.Locations
                .Count(referenceLocation => referenceLocation.Document.Name == "File1.cs"));
            Assert.AreEqual(2, methodReference.Locations
                .Count(referenceLocation => referenceLocation.Document.Name == "File2.cs"));
        }