Пример #1
0
        public virtual ScriptCompilationContext <TReturn> CreateCompilationContext <TReturn, THost>(ScriptContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            Logger.Verbose($"Current runtime is '{RuntimeHelper.GetPlatformIdentifier()}'.");

            var runtimeDependencies = RuntimeDependencyResolver.GetDependencies(context.WorkingDirectory, context.ScriptMode, context.Code.ToString()).ToArray();

            var scriptOptions = CreateScriptOptions(context, runtimeDependencies.ToList());

            var loadedAssembliesMap = CreateLoadedAssembliesMap();

            var scriptDependenciesMap = CreateScriptDependenciesMap(runtimeDependencies);

            scriptOptions = AddScriptReferences(scriptOptions, loadedAssembliesMap, scriptDependenciesMap);

            LoadNativeAssets(runtimeDependencies);

            AppDomain.CurrentDomain.AssemblyResolve +=
                (sender, args) => MapUnresolvedAssemblyToRuntimeLibrary(scriptDependenciesMap, loadedAssembliesMap, args);

            string code = GetScriptCode(context);

            var loader = new InteractiveAssemblyLoader();

            var script = CSharpScript.Create <TReturn>(code, scriptOptions, typeof(THost), loader);

            SetOptimizationLevel(context, script);

            EvaluateDiagnostics(script);

            return(new ScriptCompilationContext <TReturn>(script, context.Code, loader, scriptOptions));
        }
