private async Task <MetadataReference> GetFileStreamExternal(string url) { try { Console.WriteLine($"Fetching External: {url}"); if (http_external == null) { http_external = new HttpClient(); } MetadataReference mr = null; using (var stream = await http_external.GetStreamAsync(url).ConfigureAwait(false)) using (var outputStream = new MemoryStream()) { await stream.CopyToAsync(outputStream).ConfigureAwait(false); // Make sure to set the position to 0 outputStream.Position = 0; mr = MetadataReference.CreateFromStream(outputStream); } return(mr); }catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); return(null); } }
public async virtual Task <MemoryStream> CreateAssembly(string code) { _mscorlib = _mscorlib ?? MetadataReference.CreateFromStream(new MemoryStream(await _mscorlibProvider.Get())); CSharpCompilation previousCompilation = null; var scriptCompilation = CSharpCompilation.CreateScriptCompilation(Guid.NewGuid().ToString(), CSharpSyntaxTree.ParseText(code, CSharpParseOptions.Default.WithKind(SourceCodeKind.Script).WithLanguageVersion(LanguageVersion.Latest)), references: new[] { _mscorlib }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release, concurrentBuild: false, usings: new[] { "System", "System.Threading.Tasks" }), previousCompilation); var errorDiagnostics = scriptCompilation.GetDiagnostics().Where(x => x.Severity == DiagnosticSeverity.Error); if (errorDiagnostics.Any()) { Console.WriteLine(string.Join(",\r\n", errorDiagnostics.Select(e => e.GetMessage()))); return(null); } var stream = new MemoryStream(); if (scriptCompilation.Emit(stream).Success) { return(await Task.FromResult(stream)); } return(null); }
public async Task <List <MetadataReference> > GetAssemblies(bool isConsole, List <string> loadedAssemblies) { var assemblies = AppDomain.CurrentDomain.GetAssemblies() .Where(x => !x.IsDynamic) .Select(x => x.GetName().Name) .Union(new[] { // Add any required dll that are not referenced in the Blazor application "System.Console", "System.Linq" //"" }) .Distinct() .Where(x => !string.IsNullOrWhiteSpace(x)) .Select(x => $"_framework/{x}.dll"); var references = new List <MetadataReference>(); foreach (var assembly in assemblies) { // Download the assembly references.Add( MetadataReference.CreateFromStream( await _http.GetStreamAsync(assembly))); } return(references); }
public int SetReferences(IEnumerable <string> references) { var totalBytes = 0; var rs = new List <MetadataReference>(); foreach (var r in references) { var exists = File.Exists(r); Console.WriteLine("MetaRef: {0} (exists? {1})", r, exists ? "yes" : "no"); // first, copy the file to some random place var newFile = Path.GetTempFileName(); Console.WriteLine("Copy {0} => {1}", r, newFile); File.Copy(r, newFile, true); var bytes = File.ReadAllBytes(newFile); Console.WriteLine("Delete: {0}", newFile); Console.WriteLine("STILL EXISTS? {0}", File.Exists(r) ? "YES": "NO"); File.Delete(newFile); totalBytes += bytes.Length; var stream = new MemoryStream(bytes); rs.Add(MetadataReference.CreateFromStream(stream)); } References = rs; Console.WriteLine("Quitting program because ??"); Environment.Exit(0); return(totalBytes); }
public static void InitializeMetadataReferences(HttpClient client) { async Task InitializeInternal() { var response = await client.GetJsonAsync <BlazorBoot>("_framework/blazor.boot.json"); string[] assemblyNames = response.resources.assembly.Keys.ToArray().Where(x => x.EndsWith(".dll")).ToArray(); var assemblies = await Task.WhenAll(assemblyNames.Select(x => client.GetAsync("_framework/" + x))); var references = new List <MetadataReference>(assemblyNames.Length); foreach (var asm in assemblies) { using (var task = await asm.Content.ReadAsStreamAsync()) { references.Add(MetadataReference.CreateFromStream(task)); } } Compiler.references = references; } initializationTask = InitializeInternal(); }
internal static PortableExecutableReference CreateMetadataReferenceFromHexGZipImage( string image, MetadataReferenceProperties properties = default(MetadataReferenceProperties), DocumentationProvider documentation = null, string filePath = null ) { if (image == null) { throw new ArgumentNullException(nameof(image)); } using (var compressed = new MemoryStream(SoapHexBinary.Parse(image).Value)) using (var gzipStream = new GZipStream(compressed, CompressionMode.Decompress)) using (var uncompressed = new MemoryStream()) { gzipStream.CopyTo(uncompressed); uncompressed.Position = 0; return(MetadataReference.CreateFromStream( uncompressed, properties, documentation, filePath )); } }
public void NoDecimalConversion() { var source1 = @"namespace System { public class Object { } public struct Void { } public class ValueType { } public struct Int32 { } public struct Decimal { } }"; var compilation1 = CreateEmptyCompilation(source1, assemblyName: GetUniqueName()); var reference1 = MetadataReference.CreateFromStream(compilation1.EmitToStream()); var source2 = @"class C { static int M(decimal d) { return (int)d; } }"; var compilation2 = CreateEmptyCompilation(source2, new[] { reference1 }); // Should report "CS0656: Missing compiler required member 'System.Decimal.op_Explicit_ToInt32'". // Instead, we report no errors and assert during emit. // no errors for compat reasons. compilation2.VerifyDiagnostics(); // The bug has been resolved as Won't Fix for being extremely niche scenario and being a compat concern. // uncomment the following code if we are fixing this //var verifier = CompileAndVerify(compilation2); }
private static MetadataReference GetInternalLibraryMetadataReference() { var syntaxTree = VisualBasicSyntaxTree.ParseText($@"Imports System.Runtime.CompilerServices <Assembly: InternalsVisibleTo(""{Shared.WorkspaceFactory.DefaultProjectName}"")> Namespace ExternalNamespace Public Class InternalFoo Friend Overridable Function Bar() As Integer Return 1 End Function End Class End Namespace "); var references = new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) }; var compilationOptions = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary); var compilation = VisualBasicCompilation.Create("Internal", new[] { syntaxTree }, references, compilationOptions); using (var ms = new MemoryStream()) { var result = compilation.Emit(ms); if (result.Success == false) { var errors = result.Diagnostics.Where(diag => diag.IsWarningAsError || diag.Severity == DiagnosticSeverity.Error); throw new InvalidOperationException($"Internal library compilation failed: {string.Join(",", errors)}"); } ms.Seek(0, SeekOrigin.Begin); return(MetadataReference.CreateFromStream(ms)); } }
private static IEnumerable <MetadataReference> CreateAppCodeReferences(string appCode, IEnumerable <MetadataReference> shimReferences) { var references = new List <MetadataReference>(shimReferences); if (appCode != null) { var appCodeSyntaxTrees = new List <SyntaxTree> { CSharpSyntaxTree.ParseText(appCode) }; var compilation = CSharpCompilation.Create( "AppCode", appCodeSyntaxTrees, shimReferences, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var stream = new MemoryStream(); var compilationResult = compilation.Emit(stream, options: new EmitOptions()); stream.Position = 0; var diagString = string.Join(";", compilationResult.Diagnostics.Where(s => s.Severity == DiagnosticSeverity.Error).Select(s => s.ToString())); Assert.True(compilationResult.Success, string.Format("Application code needed for tests didn't compile!: {0}", diagString)); references.Add(MetadataReference.CreateFromStream(stream)); } return(references); }
private static PortableExecutableReference GetInternalLibraryMetadataReference() { var syntaxTree = CSharpSyntaxTree.ParseText($@" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""{TestProjectName}"")] namespace ExternalNamespace {{ public class InternalFoo {{ internal virtual int Bar() {{ return 1; }} }} }}"); var references = new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) }; var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); var compilation = CSharpCompilation.Create("Internal", new[] { syntaxTree }, references, compilationOptions); using (var ms = new MemoryStream()) { var result = compilation.Emit(ms); if (result.Success == false) { var errors = result.Diagnostics.Where(diag => diag.IsWarningAsError || diag.Severity == DiagnosticSeverity.Error); throw new InvalidOperationException($"Internal library compilation failed: {string.Join(",", errors)}"); } ms.Seek(0, SeekOrigin.Begin); return(MetadataReference.CreateFromStream(ms)); } }
static AdhocWorkspace CreateWorkspace() { var workspace = new AdhocWorkspace(); var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "MyProject", "MyProject", LanguageNames.CSharp); var references = new List <MetadataReference>(); if (Maker.IsMonoRuntime) { if (SystemDlls != null) { references.AddRange(SystemDlls.Select(sd => MetadataReference.CreateFromStream(sd))); } } else { references.Add(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)); } projectInfo = projectInfo.WithMetadataReferences(references); var project = workspace.AddProject(projectInfo); //var document = workspace.AddDocument(project.Id, "MyFile.cs", SourceText.From(code)); return(workspace); }
private static SemanticModel GetSemanticModelWithIgnoreAccessibility() { var compilationA = CreateCompilation(@" namespace N { class A { A M() { return new A(); } int _num; } }" ); var referenceA = MetadataReference.CreateFromStream(compilationA.EmitToStream()); var compilationB = CreateCompilation(@" using A = N.A; class B { void Main() { new A().M(); } } ", new MetadataReference[] { referenceA }, TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); var syntaxTree = compilationB.SyntaxTrees[0]; return(compilationB.GetSemanticModel(syntaxTree, ignoreAccessibility: true)); }
public void DoNotIgnorePrivateStructFieldsOfTypeParameterTypeFromMetadata() { var comp1 = CreateCompilationWithMscorlib( @"public struct GenericStruct<T> where T : class { T PrivateData; } "); var sourceReference = new CSharpCompilationReference(comp1); var metadataReference = MetadataReference.CreateFromStream(comp1.EmitToStream()); var source2 = @"class Program<T> where T : class { public static void Main() { GenericStruct<T> r1; var r2 = r1; } }"; CreateCompilationWithMscorlib(source2, references: new MetadataReference[] { sourceReference }).VerifyDiagnostics( // (6,18): error CS0165: Use of unassigned local variable 'r1' // var r2 = r1; Diagnostic(ErrorCode.ERR_UseDefViolation, "r1").WithArguments("r1").WithLocation(6, 18) ); CreateCompilationWithMscorlib(source2, references: new MetadataReference[] { metadataReference }).VerifyDiagnostics( // (6,18): error CS0165: Use of unassigned local variable 'r1' // var r2 = r1; Diagnostic(ErrorCode.ERR_UseDefViolation, "r1").WithArguments("r1").WithLocation(6, 18) ); }
public void IgnoreInternalStructFieldsOfReferenceTypeFromMetadata() { var comp1 = CreateCompilationWithMscorlib( @"public struct Struct { internal string data; } "); var sourceReference = new CSharpCompilationReference(comp1); var metadataReference = MetadataReference.CreateFromStream(comp1.EmitToStream()); var source2 = @"class Program { public static void Main() { Struct r1; var r2 = r1; } }"; CreateCompilationWithMscorlib(source2, references: new MetadataReference[] { sourceReference }).VerifyDiagnostics( // NOTE: no errors expected because we treat all imported data the same as if imported from metadata. ////// (6,18): error CS0165: Use of unassigned local variable 'r1' ////// var r2 = r1; ////Diagnostic(ErrorCode.ERR_UseDefViolation, "r1").WithArguments("r1").WithLocation(6, 18) ); CreateCompilationWithMscorlib(source2, references: new MetadataReference[] { metadataReference }).VerifyDiagnostics( ); }
internal static Assembly EmitCompilationAndLoadAssembly(CSharpCompilation compilation, bool makeAssemblyDebuggable, out string errorMessages) { Contract.Requires(compilation.SyntaxTrees.Count() == 1); Assembly a = null; EmitResult emitResult; if (makeAssemblyDebuggable) { var tree = compilation.SyntaxTrees.Single(); var baseFile = tree.FilePath; var sourceFile = Path.ChangeExtension(baseFile, ".cs"); File.WriteAllText(sourceFile, tree.GetRoot().ToFullString()); var assemblyFile = Path.ChangeExtension(baseFile, ".dll"); using (var assemblyStream = File.Open(assemblyFile, FileMode.Create, FileAccess.Write)) using (var pdbStream = File.Open(Path.ChangeExtension(baseFile, ".pdb"), FileMode.Create, FileAccess.Write)) { emitResult = compilation.Emit(assemblyStream, pdbStream, options: new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); } if (emitResult.Success) { #if DOTNETCORE a = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyFile); #else a = Assembly.LoadFrom(assemblyFile); #endif } } else { using (var stream = new MemoryStream()) { emitResult = compilation.Emit(stream); if (emitResult.Success) { stream.Position = 0; #if DOTNETCORE a = AssemblyLoadContext.Default.LoadFromStream(stream); stream.Position = 0; // Must reset it! Loading leaves its position at the end #else var assembly = stream.ToArray(); a = Assembly.Load(assembly); #endif loader.RegisterDependency(a); var aref = MetadataReference.CreateFromStream(stream); metadataReferenceCache.Add(a, aref); } } } errorMessages = string.Join("\n", emitResult.Diagnostics); if (makeAssemblyDebuggable && emitResult.Diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error)) { System.Diagnostics.Debug.WriteLine(errorMessages); } return(a); }
public void NoDecimalConversion() { var source1 = @"namespace System { public class Object { } public struct Void { } public class ValueType { } public struct Int32 { } public struct Decimal { } }"; var compilation1 = CreateCompilation(source1, assemblyName: GetUniqueName()); var reference1 = MetadataReference.CreateFromStream(compilation1.EmitToStream()); var source2 = @"class C { static int M(decimal d) { return (int)d; } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); // Should report "CS0656: Missing compiler required member 'System.Decimal.op_Explicit_ToInt32'". // Instead, we report no errors and assert during emit. compilation2.VerifyDiagnostics(); var verifier = CompileAndVerify(compilation2); }
private void LoadServiceAssembly(string org, string service, ServicePackageDetails servicePackageDetails, ZipArchive zipArchive) { var assemblykey = org + "_" + service; var assemblyName = servicePackageDetails.AssemblyName + ".dll"; MemoryStream memoryStream = new MemoryStream(); using (Stream input = zipArchive.Entries.First(e => e.Name == assemblyName).Open()) { input.CopyTo(memoryStream); } memoryStream.Position = 0; AssemblyLoadContext.Default.LoadFromStream(memoryStream); if (_compilation.ServiceReferences.ContainsKey(assemblykey)) { _compilation.ServiceReferences.Remove(assemblykey); } memoryStream.Seek(0, SeekOrigin.Begin); MetadataReference newReference = MetadataReference.CreateFromStream(memoryStream); _compilation.ServiceReferences.Add(assemblykey, newReference); }
private static MetadataReference LoadVulcanRuntime() { if (_vrt == null) { MetadataReference[] refs = new MetadataReference[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location) }; var args = CSharpCommandLineParser.SplitCommandLineIntoArguments("/dialect:vulcan /r:VulcanRTFuncs.dll /r:VulcanRT.dll /unsafe", false); var cmdParser = new CSharpCommandLineParser(); var parsedArgs = cmdParser.Parse(args, ".", null); var c = CSharpCompilation.Create( "VulcanRTdummy.dll", syntaxTrees: new[] { VulcanRuntime }, references: refs, options: parsedArgs.CompilationOptions.WithOutputKind(OutputKind.DynamicallyLinkedLibrary) ); var ms = new System.IO.MemoryStream(); EmitResult r = c.Emit(ms); if (!r.Success) { string err = ""; r.Diagnostics.Where(d => d.IsWarningAsError || d.Severity == DiagnosticSeverity.Error).ToList().ForEach(d => err += d.ToString() + "\r\n"); throw new Exception(err); } ms.Seek(0, System.IO.SeekOrigin.Begin); _vrt = ms.ToArray(); _vrta = System.Reflection.Assembly.Load(_vrt); System.AppDomain.CurrentDomain.AssemblyResolve += currentDomain_AssemblyResolve; } return(MetadataReference.CreateFromStream(new System.IO.MemoryStream(_vrt))); }
public static void InitializeMetadataReferences(HttpClient client) { async Task InitializeInternal() { var model = new Model(); Console.WriteLine("Initializing the code editor..."); // TODO: This loads every assembly that is available. We should // see if we can limit this to just the ones that we need. var response = await client.GetFromJsonAsync <BlazorBoot>("_framework/blazor.boot.json"); var assemblies = await Task.WhenAll(response.resources.assembly.Keys.Select(x => client.GetAsync("_framework/" + x))); var references = new List <MetadataReference>(assemblies.Length); foreach (var asm in assemblies) { using var task = await asm.Content.ReadAsStreamAsync(); references.Add(MetadataReference.CreateFromStream(task)); } References = references; } InitializationTask = InitializeInternal(); }
public void CreateFrom_Errors() { Assert.Throws <ArgumentNullException>(() => MetadataReference.CreateFromImage(null)); Assert.Throws <ArgumentNullException>( () => MetadataReference.CreateFromImage(default(ImmutableArray <byte>)) ); Assert.Throws <ArgumentNullException>(() => MetadataReference.CreateFromFile(null)); Assert.Throws <ArgumentNullException>( () => MetadataReference.CreateFromFile(null, default(MetadataReferenceProperties)) ); Assert.Throws <ArgumentNullException>(() => MetadataReference.CreateFromStream(null)); Assert.Throws <ArgumentNullException>( () => MetadataReference.CreateFromAssemblyInternal(null) ); Assert.Throws <ArgumentException>( () => MetadataReference.CreateFromAssemblyInternal( typeof(object).Assembly, new MetadataReferenceProperties(MetadataImageKind.Module) ) ); var dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName { Name = "Goo" }, System.Reflection.Emit.AssemblyBuilderAccess.Run ); Assert.Throws <NotSupportedException>( () => MetadataReference.CreateFromAssemblyInternal(dynamicAssembly) ); }
/// <summary> /// 创建程序集 /// </summary> /// <exception cref="Exception"></exception> /// <param name="messages">代码编译时的分析结果</param> public bool CreateDomain(out ImmutableArray <Diagnostic> messages) { HashSet <PortableExecutableReference> references = new HashSet <PortableExecutableReference>(); if (_state.UseAutoAssembly) { _ = AppDomain.CurrentDomain.GetAssemblies() .Where(i => !i.IsDynamic && !string.IsNullOrWhiteSpace(i.Location)) .Distinct() .Select(i => MetadataReference.CreateFromFile(i.Location)) .Execute(item => { references.Add(item); }); } _ = _state.Assemblies.Select(x => x.GetFiles()).Execute(item => { item.Execute(file => { references.Add(MetadataReference.CreateFromStream(file)); }); }); _option = _option ?? new DomainOptionBuilder(); CSharpCompilationOptions options = _option.Build(); SyntaxTree[] syntaxTrees = _state.Namespaces.Select(item => ParseToSyntaxTree(item.ToFullCode(), _option)).ToArray(); var result = BuildCompilation(_state.Path, _state.AssemblyName, syntaxTrees, references.ToArray(), options); messages = result.Diagnostics; return(result.Success); }
public static IAssemblySymbol GetCompilation(Stream stream) { PortableExecutableReference reference; using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); memoryStream.Position = 0; // MetadataReference.CreateFromStream closes the stream reference = MetadataReference.CreateFromStream(memoryStream); } var compilation = CSharpCompilation.Create(null).AddReferences(reference); var corlibLocation = typeof(object).Assembly.Location; var runtimeFolder = Path.GetDirectoryName(corlibLocation); compilation = compilation.AddReferences(MetadataReference.CreateFromFile(corlibLocation)); var trustedAssemblies = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")).Split(Path.PathSeparator); foreach (var tpl in trustedAssemblies) { if (tpl.StartsWith(runtimeFolder)) { compilation = compilation.AddReferences(MetadataReference.CreateFromFile(tpl)); } } return((IAssemblySymbol)compilation.GetAssemblyOrModuleSymbol(reference)); }
public static BuildReference ByName(string name, bool copyLocal = false) { if (CompilationServices.Default != null) { var library = CompilationServices.Default.LibraryExporter.GetExport(name); if (library != null) { var metadataReference = library.MetadataReferences.Single(); var roslynMetadataReference = metadataReference as IRoslynMetadataReference; if (roslynMetadataReference != null) { if (copyLocal) { throw new InvalidOperationException( $"In-memory assembly '{name}' cannot be copied locally."); } return(new BuildReference(roslynMetadataReference.MetadataReference)); } var metadataFileReference = metadataReference as IMetadataFileReference; if (metadataFileReference != null) { return(ByPath(metadataFileReference.Path, copyLocal)); } var metadataProjectReference = metadataReference as IMetadataProjectReference; if (metadataProjectReference != null) { if (copyLocal) { throw new InvalidOperationException( $"In-memory assembly '{name}' cannot be copied locally."); } using (var stream = new MemoryStream()) { metadataProjectReference.EmitReferenceAssembly(stream); return(new BuildReference(MetadataReference.CreateFromStream(stream))); } } } } #if DNX451 var assembly = Assembly.Load(name); if (!string.IsNullOrEmpty(assembly.Location)) { return(new BuildReference( MetadataReference.CreateFromFile(assembly.Location), copyLocal, new Uri(assembly.CodeBase).LocalPath)); } #endif throw new InvalidOperationException( $"Assembly '{name}' not found."); }
public void InvalidPublicKey() { var r = MetadataReference.CreateFromStream(new MemoryStream(TestResources.SymbolsTests.Metadata.InvalidPublicKey, writable: false)); Assert.Equal(CodeAnalysisResources.InMemoryAssembly, r.Display); Assert.Throws <BadImageFormatException>((Func <object>)((AssemblyMetadata)r.GetMetadataNoCopy()).GetAssembly); }
public async Task TestCompileAndRun_MetadataReference() { string greetingClass = @" namespace TestAssembly { public static class Greeting { public static string GetGreeting(string name) { return ""Hello, "" + name + ""!""; } } } "; // This needs to be done in the builder to have access to all of the assemblies added through // the various AddAssemblyReference options CSharpCompilation compilation = CSharpCompilation.Create( "TestAssembly", new[] { CSharpSyntaxTree.ParseText(greetingClass) }, GetMetadataReferences(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) ); MemoryStream memoryStream = new MemoryStream(); EmitResult emitResult = compilation.Emit(memoryStream); if (!emitResult.Success) { Assert.Fail("Unable to compile test assembly"); } memoryStream.Position = 0; // Add an assembly resolver so the assembly can be found AppDomain.CurrentDomain.AssemblyResolve += (sender, eventArgs) => new AssemblyName(eventArgs.Name ?? string.Empty).Name == "TestAssembly" ? Assembly.Load(memoryStream.ToArray()) : null; RazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate template = await razorEngine.CompileAsync(@" @using TestAssembly <p>@Greeting.GetGreeting(""Name"")</p> ", builder => { builder.AddMetadataReference(MetadataReference.CreateFromStream(memoryStream)); }); string expected = @" <p>Hello, Name!</p> "; string actual = await template.RunAsync(); Assert.AreEqual(expected, actual); }
public void CreateFromStream_MemoryStream() { var r = MetadataReference.CreateFromStream(new MemoryStream(TestResources.General.C1, writable: false)); Assert.Equal(CodeAnalysisResources.InMemoryAssembly, r.Display); Assert.Equal("C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", ((AssemblyMetadata)r.GetMetadataNoCopy()).GetAssembly().Identity.GetDisplayName()); }
private static MetadataReference LoadFromResources(Assembly assembly) { var searchAssembly = Path.GetFileName(assembly.Location); Console.WriteLine($"Seaching for {searchAssembly} in SDK"); var name = typeof(CSharpLanguage).Assembly.GetManifestResourceNames().FirstOrDefault(f => f.EndsWith(searchAssembly)); return(MetadataReference.CreateFromStream(typeof(CSharpLanguage).Assembly.GetManifestResourceStream(name))); }
public void CreateFromStream_MemoryStream() { var r = MetadataReference.CreateFromStream(new MemoryStream(TestResources.SymbolsTests.General.C1, writable: false)); Assert.Equal("<in-memory assembly>".NeedsLocalization(), r.Display); Assert.Equal("C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", ((AssemblyMetadata)r.GetMetadata()).GetAssembly().Identity.GetDisplayName()); }
// Wyam - Use the Roslyn scripting engine for compilation // In MVC, this part is done in RoslynCompilationService private Type Compile([NotNull] RelativeFileInfo file, [NotNull] string compilationContent) { HashSet <Assembly> assemblies = new HashSet <Assembly>(new AssemblyEqualityComparer()) { Assembly.GetAssembly(typeof(Modules.Razor.Razor)) // Wyam.Modules.Razor }; if (_executionContext.Assemblies != null) { assemblies.UnionWith(_executionContext.Assemblies); } var assemblyName = Path.GetRandomFileName(); var parseOptions = new CSharpParseOptions(); var syntaxTree = CSharpSyntaxTree.ParseText(SourceText.From(compilationContent, Encoding.UTF8), parseOptions, assemblyName); var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location); var compilation = CSharpCompilation.Create(assemblyName, new[] { syntaxTree }, assemblies.Select(x => _metadataReferences.GetOrAdd(x.Location, y => MetadataReference.CreateFromFile(y))), compilationOptions) .AddReferences( // For some reason, Roslyn really wants these added by filename // See http://stackoverflow.com/questions/23907305/roslyn-has-no-reference-to-system-runtime _metadataReferences.GetOrAdd(Path.Combine(assemblyPath, "mscorlib.dll"), x => MetadataReference.CreateFromFile(x)), _metadataReferences.GetOrAdd(Path.Combine(assemblyPath, "System.dll"), x => MetadataReference.CreateFromFile(x)), _metadataReferences.GetOrAdd(Path.Combine(assemblyPath, "System.Core.dll"), x => MetadataReference.CreateFromFile(x)), _metadataReferences.GetOrAdd(Path.Combine(assemblyPath, "System.Runtime.dll"), x => MetadataReference.CreateFromFile(x)) ); if (_executionContext.RawConfigAssembly != null && _executionContext.RawConfigAssembly.Length > 0) { using (MemoryStream memoryStream = new MemoryStream(_executionContext.RawConfigAssembly)) { compilation = compilation.AddReferences(MetadataReference.CreateFromStream(memoryStream)); } } using (var ms = new MemoryStream()) { EmitResult result = compilation.Emit(ms); if (!result.Success) { Trace.Error("{0} errors compiling {1}:{2}{3}", result.Diagnostics.Length, file.RelativePath, Environment.NewLine, string.Join(Environment.NewLine, result.Diagnostics)); throw new AggregateException(result.Diagnostics.Select(x => new Exception(x.ToString()))); } ms.Seek(0, SeekOrigin.Begin); byte[] assemblyBytes = ms.ToArray(); Assembly assembly = Assembly.Load(assemblyBytes); var type = assembly.GetExportedTypes() .First(t => t.Name.StartsWith(_razorHost.MainClassNamePrefix, StringComparison.Ordinal)); return(type); } }
public void NoTypedRefBox_RefStruct() { var source1 = @"namespace System { public class Object { } public class String { } public struct Void { } public class ValueType { } public struct Int32 { } public struct Boolean { } public struct Decimal { } public class Attribute{ } public class ObsoleteAttribute: Attribute { public ObsoleteAttribute(string message, bool error){} } // Make the type ref struct. Should work just fine. public ref struct TypedReference { } }"; var compilation1 = CreateEmptyCompilation(source1, assemblyName: GetUniqueName()); var reference1 = MetadataReference.CreateFromStream(compilation1.EmitToStream()); var source2 = @" public class C1 { public static object rrr; public static T Read<T>() where T : new() { T result = new T(); var refresult = __makeref(result); rrr = refresult; rrr = (object)__makeref(result); return result; } } "; var compilation2 = CreateEmptyCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (10,15): error CS0029: Cannot implicitly convert type 'System.TypedReference' to 'object' // rrr = refresult; Diagnostic(ErrorCode.ERR_NoImplicitConv, "refresult") .WithArguments("System.TypedReference", "object") .WithLocation(10, 15), // (11,15): error CS0030: Cannot convert type 'System.TypedReference' to 'object' // rrr = (object)__makeref(result); Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)__makeref(result)") .WithArguments("System.TypedReference", "object") .WithLocation(11, 15) ); }