本文整理汇总了C#中Microsoft.CodeAnalysis.AdhocWorkspace.AddDocument方法的典型用法代码示例。如果您正苦于以下问题:C# AdhocWorkspace.AddDocument方法的具体用法?C# AdhocWorkspace.AddDocument怎么用?C# AdhocWorkspace.AddDocument使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CodeAnalysis.AdhocWorkspace
的用法示例。
在下文中一共展示了AdhocWorkspace.AddDocument方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Should_Add_InternalToVisible_To_AllReferencedProjects
public void Should_Add_InternalToVisible_To_AllReferencedProjects()
{
// arrange
const string expectedAttribute = @"System.Runtime.CompilerServices.InternalsVisibleTo(""Tests.dll_COVERAGE.dll"")";
const string sourceCode = "class SampleClass{}";
SyntaxNode node = CSharpSyntaxTree.ParseText(sourceCode).GetRoot();
var workspace = new AdhocWorkspace();
var referencedProject1 = workspace.AddProject("foo2.dll", LanguageNames.CSharp);
workspace.AddDocument(referencedProject1.Id, "1.cs", SourceText.From(""));
var testsProject = workspace.AddProject("Tests.dll", LanguageNames.CSharp);
var solution = workspace.CurrentSolution.AddProjectReference(testsProject.Id, new ProjectReference(referencedProject1.Id));
_auditVariablesRewriterMock.Rewrite(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<SyntaxNode>()).
Returns(new RewrittenDocument(node.SyntaxTree, null, false));
// act
RewriteResult result = _solutionRewriter.RewriteAllClasses(solution.Projects);
List<RewrittenDocument> projectItems1 = result.Items.Values.First();
var attributes = projectItems1[0].SyntaxTree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().ToArray();
// assert
Assert.That(result.Items.Count, Is.EqualTo(1));
Assert.That(projectItems1.Count, Is.EqualTo(1));
Assert.That(attributes.Length, Is.EqualTo(1));
Assert.That(attributes[0].ToString(), Is.EqualTo(expectedAttribute));
}
示例2: Should_RewriteOneDocument
public void Should_RewriteOneDocument()
{
// arrange
const string sourceCode = "class SampleClass{}";
SyntaxNode node = CSharpSyntaxTree.ParseText(sourceCode).GetRoot();
var workspace = new AdhocWorkspace();
var project = workspace.AddProject("foo.dll", LanguageNames.CSharp);
string documentPath = "c:\\helloworld.cs";
DocumentInfo documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "HelloWorld.cs",
filePath: documentPath);
Document document = workspace.AddDocument(documentInfo);
_auditVariablesRewriterMock.Rewrite(Arg.Any<string>(), documentPath, Arg.Any<SyntaxNode>()).
Returns(new RewrittenDocument(node.SyntaxTree, null, false));
// act
RewriteResult result = _solutionRewriter.RewriteAllClasses(workspace.CurrentSolution.Projects);
// assert
Assert.That(result.Items.Count, Is.EqualTo(1));
Assert.That(result.Items.Keys.First().Id, Is.EqualTo(project.Id));
Assert.That(result.Items.Values.First().Count, Is.EqualTo(1));
}
示例3: CreateDocument
internal static Document CreateDocument(string code, string fileName,
Func<Solution, ProjectId, Solution> modifySolution)
{
var projectName = "Test";
var projectId = ProjectId.CreateNewId(projectName);
var solution = new AdhocWorkspace()
.CurrentSolution
.AddProject(projectId, projectName, projectName, LanguageNames.CSharp)
.AddMetadataReference(projectId,
MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
.AddMetadataReference(projectId,
MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location))
.AddMetadataReference(projectId,
MetadataReference.CreateFromFile(typeof(CSharpCompilation).Assembly.Location))
.AddMetadataReference(projectId,
MetadataReference.CreateFromFile(typeof(Compilation).Assembly.Location));
var documentId = DocumentId.CreateNewId(projectId);
solution = solution.AddDocument(documentId, fileName, SourceText.From(code));
if(modifySolution != null)
{
solution = modifySolution(solution, projectId);
}
return solution.GetProject(projectId).Documents.First();
}
示例4: AssertEnforcementAsync
public static async Task AssertEnforcementAsync(
IStyleRule rule, string originalText, string expectedText, Func<OptionSet, OptionSet> applyOptions)
{
using (var workspace = new AdhocWorkspace())
{
workspace.Options = applyOptions(workspace.Options);
Project project = workspace.AddProject(BuildProject());
Document document = workspace.AddDocument(project.Id, "TestFile.cs", SourceText.From(originalText));
Solution enforcedSolution = await rule.EnforceAsync(document);
Document enforcedDocument = enforcedSolution.GetDocument(document.Id);
if (document.Equals(enforcedDocument))
{
Assert.Fail("Expected enforcement, but no changes were made to the document");
}
SyntaxTree enforcedSyntax = await enforcedDocument.GetSyntaxTreeAsync();
SyntaxTree expectedSyntax = SyntaxFactory.ParseCompilationUnit(expectedText).SyntaxTree;
List<TextChange> unexpectedChanges = expectedSyntax.GetChanges(enforcedSyntax).ToList();
if (unexpectedChanges.Count > 0)
{
Console.WriteLine("Unexpected changes:");
List<TextChange> changes = (await enforcedDocument.GetTextChangesAsync(document)).ToList();
foreach (TextChange change in changes)
{
Console.WriteLine($"\t{change}");
}
Assert.Fail($"Enforced document has {changes.Count} unexpected changes");
}
}
}
示例5: AssertNoEnforcementAsync
public static async Task AssertNoEnforcementAsync(
IStyleRule rule, string documentText, Func<OptionSet, OptionSet> applyOptions)
{
using (var workspace = new AdhocWorkspace())
{
workspace.Options = applyOptions(workspace.Options);
Project project = workspace.AddProject(BuildProject());
Document document = workspace.AddDocument(project.Id, "TestFile.cs", SourceText.From(documentText));
Solution enforcedSolution = await rule.EnforceAsync(document);
Document enforcedDocument = enforcedSolution.GetDocument(document.Id);
if (!document.Equals(enforcedDocument))
{
List<TextChange> changes = (await enforcedDocument.GetTextChangesAsync(document)).ToList();
if (changes.Count == 0)
{
Assert.Fail("Solution mutated without document changes");
}
Console.WriteLine("Document changes:");
foreach (TextChange change in changes)
{
Console.WriteLine($"\t{change}");
}
Assert.Fail($"Enforced document has {changes.Count} changes; expected none");
}
}
}
示例6: TestInit
public void TestInit()
{
try
{
workspace = new AdhocWorkspace();
project = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "TestProj", "TestProj", LanguageNames.CSharp)
.WithMetadataReferences(new[] {
MetadataReference.CreateFromFile(typeof(DotvvmConfiguration).Assembly.Location),
MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
});
workspace.AddProject(project);
workspace.AddDocument(project.Id, "test", SourceText.From("class A {}"));
context = new DothtmlCompletionContext()
{
Configuration = DotvvmConfiguration.CreateDefault(),
RoslynWorkspace = workspace
};
}
catch (ReflectionTypeLoadException ex)
{
throw new Exception(string.Join("\r\n", ex.LoaderExceptions.Select(e => e.ToString())));
}
}
示例7: CreateProject
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;
}
示例8: CreateSolution
protected Solution CreateSolution(string[] sources, string[] preprocessorSymbols = null, string language = LanguageNames.CSharp)
{
string fileExtension = language == LanguageNames.CSharp ? CSharpFileExtension : VBFileExtension;
var projectId = ProjectId.CreateNewId(TestProjectName);
var solution = new AdhocWorkspace()
.CurrentSolution
.AddProject(projectId, TestProjectName, TestProjectName, language)
.AddMetadataReferences(projectId, GetSolutionMetadataReferences());
if (preprocessorSymbols != null)
{
var project = solution.Projects.Single();
project = project.WithParseOptions(
((CSharpParseOptions)project.ParseOptions).WithPreprocessorSymbols(preprocessorSymbols));
solution = project.Solution;
}
int count = 0;
foreach (var source in sources)
{
var fileName = FileNamePrefix + count + fileExtension;
var documentId = DocumentId.CreateNewId(projectId, fileName);
solution = solution.AddDocument(documentId, fileName, SourceText.From(source));
}
return solution;
}
示例9: TestHelper
public TestHelper(string source)
{
Workspace = new AdhocWorkspace();
string projName = "NewProject";
var projectId = ProjectId.CreateNewId();
var versionStamp = VersionStamp.Create();
var projectInfo = ProjectInfo.Create(projectId, versionStamp, projName, projName, LanguageNames.CSharp);
var newProject = Workspace.AddProject(projectInfo);
var sourceText = SourceText.From(source);
Document = Workspace.AddDocument(newProject.Id, "NewFile.cs", sourceText);
}
示例10: TestCodeGeneration
public async Task TestCodeGeneration(string resourceBaseName, Language language)
{
var inputResourceName = "BrightstarDB.CodeGeneration.Tests.GeneratorTestsResources." + resourceBaseName + "Input_" + language.ToString() + ".txt";
var outputResourceName = "BrightstarDB.CodeGeneration.Tests.GeneratorTestsResources." + resourceBaseName + "Output_" + language.ToString() + ".txt";
using (var inputStream = this.GetType().Assembly.GetManifestResourceStream(inputResourceName))
using (var outputStream = this.GetType().Assembly.GetManifestResourceStream(outputResourceName))
using (var outputStreamReader = new StreamReader(outputStream))
{
var workspace = new AdhocWorkspace();
var projectId = ProjectId.CreateNewId();
var versionStamp = VersionStamp.Create();
var projectInfo = ProjectInfo.Create(
projectId,
versionStamp,
"AdhocProject",
"AdhocProject",
language.ToSyntaxGeneratorLanguageName(),
metadataReferences: new[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Uri).Assembly.Location),
MetadataReference.CreateFromFile(typeof(BrightstarException).Assembly.Location)
});
var project = workspace.AddProject(projectInfo);
workspace.AddDocument(projectId, "Source.cs", SourceText.From(inputStream));
var solution = workspace.CurrentSolution;
var results = await Generator
.GenerateAsync(
language,
solution,
"BrightstarDB.CodeGeneration.Tests",
interfacePredicate: x => true);
var result = results
.Aggregate(
new StringBuilder(),
(current, next) => current.AppendLine(next.ToString()),
x => x.ToString());
var expectedCode = outputStreamReader.ReadToEnd();
// make sure version changes don't break the tests
expectedCode = expectedCode.Replace("$VERSION$", typeof(BrightstarException).Assembly.GetName().Version.ToString());
//// useful when converting generated code to something that can be pasted into an expectation file
//var sanitisedResult = result.Replace("1.10.0.0", "$VERSION$");
//System.Diagnostics.Debug.WriteLine(sanitisedResult);
Assert.AreEqual(expectedCode, result);
}
}
示例11: can_generate_simple_mock
// TODO: VB is totally borked - calls to syntaxGenerator.WithStatements don't seem to add the statements! Will need to look into this at a later date
//[InlineData("SimpleInterface", Language.VisualBasic)]
//[InlineData("InterfaceWithGenericMethods", Language.VisualBasic)]
//[InlineData("GenericInterface", Language.VisualBasic)]
//[InlineData("InterfaceWithNonMockableMembers", Language.VisualBasic)]
//[InlineData("PartialInterface", Language.VisualBasic)]
//[InlineData("InheritingInterface", Language.VisualBasic)]
public async Task can_generate_simple_mock(string resourceBaseName, Language language)
{
var inputResourceName = "PCLMock.UnitTests.CodeGeneration.GeneratorFixtureResources." + resourceBaseName + "Input_" + language.ToString() + ".txt";
var outputResourceName = "PCLMock.UnitTests.CodeGeneration.GeneratorFixtureResources." + resourceBaseName + "Output_" + language.ToString() + ".txt";
using (var inputStream = this.GetType().Assembly.GetManifestResourceStream(inputResourceName))
using (var outputStream = this.GetType().Assembly.GetManifestResourceStream(outputResourceName))
using (var outputStreamReader = new StreamReader(outputStream))
{
var workspace = new AdhocWorkspace();
var projectId = ProjectId.CreateNewId();
var versionStamp = VersionStamp.Create();
var projectInfo = ProjectInfo.Create(
projectId,
versionStamp,
"AdhocProject",
"AdhocProject",
language.ToSyntaxGeneratorLanguageName(),
metadataReferences: new[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Uri).Assembly.Location),
MetadataReference.CreateFromFile(typeof(MockBase<>).Assembly.Location)
});
var project = workspace.AddProject(projectInfo);
workspace.AddDocument(projectId, "Source.cs", SourceText.From(inputStream));
var solution = workspace.CurrentSolution;
var results =
(await Generator.GenerateMocksAsync(
language,
solution,
x => true,
x => "The.Namespace",
x => "Mock"));
var result = results
.Single()
.ToString();
var expectedCode = outputStreamReader.ReadToEnd();
// make sure version changes don't break the tests
expectedCode = expectedCode.Replace("$VERSION$", typeof(MockBase<>).Assembly.GetName().Version.ToString());
// useful when converting generated code to something that can be pasted into an expectation file
var sanitisedResult = result.Replace(typeof(MockBase<>).Assembly.GetName().Version.ToString(), "$VERSION$");
Assert.Equal(expectedCode, result);
}
}
示例12: Options
internal Options(
IEnumerable<Project> projects = null,
IEnumerable<string> projectPaths = null,
IEnumerable<string> sourcePaths = null,
IEnumerable<IEnumerable<string>> symbolConfigurations = null,
IEnumerable<string> alwaysIgnoredSymbols = null,
IEnumerable<string> alwaysDefinedSymbols = null,
IEnumerable<string> alwaysDisabledSymbols = null,
Tristate undefinedSymbolValue = default(Tristate),
IAnalysisLogger logger = null)
{
if (projectPaths != null)
{
projects = Task.WhenAll(from path in projectPaths select MSBuildWorkspace.Create().OpenProjectAsync(path, CancellationToken.None)).Result;
}
if (projects != null)
{
Documents = GetSharedDocuments(projects);
}
if (projects == null && sourcePaths != null)
{
var projectId = ProjectId.CreateNewId("AnalysisProject");
var solution = new AdhocWorkspace()
.CurrentSolution
.AddProject(projectId, "AnalysisProject", "AnalysisProject", LanguageNames.CSharp);
foreach (var path in sourcePaths)
{
var documentId = DocumentId.CreateNewId(projectId);
solution = solution.AddDocument(
documentId,
Path.GetFileName(path),
new FileTextLoader(path, defaultEncoding: Encoding.UTF8));
}
Documents = solution.Projects.Single().Documents.ToImmutableArray();
}
_symbolConfigurations = CalculateSymbolConfigurations(
alwaysDisabledSymbols,
alwaysDefinedSymbols,
alwaysIgnoredSymbols,
symbolConfigurations);
_undefinedSymbolValue = undefinedSymbolValue;
Logger = logger ?? new ConsoleAnalysisLogger();
}
示例13: CreateAndManipulateAdhocWorkspace_UnderstandingIsCorrect
public void CreateAndManipulateAdhocWorkspace_UnderstandingIsCorrect()
{
using (var adhocWorkspace = new AdhocWorkspace())
{
var solution = adhocWorkspace.CurrentSolution;
var newProject = adhocWorkspace.AddProject("Project.Test", LanguageNames.CSharp);
adhocWorkspace.AddDocument(newProject.Id, "TestFile.cs", SourceText.From("public class Bar { }"));
Assert.AreEqual(1, adhocWorkspace.CurrentSolution.Projects.Count());
var project = adhocWorkspace.CurrentSolution.Projects.Single();
Assert.AreEqual("Project.Test", project.Name);
Assert.AreEqual(1, project.Documents.Count());
Assert.AreEqual("TestFile.cs", project.Documents.Single().Name);
}
}
示例14: CreateProject
static Project CreateProject(string source)
{
var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
var projectId = ProjectId.CreateNewId();
var solution = new AdhocWorkspace()
.CurrentSolution
.AddProject(projectId, "TestProject", "TestProject", LanguageNames.CSharp)
.WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location))
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")))
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(ConstAttribute).Assembly.Location));
var documentId = DocumentId.CreateNewId(projectId);
solution = solution.AddDocument(documentId, "Test.cs", SourceText.From(source));
return solution.GetProject(projectId);
}
示例15: Create
internal static Document Create(string code)
{
var projectName = "Test";
var projectId = ProjectId.CreateNewId(projectName);
var solution = new AdhocWorkspace()
.CurrentSolution
.AddProject(projectId, projectName, projectName, LanguageNames.CSharp)
.WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.AddMetadataReference(projectId, MetadataReference.CreateFromAssembly(typeof(object).Assembly))
.AddMetadataReference(projectId, MetadataReference.CreateFromAssembly(typeof(Enumerable).Assembly))
.AddMetadataReference(projectId, MetadataReference.CreateFromAssembly(typeof(CSharpCompilation).Assembly))
.AddMetadataReference(projectId, MetadataReference.CreateFromAssembly(typeof(Compilation).Assembly))
.AddMetadataReference(projectId, MetadataReference.CreateFromAssembly(typeof(BusinessBase<>).Assembly));
var documentId = DocumentId.CreateNewId(projectId);
solution = solution.AddDocument(documentId, "Test.cs", SourceText.From(code));
return solution.GetProject(projectId).Documents.First();
}