/// <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="solution">The created workspace containing the project</param>
        /// <returns>A Project created out of the Douments created from the source strings</returns>
        public static Project CreateProject(string[] sources,
                                            out CustomWorkspace workspace, string language = LanguageNames.CSharp)
        {
            var fileNamePrefix = DefaultFilePathPrefix;
            var fileExt        = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;

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

            workspace = new CustomWorkspace();

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

            workspace.AddProject(projectInfo);

            const int count = 0;

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

            var project = workspace.CurrentSolution.GetProject(projectId);
            var newCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(diagOptions);
            var solution   = workspace.CurrentSolution.WithProjectCompilationOptions(projectId, newCompilationOptions);
            var newProject = solution.GetProject(projectId);

            return(newProject);
        }
Example #2
0
        public void TestAddSolution_SolutionInfo()
        {
            using (var ws = new CustomWorkspace())
            {
                var pinfo = ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    version: VersionStamp.Default,
                    name: "TestProject",
                    assemblyName: "TestProject.dll",
                    language: LanguageNames.CSharp);

                var sinfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default, projects: new ProjectInfo[] { pinfo });

                var solution = ws.AddSolution(sinfo);

                Assert.Same(ws.CurrentSolution, solution);
                Assert.Equal(solution.Id, sinfo.Id);

                Assert.Equal(sinfo.Projects.Count, solution.ProjectIds.Count);
                var project = solution.Projects.FirstOrDefault();
                Assert.NotNull(project);
                Assert.Equal(pinfo.Name, project.Name);
                Assert.Equal(pinfo.Id, project.Id);
                Assert.Equal(pinfo.AssemblyName, project.AssemblyName);
                Assert.Equal(pinfo.Language, project.Language);
            }
        }
Example #3
0
        protected void AssertFormat(
            string expected,
            string code,
            IEnumerable <TextSpan> spans,
            string language,
            bool debugMode = false,
            Dictionary <OptionKey, object> changedOptionSet = null,
            bool treeCompare = true)
        {
            using (var workspace = new CustomWorkspace())
            {
                var project  = workspace.CurrentSolution.AddProject("Project", "Project.dll", language);
                var document = project.AddDocument("Document", SourceText.From(code));

                var syntaxTree = document.GetSyntaxTreeAsync().Result;

                var options = workspace.GetOptions();
                if (changedOptionSet != null)
                {
                    foreach (var entry in changedOptionSet)
                    {
                        options = options.WithChangedOption(entry.Key, entry.Value);
                    }
                }

                var root = syntaxTree.GetRoot();
                AssertFormat(workspace, expected, root, spans, options, document.GetTextAsync().Result);

                // format with node and transform
                AssertFormatWithTransformation(workspace, expected, root, spans, options, treeCompare);
            }
        }
Example #4
0
        protected void AssertFormat(
            string expected,
            string code,
            IEnumerable<TextSpan> spans,
            string language,
            bool debugMode = false,
            Dictionary<OptionKey, object> changedOptionSet = null,
            bool treeCompare = true)
        {
            using (var workspace = new CustomWorkspace())
            {
                var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", language);
                var document = project.AddDocument("Document", SourceText.From(code));

                var syntaxTree = document.GetSyntaxTreeAsync().Result;

                var options = workspace.GetOptions();
                if (changedOptionSet != null)
                {
                    foreach (var entry in changedOptionSet)
                    {
                        options = options.WithChangedOption(entry.Key, entry.Value);
                    }
                }

                var root = syntaxTree.GetRoot();
                AssertFormat(workspace, expected, root, spans, options, document.GetTextAsync().Result);

                // format with node and transform
                AssertFormatWithTransformation(workspace, expected, root, spans, options, treeCompare);
            }
        }
        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());
        }
Example #6
0
        public void TestAddProject_CommandLineProject()
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());

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

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

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

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

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

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

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

                var compilation = project.GetCompilationAsync().Result;
            }
        }
        /// <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));
        }
        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.AddDocument("Document", SourceText.From(code)));
        }
Example #9
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());
        }
        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.AddMetadataReference(new MetadataFileReference(typeof(int).Assembly.Location))
                   .AddDocument("Document", SourceText.From(code)));
        }
Example #11
0
        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.AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib)
                   .AddDocument("Document", SourceText.From(code)));
        }
        protected RefactorRule(IncludeExcludeCollection sourceFileFilters, IFileSystemHelper fileSystemHelper, string fileNamePattern = "*.cs", bool isBackupEnabled = true)
            : base(sourceFileFilters, fileSystemHelper, fileNamePattern, isBackupEnabled)
        {
            var workspace = new CustomWorkspace();
            var solution  = workspace.CurrentSolution;

            _project  = solution.AddProject("dummyProjectName", "dummyAssemblyName", LanguageNames.CSharp);
            Parameter = new ExpandoObject();
        }
        public void TestUnrootedPathOutsideProjectCone()
        {
            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);
        }
