コード例 #1
0
        /// <summary>
        /// Create a project using the inputted strings as sources.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source code is in</param>
        /// <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);
        }
        protected static void AssertThatRefactoringOriginalCodeThrowsPreconditionException(string code, params InvocationExpressionFinder[] invocationExpressionFinders)
        {
            if (code == null) throw new ArgumentNullException("code");
            if (invocationExpressionFinders == null) throw new ArgumentNullException("invocationExpressionFinders");

            if (invocationExpressionFinders.Length == 0) throw new ArgumentException("Must provide at least one StatementFinder");

            Logger.Debug("\n=== CODE TO BE CHECKED FOR REFACTORING PRECONDITION ===\n{0}\n=== END OF CODE ===", code);

            var workspace = new CustomWorkspace();

            Document document;

            var solution = AnnotateSolution(code, invocationExpressionFinders, workspace, out document);

            try
            {
                RefactorDocument(document, solution, invocationExpressionFinders.Length, workspace);

                Assert.Fail("No PreconditionException was thrown");
            }
            catch (PreconditionException e)
            {
                Logger.Debug("PreconditionException caught as expected.");
            }
        }
        private static void TestSyntaxTreeFactoryService(ISyntaxTreeFactoryService service, string text, string fileName)
        {
            var parseOptions = service.GetDefaultParseOptions();
            var workspace = new CustomWorkspace(TestHost.Services, "Test");

            var tree = service.ParseSyntaxTree(
                fileName,
                parseOptions,
                SourceText.From(text),
                CancellationToken.None);

            var textAndVersion = TextAndVersion.Create(
                tree.GetText(),
                VersionStamp.Create(),
                fileName);

            var valueSource = new AsyncLazy<TextAndVersion>(textAndVersion);

            var recoverableTree = service.CreateRecoverableTree(
                tree.FilePath,
                tree.Options,
                valueSource,
                tree.GetRoot());

            workspace.Services.GetService<ISyntaxTreeCacheService>().Clear();

            var trivia = tree.GetRoot().GetLeadingTrivia().First();
            var actualTrivia = recoverableTree.GetRoot().GetLeadingTrivia().First();

            Assert.Equal(trivia.ToFullString(), actualTrivia.ToFullString());
        }
