예제 #1
0
        async Task <object[]> IsNumber(string str)
        {
            object[] retArray = { "false", "" };
            try {
                var res = await CSharpScript.EvaluateAsync(str);

                float.Parse(res.ToString());
                retArray[1] = res;
                retArray[0] = "true";
            } catch {
                retArray[0] = "false";
            }
            return(retArray);
        }
예제 #2
0
        public async Task EvaluateAsync([Remainder] string code)
        {
            if (code.Contains("\\`"))
            {
                code = code.Replace("\\", "`");
            }
            if (Regex.IsMatch(code, PublicVariables.CodeBlockRegex, RegexOptions.Compiled | RegexOptions.Multiline))
            {
                code =
                    $"{Regex.Match(code, PublicVariables.CodeBlockRegex, RegexOptions.Compiled | RegexOptions.Multiline).Groups[2]}";
            }
            var assemblys = Assembly.GetEntryAssembly().GetReferencedAssemblies().Select(Assembly.Load).ToList();

            assemblys.Add(Assembly.GetEntryAssembly());
            var scriptOptions = ScriptOptions.Default
                                .WithReferences(assemblys.Select(x => MetadataReference.CreateFromFile(x.Location)))
                                .WithImports(Assembly.GetEntryAssembly().GetTypes().Select(x => x.Namespace).Distinct());
            var embed   = NormalizeEmbed("Evaluate Code", "Debugging...");
            var message = await ReplyAsync(embed : embed.Build());

            try
            {
                var result = await CSharpScript.EvaluateAsync(
                    $"{string.Join("\n", _dependencies.Select(x => $"using {x};"))}\n{code}", scriptOptions,
                    new EvaluateObject
                {
                    Client   = Context.Client,
                    Context  = Context,
                    Database = Database,
                    Random   = Random,
                    Server   = Server
                }, typeof(EvaluateObject));

                embed.WithTitle("Completed")
                .WithDescription($"Result: {result ?? "none"}");
                await message.ModifyAsync(x => x.Embed = embed.Build());
            }
            catch (Exception e)
            {
                embed.WithTitle("Failure")
                .WithDescription($"Reason: {e.Message ?? e.InnerException.Message}");
                await message.ModifyAsync(x => x.Embed = embed.Build());
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
예제 #3
0
        public async Task <Object> Evaluate(S4JExecutor Executor, S4JToken token, IDictionary <String, object> variables)
        {
            S4JTokenFunction function = token as S4JTokenFunction;
            StringBuilder    code     = new StringBuilder();

            CSharpEvaluatorGlobals       globals        = new CSharpEvaluatorGlobals();
            IDictionary <string, object> globaVariables = globals.Globals as IDictionary <string, object>;

            // var globalObject = new Dictionary<string, object>();

            foreach (KeyValuePair <string, object> keyAndVal in variables)
            {
                globaVariables[keyAndVal.Key] = keyAndVal.Value;
                code.Append("var ").Append(keyAndVal.Key).Append(" = ").Append("Globals.").Append(keyAndVal.Key).Append(";");
            }

            dynamic dbProxy = new ExpandoObject();

            foreach (var source in Executor.Sources)
            {
                (dbProxy as IDictionary <string, object>)[source.Key] = new DbApi(source.Value);
            }
            globaVariables["db"] = dbProxy;
            code.Append("var ").Append("db").Append(" = ").Append("Globals.").Append("db").Append(";");

            code.Append(function.ToJsonWithoutGate());

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

            var imports = ScriptOptions.Default.
                          WithImports(
                "System",
                "System.Text",
                "System.Linq",
                "System.Collections",
                "System.Collections.Generic").
                          WithReferences(refs);

            object result = await CSharpScript.EvaluateAsync(
                code.ToString(),
                imports,
                globals);

            return(result);
        }
예제 #4
0
        private async void Eval()
        {
            string exp    = this.tbxExpression.Text;
            string output = string.Empty;

            try {
                object res = await CSharpScript.EvaluateAsync(exp);

                output = exp + " = " + res.ToString();
            } catch (Exception ex) {
                output = exp + " = " + ex.Message;
            }
            this.lbxResult.Items.Insert(0, output);
            this.tbxExpression.Clear();
        }
예제 #5
0
        public async Task should_have_same_specified_machine_id_in_all_generated_ids(string machineIdScript)
        {
            var machineId = await CSharpScript.EvaluateAsync <int>(machineIdScript,
                                                                   ScriptOptions.Default.WithReferences(typeof(Snowflake).Assembly));

            var snowflake = new Snowflake(machineId);

            var lastId = snowflake.Next();
            var nextId = snowflake.Next();

            var idWithOnlyMachineId = ((long)machineId) << (64 - MachineIdOffset - MachineIdLength);

            (lastId & MachineIdMask).Should().Be(idWithOnlyMachineId);
            (nextId & MachineIdMask).Should().Be(idWithOnlyMachineId);
        }
예제 #6
0
 public async Task <T> EvaluateAsync <T>(string code, object globals = null)
 {
     try
     {
         return(await CSharpScript.EvaluateAsync <T>(code,
                                                     ScriptOptions.Default
                                                     .WithReferences(typeof(ScriptEngine).Assembly)
                                                     .WithImports(nameof(SDLGame)),
                                                     globals));
     }
     catch (CompilationErrorException exception)
     {
         throw new Exception(string.Join(Environment.NewLine, exception.Diagnostics));
     }
 }
예제 #7
0
        public T Eval <T>(string expression)
        {
            T result = default(T);

            try
            {
                result = CSharpScript.EvaluateAsync <T>(expression).Result;
            }
            catch (Exception ex)
            {
                // log ex
                result = default(T);
            }
            return(result);
        }
예제 #8
0
        private async Task <IActionResult> Counting(Example result)
        {
            string value = (await CSharpScript.EvaluateAsync($"{result.Left} {result.Operator} {result.Right}")).ToString();

            if (result.Result == value)
            {
                ViewData["Success"] = result;
                return(View("Counting", mathProvider.GetExample(result.Template)));
            }
            else
            {
                ViewData["Fail"] = result.Result;
                return(View("Counting", result));
            }
        }
        public async Task <IActionResult> GlobalsParameter([FromBody] SampleVM sampleVM)
        {
            string expression = DynamicRule.Replace("\'", "\"");

            var resultScript = CSharpScript.EvaluateAsync(expression, globals: sampleVM).Result;

            var result = new
            {
                time = GetTime(),
                expression,
                result = resultScript
            };

            return(Ok(result));
        }
예제 #10
0
        public void ImplicitlyTypedFields()
        {
            var result = CSharpScript.EvaluateAsync <object[]>(@"
var x = 1;
var y = x;
var z = foo(x);

string foo(int a) { return null; } 
int foo(string a) { return 0; }

new object[] { x, y, z }
").Result;

            AssertEx.Equal(new object[] { 1, 1, null }, result);
        }
예제 #11
0
        public override void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            // Create the script options dynamically.
            var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
                          .WithImports(Namespaces)
                          .AddReferences(References)
                          .AddReferences(ReferencePaths.Select(r => r.FullPath));

            _log.Verbose("Compiling build script...");
            CSharpScript.EvaluateAsync(code, options, _host).Wait();
        }
예제 #12
0
        public void Closure()
        {
            var f = CSharpScript.EvaluateAsync <Func <int, int> >(@"
int Foo(int arg) { return arg + 1; }

System.Func<int, int> f = (arg) =>
{
    return Foo(arg);
};

f
").Result;

            Assert.Equal(3, f(2));
        }
예제 #13
0
        void IModule.Install(ModuleManager manager)
        {
            _client = manager.Client;

            _scriptOptions = _scriptOptions.AddReferences(
                typeof(object).Assembly,
                typeof(Enumerable).Assembly,
                _client.GetType().Assembly)
                             .AddImports("System", "System.Linq", "System.Collections.Generic", "Discord");

            manager.CreateCommands("exec", group =>
            {
                group.MinPermissions((int)PermissionLevel.BotOwner);

                group.CreateCommand("")
                .Description("Compiles and runs a C# script.")
                .Parameter("query", ParameterType.Unparsed)
                .Do(async e =>
                {
                    if (e.User.Name != "SSStormy" ||
                        e.User.Id != Constants.UserOwner)
                    {
                        return;     // really have to make sure that it's me calling this tbh.
                    }
                    try
                    {
                        object output =
                            await
                            CSharpScript.EvaluateAsync(e.GetArg("query"), _scriptOptions,
                                                       new Globals(e, _client));

                        if (output == null || (output as Task) != null || (output as string) == string.Empty)
                        {
                            await e.Channel.SafeSendMessage("Output was empty or null.");
                        }
                        else
                        {
                            await e.Channel.SafeSendMessage(output.ToString());
                        }
                    }
                    catch (CompilationErrorException ex)
                    {
                        await e.Channel.SafeSendMessage($"Compilation failed: {Format.Code(ex.Message)}");
                    }
                    GC.Collect();
                });
            });
        }
예제 #14
0
        public bool IsFeatureEnabledExpr(string key)
        {
            bool result = false;

            try
            {
                var expression = _config[key];
                result = CSharpScript.EvaluateAsync <bool>(expression).Result;
            }
            catch (Exception ex)
            {
                // log ex
                result = false;
            }
            return(result);
        }
예제 #15
0
        public void HostObjectInRootNamespace()
        {
            var obj = new InteractiveFixtures_TopLevelHostObject {
                X = 1, Y = 2, Z = 3
            };
            var r0 = CSharpScript.EvaluateAsync <int>("X + Y + Z", globals: obj);

            Assert.Equal(6, r0.Result);

            obj = new InteractiveFixtures_TopLevelHostObject {
                X = 1, Y = 2, Z = 3
            };
            var r1 = CSharpScript.EvaluateAsync <int>("X", globals: obj);

            Assert.Equal(1, r1.Result);
        }
예제 #16
0
 /// <summary>Runs the code.</summary>
 /// <param name="result">The parse result.</param>
 /// <param name="request">The parse request.</param>
 /// <returns>The await handle</returns>
 private static async Task RunCode(ParseResult result, ParseRequest request)
 {
     try
     {
         var scriptOptions = ScriptOptions.Default;
         scriptOptions = scriptOptions.AddReferences(typeof(TemplateService).Assembly);
         scriptOptions = scriptOptions.AddReferences(typeof(Dictionary <string, string>).Assembly);
         scriptOptions = scriptOptions.AddImports("System", "RazorEngineSandbox.Data", "System.Collections.Generic");
         //scriptOptions.all
         result.Model = await CSharpScript.EvaluateAsync(request.Code, scriptOptions);
     }
     catch (CompilationErrorException e)
     {
         result.CodeDiagnostics = e.Message;
     }
 }
        public void RelationPath()
        {
            var myEntity = new MyEntity()
            {
                Id = 1, ChildEntity = new MyEntity()
            };

            Func <MyEntity, MyEntity> getChild = e => e.ChildEntity;
            var getChildCompiled = (Func <MyEntity, MyEntity>)CSharpScript.EvaluateAsync(
                "(Func<CSharpScriptExamples.MyEntity, CSharpScriptExamples.MyEntity>)(e => e.ChildEntity)",
                ScriptOptions.Default
                .WithReferences(typeof(MyEntity).Assembly, typeof(Func <,>).Assembly)
                .WithImports("System", typeof(MyEntity).Namespace)).Result;

            Assert.Same(getChild(myEntity), getChildCompiled(myEntity));
        }
예제 #18
0
        public static async Task <T> ExecuteAsync <T>(this string cSharpCode)
        {
            var assemblies = ScriptOptions.Default;

            //WithImports = "using System.Math" at the top of the script
            assemblies = assemblies.WithImports(
                "System.Math",
                "Hein.Framework.Extensions");
            //WithReferences = pulling in actual .dlls outside of System
            assemblies = assemblies.WithReferences(
                typeof(Hein.Framework.Extensions.GenericExtensions).Assembly);

            var result = await CSharpScript.EvaluateAsync <T>(cSharpCode, assemblies);

            return(result);
        }
예제 #19
0
        /// <summary>
        /// <see cref="IScriptEngineService.TerminalOutputParseAsync(string, string, int, CancellationToken)"/>
        /// </summary>
        public async Task <ScriptOutput> TerminalOutputParseAsync(string script, string lineInput, int lineInputCount, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var globals = new Globals {
                lineInput = lineInput, lineInputCount = lineInputCount
            };

            return(await CSharpScript.EvaluateAsync <ScriptOutput>(script,
                                                                   ScriptOptions.Default.WithImports("ReconNess.Core.Models.ScriptOutput")
                                                                   .AddReferences(
                                                                       Assembly.GetAssembly(typeof(ScriptOutput)),
                                                                       Assembly.GetAssembly(typeof(Exception)),
                                                                       Assembly.GetAssembly(typeof(System.Text.RegularExpressions.Regex)))
                                                                   , globals : globals));
        }
예제 #20
0
        async static public Task <CompileError[]> ExpectErrorsAsync(
            string sourceCode, params CompileError[] diagnostics)
        {
            try
            {
                await CSharpScript.EvaluateAsync(sourceCode);
            }
            catch (CompilationErrorException exception)
            {
                Assert.IsTrue(exception.Diagnostics.Length > 0);

                CompileError[] actualCompileErrors;
                actualCompileErrors = exception.Diagnostics.Select(item =>
                                                                   new CompileError(item.Id, item.GetMessage())).ToArray();

                if (diagnostics is { } && diagnostics.Length > 0)
예제 #21
0
        public async Task <T> ExecuteAsync <T>(string text)
        {
            var source = text.Trim();

            if (source.Length > 1 && source[0] == '@')
            {
                var code   = source.Substring(1);
                var result = await CSharpScript.EvaluateAsync(code, scriptOptions, globals);

                return((T)Convert.ChangeType(result, typeof(T)));
            }
            else
            {
                return((T)Convert.ChangeType(text, typeof(T)));
            }
        }
예제 #22
0
        public void Closure2()
        {
            var result = CSharpScript.EvaluateAsync <List <string> >(@"
#r ""System.Core""
using System;
using System.Linq;
using System.Collections.Generic;

List<string> result = new List<string>();
string s = ""hello"";
Enumerable.ToList(Enumerable.Range(1, 2)).ForEach(x => result.Add(s));
result
").Result;

            AssertEx.Equal(new[] { "hello", "hello" }, result);
        }
        public async Task Logic_Class_Contains_Accessible_Texture_FileName()
        {
            var settings = new EmitterSettings
            {
                Trigger         = new OneShotTrigger(),
                TextureFileName = @"C:\test\some.png",
            };

            var code          = EmitterLogicClassGenerator.Generate(settings, "ParmeTest", "ParmeClass", true);
            var scriptOptions = ScriptOptions.Default.WithReferences(typeof(IEmitterLogic).Assembly);

            var emitterLogic = await CSharpScript.EvaluateAsync <IEmitterLogic>(code, scriptOptions);

            emitterLogic.ShouldNotBeNull();
            emitterLogic.TextureFilePath.ShouldBe(settings.TextureFileName);
        }
        public void References2()
        {
            var options = ScriptOptions.Default.
                          WithMetadataResolver(ScriptMetadataResolver.Default.WithSearchPaths(RuntimeEnvironment.GetRuntimeDirectory())).
                          AddReferences("System.Core", "System.dll").
                          AddReferences(typeof(System.Data.DataSet).Assembly);

            var process = CSharpScript.EvaluateAsync <Process>($@"
#r ""{typeof(System.Xml.Serialization.IXmlSerializable).Assembly.Location}""
new System.Data.DataSet();
System.Linq.Expressions.Expression.Constant(123);
System.Diagnostics.Process.GetCurrentProcess()
", options).Result;

            Assert.NotNull(process);
        }
예제 #25
0
        public async Task <List <OrderScriptAction> > GetOrderScriptActions(UserScript script, List <Order> orders)
        {
            var scriptToExecute = script.Code + @"
                var script = new " + script.Name + @"(Data, Logger);
                var actions = script.GenerateActions(Orders);
                script.Cleanup();
                return actions;";

            var globals = new Globals {
                Data = _data, Orders = orders, Logger = _logger
            };
            var options = ScriptOptions.Default
                          .WithReferences(Assembly.GetExecutingAssembly());

            return(await CSharpScript.EvaluateAsync <List <OrderScriptAction> >(scriptToExecute, options, globals).ConfigureAwait(false));
        }
예제 #26
0
 public async Task <object> Fetch()
 {
     try
     {
         return(await CSharpScript.EvaluateAsync(CSharpCode, ScriptOptions.Default.WithImports("System",
                                                                                               "System.Collections.Generic",
                                                                                               "System.Linq",
                                                                                               "System.Text",
                                                                                               "System.Collections")));
     }
     catch (Exception e)
     {
         //TODO Fetch compile errors and display
         return(null);
     }
 }
예제 #27
0
        public static async void main()
        {
            var res = await CSharpScript.EvaluateAsync("5+5");

            Console.WriteLine(res);


            res = await CSharpScript.EvaluateAsync(@"""Sample""");

            Console.WriteLine(res);

            res = await CSharpScript.EvaluateAsync("int x = 5; int y = 3; y-x");

            Console.WriteLine(res);
            Console.ReadLine();
        }
예제 #28
0
        async static Task Main(string[] args)
        {
            var result = await CSharpScript.EvaluateAsync("1 + 2");

            Console.WriteLine(result); // 1 + 2 sarà valutato come 3

            double d = await CSharpScript.EvaluateAsync <double>("5/(3-1)*3.5");

            Console.WriteLine(d); // 7

            var sum = await CSharpScript.EvaluateAsync("int x=1; int y=2; int z=x+y; z");

            Console.WriteLine(sum); // 3

            try
            {
                await CSharpScript.EvaluateAsync("1+a");
            }
            catch (CompilationErrorException e)
            {
                Console.WriteLine(string.Join(Environment.NewLine, e.Diagnostics)); //stampa gli errori di compilazione
            }

            var state = await CSharpScript.RunAsync("int x=0;int y=x+1; y");

            ScriptVariable y         = state.Variables.First(sv => sv.Name == "y");
            var            returnVal = state.ReturnValue;


            ScriptOptions scriptOptions = ScriptOptions.Default;
            var           systemCore    = typeof(System.Linq.Enumerable).Assembly;

            //Aggiunge riferimento
            scriptOptions = scriptOptions.AddReferences(systemCore);
            //Aggiunge namespaces
            scriptOptions = scriptOptions.AddImports("System");
            scriptOptions = scriptOptions.AddImports("System.Linq");
            scriptOptions = scriptOptions.AddImports("System.Collections.Generic");

            var state1 = await CSharpScript.RunAsync(@"var list = new List<int>(){1,2,3,4,5};", scriptOptions);

            state1 = await state1.ContinueWithAsync("var sum = list.Sum();");

            var sum1 = state1.Variables.FirstOrDefault(v => v.Name == "sum");

            Console.WriteLine($"sum={sum1.Value}");
        }
예제 #29
0
        private async Task ExecuteScriptAsync(string code, VolteContext ctx)
        {
            var sopts = ScriptOptions.Default.WithImports(_imports).WithReferences(
                AppDomain.CurrentDomain.GetAssemblies()
                .Where(x => !x.IsDynamic && !x.Location.IsNullOrWhitespace()));

            var embed = ctx.CreateEmbedBuilder();
            var msg   = await embed.WithTitle("Evaluating").WithDescription(Format.Code(code, "cs")).SendToAsync(ctx.Channel);

            try
            {
                var sw     = Stopwatch.StartNew();
                var result = await CSharpScript.EvaluateAsync(code, sopts, CreateEvalEnvironment(ctx));

                sw.Stop();
                if (result is null)
                {
                    await msg.DeleteAsync();

                    await ctx.ReactSuccessAsync();
                }
                else
                {
                    var res = result switch
                    {
                        string str => str,
                        IEnumerable enumerable => enumerable.Cast <object>().Select(x => $"{x}").Join(", "),
                        _ => result.ToString()
                    };
                    await msg.ModifyAsync(m =>
                                          m.Embed = embed.WithTitle("Eval")
                                          .AddField("Elapsed Time", $"{sw.Elapsed.Humanize()}", true)
                                          .AddField("Return Type", result.GetType(), true)
                                          .WithDescription(Format.Code(res, "ini")).Build());
                }
            }
            catch (Exception e)
            {
                await msg.ModifyAsync(m =>
                                      m.Embed = embed
                                      .AddField("Exception Type", e.GetType(), true)
                                      .AddField("Message", e.Message, true)
                                      .WithTitle("Error")
                                      .Build()
                                      );
            }
        }
        public void References_Versioning_WeakNames1()
        {
            var c1 = Temp.CreateFile(extension: ".dll").WriteAllBytes(
                CreateCSharpCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {}", new[] { TestReferences.NetFx.v4_0_30319.mscorlib }, assemblyName: "C").EmitToArray());

            var c2 = Temp.CreateFile(extension: ".dll").WriteAllBytes(
                CreateCSharpCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {}", new[] { TestReferences.NetFx.v4_0_30319.mscorlib }, assemblyName: "C").EmitToArray());

            var result = CSharpScript.EvaluateAsync($@"
#r ""{c1.Path}""
#r ""{c2.Path}""

new C()
").Result;

            Assert.NotNull(result);
        }