Example #14
0
 public void TestAddProject_NameAndLanguage()
 {
     using (var ws = new CustomWorkspace())
     {
         var project = ws.AddProject("TestProject", LanguageNames.CSharp);
         Assert.Same(project, ws.CurrentSolution.Projects.FirstOrDefault());
         Assert.Equal("TestProject", project.Name);
         Assert.Equal(LanguageNames.CSharp, project.Language);
     }
 }
Example #15
0
 public void TestAddProject_NameAndLanguage()
 {
     using (var ws = new CustomWorkspace())
     {
         var project = ws.AddProject("TestProject", LanguageNames.CSharp);
         Assert.Same(project, ws.CurrentSolution.Projects.FirstOrDefault());
         Assert.Equal("TestProject", project.Name);
         Assert.Equal(LanguageNames.CSharp, project.Language);
     }
 }
        public void TestRootedSubPathInsideProjectCone()
        {
            string commandLine = @"c:\projectDirectory\subdir\foo.cs";
            var ws = new CustomWorkspace();
            var info = CommandLineProject.CreateProjectInfo(ws, "TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");

            var docInfo = info.Documents.First();
            Assert.Equal(1, docInfo.Folders.Count);
            Assert.Equal("subdir", docInfo.Folders[0]);
            Assert.Equal("foo.cs", docInfo.Name);
        }
Example #17
0
        public SyntaxNode Format(SyntaxNode node)
        {
            //var span = node.FullSpan;
            //node = Formatter.Format(node, span, new CustomWorkspace()) as SyntaxNode;
            var ws      = new CustomWorkspace();
            var options = ws.Options;

            // options = options.WithChangedOption(CSharpFormattingOptions.)
            node = Formatter.Format(node, new CustomWorkspace());
            return(node);
        }
        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);
        }
        public RoslynSession(SourceText sourceText, ProjectInfo projectInfo, MefHostServices hostServices, ImmutableArray <DiagnosticAnalyzer> analyzers, ImmutableDictionary <string, ImmutableArray <CodeFixProvider> > codeFixProviders, ImmutableArray <ISignatureHelpProviderWrapper> signatureHelpProviders)
        {
            _workspace         = new CustomWorkspace(hostServices);
            _sourceText        = sourceText;
            _document          = CreateProjectAndOpenNewDocument(_workspace, projectInfo, sourceText);
            _completionService = GetCompletionService(_document);

            Analyzers = analyzers;
            SignatureHelpProviders = signatureHelpProviders;
            CodeFixProviders       = codeFixProviders;
        }
Example #20
0
        public void TestUnrootedPathOutsideProjectCone()
        {
            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);
        }
Example #21
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();
    }
        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);
        }
Example #23
0
        public void TestAdditionalFiles()
        {
            string commandLine = @"foo.cs /additionalfile:bar.cs";
            var    ws          = new CustomWorkspace();
            var    info        = CommandLineProject.CreateProjectInfo(ws, "TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");

            var firstDoc  = info.Documents.Single();
            var secondDoc = info.AdditionalDocuments.Single();

            Assert.Equal("foo.cs", firstDoc.Name);
            Assert.Equal("bar.cs", secondDoc.Name);
        }
Example #24
0
        public void TestRootedSubPathInsideProjectCone()
        {
            string commandLine = @"c:\projectDirectory\subdir\foo.cs";
            var    ws          = new CustomWorkspace();
            var    info        = CommandLineProject.CreateProjectInfo(ws, "TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");

            var docInfo = info.Documents.First();

            Assert.Equal(1, docInfo.Folders.Count);
            Assert.Equal("subdir", docInfo.Folders[0]);
            Assert.Equal("foo.cs", docInfo.Name);
        }
Example #25
0
        public void TestAddDocument_DocumentInfo()
        {
            using (var ws = new CustomWorkspace())
            {
                var project = ws.AddProject("TestProject", LanguageNames.CSharp);
                var info    = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "code.cs");
                var doc     = ws.AddDocument(info);

                Assert.Equal(ws.CurrentSolution.GetDocument(info.Id), doc);
                Assert.Equal(info.Name, doc.Name);
            }
        }
Example #26
0
        public void TestAddDocument_DocumentInfo()
        {
            using (var ws = new CustomWorkspace())
            {
                var project = ws.AddProject("TestProject", LanguageNames.CSharp);
                var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "code.cs");
                var doc = ws.AddDocument(info);

                Assert.Equal(ws.CurrentSolution.GetDocument(info.Id), doc);
                Assert.Equal(info.Name, doc.Name);                
            }
        }
Example #27
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);
        }