コード例 #4
0
        public static string Simplify(SyntaxNode node)
        {
            var source = node.ToString();
            var projectId = ProjectId.CreateNewId();
            var documentId = DocumentId.CreateNewId(projectId);

            var solution = new CustomWorkspace().CurrentSolution
                .AddProject(projectId, "MyProject", "MyProject", LanguageNames.CSharp)
                .AddMetadataReference(projectId, RoslynRDomUtilities.Mscorlib)
                .AddMetadataReference(projectId, AppDomain.CurrentDomain.GetAssemblies()
                    .Where(a => string.Compare(a.GetName().Name, "System", StringComparison.OrdinalIgnoreCase) == 0)
                    .Select(a => new MetadataFileReference(a.Location)).Single())
                .AddDocument(documentId, "MyFile.cs", source);
            var document = solution.GetDocument(documentId);

            // Format the document.
            document = Formatter.FormatAsync(document).Result;

            // Simplify names used in the document i.e. remove unnecessary namespace qualifiers.
            var newRoot = (SyntaxNode)document.GetSyntaxRootAsync().Result;
            newRoot = new SimplifyNamesAnnotionRewriter().Visit(newRoot);
            document = document.WithSyntaxRoot(newRoot);

            document = Simplifier.ReduceAsync(document).Result;
            var ret = document.GetSyntaxRootAsync().Result.ToString();
            return ret;
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: MartinJohns/RoslynDemo
        static async Task MainAsync()
        {
            var workspace = new CustomWorkspace();
            var solution = workspace.CurrentSolution;
            var project = solution.AddProject("projectName", "assemblyName", LanguageNames.CSharp);
            var document = project.AddDocument("name.cs",
                @"using System;
public namespace Demo{public static class Program
    {public static void Main()
        {Console.WriteLine(""Hello Roslyn!"");
}}}");

            document = await Formatter.FormatAsync(document);
            var source = await document.GetTextAsync();

            var classifiedSpans = await Classifier.GetClassifiedSpansAsync(document, TextSpan.FromBounds(0, source.Length));
            Console.BackgroundColor = ConsoleColor.Black;

            var ranges = classifiedSpans.Select(x => new Range(x, source.GetSubText(x.TextSpan).ToString()));

            ranges = FillGaps(source, ranges);

            foreach (var range in ranges)
            {
                switch (range.ClassificationType)
                {
                    case "keyword":
                        Console.ForegroundColor = ConsoleColor.DarkCyan;
                        break;
                    case "class name":
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        break;
                    case "string":
                        Console.ForegroundColor = ConsoleColor.DarkYellow;
                        break;
                    case "punctuation":
                        Console.ForegroundColor = ConsoleColor.Red;
                        break;
                    case "operator":
                        Console.ForegroundColor = ConsoleColor.DarkGreen;
                        break;
                    case "identifier":
                        Console.ForegroundColor = ConsoleColor.Gray;
                        break;
                    default:
                        Console.ForegroundColor = ConsoleColor.DarkBlue;
                        break;
                }

                Console.Write(range.Text);
            }

            Console.ResetColor();
            Console.ReadLine();
        }
        public void CSharpSyntaxTreeFactoryServiceTest()
        {
            var workspace = new CustomWorkspace(TestHost.Services, "Test");
            var service = workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ISyntaxTreeFactoryService>();

            var text = @"/// <summary>XML</summary>
class C { }";
            var fileName = @"C:\1.cs";

            TestSyntaxTreeFactoryService(service, text, fileName);
        }
コード例 #7
0
        private Document CreateSolutionDocument(string sourceText)
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var solution = new CustomWorkspace().CurrentSolution
                    .AddProject(pid, "test", "test", LanguageNames.CSharp)
                    .AddMetadataReference(pid, mscorlib)
                    .AddDocument(did, "foo.cs", SourceText.From(sourceText));

            return solution.GetDocument(did);
        }
        public void VisualBasicSyntaxTreeFactoryServiceTest()
        {
            var workspace = new CustomWorkspace(TestHost.Services, "Test");
            var service = workspace.Services.GetLanguageServices(LanguageNames.VisualBasic).GetService<ISyntaxTreeFactoryService>();

            var text = @"''' <summary>XML</summary>
Class C
End Class";
            var fileName = @"C:\1.vb";

            TestSyntaxTreeFactoryService(service, text, fileName);
        }
コード例 #9
0
    private static async Task TestFormatterAndClassifierAsync()
    {
        CustomWorkspace workspace = new CustomWorkspace();
        Solution solution = workspace.CurrentSolution;
        Project project = solution.AddProject("projectName", "assemblyName", LanguageNames.CSharp);
        Document document = project.AddDocument("name.cs", 
@"class C
{
static void Main()
{
WriteLine(""Hello, World!"");
}
}");
        document = await Formatter.FormatAsync(document);
        SourceText text = await document.GetTextAsync();

        IEnumerable<ClassifiedSpan> classifiedSpans = await Classifier.GetClassifiedSpansAsync(document, TextSpan.FromBounds(0, text.Length));
        Console.BackgroundColor = ConsoleColor.Black;

        var ranges = classifiedSpans.Select(classifiedSpan => 
            new Range(classifiedSpan, text.GetSubText(classifiedSpan.TextSpan).ToString()));

        ranges = FillGaps(text, ranges);

        foreach (Range range in ranges)
        {
            switch (range.ClassificationType)
            {
                case "keyword":
                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                    break;
                case "class name":
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    break;
                case "string":
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    break;
                default:
                    Console.ForegroundColor = ConsoleColor.White;
                    break;
            }

            Console.Write(range.Text);
        }

        Console.ResetColor();
        Console.WriteLine();
    }
コード例 #10
0
ファイル: WorkspaceViewModel.cs プロジェクト: khellang/Runt
        public WorkspaceViewModel(ShellViewModel shell, string path)
            : base(null, path)
        {
            var runtime = Kvm.GetRuntime(shell.SelectedRuntime);
            _host = new Host(path);
            _host.Connected += HostConnected;
            _host.Configurations += HostConfigurations;
            _host.References += HostReferences;
            _host.Start(runtime);

            _watcher = new FileSystemWatcher(path);
            _watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.DirectoryName | NotifyFilters.LastAccess;
            _watcher.Filter = "*.*";
            _watcher.Changed += FileChanged;

            _workspace = new CustomWorkspace();
        }
コード例 #11
0
        public WorkspaceViewModel(ShellViewModel shell, string path)
            : base(null, path)
        {
            _host = new Host(path);
            _host.Connected += HostConnected;
            _host.Configurations += HostConfigurations;
            _host.References += HostReferences;

            _watcher = new FileSystemWatcher(path);
            _watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.DirectoryName | NotifyFilters.LastAccess;
            _watcher.Filter = "*.*";
            _watcher.Changed += FileChanged;

            _workspace = new CustomWorkspace();
            _shell = shell;

            InitializeWorkspace();
        }
        /// <summary>
        /// Assert that given original code containing both the BeginXxx method
        /// call, callback method declaration and EndXxx method call, is
        /// correctly refactored to the given refactored code statement. The
        /// statementFinder is used to return the APM invocation expression
        /// statement that must be refactored.
        /// </summary>
        /// <param name="originalCode">The original code to refactor.</param>
        /// <param name="refactoredCode">The refactored code to check against.</param>
        /// <param name="invocationExpressionFinders">One or more delegates that returns the APM BeginXxx
        /// invocation expression statement(s) that must be refactored.</param>
        protected static void AssertThatOriginalCodeIsRefactoredCorrectly(string originalCode, string refactoredCode, params InvocationExpressionFinder[] invocationExpressionFinders)
        {
            if (originalCode == null) throw new ArgumentNullException("originalCode");
            if (refactoredCode == null) throw new ArgumentNullException("refactoredCode");
            if (invocationExpressionFinders == null) throw new ArgumentNullException("invocationExpressionFinders");

            if (invocationExpressionFinders.Length == 0) throw new ArgumentException("Must provide at least one StatementFinder");

            Logger.Debug("\n=== CODE TO BE REFACTORED ===\n{0}\n=== END OF CODE ===", originalCode);

            var workspace = new CustomWorkspace();

            Document annotatedDocument;
            var annotatedSolution = AnnotateSolution(originalCode, invocationExpressionFinders, workspace, out annotatedDocument);

            var refactoredSyntax = RefactorDocument(annotatedDocument, annotatedSolution, invocationExpressionFinders.Length, workspace);

            var expectedSyntaxTree = SyntaxTree.ParseText(refactoredCode);
            var expectedSyntax = expectedSyntaxTree.GetCompilationUnitRoot();

            Assert.IsNotNull(refactoredSyntax);
            Assert.That(refactoredSyntax.ToString().Replace("\r\n", "\n"), Is.EqualTo(expectedSyntax.ToString().Replace("\r\n", "\n")));
        }
        public static Solution CreateOriginalDocument(string originalCode, CustomWorkspace workspace, out DocumentId documentId)
        {
            var projectId = workspace.AddProject("ProjectUnderTest", LanguageNames.CSharp);
            documentId = workspace.AddDocument(projectId, "SourceUnderTest.cs", originalCode);

            var solution = workspace.CurrentSolution
                .AddMetadataReference(projectId, mscorlib)
                .AddMetadataReference(projectId, System)
                .AddMetadataReference(projectId, SystemCore);

            return solution;
        }
コード例 #14
0
        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());
        }
