private static Project CreateProject(FileAndSource[] sources) { string fileNamePrefix = DefaultFilePathPrefix; string fileExt = CSharpDefaultFileExt; CompilationOptions options = s_CSharpDefaultOptions; ProjectId projectId = ProjectId.CreateNewId(debugName: TestProjectName); var defaultReferences = ReferenceAssemblies.NetFramework.Net48.Default; var references = Task.Run(() => defaultReferences.ResolveAsync(LanguageNames.CSharp, CancellationToken.None)).GetAwaiter().GetResult(); #pragma warning disable CA2000 // Dispose objects before losing scope - Current solution/project takes the dispose ownership of the created AdhocWorkspace Project project = new AdhocWorkspace().CurrentSolution #pragma warning restore CA2000 // Dispose objects before losing scope .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp) .AddMetadataReferences(projectId, references) .AddMetadataReference(projectId, AdditionalMetadataReferences.CodeAnalysisReference) .AddMetadataReference(projectId, AdditionalMetadataReferences.WorkspacesReference) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemWebReference) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemRuntimeSerialization) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemDirectoryServices) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemXaml) .AddMetadataReference(projectId, AdditionalMetadataReferences.PresentationFramework) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemWebExtensions) .WithProjectCompilationOptions(projectId, options) .WithProjectParseOptions(projectId, null) .GetProject(projectId); // Enable Flow-Analysis feature on the project var parseOptions = project.ParseOptions.WithFeatures( project.ParseOptions.Features.Concat( new[] { new KeyValuePair <string, string>("flow-analysis", "true") })); project = project.WithParseOptions(parseOptions); MetadataReference symbolsReference = AdditionalMetadataReferences.CSharpSymbolsReference; project = project.AddMetadataReference(symbolsReference); project = project.AddMetadataReference(AdditionalMetadataReferences.SystemCollectionsImmutableReference); project = project.AddMetadataReference(AdditionalMetadataReferences.SystemXmlDataReference); int count = 0; foreach (FileAndSource source in sources) { string newFileName = source.FilePath ?? fileNamePrefix + count++ + "." + fileExt; DocumentId documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); project = project.AddDocument(newFileName, SourceText.From(source.Source)).Project; } return(project); }
protected Project CreateProject(Dictionary <string, string> sources) { string fileNamePrefix = DefaultFilePathPrefix; string fileExt = CSharpDefaultFileExt; var projectId = ProjectId.CreateNewId(debugName: TestProjectName); var solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp); foreach (var reference in References) { solution = solution.AddMetadataReference(projectId, reference); } int count = 0; foreach (var source in sources) { var newFileName = source.Key; var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); solution = solution.AddDocument(documentId, newFileName, SourceText.From(source.Value)); count++; } var project = solution.GetProject(projectId) .WithCompilationOptions(CompilationOptions); return(project); }
/// <summary> /// Create a project using the inputted strings as sources. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the source code is in</param> /// <returns>A Project created out of the Documents created from the source strings</returns> private static Project CreateProject(string[] sources, string language = LanguageNames.CSharp) { string fileNamePrefix = DefaultFilePathPrefix; string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt; var projectId = ProjectId.CreateNewId(debugName: TestProjectName); var solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, language) .AddMetadataReference(projectId, CorlibReference) .AddMetadataReference(projectId, SystemCoreReference) .AddMetadataReference(projectId, CSharpSymbolsReference) .AddMetadataReference(projectId, CodeAnalysisReference); foreach (var reference in ExtraReferences) { solution = solution.AddMetadataReference(projectId, MetadataReference.CreateFromFile(reference.Location)); } 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 Project CreateProject(string[] sources) { var fileNamePrefix = DefaultFilePathPrefix; var projectId = ProjectId.CreateNewId(debugName: TestProjectName); var solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp); foreach (var defaultCompileLibrary in DependencyContext.Load(GetType().Assembly).CompileLibraries) { foreach (var resolveReferencePath in defaultCompileLibrary.ResolveReferencePaths(new AppLocalResolver())) { solution = solution.AddMetadataReference(projectId, MetadataReference.CreateFromFile(resolveReferencePath)); } } for (var i = 0; i < sources.Length; i++) { var newFileName = fileNamePrefix; if (sources.Length > 1) { newFileName += i; } newFileName += ".cs"; var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); solution = solution.AddDocument(documentId, newFileName, SourceText.From(sources[i])); } return(solution.GetProject(projectId)); }
/// <summary> /// Create a project using the inputted strings as sources. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <returns>A Project created out of the Documents created from the source strings</returns> private static Project CreateProject(string[] sources) { string fileNamePrefix = DefaultFilePathPrefix; var projectId = ProjectId.CreateNewId(debugName: TestProjectName); var solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp); foreach (var defaultCompileLibrary in DependencyContext.Load(typeof(DiagnosticVerifier).Assembly).CompileLibraries) { foreach (var resolveReferencePath in defaultCompileLibrary.ResolveReferencePaths(new AppLocalResolver())) { solution = solution.AddMetadataReference(projectId, MetadataReference.CreateFromFile(resolveReferencePath)); } } int count = 0; foreach (var source in sources) { var newFileName = fileNamePrefix + count; var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); solution = solution.AddDocument(documentId, newFileName, SourceText.From(source)); count++; } return(solution.GetProject(projectId)); }
protected void PositionAtStarShouldProduceExpectedUsingAdditonalLibraries(string code, AnalyzerOutput expected, bool isCSharp, Profile profileOverload, params string[] additionalLibraryPaths) { var pos = code.IndexOf("*", StringComparison.Ordinal); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var language = isCSharp ? LanguageNames.CSharp : LanguageNames.VisualBasic; var fileExt = isCSharp ? "cs" : "vb"; var solution = new AdhocWorkspace().CurrentSolution .AddProject(projectId, "MyProject", "MyProject", language) .AddDocument(documentId, $"MyFile.{fileExt}", code.Replace("*", string.Empty)); foreach (var libPath in additionalLibraryPaths) { var lib = MetadataReference.CreateFromFile(libPath); solution = solution.AddMetadataReference(projectId, lib); } var document = solution.GetDocument(documentId); var semModel = document.GetSemanticModelAsync().Result; var syntaxTree = document.GetSyntaxTreeAsync().Result; var analyzer = isCSharp ? new CSharpAnalyzer(DefaultTestLogger.Create()) as IDocumentAnalyzer : new VisualBasicAnalyzer(DefaultTestLogger.Create()); var actual = analyzer.GetSingleItemOutput(syntaxTree.GetRoot(), semModel, pos, new TestVisualStudioAbstraction().XamlIndent, profileOverload); Assert.AreEqual(expected.OutputType, actual.OutputType); Assert.AreEqual(expected.Name, actual.Name); StringAssert.AreEqual(expected.Output, actual.Output); }
/// <summary> /// Create a project using the inputted strings as sources. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="testingFramework">Classes used to determine what classes are tests.</param> /// <param name="language">The language the source code is in</param> /// <returns>A Project created out of the Documents created from the source strings</returns> private static Project CreateProject(string[] sources, IEnumerable <Type> testingFramework, string language = LanguageNames.CSharp) { string fileNamePrefix = DefaultFilePathPrefix; string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt; var projectId = ProjectId.CreateNewId(debugName: TestProjectName); var solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, language) .AddMetadataReference(projectId, _CorlibReference) .AddMetadataReference(projectId, _SystemCoreReference) .AddMetadataReference(projectId, _SystemRuntimeReference) .AddMetadataReference(projectId, _SystemLinqExpressionsReference) .AddMetadataReference(projectId, _CSharpSymbolsReference) .AddMetadataReference(projectId, _CodeAnalysisReference) .AddMetadataReference(projectId, _SmartTestReference); if (testingFramework == null) { solution = solution.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(TestFixtureAttribute).Assembly.Location)); } else { foreach (var type in testingFramework) { solution = solution.AddMetadataReference(projectId, MetadataReference.CreateFromFile(type.Assembly.Location)); } } int count = 0; foreach (var source in sources) { var newFileName = fileNamePrefix + count + "." + fileExt; var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); solution = solution.AddDocument(documentId, newFileName, SourceText.From(source)); count++; } return(solution.GetProject(projectId)); }
/// <summary> /// Creates a solution that will be used as parent for the sources that need to be checked. /// </summary> /// <param name="projectId">The project identifier to use.</param> /// <param name="language">The language for which the solution is being created.</param> /// <returns>The created solution.</returns> protected virtual Solution CreateSolution(ProjectId projectId, string language) { var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true); Solution solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, language) .WithProjectCompilationOptions(projectId, compilationOptions) .AddMetadataReference(projectId, MetadataReferences.CorlibReference) .AddMetadataReference(projectId, MetadataReferences.SystemReference) .AddMetadataReference(projectId, MetadataReferences.SystemCoreReference) .AddMetadataReference(projectId, MetadataReferences.CSharpSymbolsReference) .AddMetadataReference(projectId, MetadataReferences.CodeAnalysisReference); if (MetadataReferences.SystemThreadingTasksReference != null) { solution = solution.AddMetadataReference(projectId, MetadataReferences.SystemThreadingTasksReference); } if (MetadataReferences.SystemThreadingTasksExtensionsReference != null) { solution = solution.AddMetadataReference(projectId, MetadataReferences.SystemThreadingTasksExtensionsReference); } var settings = this.GetSettings(); if (!string.IsNullOrEmpty(settings)) { var documentId = DocumentId.CreateNewId(projectId); solution = solution.AddAdditionalDocument(documentId, SettingsFileName, settings); } ParseOptions parseOptions = solution.GetProject(projectId).ParseOptions; return(solution.WithProjectParseOptions(projectId, parseOptions.WithDocumentationMode(DocumentationMode.Diagnose))); }
/// <summary> /// Creates a project using the inputted strings as sources. /// </summary> /// <param name="sources">Classes in the form of strings.</param> /// <param name="language">The language the source code is in.</param> /// <returns>A project created out of the documents created from /// the source strings.</returns> private static Project CreateProject( string[] sources, string language = LanguageNames.CSharp ) { string fileNamePrefix = DefaultFilePathPrefix; string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt; var projectId = ProjectId.CreateNewId(debugName: TestProjectName); var solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, language); IEnumerable <Assembly> assemblies = GetAssemblies( typeof(object), typeof(Enumerable), typeof(Compilation), typeof(Address), typeof(IValue) ); foreach (Assembly assembly in assemblies) { if (assembly.IsDynamic) { continue; } solution = solution.AddMetadataReference( projectId, MetadataReference.CreateFromFile(assembly.Location) ); } 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)); }
public static Project Create(Assembly testAssembly, LanguageVersion languageVersion, string[] sources) { Solution solution; lock (_solutionCache) { if (!_solutionCache.TryGetValue(testAssembly, out solution)) { var projectId = ProjectId.CreateNewId(debugName: TestProjectName); solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp) .WithProjectParseOptions(projectId, new CSharpParseOptions(languageVersion)); foreach (var defaultCompileLibrary in DependencyContext.Load(testAssembly).CompileLibraries) { foreach (var resolveReferencePath in defaultCompileLibrary.ResolveReferencePaths(new AppLocalResolver())) { solution = solution.AddMetadataReference(projectId, MetadataReference.CreateFromFile(resolveReferencePath)); } } _solutionCache.Add(testAssembly, solution); } } var testProject = solution.ProjectIds.Single(); var fileNamePrefix = DefaultFilePathPrefix; for (var i = 0; i < sources.Length; i++) { var newFileName = fileNamePrefix; if (sources.Length > 1) { newFileName += i; } newFileName += ".cs"; var documentId = DocumentId.CreateNewId(testProject, debugName: newFileName); solution = solution.AddDocument(documentId, newFileName, SourceText.From(sources[i])); } return(solution.GetProject(testProject)); }
public async Task SnapshotWithMissingReferencesTest() { var hostServices = MefHostServices.Create( MefHostServices.DefaultAssemblies.Add(typeof(Host.TemporaryStorageServiceFactory.TemporaryStorageService).Assembly)); var project = new AdhocWorkspace(hostServices).CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var metadata = new MissingMetadataReference(); var analyzer = new AnalyzerFileReference("missing_reference", new MissingAnalyzerLoader()); project = project.AddMetadataReference(metadata); project = project.AddAnalyzerReference(analyzer); var snapshotService = (new RemotableDataServiceFactory()).CreateService(project.Solution.Workspace.Services) as IRemotableDataService; using var snapshot = await snapshotService.CreatePinnedRemotableDataScopeAsync(project.Solution, CancellationToken.None).ConfigureAwait(false); // this shouldn't throw var recovered = await GetSolutionAsync(snapshotService, snapshot).ConfigureAwait(false); }
protected async Task PositionAtStarShouldProduceExpectedUsingAdditionalLibraries(string code, ParserOutput expected, bool isCSharp, Profile profileOverload, params string[] additionalLibraryPaths) { this.EnsureOneStar(code); var(pos, actualCode) = this.GetCodeAndCursorPos(code); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var language = isCSharp ? LanguageNames.CSharp : LanguageNames.VisualBasic; var fileExt = isCSharp ? "cs" : "vb"; var solution = new AdhocWorkspace().CurrentSolution .AddProject(projectId, "MyProject", "MyProject", language) .AddDocument(documentId, $"MyFile.{fileExt}", actualCode); foreach (var libPath in additionalLibraryPaths) { var lib = MetadataReference.CreateFromFile(libPath); solution = solution.AddMetadataReference(projectId, lib); } var document = solution.GetDocument(documentId); var semModel = await document.GetSemanticModelAsync(); var syntaxTree = await document.GetSyntaxTreeAsync(); var indent = new TestVisualStudioAbstraction().XamlIndent; var parser = isCSharp ? new CSharpParser(DefaultTestLogger.Create(), indent, profileOverload) as IDocumentParser : new VisualBasicParser(DefaultTestLogger.Create(), indent, profileOverload); var actual = parser.GetSingleItemOutput(await syntaxTree.GetRootAsync(), semModel, pos); this.AssertOutput(expected, actual); }
/// <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="includeMassTransit">Whether the resulting Project has a dependency on MassTransit or not</param> /// <returns>A Project created out of the Documents created from the source strings</returns> static Project CreateProject(string[] sources, string language = LanguageNames.CSharp, bool includeMassTransit = true) { var fileNamePrefix = DefaultFilePathPrefix; var fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt; var projectId = ProjectId.CreateNewId(TestProjectName); var solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, language) .AddMetadataReference(projectId, CoreLibReference) .AddMetadataReference(projectId, SystemCoreReference) .AddMetadataReference(projectId, CSharpSymbolsReference) .AddMetadataReference(projectId, CodeAnalysisReference) .AddMetadataReference(projectId, CollectionsReference) .AddMetadataReference(projectId, RuntimeReference) .AddMetadataReference(projectId, NetStandardReference) .AddMetadataReference(projectId, SystemPrivateUriReference); if (includeMassTransit) { solution = solution.AddMetadataReference(projectId, MassTransitReference) .AddMetadataReference(projectId, GreenPipesReference) .AddMetadataReference(projectId, NewIdReference); } var count = 0; foreach (var source in sources) { var newFileName = fileNamePrefix + count + "." + fileExt; var documentId = DocumentId.CreateNewId(projectId, newFileName); solution = solution.AddDocument(documentId, newFileName, SourceText.From(source)); count++; } return(solution.GetProject(projectId)); }
public async Task SnapshotWithMissingReferencesTest() { var hostServices = MefHostServices.Create( MefHostServices.DefaultAssemblies.Add(typeof(Host.TemporaryStorageServiceFactory.TemporaryStorageService).Assembly)); var project = new AdhocWorkspace(hostServices).CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var metadata = new MissingMetadataReference(); var analyzer = new AnalyzerFileReference("missing_reference", new MissingAnalyzerLoader()); project = project.AddMetadataReference(metadata); project = project.AddAnalyzerReference(analyzer); var snapshotService = (new SolutionSynchronizationServiceFactory()).CreateService(project.Solution.Workspace.Services) as ISolutionSynchronizationService; using (var snapshot = await snapshotService.CreatePinnedRemotableDataScopeAsync(project.Solution, CancellationToken.None).ConfigureAwait(false)) { // this shouldn't throw var recovered = await GetSolutionAsync(snapshotService, snapshot).ConfigureAwait(false); } }
/// <summary> /// Creates a solution that will be used as parent for the sources that need to be checked. /// </summary> /// <param name="projectId">The project identifier to use.</param> /// <param name="language">The language for which the solution is being created.</param> /// <returns>The created solution.</returns> protected virtual Solution CreateSolution(ProjectId projectId, string language) { var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true); Solution solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, language) .WithProjectCompilationOptions(projectId, compilationOptions) .AddMetadataReference(projectId, MetadataReferences.CorlibReference) .AddMetadataReference(projectId, MetadataReferences.SystemReference) .AddMetadataReference(projectId, MetadataReferences.SystemCoreReference) .AddMetadataReference(projectId, MetadataReferences.CSharpSymbolsReference) .AddMetadataReference(projectId, MetadataReferences.CodeAnalysisReference); if (MetadataReferences.SystemRuntimeReference != null) { solution = solution.AddMetadataReference(projectId, MetadataReferences.SystemRuntimeReference); } if (MetadataReferences.SystemValueTupleReference != null) { solution = solution.AddMetadataReference(projectId, MetadataReferences.SystemValueTupleReference); } solution.Workspace.Options = solution.Workspace.Options .WithChangedOption(FormattingOptions.IndentationSize, language, this.IndentationSize) .WithChangedOption(FormattingOptions.TabSize, language, this.TabSize) .WithChangedOption(FormattingOptions.UseTabs, language, this.UseTabs); var settings = this.GetSettings(); StyleCopSettings defaultSettings = new StyleCopSettings(); if (this.IndentationSize != defaultSettings.Indentation.IndentationSize || this.UseTabs != defaultSettings.Indentation.UseTabs || this.TabSize != defaultSettings.Indentation.TabSize) { var indentationSettings = $@" {{ ""settings"": {{ ""indentation"": {{ ""indentationSize"": {this.IndentationSize}, ""useTabs"": {this.UseTabs.ToString().ToLowerInvariant()}, ""tabSize"": {this.TabSize} }} }} }} "; if (string.IsNullOrEmpty(settings)) { settings = indentationSettings; } else { JsonObject indentationObject = JsonReader.Parse(indentationSettings).AsJsonObject; JsonObject settingsObject = JsonReader.Parse(settings).AsJsonObject; JsonObject mergedSettings = MergeJsonObjects(settingsObject, indentationObject); using (var writer = new JsonWriter(pretty: true)) { settings = writer.Serialize(mergedSettings); } } } if (!string.IsNullOrEmpty(settings)) { var documentId = DocumentId.CreateNewId(projectId); solution = solution.AddAdditionalDocument(documentId, this.GetSettingsFileName(), settings); } ParseOptions parseOptions = solution.GetProject(projectId).ParseOptions; return(solution.WithProjectParseOptions(projectId, parseOptions.WithDocumentationMode(DocumentationMode.Diagnose))); }