2017-07-21 2 views
0

Ich versuche, einfache Benutzer Formel auszuführen.Ausführen von Benutzercode mit CodeAnalysis CSharpScript (.NET Core)

Ich verwende MS VS 2017 15.2 (26430.16), .NET Core 1.1.

Ich folgte: https://github.com/dotnet/roslyn/wiki/Scripting-API-Samples

Ich habe ASP.NET Core-Web App hinzugefügt NuGet Paket:

Install-Package Microsoft.CodeAnalysis.CSharp.Scripting 

Aber nach, dass die App gab einen Fehler:

An unhandled exception occurred while processing the request. 
ArgumentException: Must include private members unless emitting a ref assembly. 
Parameter name: IncludePrivateMembers 
Microsoft.CodeAnalysis.Compilation.Emit(Stream peStream, Stream pdbStream, Stream xmlDocumentationStream, Stream win32Resources, IEnumerable<ResourceDescription> manifestResources, EmitOptions options, IMethodSymbol debugEntryPoint, Stream sourceLinkStream, IEnumerable<EmbeddedText> embeddedTexts, Stream metadataPEStream, CancellationToken cancellationToken) 

Nach Ich fügte

using Microsoft.CodeAnalysis.CSharp.Scripting; 
hinzu

für

object result = CSharpScript.EvaluateAsync("1 + 2"); 

aber es war nicht zu sehen, so habe ich

<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="2.3.1" /> 

in "MyProject.csproj".

Aber ich habe den gleichen Fehler.

Kann mir jemand helfen?

Update 1:

Stack:

Microsoft.CodeAnalysis.Compilation.Emit(Stream peStream, Stream pdbStream, Stream xmlDocumentationStream, Stream win32Resources, IEnumerable<ResourceDescription> manifestResources, EmitOptions options, IMethodSymbol debugEntryPoint, Stream sourceLinkStream, IEnumerable<EmbeddedText> embeddedTexts, Stream metadataPEStream, CancellationToken cancellationToken) 
Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRoslynCompilationService.Compile(RelativeFileInfo fileInfo, string compilationContent) 
Microsoft.AspNetCore.Mvc.Razor.Internal.RazorCompilationService.Compile(RelativeFileInfo file) 
Microsoft.AspNetCore.Mvc.Razor.Internal.CompilerCache.CreateCacheEntry(string relativePath, string normalizedPath, Func<RelativeFileInfo, CompilationResult> compile) 
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
Microsoft.AspNetCore.Mvc.Razor.Internal.CompilerCache.GetOrAdd(string relativePath, Func<RelativeFileInfo, CompilationResult> compile) 
Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorPageFactoryProvider.CreateFactory(string relativePath) 
Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.CreateCacheResult(HashSet<IChangeToken> expirationTokens, string relativePath, bool isMainPage) 
Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.OnCacheMiss(ViewLocationExpanderContext expanderContext, ViewLocationCacheKey cacheKey) 
Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.LocatePageFromViewLocations(ActionContext actionContext, string pageName, bool isMainPage) 
Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.FindView(ActionContext context, string viewName, bool isMainPage) 
Microsoft.AspNetCore.Mvc.ViewEngines.CompositeViewEngine.FindView(ActionContext context, string viewName, bool isMainPage) 
Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor.FindView(ActionContext actionContext, ViewResult viewResult) 
Microsoft.AspNetCore.Mvc.ViewResult+<ExecuteResultAsync>d__26.MoveNext() 
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeResultAsync>d__30.MoveNext() 
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResultFilterAsync>d__28.MoveNext() 
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResultExecutedContext context) 
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) 
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResourceFilter>d__22.MoveNext() 
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context) 
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) 
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeAsync>d__20.MoveNext() 
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext() 
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
Microsoft.VisualStudio.Web.BrowserLink.BrowserLinkMiddleware+<ExecuteWithFilter>d__7.MoveNext() 
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext() 

Update 2:

Schließlich habe ich es auf diese Weise (ohne Pakete):

string user_code = "1 + 2"; 
string code = $"int? r = {user_code};"; 
string codeToCompile = @"using System; 
namespace RoslynCompile 
{ 
    public class Calculator 
    { 
     public int? Calculate() 
     { 
      " + code + @" 
      return r; 
     } 
    } 
}"; 
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(codeToCompile); 
string assemblyName = Path.GetRandomFileName(); 
MetadataReference[] references = new MetadataReference[] 
{ 
MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location) 
}; 
CSharpCompilation compilation = CSharpCompilation.Create(
    assemblyName, 
    syntaxTrees: new[] { syntaxTree }, 
    references: references, 
    options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); 
using (var ms = new MemoryStream()) 
{ 
    EmitResult emitResult = compilation.Emit(ms); 
    if (!emitResult.Success) 
    { 
     // some errors 
     IEnumerable<Diagnostic> failures = emitResult.Diagnostics.Where(diagnostic => 
      diagnostic.IsWarningAsError || 
      diagnostic.Severity == DiagnosticSeverity.Error); 
    } 
    else 
    { 
     ms.Seek(0, SeekOrigin.Begin); 
     Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms); 
     var type = assembly.GetType("RoslynCompile.Calculator"); 
     var instance = assembly.CreateInstance("RoslynCompile.Calculator"); 
     var meth = type.GetMember("Calculate").First() as MethodInfo; 
     // get result 
     int? result = meth.Invoke(instance, null) as int?; 
    } 
} 
+0

Was ist der Stack-Trace? – SLaks

Antwort

2

I bin mir nicht sicher was cau Ses dieser Fehler, aber wir rollten zurück zu v2.2.0 des Microsoft.CodeAnalysis.CSharp Pakets.

Es scheint zu geschehen seit v2.3.0. Zum Zeitpunkt des Schreibens ist v2.3.1 aus und verursacht immer noch dieses Problem.

Überprüfen Sie die issue auf GitHub.