// Initializes the conversation // Returns true on success public bool initialize(AdvancedDialogue _dialog) { // Local variables DynamicScript script = null; int id = 0; // Define function: enabled if (m_funcValueStartTextID == null || m_funcValueStartTextID.Length == 0) { m_funcGetStartTextID = null; } else if (System.Int32.TryParse(m_funcValueStartTextID, out id) == true) { m_funcGetStartTextID = new System.Func <int>(() => { return(id); }); } else { // Try to get script if (_dialog.DynamicScripts.ContainsKey(m_funcValueStartTextID) == false) { return(false); } script = _dialog.DynamicScripts[m_funcValueStartTextID]; m_funcGetStartTextID = new System.Func <int>(() => { object v = null; Game.Instance.ScriptEngine.executeScript(script, ref v); return((System.Int32)v); }); } return(true); }
public void Reference() { IScriptEngineProvider scriptEngineProvider = new ScriptEngineProvider(); DynamicScript script = new DynamicScript(); script.TenantId = 0; script.Language = DynamicScriptLanguage.CSharp; script.ProjectName = "TestApp"; script.Script = @" using System; using Newtonsoft.Json; //EndUsing public string GetA(int a) { var b = JsonConvert.SerializeObject(a); return b; } "; script.FunctionName = "GetA"; script.Parameters = new object[] { 111 }; var result = scriptEngineProvider.RunScript <object>(script); }
public void CheckScript() { IScriptEngineProvider scriptEngineProvider = new ScriptEngineProvider(); DynamicScript script = new DynamicScript(); script.TenantId = 0; script.Language = DynamicScriptLanguage.CSharp; script.ProjectName = "TestApp"; script.Script = @" using System; //EndUsing public int GetA(int a) { return a;int } "; script.FunctionName = "GetA"; script.Parameters = new object[] { 111 }; var result = scriptEngineProvider.CheckScript(script); Assert.False(result.IsSuccess); }
public ExecutionResult <object> Run(Guid scripeId) { //脚本的信息从库里获取 DynamicScript script = new DynamicScript(); script.Language = DynamicScriptLanguage.CSharp; script.Script = @" using System; using Chameleon.Common.Context; using Newtonsoft.Json; public class Test { public string Method() { var query = ChameleonContext.Current.Get(""FaasRequestQuery""); return (JsonConvert.SerializeObject(query)); } } "; script.ClassFullName = "Test"; script.FunctionName = "Method"; return(_scriptEngine.Execute <object>(script)); }
// Initializes the dialogue private void initialize() { // Local variables DynamicScript script = null; int id = 0; // Define function: override start conversation ID if (m_funcValueOverrideStartConvID == null || m_funcValueOverrideStartConvID.Length == 0) { m_funcOverrideStartConvID = null; } else if (System.Int32.TryParse(m_funcValueOverrideStartConvID, out id) == true) { m_funcOverrideStartConvID = new System.Func <int>(() => { return(id); }); } else { // Try to get script if (m_dynamicScriptList.ContainsKey(m_funcValueOverrideStartConvID) == false) { return; } script = m_dynamicScriptList[m_funcValueOverrideStartConvID]; m_funcOverrideStartConvID = new System.Func <int>(() => { object v = null; Game.Instance.ScriptEngine.executeScript(script, ref v); return((System.Int32)v); }); } }
public void Execute() { IScriptEngine scriptEngineProvider = new CSharpScriptEngine(); DynamicScript script = new DynamicScript(); script.Language = DynamicScriptLanguage.CSharp; script.Script = @" using System; public class Test { public int GetA(int a) { return a; } } "; script.ClassFullName = "Test"; script.FunctionName = "GetA"; script.Parameters = new object[] { 111 }; script.IsExecutionInSandbox = false; var result = scriptEngineProvider.Execute <int>(script); Assert.True(result.IsSuccess); Assert.Equal(111, result.Data); }
public void ExecuteUntrastedCode() { IScriptEngine scriptEngineProvider = new CSharpScriptEngine(); DynamicScript script = new DynamicScript(); script.Language = DynamicScriptLanguage.CSharp; script.Script = @" using System; public class Test { public int GetC(int a) { int c = 0; for(; ; ) { c += 1; } return c; } } "; script.ClassFullName = "Test"; script.FunctionName = "GetC"; script.Parameters = new object[] { 1 }; script.IsExecutionInSandbox = true; //沙箱环境执行 script.ExecutionInSandboxMillisecondsTimeout = 100; //沙箱环境执行超时时间 var result = scriptEngineProvider.Execute <int>(script); Assert.False(result.IsSuccess); Assert.Equal("execution timed out!", result.Message); }
private DynamicScriptExecuteResult <T> CallFunction <T>(DynamicScript dynamicScript) { if (dynamicScript.FunctionName.IsNullOrEmpty()) { return(DynamicScriptExecuteResult <T> .Error($"function name can not be null.")); } if (_scriptHash.IsNullOrEmpty() || !_scriptTypeDict.ContainsKey(_scriptHash)) { return(DynamicScriptExecuteResult <T> .Error($"type not found.")); } var type = _scriptTypeDict[_scriptHash]; var methodInfo = type.Method(dynamicScript.FunctionName); if (methodInfo == null) { return(DynamicScriptExecuteResult <T> .Error($"function name can not be null.")); } if (dynamicScript.IsTrustedScript) { return(ExecuteTrustedCode <T>(type, methodInfo, dynamicScript.Parameters)); } else { if (dynamicScript.MillisecondsTimeout <= 0) { return(DynamicScriptExecuteResult <T> .Error("if execute untrusted code,please setting the milliseconds timeout!")); } return(ExecuteUntrustedCode <T>(type, methodInfo, dynamicScript.MillisecondsTimeout, dynamicScript.Parameters)); } }
public void DeadCycile() { IDynamicScriptEngine scriptEngineProvider = new CSharpDynamicScriptEngine(); DynamicScript script = new DynamicScript(); script.TenantId = 0; script.Language = DynamicScriptLanguage.Csharp; script.Script = @" using System; public class Test { public int GetA(int a) { for(;;){} return a; } } "; script.ClassFullName = "Test"; script.FunctionName = "GetA"; script.Parameters = new object[] { 111 }; script.IsTrustedScript = false; //因为有死循环,所以非信任脚本测试,测试是否会超时 script.MillisecondsTimeout = 1000; var result = scriptEngineProvider.Execute <int>(script); Assert.False(result.IsSuccess); Assert.Equal("execution timed out!", result.Message); }
public void Execute() { var channel = GrpcChannel.ForAddress("http://*****:*****@" using System; public class Test { public int GetA(int a) { return a; } } "; script.ClassFullName = "Test"; script.FunctionName = "GetA"; script.IsTrustedScript = true; script.Parameters = JsonSerializer.Serialize(new object[] { 111 }); var reply = client.Execute(script); Assert.Equal("111", reply.Data); }
public void DownloadPackage() { IScriptEngine scriptEngineProvider = new CSharpScriptEngine(); DynamicScript script = new DynamicScript(); script.Language = DynamicScriptLanguage.CSharp; script.Script = @" using System; using Newtonsoft.Json; public class Test { public string GetA(int a) { return JsonConvert.SerializeObject(a); } } "; script.ClassFullName = "Test"; script.FunctionName = "GetA"; script.Parameters = new object[] { 111 }; script.IsExecutionInSandbox = false; var result = scriptEngineProvider.Execute <string>(script); Assert.True(result.IsSuccess); Assert.Equal("111", result.Data); }
public void ReferenceArguments() { IDynamicScriptEngine scriptEngineProvider = new CSharpDynamicScriptEngine(); DynamicScript script = new DynamicScript(); script.TenantId = 0; script.Language = DynamicScriptLanguage.Csharp; script.Script = @" using System; using System.Collections.Generic; public class Test { public List<int> GetA(List<int> a) { a[0] = 3; return a; } } "; script.ClassFullName = "Test"; script.FunctionName = "GetA"; script.Parameters = new object[] { new List <int> { 1, 2 } }; var result = scriptEngineProvider.Execute <object>(script); DynamicScript script2 = new DynamicScript(); script2.TenantId = 0; script2.Language = DynamicScriptLanguage.Csharp; script2.Script = @" using System; using System.Collections.Generic; public class Test { public List<int> GetA(List<int> a) { return a; } } "; script2.ClassFullName = "Test"; script2.FunctionName = "GetA"; script2.Parameters = script.Parameters; var result2 = scriptEngineProvider.Execute <List <int> >(script2); Assert.Equal(3, result2.Data[0]); Assert.Equal(3, (script.Parameters[0] as List <int>)[0]); }
private void ArgumentCheckSet(DynamicScript dynamicScript) { _tenantId = dynamicScript.TenantId; dynamicScript.Script.CheckNullOrEmpty("script can not be null"); dynamicScript.FunctionName.CheckNullOrEmpty("function name can not be null"); if (!string.IsNullOrEmpty(dynamicScript.ProjectName)) { _projectName = dynamicScript.ProjectName; } }
public void RepeatClassExecute() { IDynamicScriptEngine scriptEngineProvider = new CSharpDynamicScriptEngine(); DynamicScript script = new DynamicScript(); script.TenantId = 0; script.Language = DynamicScriptLanguage.Csharp; //先编译A执行A script.Script = @" using System; public class Test { public int GetA(int a) { return a; } } "; script.ClassFullName = "Test"; script.FunctionName = "GetA"; script.Parameters = new object[] { 111 }; var result1 = scriptEngineProvider.Execute <int>(script); //编译B执行B script.Script = @" using System; public class Test { public int GetB(int a) { return a; } } "; script.ClassFullName = "Test"; script.FunctionName = "GetB"; script.Parameters = new object[] { 99999999 }; var result2 = scriptEngineProvider.Execute <int>(script); //再执行A,这次是从B的脚本对应的Hash值去找Test类型,里面并没有A,所以报错没有找到方法A //也就是说,用B的脚本去调用A是错误的用法,即便类的名称是一样的,但其实不是一个类 script.ClassFullName = "Test"; script.FunctionName = "GetA"; script.Parameters = new object[] { 333 }; var result3 = scriptEngineProvider.Execute <int>(script); }
// Parses a dynamic script private static DynamicScript parseDynamicScript(XmlNode _node) { // Local variables string scriptName = ""; string runType = ""; string resultName = ""; string resultType = ""; string code = ""; DynamicScript dynscript = null; XmlNode xmlNodeAtt = null; // Get attribute: name xmlNodeAtt = _node.Attributes.GetNamedItem("name"); if (xmlNodeAtt == null) { Debug.LogError("Dynamic scripts need unique names!"); return(null); } scriptName = xmlNodeAtt.Value; // Get attribute: run-type xmlNodeAtt = _node.Attributes.GetNamedItem("run"); if (xmlNodeAtt != null) { runType = xmlNodeAtt.Value; } // Get attribute: result xmlNodeAtt = _node.Attributes.GetNamedItem("result"); if (xmlNodeAtt != null) { resultName = xmlNodeAtt.Value; } // Get attribute: type xmlNodeAtt = _node.Attributes.GetNamedItem("type"); if (xmlNodeAtt != null) { resultType = xmlNodeAtt.Value; } // Get text code = _node.InnerText; if (code == null || code.Length == 0) { Debug.LogError("Dynamic scripts need text!"); return(null); } // Create choice dynscript = new DynamicScript(scriptName, runType, resultName, resultType, code); return(dynscript); }
public Result CompilateAndCheckScript(string script, string applicationCode) { var dynamicScript = new DynamicScript { Script = script, Language = DynamicScriptLanguage.CSharp, ProjectName = applicationCode, FunctionName = "Test"//这里 }; return(_scriptEngineProvider.CheckScript(dynamicScript)); }
private void CheckRequiredArguments(DynamicScript request) { Ensure.ArgumentNotNullOrEmpty(request.ClassFullName, "ClassFullName"); Ensure.ArgumentNotNullOrEmpty(request.FunctionName, "FunctionName"); Ensure.ArgumentNotNullOrEmpty(request.Script, "Script"); if (request.Language <= 0) { throw new ArgumentException("Language must be provide"); } if (request.Language != DynamicScriptLanguage.Csharp) { throw new ArgumentException("Language is not csharp, please check your code or language argument."); } }
public static ScriptEngine.DynamicScript ToScriptEngineDynamicScript(this DynamicScript dynamicScript) { return(new ScriptEngine.DynamicScript { ClassFullName = dynamicScript.ClassFullName, FunctionName = dynamicScript.FunctionName, IsExecutionStatistics = dynamicScript.IsExecutionStatistics, Script = dynamicScript.Script, IsTrustedScript = dynamicScript.IsTrustedScript, Language = dynamicScript.Language.ToScriptEngineDynamicScriptLanguage(), MillisecondsTimeout = dynamicScript.MillisecondsTimeout, Parameters = Newtonsoft.Json.JsonConvert.DeserializeObject <object[]>(dynamicScript.Parameters), TenantId = dynamicScript.TenantId }); }
public override Task <DynamicScriptExecuteResult> Execute(DynamicScript request, ServerCallContext context) { try { CheckRequiredArguments(request); return(Task.FromResult(_dynamicScriptEngine.Execute <object>(request.ToScriptEngineDynamicScript()).ToGRpcDynamicScriptExecuteResult())); } catch (Exception ex) { _logger.LogError(ex, "Execute Error"); return(Task.FromResult(new DynamicScriptExecuteResult { IsSuccess = false, Message = ex.InnerException?.ToString() ?? ex.ToString() })); } }
/// <summary> /// 执行单个脚本 /// </summary> /// <param name="script"></param> /// <param name="parameters"></param> /// <param name="scriptResult"></param> /// <param name="functionName"></param> /// <returns></returns> private static bool RunningDynamicScript <T>(DynamicScript script, object[] parameters, ref object scriptResult, List <string> errorMessage) { var watch = new Stopwatch(); watch.Restart(); var dynamicScript = CreateScriptEngine.Instance.CreateDynamicScript(script); if (!dynamicScript.Compiled) { errorMessage.AddRange(dynamicScript.CompileErrorMessage); return(false); } scriptResult = dynamicScript.CallFunction <T>(script.FunctionName, parameters); watch.Stop(); return(true); }
private void ArgumentsCheck(DynamicScript dynamicScript) { dynamicScript.Script.CheckNullOrEmpty("script can not be null."); dynamicScript.ClassFullName.CheckNullOrEmpty("classFullName cannot be null."); dynamicScript.FunctionName.CheckNullOrEmpty("FunctionName can not be null."); if (dynamicScript.Language != DynamicScriptLanguage.Csharp) { throw new ArgumentOutOfRangeException("dynamicScript language is not csharp, please check code or language argument."); } if (!dynamicScript.IsTrustedScript && dynamicScript.MillisecondsTimeout <= 0) { throw new ArgumentException("if execute untrusted code,please setting the milliseconds timeout!", "dynamicScript.MillisecondsTimeout"); } }
public void Test1() { IScriptEngineProvider scriptEngineProvider = new ScriptEngineProvider(); DynamicScript script = new DynamicScript(); script.TenantId = 0; script.Language = DynamicScriptLanguage.CSharp; script.ProjectName = "TestApp"; script.Script = @" using System; //EndUsing public int GetA(int a) { return a; } "; script.FunctionName = "GetA"; script.Parameters = new object[] { 111 }; for (int i = 0; i < 10000; i++) { var result = scriptEngineProvider.RunScript <int>(script); } script.Script = @" using System; //EndUsing public int GetB(int a) { return a; } "; script.FunctionName = "GetB"; script.Parameters = new object[] { 99999999 }; for (int i = 0; i < 10000; i++) { var result = scriptEngineProvider.RunScript <int>(script); } }
// Executes a script (parameters are not supported yet!) // Returns the script result (parameter _result) // Returns true on success public bool executeScript <_T>(DynamicScript _script, ref _T _result) where _T : new() { // Local variables Type resultParamType = null; _T defaultValueResultParam; bool hasResult = false; // Result required? if (_script.ResultName != null && _script.ResultName.Length > 0 && _script.ResultTypeName != null && _script.ResultTypeName.Length > 0) { // Get type for the result param resultParamType = Type.GetType(_script.ResultTypeName); if (resultParamType == null) { return(false); } if (resultParamType.IsValueType == false || Nullable.GetUnderlyingType(resultParamType) != null) { return(false); } // Get default parameter for the result type defaultValueResultParam = new _T(); if (defaultValueResultParam == null) { return(false); } // Set global parameter for the result m_scriptEngine.SetGlobalValue(_script.ResultName, defaultValueResultParam); // Set flag hasResult = true; } // Execute script m_scriptEngine.Execute(_script.Code); // Get result if (hasResult) { _result = m_scriptEngine.GetGlobalValue <_T>(_script.ResultName); } return(true); }
public IDynamicScript CreateDynamicScript(DynamicScript script) { IDynamicScript dynamicScript = null; switch (script.RunTime.Language) { case DynamicScriptLanguageEnum.CSharp: dynamicScript = new CSharpScriptEngine(script.ApplicationName) .LoadNameSpaces(script.CompileTime.ScriptReferenceNamespace) .LoadAssembly(script.CompileTime.ScriptReferenceAssemblies) .LoadAssembly(script.CompileTime.ScriptReferenceAssemblyNames) .InitMetadataReference() .BuildDynamicScript(script.CompileTime); break; } return(dynamicScript); }
public void MultiExecute() { IDynamicScriptEngine scriptEngineProvider = new CSharpDynamicScriptEngine(); DynamicScript script = new DynamicScript(); script.TenantId = 0; script.Language = DynamicScriptLanguage.Csharp; script.Script = @" using System; public class Test { public int GetA(int a) { return a; } } "; script.ClassFullName = "Test"; script.FunctionName = "GetA"; script.Parameters = new object[] { 1 }; //script.ExecutionStatistics = true;//可以输出执行耗时,内存占用 Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); //结果相加 int sum = 0; for (int i = 0; i < 10000; i++) { var result = scriptEngineProvider.Execute <int>(script); //Trace.WriteLine($"Execute{i} -> IsSuccess:{result.IsSuccess},Data={result.Data},Message={result.Message},TotalMemoryAllocated={result.TotalMemoryAllocated},ProcessorTime={result.ProcessorTime.TotalSeconds}"); if (result.IsSuccess) { sum += result.Data; } } stopwatch.Stop(); var cos = stopwatch.ElapsedMilliseconds; Assert.Equal(10000, sum); }
static void Main(string[] args) { var code = @" using System; using System.Collections; using System.Collections.Generic; namespace BeimingForce { public class Currency { public string add(string a,string b,string z){ string c = a + b + z; asda Console.Write(c); return c;} } } "; //var vvv = // Entry.RunDynamicScript<string>("BeimingForce", code, DynamicScriptSequentialEnum.After, new object[] { "熊霄宇", "是天才", "噢" }); DynamicScript dynamicScript = new DynamicScript() { FunctionName = "add", ApplicationName = "BeimingTest", CompileTime = new DynamicScriptCompileTime() { ScriptText = code, ScriptReferenceAssemblyNames = new[] { "Dapper" } }, RunTime = new DynamicScriptRunTime() { Language = DynamicScriptLanguageEnum.CSharp, ScriptDescription = "说明", ThreadType = DynamicScriptThreadTypeEnum.Sync, } }; List <string> ErrorMessage = new List <string>(); var vv = Entry.RunDynamicScript <string>(new List <DynamicScript>() { dynamicScript }, ErrorMessage, new object[] { "熊霄宇", "是天才", "噢" }); }
public Result CheckScript(TriggerScript triggerScript) { var dynamicScript = new DynamicScript { ClassFullName = triggerScript.ClassFullName, FunctionName = triggerScript.FunctionName, Script = triggerScript.Script, Language = (DynamicScriptLanguage)triggerScript.Language, }; var result = _dynamicScriptEngine.CheckScript(dynamicScript); return(new Result { IsSuccess = result.IsSuccess, Message = result.Message, }); }
public Result <TResult> ExecuteTriggerScript <TResult>(TriggerScript triggerScript, object[] parameters) { var dynamicScript = new DynamicScript { ClassFullName = triggerScript.ClassFullName, FunctionName = triggerScript.FunctionName, Script = triggerScript.Script, Language = (DynamicScriptLanguage)triggerScript.Language, Parameters = parameters }; var result = _dynamicScriptEngine.Execute <TResult>(dynamicScript); return(new Result <TResult> { IsSuccess = result.IsSuccess, Message = result.Message, Data = result.Data }); }
private DynamicScriptExecuteResult <T> RunningDynamicScript <T>(DynamicScript dynamicScript) { //检查编译 if (!BuildDynamicScript(dynamicScript, out string errorMessage)) { _logger.LogError($"Build Script Error ! Script Info:{JsonConvert.SerializeObject(dynamicScript)}"); return(DynamicScriptExecuteResult <T> .Error(errorMessage)); } try { //是否开启执行分析,统计非常耗时且会带来更多GC开销,正常运行过程请关闭! if (dynamicScript.IsExecutionStatistics) { Stopwatch stopwatch = new Stopwatch(); //程序执行时间 var startMemory = GC.GetTotalMemory(true); //方法调用内存占用 stopwatch.Start(); var result = CallFunction <T>(dynamicScript); stopwatch.Stop(); result.TotalMemoryAllocated = GC.GetTotalMemory(true) - startMemory; result.ProcessorTime = stopwatch.ElapsedMilliseconds; return(result); } return(CallFunction <T>(dynamicScript)); } catch (MissingMethodException missingMethod) { _logger.LogError(missingMethod, string.Format("TenantId:{0},FunctionName:{1},Language:{2},AppName:{3},ScriptHash:{4},ParameterCount:{5},ErrorMsg: {6}", _tenantId, dynamicScript.FunctionName, "CSharp", _currentAppName, _scriptHash, dynamicScript.Parameters?.Length, missingMethod.Message)); return(DynamicScriptExecuteResult <T> .Error($"function name can not be null.")); } catch (Exception ex) { _logger.LogError(ex, string.Format("Script objectId:{0},tenantId:{1},appName:{2},functionName:{3},errorMsg:{4}", null, dynamicScript.TenantId, _currentAppName, dynamicScript.FunctionName, ex.Message)); return(DynamicScriptExecuteResult <T> .Error(ex.Message + ",innerEx:" + ex.InnerException?.Message)); } }
private bool BuildDynamicScript(DynamicScript dynamicScript, out string errorMessage) { errorMessage = string.Empty; try { if (_scriptTypeDict.ContainsKey(_scriptHash)) { return(true); } lock (_lock) { if (_scriptTypeDict.ContainsKey(_scriptHash)) { return(true); } var asm = CreateAsmExecutor(dynamicScript.Script, out errorMessage); if (asm != null) { var type = asm.GetType(dynamicScript.ClassFullName); if (type == null) { errorMessage = $"type [{dynamicScript.ClassFullName}] not found in the assembly [{asm.FullName}]."; return(false); } _scriptTypeDict.Add(_scriptHash, type); return(true); } } return(false); } catch (Exception ex) { errorMessage = ex.ToString(); _logger.LogError(ex, "BuildDynamicScript Error"); return(false); } }