Пример #2
0
        public async Task ReturnIntWithTrailingDoubleExpression()
        {
            var script = CSharpScript.Create(@"
bool condition = false;
if (condition)
{
    return 1;
}
1.1");
            var result = await script.EvaluateAsync();

            Assert.Equal(1.1, result);

            script = CSharpScript.Create(@"
bool condition = true;
if (condition)
{
    return 1;
}
1.1");
            result = await script.EvaluateAsync();

            Assert.Equal(1, result);
        }
Пример #3
0
        public async Task MultipleLoadedFilesWithReturnAndTrailingExpression()
        {
            var resolver = TestSourceReferenceResolver.Create(
                KeyValuePair.Create("a.csx", "return 1;"),
                KeyValuePair.Create("b.csx", @"
#load ""a.csx""
2"));
            var options = ScriptOptions.Default.WithSourceResolver(resolver);
            var script  = CSharpScript.Create("#load \"b.csx\"", options);
            var result  = await script.EvaluateAsync();

            Assert.Equal(1, result);

            resolver = TestSourceReferenceResolver.Create(
                KeyValuePair.Create("a.csx", "return 1;"),
                KeyValuePair.Create("b.csx", "2"));
            options = ScriptOptions.Default.WithSourceResolver(resolver);
            script  = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""", options);
            result  = await script.EvaluateAsync();

            Assert.Equal(1, result);

            resolver = TestSourceReferenceResolver.Create(
                KeyValuePair.Create("a.csx", "return 1;"),
                KeyValuePair.Create("b.csx", "2"));
            options = ScriptOptions.Default.WithSourceResolver(resolver);
            script  = CSharpScript.Create(@"
#load ""a.csx""
#load ""b.csx""
return 3;", options);
            result  = await script.EvaluateAsync();

            Assert.Equal(1, result);
        }
Пример #4
0
        private async Task <List <(string, Type)> > GetParameters()
        {
            var csharScript = CSharpScript.Create(_code, ScriptOptions.Default);

            var compilation = csharScript.GetCompilation();

            var syntaxTree    = compilation.SyntaxTrees.Single();
            var semanticModel = compilation.GetSemanticModel(syntaxTree);

            var descendants = (await syntaxTree.GetRootAsync())
                              .DescendantNodes().ToList();

            var declarations = descendants.OfType <PropertyDeclarationSyntax>().ToList();
            var result       = new List <(string, Type)>();

            if (declarations?.Any() != true)
            {
                return(result);
            }

            var symbolDisplayFormat =
                new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces);

            foreach (var propertyDeclaration in declarations)
            {
                var name     = propertyDeclaration.Identifier.Text;
                var typeInfo = semanticModel.GetTypeInfo(propertyDeclaration.Type);

                var typeName = typeInfo.Type.ToDisplayString(symbolDisplayFormat);
                var type     = Type.GetType(typeName, true);

                result.Add((name, type));
            }

            return(result);
        }
Пример #5
0
        public void HostObjectInInMemoryAssembly()
        {
            var lib      = CreateCompilationWithMscorlib("public class C { public int X = 1, Y = 2; }", "HostLib");
            var libImage = lib.EmitToArray();
            var libRef   = MetadataImageReference.CreateFromImage(libImage);

            var libAssembly = Assembly.Load(libImage.ToArray());
            var globalsType = libAssembly.GetType("C");
            var globals     = Activator.CreateInstance(globalsType);

            using (var loader = new InteractiveAssemblyLoader())
            {
                loader.RegisterDependency(libAssembly);

                var script = CSharpScript.Create <int>(
                    "X+Y",
                    ScriptOptions.Default.WithReferences(libRef),
                    globalsType: globalsType,
                    assemblyLoader: loader);

                int result = script.RunAsync(globals).Result.ReturnValue;
                Assert.Equal(3, result);
            }
        }
        /// <summary>
        /// Instanciate Expression Evaluation
        /// </summary>
        /// <param name="Type">Model type (Required for precompile)</param>
        /// <param name="Expression">Expression string (Required for precompile)</param>
        /// <param name="references">Script references</param>
        /// <param name="namespaces">Script namespaces</param>
        public Evaluate(Type Type = null, string Expression = null, List <Assembly> references = null, List <string> namespaces = null)
        {
            // Add References
            if (references == null)
            {
                _scriptOptions = _scriptOptions.AddReferences(typeof(System.Object).GetTypeInfo().Assembly, typeof(System.Linq.Enumerable).GetTypeInfo().Assembly);
            }
            else
            {
                _scriptOptions = _scriptOptions.AddReferences(references.ToArray());
            }

            // Add namespaces
            if (namespaces == null)
            {
                // Default namespaces
                _scriptOptions = _scriptOptions.AddImports("System");
                _scriptOptions = _scriptOptions.AddImports("System.Linq");
                _scriptOptions = _scriptOptions.AddImports("System.Collections.Generic");
            }
            else
            {
                foreach (var n in namespaces)
                {
                    _scriptOptions = _scriptOptions.AddImports(n);
                }
            }

            // Precompile
            if (Type != null && Expression != null)
            {
                _script = CSharpScript.Create(Expression, _scriptOptions, Type);
                _script.Compile();
                _preCompiled = true;
            }
        }
Пример #7
0
        private async void CommandBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && !Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
            {
                Debug.WriteLine(CommandBox.Text);
                e.Handled            = true;
                CommandBox.IsEnabled = false;
                object result;
                try
                {
                    using (var loader = new InteractiveAssemblyLoader())
                    {
                        loader.RegisterDependency(typeof(UndertaleObject).GetTypeInfo().Assembly);

                        var script = CSharpScript.Create <object>(CommandBox.Text, ScriptOptions.Default
                                                                  .WithImports("UndertaleModLib", "UndertaleModLib.Models", "UndertaleModLib.Decompiler", "System", "System.IO", "System.Collections.Generic")
                                                                  .WithReferences(Program.GetAssemblyMetadata(typeof(UndertaleObject).GetTypeInfo().Assembly)),
                                                                  this.GetType(), loader);

                        result = (await script.RunAsync(this)).ReturnValue;
                    }
                }
                catch (CompilationErrorException exc)
                {
                    result = exc.Message;
                    Debug.WriteLine(exc);
                }
                catch (Exception exc)
                {
                    result = exc;
                }
                CommandBox.Text = result != null?result.ToString() : "";

                CommandBox.IsEnabled = true;
            }
        }
Пример #8
0
        //public void GetRequestHash(ActionExecutingContext actionExecutingContext)
        //{
        //    //actionExecutingContext.HttpContext.req
        //}

        private async static Task RunComposity(int requsetHash, HttpContext httpContext, RuntimeStepModel newrunmodel, ISqlSugarClient dbFactory, ISysDatabaseService codeService, IConfiguration config)
        {
            var cons = newrunmodel.ComposeEntity;

            if (cons.RunMode == RunMode.Coding)
            {
                if (newrunmodel.ComposeTemplate != null)
                {
                    //TODO :add template
                }
                //Manager.RuntimeModels.Add(newrunmodel);
                else
                {
                    var steps = FindSteps(cons.Guid, codeService);

                    foreach (var s in steps)
                    {
                        object rebject    = null;
                        object DynaObject = null;

                        if (s.IsUsingAuth.ToBool())
                        {
                            await httpContext.AuthenticateAsync();

                            if (httpContext.User.Identity.Name != s.UserName || !httpContext.User.Identity.IsAuthenticated)
                            {
                                APPCommon.ResponseUnAuth((ActionExecutingContext)newrunmodel.Res["__actioncontext"], s.LoginUrl);

                                return;
                            }
                        }

                        var    cacheKey   = string.Concat(cons.Guid, "_", s.ExcuteType, "_", s.FlowStepType, "_", s.Guid, "_", s.ArgNames);
                        object stepResult = APP.RuntimeCache.GetOrCreate(cacheKey, entry =>
                        {
                            object newobj = null;
                            APP.RuntimeCache.Set(cacheKey, newobj);
                            return(newobj);
                        });

                        if (s.IsUsingCache && stepResult != null)
                        {
                            rebject = stepResult;
                        }
                        else
                        {
                            if (!s.IsUsingCache || stepResult == null)
                            {
                                switch (s.FlowStepType)
                                {
                                case FlowStepType.Declare:
                                {
                                    lock (lockobj)
                                    {
                                        //root.Usings[2].Name.ToString()
                                        // var rebject2 = Manager.GetData(spec.InParamter1, spec.InParamter2);
                                        var runcode    = APP.FindOrAddRumtimeCode(s.Guid);
                                        var so_default = ScriptOptions.Default;
                                        if (runcode == null)
                                        {
                                            runcode = new RuntimeCode()
                                            {
                                                StepGuid  = s.Guid,
                                                CodeLines = s.ProxyCode,
                                            };
                                            List <string> dlls = new List <string>();

                                            var    isref   = false;
                                            string dllbase = APPCommon.AppRootDir;


                                            if (!string.IsNullOrEmpty(s.TypeLib))
                                            {
                                                var dllfile = dllbase + s.TypeLib;
                                                if (APP.DynamicReferenceDlls.Contains(dllfile))
                                                {
                                                    isref = false;
                                                }
                                                else
                                                {
                                                    APP.DynamicReferenceDlls.Add(dllfile);
                                                    isref = true;
                                                    dlls.Add(dllfile);
                                                }
                                            }
                                            if (!string.IsNullOrEmpty(s.ReferenceDlls))
                                            {
                                                isref = true;
                                                string[] dllnams = s.ReferenceDlls.Split(',');
                                                foreach (var n in dllnams)
                                                {
                                                    APP.DynamicReferenceDlls.Add(dllbase + n);
                                                }

                                                dlls.AddRange(dllnams);
                                            }
                                            if (isref)
                                            {
                                                so_default = so_default.WithReferences(dlls.ToArray());
                                            }
                                            so_default = so_default.WithReferences(Assembly.GetExecutingAssembly());

                                            var state = CSharpScript.Create <object>(s.ProxyCode, so_default, typeof(Dictionary <string, object>));

                                            runcode.Script = state;
                                            APP.RuntimeCodes.Add(s.Guid, runcode);
                                        }
                                        if (!string.IsNullOrEmpty(s.ReferenceDlls))
                                        {
                                            string dllbase = APPCommon.AppRootDir;
                                        }
                                        rebject = runcode.Script.RunAsync(newrunmodel.Res).Result.ReturnValue;
                                        Logger.LogInfo(LoggerName, $"AComposityId id {s.AComposityId} ,step {s.StepOrder}, Declare: result {rebject}  ");
                                    }
                                }
                                break;

                                case FlowStepType.GetData:
                                {
                                    DynaObject = HandleGetData(httpContext, newrunmodel, dbFactory, s);
                                }
                                break;

                                case FlowStepType.CallMethod:
                                {
                                    var methodsub = APP.GetMethodFromConfig(s.IsBuildIn.Value, s.TypeLib, s.TypeFullName, s.MethodName);
                                    var objParams = new List <object>();
                                    if (!string.IsNullOrEmpty(s.ArgNames))
                                    {
                                        objParams = newrunmodel.GetPoolResuce(s.ArgNames.Split(','));
                                    }

                                    else
                                    {
                                        objParams = null;
                                    }
                                    try
                                    {
                                        if (methodsub.IsStatic)
                                        {
                                            DynaObject = methodsub.Invoke(null, objParams.ToArray());
                                        }
                                        else
                                        {
                                            var instance = newrunmodel.Res[s.InstanceName];
                                            DynaObject = methodsub.Invoke(instance, objParams.ToArray());
                                        }
                                    }
                                    catch (Exception exp)
                                    {
                                        Logger.LogError(logName, "Run -> FlowStepType.CallMethod error,composity:{0},step:{1},-------------exception:{2}", cons.Id, s.Guid, LoggerHelper.GetExceptionString(exp));
                                        break;
                                    }
                                    Logger.LogInfo(LoggerName, $"AComposityId id {s.AComposityId} ,step {s.StepOrder}, CallMethod {s.MethodName}: result {DynaObject}  ");
                                }
                                break;

                                case FlowStepType.Text:
                                {
                                    rebject = s.OutPutText;
                                }
                                break;

                                case FlowStepType.Function:
                                {
                                    DynaObject = DealTheFunction(newrunmodel, s, httpContext);
                                    Logger.LogInfo(LoggerName, $"DealTheFunction: result {DynaObject}  ");
                                }
                                break;

                                case FlowStepType.RazorKey:
                                    try
                                    {
                                        rebject = stepResult = await HandleRazorKey(newrunmodel, s);
                                    }
                                    catch (Exception exp)
                                    {
                                        Logger.LogError(logName, $"parser RazorText wrong: {exp.Message}-------{LoggerHelper.GetExceptionString(exp)}");
                                    }
                                    break;

                                case FlowStepType.RazorText:
                                    try
                                    {
                                        rebject = stepResult = await HandleRazorText(newrunmodel, s, httpContext, s.ProxyCode);
                                    }
                                    catch (Exception exp)
                                    {
                                        Logger.LogError(logName, $"parser RazorText wrong: {exp.Message}-------{LoggerHelper.GetExceptionString(exp)}");
                                    }
                                    break;

                                case FlowStepType.RazorFile:
                                    try
                                    {
                                        var    filePath = s.ProxyCode;
                                        string template = File.ReadAllText(Path.Combine(APPCommon.UserUploadBaseDir, filePath));
                                        rebject = stepResult = await HandleRazorText(newrunmodel, s, httpContext, template);
                                    }
                                    catch (Exception exp)
                                    {
                                        Logger.LogError(logName, "parser RazorFile wrong: " + exp.Message + "-------" + LoggerHelper.GetExceptionString(exp));
                                    }
                                    break;
                                }

                                if (rebject == null)
                                {
                                    rebject = MagicExtension.BackToInst(DynaObject);
                                }
                                if (s.IsUsingCache)
                                {
                                    APP.RuntimeCache.Set(cacheKey, rebject);
                                }
                            }
                        }

                        if (!string.IsNullOrEmpty(s.StorePoolKey) && rebject != null)
                        {
                            newrunmodel.SetComposityResourceValue(s.StorePoolKey, rebject);
                        }
                    }
                    await CheckAndRunNextRuntimeComposity(requsetHash, httpContext, newrunmodel, dbFactory, codeService, config);
                }

                //Manager.RuntimeModels.Remove(newrunmodel);
            }
        }
Пример #9
0
 protected override Script <T> Create <T>(string code, ScriptOptions options, Type globalsType, InteractiveAssemblyLoader assemblyLoader) =>
 CSharpScript.Create <T>(code, options, globalsType, assemblyLoader);
        public void References_Versioning_FxUnification2()
        {
            if (!s_isSystemV2AndV4Available.Value)
            {
                return;
            }

            var script0 = CSharpScript.Create($@"
#r ""System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089""
");
            var script1 = script0.ContinueWith($@"
#r ""System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089""
");
            var script2 = script1.ContinueWith(@"
System.Diagnostics.Process.GetCurrentProcess()
");

            script0.GetCompilation().VerifyAssemblyVersionsAndAliases(
                "System, Version=2.0.0.0",
                "mscorlib, Version=4.0.0.0",
                "System.Configuration, Version=2.0.0.0: <implicit>,global",
                "System.Xml, Version=2.0.0.0: <implicit>,global",
                "System.Data.SqlXml, Version=2.0.0.0: <implicit>,global",
                "System.Security, Version=2.0.0.0: <implicit>,global");

            // TODO (https://github.com/dotnet/roslyn/issues/6456):
            // This is not correct. "global" alias should be recursively applied on all
            // dependencies of System, V4. The problem is in ResolveReferencedAssembly which considers
            // System, V2 equivalent to System, V4 and immediately returns, instead of checking if a better match exists.
            // This is not a problem in csc since it can't have both System, V2 and System, V4 among definitions.
            script1.GetCompilation().VerifyAssemblyVersionsAndAliases(
                "System, Version=4.0.0.0",
                "System, Version=2.0.0.0: <superseded>",
                "mscorlib, Version=4.0.0.0",
                "System.Configuration, Version=2.0.0.0: <superseded>",
                "System.Xml, Version=2.0.0.0: <superseded>",
                "System.Data.SqlXml, Version=2.0.0.0: <superseded>",
                "System.Security, Version=2.0.0.0: <superseded>",
                "System.Configuration, Version=4.0.0.0: <implicit>",
                "System.Xml, Version=4.0.0.0: <implicit>",
                "System.Data.SqlXml, Version=4.0.0.0: <implicit>",
                "System.Security, Version=4.0.0.0: <implicit>",
                "System.Core, Version=4.0.0.0: <implicit>",
                "System.Numerics, Version=4.0.0.0: <implicit>");

            // TODO (https://github.com/dotnet/roslyn/issues/6456):
            // "global" alias should be recursively applied on all
            script2.GetCompilation().VerifyAssemblyVersionsAndAliases(
                "System, Version=4.0.0.0",
                "System, Version=2.0.0.0: <superseded>",
                "mscorlib, Version=4.0.0.0",
                "System.Configuration, Version=2.0.0.0: <superseded>",
                "System.Xml, Version=2.0.0.0: <superseded>",
                "System.Data.SqlXml, Version=2.0.0.0: <superseded>",
                "System.Security, Version=2.0.0.0: <superseded>",
                "System.Configuration, Version=4.0.0.0: <implicit>",
                "System.Xml, Version=4.0.0.0: <implicit>",
                "System.Data.SqlXml, Version=4.0.0.0: <implicit>",
                "System.Security, Version=4.0.0.0: <implicit>",
                "System.Core, Version=4.0.0.0: <implicit>",
                "System.Numerics, Version=4.0.0.0: <implicit>");

            Assert.NotNull(script2.EvaluateAsync().Result);
        }
Пример #11
0
        public Task Pdb_CreateFromStream_InlineCode_WithoutEmitDebugInformation_ResultInPdbNotEmitted()
        {
            var opts = ScriptOptions.Default.WithEmitDebugInformation(false);

            return(VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts)));
        }
Пример #12
0
        public Task Pdb_CreateFromString_InlineCode_WithEmitDebugInformation_WithoutFileEncoding_ResultInPdbEmitted()
        {
            var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFileEncoding(null);

            return(VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: ""));
        }
Пример #13
0
 public void TestCreateFromStreamScript_StreamIsNull()
 {
     Assert.Throws <ArgumentNullException>(() => CSharpScript.Create((Stream)null));
 }
Пример #14
0
 /// <summary>
 /// 新建脚本
 /// </summary>
 /// <param name="code">脚本语言代码</param>
 public Script(string code)
 {
     script = CSharpScript.Create(code, ScriptOptions.Default, typeof(Globals));
     script.Compile();
 }
Пример #15
0
        public virtual ScriptCompilationContext <TReturn> CreateCompilationContext <TReturn, THost>(ScriptContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var runtimeIdentitfer = GetRuntimeIdentitifer();

            _logger.Verbose($"Current runtime is '{runtimeIdentitfer}'.");

            var opts = CreateScriptOptions(context);

            var runtimeId = RuntimeEnvironment.GetRuntimeIdentifier();
            var inheritedAssemblyNames = DependencyContext.Default.GetRuntimeAssemblyNames(runtimeId).Where(x =>
                                                                                                            x.FullName.StartsWith("system.", StringComparison.OrdinalIgnoreCase) ||
                                                                                                            x.FullName.StartsWith("microsoft.codeanalysis", StringComparison.OrdinalIgnoreCase) ||
                                                                                                            x.FullName.StartsWith("mscorlib", StringComparison.OrdinalIgnoreCase));

            foreach (var inheritedAssemblyName in inheritedAssemblyNames)
            {
                _logger.Verbose("Adding reference to an inherited dependency => " + inheritedAssemblyName.FullName);
                var assembly = Assembly.Load(inheritedAssemblyName);
                opts = opts.AddReferences(assembly);
            }

            var runtimeContext = File.Exists(Path.Combine(context.WorkingDirectory, Project.FileName)) ? ProjectContext.CreateContextForEachTarget(context.WorkingDirectory).FirstOrDefault() : null;

            if (runtimeContext == null)
            {
                _logger.Verbose("Unable to find project context for CSX files. Will default to non-context usage.");
                var scriptProjectProvider = ScriptProjectProvider.Create(new LoggerFactory());
                var scriptProjectInfo     = scriptProjectProvider.CreateProject(context.WorkingDirectory, "netcoreapp1.1");
                runtimeContext = ProjectContext.CreateContextForEachTarget(scriptProjectInfo.PathToProjectJson).FirstOrDefault();
            }

            _logger.Verbose($"Found runtime context for '{runtimeContext.ProjectFile.ProjectFilePath}'.");
            var projectExporter = runtimeContext.CreateExporter(context.Configuration);

            var runtimeDependencies = new HashSet <string>();
            var projectDependencies = projectExporter.GetDependencies();

            foreach (var projectDependency in projectDependencies)
            {
                var runtimeAssemblyGroups = projectDependency.RuntimeAssemblyGroups;

                foreach (var libraryAsset in runtimeAssemblyGroups.GetDefaultAssets())
                {
                    var runtimeAssemblyPath = libraryAsset.ResolvedPath;
                    _logger.Verbose($"Discovered runtime dependency for '{runtimeAssemblyPath}'");
                    runtimeDependencies.Add(runtimeAssemblyPath);
                }

                foreach (var runtimeAssemblyGroup in runtimeAssemblyGroups)
                {
                    if (!string.IsNullOrWhiteSpace(runtimeAssemblyGroup.Runtime) && runtimeAssemblyGroup.Runtime == runtimeIdentitfer)
                    {
                        foreach (var runtimeAsset in runtimeAssemblyGroups.GetRuntimeAssets(GetRuntimeIdentitifer()))
                        {
                            var runtimeAssetPath = runtimeAsset.ResolvedPath;
                            _logger.Verbose($"Discovered runtime asset dependency ('{runtimeIdentitfer}') for '{runtimeAssetPath}'");
                            runtimeDependencies.Add(runtimeAssetPath);
                        }
                    }
                }
            }

            foreach (var runtimeDep in runtimeDependencies)
            {
                _logger.Verbose("Adding reference to a runtime dependency => " + runtimeDep);
                opts = opts.AddReferences(MetadataReference.CreateFromFile(runtimeDep));
            }

            var loader             = new InteractiveAssemblyLoader();
            var script             = CSharpScript.Create <TReturn>(context.Code.ToString(), opts, typeof(THost), loader);
            var orderedDiagnostics = script.GetDiagnostics(SuppressedDiagnosticIds);

            if (orderedDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                foreach (var diagnostic in orderedDiagnostics)
                {
                    _logger.Log(diagnostic.ToString());
                }

                throw new CompilationErrorException("Script compilation failed due to one or more errors.",
                                                    orderedDiagnostics.ToImmutableArray());
            }

            return(new ScriptCompilationContext <TReturn>(script, context.Code, loader));
        }
Пример #16
0
        public void TestCreateFromStreamScript()
        {
            var script = CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("1 + 2")));

            Assert.Equal("1 + 2", script.Code);
        }
Пример #17
0
 public void NoReturn()
 {
     Assert.Null(ScriptingTestHelpers.EvaluateScriptWithOutput(
                     CSharpScript.Create("System.Console.WriteLine();"), ""));
 }
Пример #18
0
        public static List <Diagnostic> ValidateScript(string code, Type globalsType)
        {
            var script = CSharpScript.Create(code, ScriptOptions, globalsType);

            return(script.GetCompilation().GetDiagnostics().ToList());
        }
Пример #19
0
        public Task Pdb_CreateFromStream_CodeFromFile_WithEmitDebugInformation_ResultInPdbEmitted()
        {
            var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx");

            return(VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts), line: 1, column: 1, filename: "debug.csx"));
        }
Пример #20
0
        public CompiledScript CompileScript(string scriptCode)
        {
            var compiledScript = CSharpScript.Create <object>(scriptCode, _roslynScriptOptions, Globals.GetType());

            return(new CompiledScript(compiledScript, this));
        }
Пример #21
0
        public Task Pdb_CreateFromString_InlineCode_WithoutEmitDebugInformation_WithFileEncoding_ResultInPdbNotEmitted()
        {
            var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFileEncoding(Encoding.UTF8);

            return(VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts)));
        }
Пример #22
0
        public async Task RunAll()
        {
            var iteration = 1000;
            var unit      = 10000;

            var formula = "[Param1] * 7 + [Param2]";
            var dict    = new Dictionary <string, object>()
            {
                ["Param1"] = 4, ["Param2"] = 9
            };

            Stopwatch sw = new Stopwatch();

            sw.Restart();
            for (int k = 0; k < iteration; k++)
            {
                //var output = 4 * 7 + 9;
            }
            sw.Stop();
            Console.WriteLine($"Approach Basic = {sw.ElapsedMilliseconds * unit} ms");

            sw.Restart();
            for (int k = 0; k < iteration; k++)
            {
                var output = Convert.ToInt16(dict["Param1"]) * 7 + Convert.ToInt16(dict["Param2"]);
            }
            sw.Stop();
            Console.WriteLine($"Approach Control = {sw.ElapsedMilliseconds * unit} ms");

            sw.Restart();
            for (int k = 0; k < iteration; k++)
            {
                DictionaryApproach(dict, formula);
            }
            sw.Stop();
            Console.WriteLine($"Dict (No Lamda) = {sw.ElapsedMilliseconds * unit} ms");

            sw.Restart();
            for (int k = 0; k < iteration; k++)
            {
                ReplaceApproachNoLambda(dict, formula);
            }
            sw.Stop();
            Console.WriteLine($"Replace All Digits (No Lamda) = {sw.ElapsedMilliseconds * unit} ms");

            sw.Restart();
            for (int k = 0; k < iteration; k++)
            {
                ReplaceApproachWithLambda(dict, formula);
            }
            sw.Stop();
            Console.WriteLine($"Replace All Digits (With Lamda) = {sw.ElapsedMilliseconds * unit} ms");

            sw.Restart();
            var baseScript = CSharpScript.Create("");

            for (int k = 0; k < iteration; k++)
            {
                object result = await baseScript.ContinueWith("4 * 7 + 9").RunAsync();
            }
            sw.Stop();
            Console.WriteLine($"Rolsyn = {sw.ElapsedMilliseconds * unit} ms");
        }
Пример #23
0
        public void TestCreateScript()
        {
            var script = CSharpScript.Create("1 + 2");

            Assert.Equal("1 + 2", script.Code);
        }
Пример #24
0
        public void Execute(Script script)
        {
            var    scriptName        = _settings.Script.GetFilename();
            var    cacheDLLFileName  = $"{scriptName}.dll";
            var    cacheHashFileName = $"{scriptName}.hash";
            var    cachedAssembly    = _scriptCachePath.CombineWithFilePath(cacheDLLFileName);
            var    hashFile          = _scriptCachePath.CombineWithFilePath(cacheHashFileName);
            string scriptHash        = default;

            if (_scriptCacheEnabled && _fileSystem.Exist(cachedAssembly) && !_regenerateCache)
            {
                _log.Verbose($"Cache enabled: Checking cache build script ({cacheDLLFileName})");
                scriptHash = FastHash.GenerateHash(Encoding.UTF8.GetBytes(string.Concat(script.Lines)));
                var cachedHash = _fileSystem.Exist(hashFile)
                               ? _fileSystem.GetFile(hashFile).ReadLines(Encoding.UTF8).FirstOrDefault()
                               : string.Empty;
                if (scriptHash.Equals(cachedHash, StringComparison.Ordinal))
                {
                    _log.Verbose("Running cached build script...");
                    RunScriptAssembly(cachedAssembly.FullPath);
                    return;
                }
                else
                {
                    _log.Verbose("Cache check failed.");
                }
            }
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            // Warn about any code generation excluded namespaces
            foreach (var @namespace in script.ExcludedNamespaces)
            {
                _log.Warning("Namespace {0} excluded by code generation, affected methods:\r\n\t{1}",
                             @namespace.Key, string.Join("\r\n\t", @namespace.Value));
            }

            // Create the script options dynamically.
            var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
                          .AddImports(Namespaces.Except(script.ExcludedNamespaces.Keys))
                          .AddReferences(References)
                          .AddReferences(ReferencePaths.Select(r => r.FullPath))
                          .WithEmitDebugInformation(_settings.Debug)
                          .WithMetadataResolver(Microsoft.CodeAnalysis.Scripting.ScriptMetadataResolver.Default);

            var roslynScript = CSharpScript.Create(code, options, _host.GetType());

            _log.Verbose("Compiling build script...");
            var compilation = roslynScript.GetCompilation();
            var diagnostics = compilation.GetDiagnostics();

            var errors = new List <Diagnostic>();

            foreach (var diagnostic in diagnostics)
            {
                // Suppress some diagnostic information. See https://github.com/cake-build/cake/issues/3337
                switch (diagnostic.Id)
                {
                // CS1701 Compiler Warning (level 2)
                // Assuming assembly reference "Assembly Name #1" matches "Assembly Name #2", you may need to supply runtime policy
                // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs1701
                case "CS1701":
                    continue;

                // CS1702 Compiler Warning (level 3)
                // Assuming assembly reference "Assembly Name #1" matches "Assembly Name #2", you may need to supply runtime policy
                // https://docs.microsoft.com/en-us/dotnet/csharp/misc/cs1702
                case "CS1702":
                    continue;

                // CS1705 Compiler Error
                // Assembly 'AssemblyName1' uses 'TypeName' which has a higher version than referenced assembly 'AssemblyName2'
                case "CS1705":
                    continue;

                default:
                    break;
                }

                switch (diagnostic.Severity)
                {
                case DiagnosticSeverity.Info:
                    _log.Information(diagnostic.ToString());
                    break;

                case DiagnosticSeverity.Warning:
                    _log.Warning(diagnostic.ToString());
                    break;

                case DiagnosticSeverity.Error:
                    _log.Error(diagnostic.ToString());
                    errors.Add(diagnostic);
                    break;

                default:
                    break;
                }
            }

            if (errors.Any())
            {
                var errorMessages = string.Join(Environment.NewLine, errors.Select(x => x.ToString()));
                var message       = string.Format(CultureInfo.InvariantCulture, "Error(s) occurred when compiling build script:{0}{1}", Environment.NewLine, errorMessages);
                throw new CakeException(message);
            }

            if (_scriptCacheEnabled)
            {
                // Verify cache directory exists
                if (!_fileSystem.GetDirectory(_scriptCachePath).Exists)
                {
                    _fileSystem.GetDirectory(_scriptCachePath).Create();
                }
                if (string.IsNullOrWhiteSpace(scriptHash))
                {
                    scriptHash = FastHash.GenerateHash(Encoding.UTF8.GetBytes(string.Concat(script.Lines)));
                }
                var emitResult = compilation.Emit(cachedAssembly.FullPath);

                if (emitResult.Success)
                {
                    using (var stream = _fileSystem.GetFile(hashFile).OpenWrite())
                        using (var writer = new StreamWriter(stream, Encoding.UTF8))
                        {
                            writer.Write(scriptHash);
                        }
                    RunScriptAssembly(cachedAssembly.FullPath);
                }
            }
            else
            {
                roslynScript.RunAsync(_host).GetAwaiter().GetResult();
            }
        }
        public void TestDynamicProperties()
        {
            var data = @"{
		        'Id': 999,
		        'ParentId': null,
		        'TypeName': 'PROCESS.ITEM.END',
		        'Name': 'END'
	        }"    ;

            var expObj = JsonConvert.DeserializeObject <ExpandoObject>(data);

            var newDataObj = expObj as IDictionary <string, Object>;

            //var newObj = new ExpandoObject() as IDictionary<string, Object>;
            //newObj.Add("FirstName", "Masallah");
            //newObj.Add("LastName", "ÖZEN");
            //newObj.Add("Age", 36);

            //var expr = $"{newObj["Age"]} ";
            //newDataObj.Add("FirstName", "Masallah");

            dynamic newObj = newDataObj.ToExpando();

            //var scriptContent = @" ((System.Collections.Generic.IDictionary<System.String, System.Object>)data)[""ParentId""] == null ";
            var scriptContent = @" data.ParentId == null ";

            var refs = new List <MetadataReference> {
                MetadataReference.CreateFromFile(typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(System.Runtime.CompilerServices.DynamicAttribute).GetTypeInfo().Assembly.Location)
            };

            var script = CSharpScript.Create(scriptContent, options: ScriptOptions.Default.AddReferences(refs), globalsType: typeof(Globals));

            script.Compile();

            // create new global that will contain the data we want to send into the script
            var g = new Globals()
            {
                data = newObj
            };

            //Execute and display result
            var r = script.RunAsync(g).Result;

            newDataObj.Add("FirstName", "Masallah");
            newDataObj.Add("HasParentId", r.ReturnValue);

            //var rule = new FilterRule
            //{
            //    Condition = "and",
            //    Field = "HasParentId",
            //    Id = "HasParentId",
            //    Input = "NA",
            //    Operator = "equal",
            //    Type = "boolean",
            //    Value = "true",
            //};

            var rule = new FilterRule
            {
                Condition = "and",
                Field     = "FirstName",
                Id        = "HasParentId",
                Input     = "NA",
                Operator  = "begins_with",
                Type      = "string",
                Value     = "M",
            };

            ExpandoObject genereatedObj = newDataObj.ToExpando();

            var createdObj = CreateDataObject(genereatedObj as IDictionary <string, Object>, out Type type);

            var ressss = GetFilterData(createdObj, rule);
        }
Пример #26
0
        public ReplApp()
            : base($"{nameof(CSharpScriptRunner)} REPL, {BuildInfo.ReleaseTag}, EXPERIMENTAL")
        {
            ColorScheme = new()
            {
                Normal    = new(Color.White, Color.Black),
                Focus     = new(Color.White, Color.Black),
                Disabled  = new(Color.White, Color.Black),
                HotNormal = new(Color.White, Color.Black),
                HotFocus  = new(Color.White, Color.Black)
            };

            Label labelInput = new() { X = 0, Y = Pos.AnchorEnd() - 1, Height = 1, Text = "> " };

            _ctrlInput = new() { X = Pos.Right(labelInput), Y = Pos.AnchorEnd() - 1, Width = Dim.Fill(), Height = 1 };

            _ctrlHistory = new() { X = 0, Y = 0, Width = Dim.Fill(), Height = Dim.Fill() - Dim.Height(_ctrlInput), ReadOnly = true };

            _ctrlIntellisense             = new() { X = 0, Y = 0, Height = MaxIntellisenseHeight, Visible = false };
            _ctrlIntellisense.ColorScheme = new()
            {
                Normal    = new(Color.White, Color.DarkGray),
                HotNormal = new(Color.White, Color.Blue),
                Focus     = new(Color.White, Color.DarkGray),
                HotFocus  = new(Color.White, Color.Blue)
            };

            Add(_ctrlHistory, _ctrlIntellisense, labelInput, _ctrlInput);

            _ctrlInput.SetFocus();

            _ctrlHistory.KeyPress  += OnKeyPressHistory;
            _ctrlInput.KeyPress    += OnKeyPressInput;
            _ctrlInput.KeyUp       += OnKeyUpInput;
            _ctrlInput.TextChanged += OnTextChangedInput;

            _script = CSharpScript.Create(string.Empty);

            // https://www.strathweb.com/2018/12/using-roslyn-c-completion-service-programmatically/
            var host = MefHostServices.DefaultHost;

            _ws        = new AdhocWorkspace(host);
            _projectId = ProjectId.CreateNewId();
            var projectInfo = ProjectInfo.Create(_projectId, VersionStamp.Default, "Script", "Script", LanguageNames.CSharp, isSubmission: true)
                              .WithCompilationOptions(_script.GetCompilation().Options)
                              .WithMetadataReferences(_script.GetCompilation().References);

            var project = _ws.AddProject(projectInfo);
            var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(_projectId), "Script", sourceCodeKind: SourceCodeKind.Script);

            _doc = _ws.AddDocument(docInfo);
        }

        void OnKeyPressHistory(View.KeyEventEventArgs args)
        {
            if (args.KeyEvent.Key == Key.Tab)
            {
                args.Handled = true;
                _ctrlInput.SetFocus();
            }
        }

        void OnKeyPressInput(View.KeyEventEventArgs args)
        {
            if (_ctrlIntellisense.Visible)
            {
                switch (args.KeyEvent.Key)
                {
                default: return;

                case Key.CursorDown:
                    if (_ctrlIntellisense.SelectedItem == _ctrlIntellisense.Source.Count - 1)
                    {
                        _ctrlIntellisense.MoveHome();
                    }
                    else
                    {
                        _ctrlIntellisense.MoveDown();
                    }
                    break;

                case Key.CursorUp:
                    if (_ctrlIntellisense.SelectedItem == 0)
                    {
                        _ctrlIntellisense.MoveEnd();
                    }
                    else
                    {
                        _ctrlIntellisense.MoveUp();
                    }
                    break;

                case Key.Tab:
                    var item       = _ctrlIntellisense.Source.ToList()[_ctrlIntellisense.SelectedItem].ToString();
                    var text       = _ctrlInput.Text.ToString();
                    var cursorsPos = text.Length + item.Length;
                    text                      = text.Substring(0, _idxIntellisense) + item;
                    _ctrlInput.Text           = text;
                    _ctrlInput.CursorPosition = cursorsPos;
                    _ctrlIntellisense.Visible = false;
                    break;
                }

                _ctrlIntellisense.SetNeedsDisplay();
                args.Handled = true;
            }
        }

        async void OnKeyUpInput(View.KeyEventEventArgs args)
        {
            if (args.KeyEvent.Key == Key.Enter)
            {
                if (_ctrlInput.Text.IsEmpty || _isProcessing)
                {
                    return;
                }

                _isProcessing = true;
                var code        = _ctrlInput.Text.ToString().TrimEnd();
                var newScript   = _script.ContinueWith(code);
                var diagnostics = newScript.Compile();

                var output = new List <string>();
                output.Add($"> {code}");
                var success = true;
                foreach (var diag in diagnostics)
                {
                    if (diag.Severity == DiagnosticSeverity.Error)
                    {
                        success = false;
                    }
                    var loc = diag.Location.GetLineSpan();
                    output.Add($"{diag.Severity} ({loc.StartLinePosition.Line}, {loc.StartLinePosition.Character}): {diag.GetMessage()}");
                }

                if (success)
                {
                    var result = await newScript.RunAsync();

                    if (result.ReturnValue is string value)
                    {
                        value = SymbolDisplay.FormatLiteral(value, true);
                    }
                    else
                    {
                        value = result.ReturnValue?.ToString();
                    }
                    if (!string.IsNullOrEmpty(value))
                    {
                        output.Add(value);
                    }
                    _script = newScript;
                    if (!code.EndsWith(';'))
                    {
                        code += ';';
                    }
                    _scriptCode += code;
                }

                output.Add(string.Empty);
                _ctrlHistory.Text += string.Join(Environment.NewLine, output);
                _ctrlHistory.MoveEnd();
                _ctrlInput.Text = string.Empty;
                _isProcessing   = false;
            }
            else if (args.KeyEvent.Key == Key.CursorLeft || args.KeyEvent.Key == Key.CursorRight)
            {
                OnTextChangedInput(_ctrlInput.Text);
            }
        }

        async void OnTextChangedInput(NStack.ustring oldText)
        {
            if (_ctrlInput.Text.IsEmpty)
            {
                _ctrlIntellisense.Visible = false;
                return;
            }

            var code       = _scriptCode + _ctrlInput.Text.ToString();
            var doc        = _doc.WithText(SourceText.From(code));
            var service    = CompletionService.GetService(doc);
            var completion = await service.GetCompletionsAsync(doc, Math.Min(_ctrlInput.CursorPosition + _scriptCode.Length, code.Length));

            if (completion == null)
            {
                _ctrlIntellisense.Visible = false;
                return;
            }

            var items = completion.Items;

            if (items != null)
            {
                var filter = code.Substring(0, Math.Min(_ctrlInput.CursorPosition + _scriptCode.Length, code.Length));
                var idx    = filter.LastIndexOfAny(completion.Rules.DefaultCommitCharacters.ToArray());
                if (idx > -1)
                {
                    filter = filter.Substring(idx);
                }
                items            = service.FilterItems(doc, items, filter);
                _idxIntellisense = idx + 1 - _scriptCode.Length;
            }

            if (items.Length == 0)
            {
                _ctrlIntellisense.Visible = false;
            }
            else
            {
                var completionItems = items.Select(x => x.DisplayText).ToList();
                _ctrlIntellisense.SetSource(completionItems);
                _ctrlIntellisense.X = Pos.Left(_ctrlInput) + _idxIntellisense;


                _ctrlIntellisense.Y     = Pos.Top(_ctrlInput) - Math.Min(completionItems.Count, MaxIntellisenseHeight);
                _ctrlIntellisense.Width = _ctrlIntellisense.Maxlength;
                // _ctrlIntellisense.Height = height;
                _ctrlIntellisense.Visible = true;
            }
        }
    }
}
Пример #27
0
        public async Task <IBuildScript> FindAndCreateBuildScriptInstanceAsync(CommandArguments args)
        {
            var           coreDir   = Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location);
            var           flubuPath = typeof(DefaultBuildScript).GetTypeInfo().Assembly.Location;
            List <string> assemblyReferenceLocations = new List <string>
            {
                Path.Combine(coreDir, "mscorlib.dll"),
                typeof(object).GetTypeInfo().Assembly.Location,
                flubuPath,
                typeof(File).GetTypeInfo().Assembly.Location,
                typeof(ILookup <string, string>).GetTypeInfo().Assembly.Location,
                typeof(Expression).GetTypeInfo().Assembly.Location,
            };

            List <MetadataReference> references = new List <MetadataReference>();

#if NETSTANDARD2_0
            assemblyReferenceLocations.Add(typeof(Console).GetTypeInfo().Assembly.Location);
#endif

            // Enumerate all assemblies referenced by this executing assembly
            // and provide them as references to the build script we're about to
            // compile.
            AssemblyName[] referencedAssemblies = Assembly.GetEntryAssembly().GetReferencedAssemblies();
            foreach (var referencedAssembly in referencedAssemblies)
            {
                Assembly loadedAssembly = Assembly.Load(referencedAssembly);
                if (string.IsNullOrEmpty(loadedAssembly.Location))
                {
                    continue;
                }

                assemblyReferenceLocations.Add(loadedAssembly.Location);
            }

            string fileName = _buildScriptLocator.FindBuildScript(args);

            List <string> code = _file.ReadAllLines(fileName);

            AnalyserResult analyserResult = _analyser.Analyze(code);
            assemblyReferenceLocations.AddRange(analyserResult.References);

            foreach (var file in analyserResult.CsFiles)
            {
                if (_file.Exists(file))
                {
                    _log.LogInformation($"File found: {file}");
                    List <string> additionalCode = _file.ReadAllLines(file);

                    AnalyserResult additionalCodeAnalyserResult = _analyser.Analyze(additionalCode);
                    if (additionalCodeAnalyserResult.CsFiles.Count > 0)
                    {
                        throw new NotSupportedException("//#imp is only supported in main buildscript .cs file.");
                    }

                    var usings = additionalCode.Where(x => x.StartsWith("using"));

                    assemblyReferenceLocations.AddRange(additionalCodeAnalyserResult.References);
                    code.InsertRange(0, usings);
                    code.AddRange(additionalCode.Where(x => !x.StartsWith("using")));
                }
                else
                {
                    _log.LogInformation($"File was not found: {file}");
                }
            }

            assemblyReferenceLocations.AddRange(FindAssemblyReferencesInDirectories(args.AssemblyDirectories));

            assemblyReferenceLocations = assemblyReferenceLocations.Distinct().ToList();
            references.AddRange(assemblyReferenceLocations.Select(i => MetadataReference.CreateFromFile(i)));
            var opts = ScriptOptions.Default
                       .WithReferences(references);

            Script script = CSharpScript
                            .Create(string.Join("\r\n", code), opts)
                            .ContinueWith(string.Format("var sc = new {0}();", analyserResult.ClassName));

            try
            {
                ScriptState result = await script.RunAsync();

                var buildScript = result.Variables[0].Value as IBuildScript;

                if (buildScript == null)
                {
                    throw new ScriptLoaderExcetpion($"Class in file: {fileName} must inherit from DefaultBuildScript or implement IBuildScipt interface. See getting started on https://github.com/flubu-core/flubu.core/wiki");
                }

                return(buildScript);
            }
            catch (CompilationErrorException e)
            {
                if (e.Message.Contains("CS0234"))
                {
                    throw new ScriptLoaderExcetpion($"Csharp source code file: {fileName} has some compilation errors. {e.Message}. If u are using flubu script correctly you have to add assembly reference with #ref directive in build script. See build script fundamentals section 'Referencing other assemblies in build script' in https://github.com/flubu-core/flubu.core/wiki for more details.Otherwise if u think u are not using flubu correctly see Getting started section in wiki.", e);
                }

                throw new ScriptLoaderExcetpion($"Csharp source code file: {fileName} has some compilation errors. {e.Message}. See getting started and build script fundamentals in https://github.com/flubu-core/flubu.core/wiki", e);
            }
        }
Пример #28
0
 public static void Initialize()
 {
     // Compile empty script to pre-load required assemblies
     CSharpScript.Create <Func <Vector, double> >("0", getOptions(), typeof(SpecialFunctions)).Compile();
 }
Пример #29
0
        public CSharpRepl()
        {
            var script = CSharpScript.Create <dynamic>("true", ScriptOptions, typeof(Context));

            ScriptState = script.RunAsync(ScriptContext).Result;
        }
Пример #30
0
 public void TestCreateScript_CodeIsNull()
 {
     Assert.Throws <ArgumentNullException>(() => CSharpScript.Create((string)null));
 }