コード例 #15
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);
        }
コード例 #16
0
ファイル: SyntaxNodeTests.cs プロジェクト: EkardNT/Roslyn
        public void TestTrackNodesWithDocument()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var sourceText = @"public class C { void M() { } }";

            var sol = new CustomWorkspace().CurrentSolution
                .AddProject(pid, "proj", "proj", LanguageNames.CSharp)
                .AddDocument(did, "doc", sourceText);

            var doc = sol.GetDocument(did);

            // find initial nodes of interest
            var root = doc.GetSyntaxRootAsync().Result;
            var classDecl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().First();
            var methodDecl = classDecl.DescendantNodes().OfType<MethodDeclarationSyntax>().First();

            // track these nodes
            var trackedRoot = root.TrackNodes(classDecl, methodDecl);

            // use some fancy document centric rewrites
            var comp = doc.Project.GetCompilationAsync().Result;

            var cgenField = CodeGenerationSymbolFactory.CreateFieldSymbol(
                attributes: null,
                accessibility: Accessibility.Private,
                modifiers: new SymbolModifiers(),
                type: comp.GetSpecialType(SpecialType.System_Int32),
                name: "X");

            var currentClassDecl = trackedRoot.GetCurrentNodes(classDecl).First();
            var classDeclWithField = Formatter.Format(
                                        CodeGenerator.AddFieldDeclaration(currentClassDecl, cgenField, sol.Workspace),
                                        sol.Workspace);

            // we can find related bits even from sub-tree fragments
            var latestMethod = classDeclWithField.GetCurrentNodes(methodDecl).First();
            Assert.NotNull(latestMethod);
            Assert.NotEqual(latestMethod, methodDecl);

            trackedRoot = trackedRoot.ReplaceNode(currentClassDecl, classDeclWithField);

            // put back into document (branch solution, etc)
            doc = doc.WithSyntaxRoot(trackedRoot);

            // re-get root of new document
            var root2 = doc.GetSyntaxRootAsync().Result;
            Assert.NotEqual(trackedRoot, root2);

            // we can still find the tracked node in the new document
            var finalClassDecl = root2.GetCurrentNodes(classDecl).First();
            Assert.Equal(@"public class C { private System.Int32 X; void M() { } }", finalClassDecl.ToString());

            // and other tracked nodes too
            var finalMethodDecl = root2.GetCurrentNodes(methodDecl).First();
            Assert.NotNull(finalMethodDecl);
            Assert.NotEqual(finalMethodDecl, methodDecl);
        }