Example #28
0
        public void TestAddDocument_NameAndText()
        {
            using (var ws = new CustomWorkspace())
            {
                var project = ws.AddProject("TestProject", LanguageNames.CSharp);
                var name = "code.cs";
                var source = "class C {}";
                var doc = ws.AddDocument(project.Id, name, SourceText.From(source));

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

                Assert.Equal(name, doc.Name);
                Assert.Equal(source, doc.GetTextAsync().Result.ToString());
            }
        }
        public void EmptySpan()
        {
            Assert.DoesNotThrow(() =>
            {
                using (var workspace = new CustomWorkspace())
                {
                    var project  = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
                    var document = project.AddDocument("Document", SourceText.From(""));

                    var syntaxTree = document.GetSyntaxTreeAsync().Result;
                    var result     = Formatter.Format(syntaxTree.GetRoot(CancellationToken.None), TextSpan.FromBounds(0, 0), workspace, cancellationToken: CancellationToken.None);
                }
            });
        }
        public CodeGenTests()
        {
            var workspace = new CustomWorkspace();
            var project   = workspace.CurrentSolution.AddProject("test", "test", "C#")
                            .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                            .AddMetadataReference(MetadataReference.CreateFromAssembly(typeof(string).Assembly))
                            .AddMetadataReference(MetadataReference.CreateFromAssembly(typeof(GenerateImmutableAttribute).Assembly))
                            .AddMetadataReference(MetadataReference.CreateFromAssembly(typeof(CodeGenerationAttribute).Assembly))
                            .AddMetadataReference(MetadataReference.CreateFromAssembly(typeof(Optional).Assembly))
                            .AddMetadataReference(MetadataReference.CreateFromAssembly(typeof(ImmutableArray).Assembly))
                            .AddMetadataReference(MetadataReference.CreateFromAssembly(Assembly.LoadWithPartialName("System.Runtime")));
            var inputDocument = project.AddDocument("input.cs", string.Empty);

            this.inputDocumentId = inputDocument.Id;
            project        = inputDocument.Project;
            this.projectId = inputDocument.Project.Id;
            this.solution  = project.Solution;
        }
Example #32
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();
        }
Example #33
0
        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();
        }
Example #34
0
        public void TestAddProject_ProjectInfo()
        {
            var info = ProjectInfo.Create(
                ProjectId.CreateNewId(),
                version: VersionStamp.Default,
                name: "TestProject",
                assemblyName: "TestProject.dll",
                language: LanguageNames.CSharp);

            using (var ws = new CustomWorkspace())
            {
                var project = ws.AddProject(info);
                Assert.Equal(project, ws.CurrentSolution.Projects.FirstOrDefault());
                Assert.Equal(info.Name, project.Name);
                Assert.Equal(info.Id, project.Id);
                Assert.Equal(info.AssemblyName, project.AssemblyName);
                Assert.Equal(info.Language, project.Language);
            }
        }
        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));
        }
Example #36
0
        public void TestAddProject_ProjectInfo()
        {
            var info = ProjectInfo.Create(
                ProjectId.CreateNewId(), 
                version: VersionStamp.Default,
                name: "TestProject",
                assemblyName: "TestProject.dll",
                language: LanguageNames.CSharp);

            using (var ws = new CustomWorkspace())
            {
                var project = ws.AddProject(info);
                Assert.Equal(project, ws.CurrentSolution.Projects.FirstOrDefault());
                Assert.Equal(info.Name, project.Name);
                Assert.Equal(info.Id, project.Id);
                Assert.Equal(info.AssemblyName, project.AssemblyName);
                Assert.Equal(info.Language, project.Language);
            }
        }
            private Project CreateProject()
            {
                var workspace = new CustomWorkspace();
                var project   = workspace.CurrentSolution.AddProject("codegen", "codegen", "C#")
                                .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                                .WithMetadataReferences(this.ReferencePath.Select(p => MetadataReference.CreateFromFile(p.ItemSpec)));

                foreach (var sourceFile in this.Compile)
                {
                    using (var stream = File.OpenRead(sourceFile.ItemSpec))
                    {
                        this.CancellationToken.ThrowIfCancellationRequested();
                        var text = SourceText.From(stream);
                        project = project.AddDocument(sourceFile.ItemSpec, text).Project;
                    }
                }

                return(project);
            }
        public void TestLinkedFileSet(string startText, List<string> updatedTexts, string expectedMergedText, string languageName)
        {
            using (var workspace = new CustomWorkspace())
            {
                var solution = new CustomWorkspace().CurrentSolution;
                var startSourceText = SourceText.From(startText);
                var documentIds = new List<DocumentId>();

                for (int i = 0; i < updatedTexts.Count; i++)
                {
                    var projectId = ProjectId.CreateNewId();
                    var documentId = DocumentId.CreateNewId(projectId);
                    documentIds.Add(documentId);

                    var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Create(), "ProjectName" + i, "AssemblyName" + i, languageName);

                    solution = solution
                        .AddProject(projectInfo)
                        .AddDocument(documentId, "DocumentName", startSourceText, filePath: "FilePath");
                }

                var startingSolution = solution;
                var updatedSolution = solution;

                for (int i = 0; i < updatedTexts.Count; i++)
                {
                    var text = updatedTexts[i];
                    if (text != startText)
                    {
                        updatedSolution = updatedSolution
                            .WithDocumentText(documentIds[i], SourceText.From(text));
                    }
                }

                var mergedSolution = updatedSolution.WithMergedLinkedFileChangesAsync(startingSolution).Result;
                for (int i = 0; i < updatedTexts.Count; i++)
                {
                    Assert.Equal(expectedMergedText, mergedSolution.GetDocument(documentIds[i]).GetTextAsync().Result.ToString());
                }
            }
        }
        public void TestAdditionalFiles()
        {
            string commandLine = @"foo.cs /additionalfile:bar.cs";
            var ws = new CustomWorkspace();
            var info = CommandLineProject.CreateProjectInfo(ws, "TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");

            var firstDoc = info.Documents.Single();
            var secondDoc = info.AdditionalDocuments.Single();
            Assert.Equal("foo.cs", firstDoc.Name);
            Assert.Equal("bar.cs", secondDoc.Name);
        }
        protected 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, TestBase.SystemRef);

            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);
        }