コード例 #17
0
ファイル: SolutionTests.cs プロジェクト: nagyist/roslyn
        private Solution CreateNotKeptAliveSolution()
        {
            var workspace = new CustomWorkspace(TestHost.Services, "NotKeptAlive");

            // prove we have the correct composition & type of workspace service provider
            var service = workspace.Services.GetService<ICompilationCacheService>();
            Assert.Equal(true, service is NotKeptAliveCompilationCacheServiceFactory.CacheService);

            return workspace.CurrentSolution;
        }
コード例 #18
0
        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());
        }
コード例 #19
0
ファイル: ReduceTokenTests.cs プロジェクト: riversky/roslyn
        private static Document CreateDocument(string code, string language)
        {
            var solution = new CustomWorkspace(SolutionId.CreateNewId("Solution")).CurrentSolution;
            var projectId = ProjectId.CreateNewId();
            var project = solution.AddProject(projectId, "Project", "Project.dll", language).GetProject(projectId);

            return project.AddMetadataReference(new MetadataFileReference(typeof(int).Assembly.Location))
                          .AddDocument("Document", SourceText.From(code));
        }
        private static Solution AnnotateSolution(string originalCode, InvocationExpressionFinder[] invocationExpressionFinders, CustomWorkspace workspace, out Document annotatedDocument)
        {
            DocumentId documentId;
            var originalSolution = CreateOriginalDocument(originalCode, workspace, out documentId);
            var originalDocument = originalSolution.GetDocument(documentId);

            annotatedDocument = AnnotateDocument(originalDocument, invocationExpressionFinders);

            return originalSolution.WithDocumentSyntaxRoot(documentId, originalDocument.GetSyntaxRootAsync().Result);
        }
コード例 #21
0
ファイル: SolutionTests.cs プロジェクト: nagyist/roslyn
        public void TestCommandLineProjectWithRelativePathOutsideProjectCone()
        {
            string commandLine = @"..\foo.cs";
            var ws = new CustomWorkspace();
            var info = CommandLineProject.CreateProjectInfo(ws, "TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");

            var docInfo = info.Documents.First();
            Assert.Equal(0, docInfo.Folders.Count);
            Assert.Equal("foo.cs", docInfo.Name);
        }
コード例 #22
0
ファイル: SolutionTests.cs プロジェクト: nagyist/roslyn
        public void TestLoadProjectFromCommandLine()
        {
            string commandLine = @"foo.cs subdir\bar.cs /out:foo.dll /target:library";
            var ws = new CustomWorkspace();
            var info = CommandLineProject.CreateProjectInfo(ws, "TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");
            ws.AddProject(info);
            var project = ws.CurrentSolution.GetProject(info.Id);

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

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

            var fooDoc = project.Documents.First(d => d.Name == "foo.cs");
            Assert.Equal(0, fooDoc.Folders.Count);
            Assert.Equal(@"C:\ProjectDirectory\foo.cs", fooDoc.FilePath);

            var barDoc = project.Documents.First(d => d.Name == "bar.cs");
            Assert.Equal(1, barDoc.Folders.Count);
            Assert.Equal("subdir", barDoc.Folders[0]);
            Assert.Equal(@"C:\ProjectDirectory\subdir\bar.cs", barDoc.FilePath);
        }
コード例 #23
0
ファイル: SolutionTests.cs プロジェクト: riversky/roslyn
        private Solution CreateNotKeptAliveSolution()
        {
            var workspace = new CustomWorkspace(GetTestWorkspaceFeatures(), "NotKeptAlive");

            // prove we have the correct composition & type of workspace service provider
            var service = WorkspaceService.GetService<Microsoft.CodeAnalysis.Host.ICompilationCacheService>(workspace);
            Assert.Equal(true, service is NotKeptAliveCompilationCacheServiceFactory.CacheService);

            return workspace.CurrentSolution;
        }