Example #41
0
        public void TestAddProject_CommandLineProject()
        {
            CreateFiles(GetSimpleCSharpSolutionFiles());

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

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

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

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

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

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

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

                var compilation = project.GetCompilationAsync().Result;
            }
        }
Example #42
0
        public void TestAddSolution_SolutionInfo()
        {
            using (var ws = new CustomWorkspace())
            {
                var pinfo = ProjectInfo.Create(
                        ProjectId.CreateNewId(),
                        version: VersionStamp.Default,
                        name: "TestProject",
                        assemblyName: "TestProject.dll",
                        language: LanguageNames.CSharp);

                var sinfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default, projects: new ProjectInfo[] { pinfo });

                var solution = ws.AddSolution(sinfo);

                Assert.Same(ws.CurrentSolution, solution);
                Assert.Equal(solution.Id, sinfo.Id);

                Assert.Equal(sinfo.Projects.Count, solution.ProjectIds.Count);
                var project = solution.Projects.FirstOrDefault();
                Assert.NotNull(project);
                Assert.Equal(pinfo.Name, project.Name);
                Assert.Equal(pinfo.Id, project.Id);
                Assert.Equal(pinfo.AssemblyName, project.AssemblyName);
                Assert.Equal(pinfo.Language, project.Language);
            }
        }
        public void EmptySpan()
        {
            Assert.DoesNotThrow(() =>
            {
                using (var workspace = new CustomWorkspace())
                {
                    var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
                    var document = project.AddDocument("Document", SourceText.From(""));

                    var syntaxTree = document.GetSyntaxTreeAsync().Result;
                    var result = Formatter.Format(syntaxTree.GetRoot(CancellationToken.None), TextSpan.FromBounds(0, 0), workspace, cancellationToken: CancellationToken.None);
                }
            });
        }
Example #44
0
        public void TestAddProjects()
        {
            var id1 = ProjectId.CreateNewId();
            var info1 = ProjectInfo.Create(
                id1,
                version: VersionStamp.Default,
                name: "TestProject1",
                assemblyName: "TestProject1.dll",
                language: LanguageNames.CSharp);

            var id2 = ProjectId.CreateNewId();
            var info2 = ProjectInfo.Create(
                id2,
                version: VersionStamp.Default,
                name: "TestProject2",
                assemblyName: "TestProject2.dll",
                language: LanguageNames.VisualBasic,
                projectReferences: new[] { new ProjectReference(id1) });

            using (var ws = new CustomWorkspace())
            {
                ws.AddProjects(new[] { info1, info2 });
                var solution = ws.CurrentSolution;
                Assert.Equal(2, solution.ProjectIds.Count);

                var project1 = solution.GetProject(id1);
                Assert.Equal(info1.Name, project1.Name);
                Assert.Equal(info1.Id, project1.Id);
                Assert.Equal(info1.AssemblyName, project1.AssemblyName);
                Assert.Equal(info1.Language, project1.Language);

                var project2 = solution.GetProject(id2);
                Assert.Equal(info2.Name, project2.Name);
                Assert.Equal(info2.Id, project2.Id);
                Assert.Equal(info2.AssemblyName, project2.AssemblyName);
                Assert.Equal(info2.Language, project2.Language);
                Assert.Equal(1, project2.ProjectReferences.Count());
                Assert.Equal(id1, project2.ProjectReferences.First().ProjectId);
            }
        }