コード例 #24
0
ファイル: SolutionTests.cs プロジェクト: riversky/roslyn
        public void TestWorkspaceLanguageServiceOverride()
        {
            var ws = new CustomWorkspace(GetTestWorkspaceFeatures(), WorkspaceKind.Host);
            var service = WorkspaceService.GetService<ILanguageServiceProviderFactory>(ws).GetLanguageServiceProvider(LanguageNames.CSharp).GetService<ITestLanguageService>();
            Assert.NotNull(service as TestLanguageServiceA);

            var ws2 = new CustomWorkspace(GetTestWorkspaceFeatures(), "Quasimodo");
            var service2 = WorkspaceService.GetService<ILanguageServiceProviderFactory>(ws2).GetLanguageServiceProvider(LanguageNames.CSharp).GetService<ITestLanguageService>();
            Assert.NotNull(service2 as TestLanguageServiceB);
        }
コード例 #25
0
ファイル: SolutionTests.cs プロジェクト: nagyist/roslyn
        public void TestDocumentFileAccessFailureMissingFile()
        {
            var solution = new CustomWorkspace().CurrentSolution;

            WorkspaceDiagnostic diagnostic = null;

            solution.Workspace.WorkspaceFailed += (sender, args) =>
            {
                diagnostic = args.Diagnostic;
            };

            ProjectId pid = ProjectId.CreateNewId();
            DocumentId did = DocumentId.CreateNewId(pid);

            solution = solution.AddProject(pid, "foo", "foo", LanguageNames.CSharp)
                               .AddDocument(did, "x", new FileTextLoader("doesnotexist.cs"));

            var doc = solution.GetDocument(did);
            var text = doc.GetTextAsync().Result;

            WaitFor(() => diagnostic != null, TimeSpan.FromSeconds(5));

            Assert.NotNull(diagnostic);
            var dd = diagnostic as DocumentDiagnostic;
            Assert.NotNull(dd);
            Assert.Equal(did, dd.DocumentId);
            Assert.Equal(WorkspaceDiagnosticKind.FileAccessFailure, dd.Kind);
        }
コード例 #26
0
ファイル: SolutionTests.cs プロジェクト: nagyist/roslyn
        public void TestWorkspaceDiagnosticHasDebuggerText()
        {
            var solution = new CustomWorkspace().CurrentSolution;

            WorkspaceDiagnostic diagnostic = null;

            solution.Workspace.WorkspaceFailed += (sender, args) =>
            {
                diagnostic = args.Diagnostic;
            };

            ProjectId pid = ProjectId.CreateNewId();
            DocumentId did = DocumentId.CreateNewId(pid);

            solution = solution.AddProject(pid, "foo", "foo", LanguageNames.CSharp)
                               .AddDocument(did, "x", new FileTextLoader("doesnotexist.cs"));

            var doc = solution.GetDocument(did);
            var text = doc.GetTextAsync().Result;

            WaitFor(() => diagnostic != null, TimeSpan.FromSeconds(5));

            Assert.NotNull(diagnostic);
            var dd = diagnostic as DocumentDiagnostic;
            Assert.NotNull(dd);
            Assert.Equal(dd.GetDebuggerDisplay(), string.Format("[{0}] {1}", dd.Kind.ToString(), dd.Message));
        }
コード例 #27
0
ファイル: CodeCleanupTests.cs プロジェクト: EkardNT/Roslyn
        private static Document CreateDocument(string code, string language)
        {
            var solution = new CustomWorkspace().CurrentSolution;
            var projectId = ProjectId.CreateNewId();
            var project = solution.AddProject(projectId, "Project", "Project.dll", language).GetProject(projectId);

            return project.AddDocument("Document", SourceText.From(code));
        }
コード例 #28
0
ファイル: SolutionTests.cs プロジェクト: nagyist/roslyn
        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);
        }
コード例 #29
0
ファイル: SolutionTests.cs プロジェクト: nagyist/roslyn
        public void TestWorkspaceLanguageServiceOverride()
        {
            var ws = new CustomWorkspace(TestHost.Services, ServiceLayer.Host);
            var service = ws.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>();
            Assert.NotNull(service as TestLanguageServiceA);

            var ws2 = new CustomWorkspace(TestHost.Services, "Quasimodo");
            var service2 = ws2.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>();
            Assert.NotNull(service2 as TestLanguageServiceB);
        }
コード例 #30
0
ファイル: FAQ.cs プロジェクト: jerriclynsjohn/roslyn
        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"));
        }